-
Notifications
You must be signed in to change notification settings - Fork 182
/
Planning.swift
732 lines (650 loc) · 27.7 KB
/
Planning.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//===--------------- Planning.swift - Swift Compilation Planning ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
public enum PlanningError: Error, DiagnosticData {
case replReceivedInput
case emitPCMWrongInputFiles
public var description: String {
switch self {
case .replReceivedInput:
return "REPL mode requires no input files"
case .emitPCMWrongInputFiles:
return "Clang module emission requires exactly one input file (the module map)"
}
}
}
/// // MARK: Standard build planning
extension Driver {
/// Plan a standard compilation, which produces jobs for compiling separate
/// primary files.
private mutating func planStandardCompile() throws -> [Job] {
precondition(compilerMode.isStandardCompilationForPlanning,
"compiler mode \(compilerMode) is handled elsewhere")
var jobs = [Job]()
func addJob(_ j: Job) {
jobs.append(j)
}
try addPrecompileModuleDependenciesJobs(addJob: addJob)
try addPrecompileBridgingHeaderJob(addJob: addJob)
try addEmitModuleJob(addJob: addJob)
let linkerInputs = try addJobsFeedingLinker(addJob: addJob)
try addLinkAndPostLinkJobs(linkerInputs: linkerInputs,
debugInfo: debugInfo,
addJob: addJob)
return jobs
}
private mutating func addPrecompileModuleDependenciesJobs(addJob: (Job) -> Void) throws {
// If asked, add jobs to precompile module dependencies
guard parsedOptions.contains(.driverExplicitModuleBuild) ||
parsedOptions.contains(.driverPrintModuleDependenciesJobs)
else {
return
}
let modulePrebuildJobs = try generateExplicitModuleBuildJobs()
if parsedOptions.contains(.driverExplicitModuleBuild) {
modulePrebuildJobs.forEach(addJob)
}
// If we've been asked to prebuild module dependencies,
// for the time being, just print the jobs' compile commands.
if parsedOptions.contains(.driverPrintModuleDependenciesJobs) {
let forceResponseFiles = parsedOptions.contains(.driverForceResponseFiles)
for job in modulePrebuildJobs {
print(try executor.description(of: job, forceResponseFiles: forceResponseFiles))
}
}
}
private mutating func addPrecompileBridgingHeaderJob(addJob: (Job) -> Void) throws {
guard
let importedObjCHeader = importedObjCHeader,
let bridgingPrecompiledHeader = bridgingPrecompiledHeader
else { return }
addJob(
try generatePCHJob(input: .init(file: importedObjCHeader,
type: .objcHeader),
output: .init(file: bridgingPrecompiledHeader,
type: .pch))
)
}
private mutating func addEmitModuleJob(addJob: (Job) -> Void) throws {
if shouldCreateEmitModuleJob {
addJob( try emitModuleJob() )
}
}
private mutating func addJobsFeedingLinker(
addJob: (Job) -> Void
) throws -> [TypedVirtualPath] {
var linkerInputs = [TypedVirtualPath]()
func addLinkerInput(_ li: TypedVirtualPath) { linkerInputs.append(li) }
var moduleInputs = [TypedVirtualPath]()
let acceptBitcodeAsLinkerInput = lto == .llvmThin || lto == .llvmFull
func addModuleInput(_ mi: TypedVirtualPath) { moduleInputs.append(mi) }
var moduleInputsFromJobOutputs = [TypedVirtualPath]()
func addModuleInputFromJobOutputs(_ mis: TypedVirtualPath) {
moduleInputsFromJobOutputs.append(mis) }
func addJobOutputs(_ jobOutputs: [TypedVirtualPath]) {
for jobOutput in jobOutputs {
switch jobOutput.type {
case .object, .autolink:
addLinkerInput(jobOutput)
case .llvmBitcode where acceptBitcodeAsLinkerInput:
addLinkerInput(jobOutput)
case .swiftModule:
addModuleInputFromJobOutputs(jobOutput)
default:
break
}
}
}
try addSingleCompileJobs(addJob: addJob,
addJobOutputs: addJobOutputs)
try addJobsForPrimaryInputs(
addJob: addJob,
addModuleInput: addModuleInput,
addLinkerInput: addLinkerInput,
addJobOutputs: addJobOutputs)
try addAutolinkExtractJob(linkerInputs: linkerInputs,
addLinkerInput: addLinkerInput,
addJob: addJob)
if let mergeJob = try mergeModuleJob(
moduleInputs: moduleInputs,
moduleInputsFromJobOutputs: moduleInputsFromJobOutputs) {
addJob(mergeJob)
try addVerifyJobs(mergeJob: mergeJob, addJob: addJob)
try addWrapJobOrMergeOutputs(
mergeJob: mergeJob,
debugInfo: debugInfo,
addJob: addJob,
addLinkerInput: addLinkerInput)
}
return linkerInputs
}
private mutating func addSingleCompileJobs(
addJob: (Job) -> Void,
addJobOutputs: ([TypedVirtualPath]) -> Void
) throws {
guard case .singleCompile = compilerMode
else { return }
if parsedOptions.hasArgument(.embedBitcode),
inputFiles.allSatisfy({ $0.type.isPartOfSwiftCompilation })
{
let job = try compileJob(primaryInputs: [],
outputType: .llvmBitcode,
addJobOutputs: addJobOutputs,
emitModuleTrace: loadedModuleTracePath != nil)
addJob(job)
for input in job.outputs.filter({ $0.type == .llvmBitcode }) {
let job = try backendJob(input: input, addJobOutputs: addJobOutputs)
addJob(job)
}
return
}
// Create a single compile job for all of the files, none of which
// are primary.
let job = try compileJob(primaryInputs: [],
outputType: compilerOutputType,
addJobOutputs: addJobOutputs,
emitModuleTrace: loadedModuleTracePath != nil)
addJob(job)
}
private mutating func addJobsForPrimaryInputs(
addJob: (Job) -> Void,
addModuleInput: (TypedVirtualPath) -> Void,
addLinkerInput: (TypedVirtualPath) -> Void,
addJobOutputs: ([TypedVirtualPath]) -> Void)
throws {
let partitions = batchPartitions()
for (index, input) in inputFiles.enumerated() {
// Only emit a loaded module trace from the first frontend job.
let emitModuleTrace = (index == inputFiles.startIndex) && (loadedModuleTracePath != nil)
try addJobs(
forPrimaryInput: input,
partitions: partitions,
addJob: addJob,
addModuleInput: addModuleInput,
addLinkerInput: addLinkerInput,
addJobOutputs: addJobOutputs,
emitModuleTrace: emitModuleTrace)
}
}
private mutating func addJobs(
forPrimaryInput input: TypedVirtualPath,
partitions: BatchPartitions?,
addJob: (Job) -> Void,
addModuleInput: (TypedVirtualPath) -> Void,
addLinkerInput: (TypedVirtualPath) -> Void,
addJobOutputs: ([TypedVirtualPath]) -> Void,
emitModuleTrace: Bool
) throws
{
switch input.type {
case .swift, .sil, .sib:
// Generate a compile job for primary inputs here.
guard compilerMode.usesPrimaryFileInputs else { break }
var primaryInputs: [TypedVirtualPath]
if let partitions = partitions, let partitionIdx = partitions.assignment[input] {
// We have a partitioning for batch mode. If this input file isn't the first
// file in the partition, skip it: it's been accounted for already.
let partition = partitions.partitions[partitionIdx]
if partition[0] != input {
return
}
if parsedOptions.hasArgument(.driverShowJobLifecycle) {
stdoutStream.write("Forming batch job from \(partition.count) constituents\n")
}
primaryInputs = partitions.partitions[partitionIdx]
} else {
primaryInputs = [input]
}
if parsedOptions.hasArgument(.embedBitcode) {
let job = try compileJob(primaryInputs: primaryInputs,
outputType: .llvmBitcode,
addJobOutputs: addJobOutputs,
emitModuleTrace: emitModuleTrace)
addJob(job)
for input in job.outputs.filter({ $0.type == .llvmBitcode }) {
let job = try backendJob(input: input, addJobOutputs: addJobOutputs)
addJob(job)
}
} else {
let job = try compileJob(primaryInputs: primaryInputs,
outputType: compilerOutputType,
addJobOutputs: addJobOutputs,
emitModuleTrace: emitModuleTrace)
addJob(job)
}
case .object, .autolink, .llvmBitcode:
if linkerOutputType != nil {
addLinkerInput(input)
} else {
diagnosticEngine.emit(.error_unexpected_input_file(input.file))
}
case .swiftModule, .swiftDocumentation:
if moduleOutputInfo.output != nil && linkerOutputType == nil {
// When generating a .swiftmodule as a top-level output (as opposed
// to, for example, linking an image), treat .swiftmodule files as
// inputs to a MergeModule action.
addModuleInput(input)
} else if linkerOutputType != nil {
// Otherwise, if linking, pass .swiftmodule files as inputs to the
// linker, so that their debug info is available.
addLinkerInput(input)
} else {
diagnosticEngine.emit(.error_unexpected_input_file(input.file))
}
default:
diagnosticEngine.emit(.error_unexpected_input_file(input.file))
}
}
/// Need a merge module job if there are module inputs
private mutating func mergeModuleJob(
moduleInputs: [TypedVirtualPath],
moduleInputsFromJobOutputs: [TypedVirtualPath]
) throws -> Job? {
guard moduleOutputInfo.output != nil,
!(moduleInputs.isEmpty && moduleInputsFromJobOutputs.isEmpty),
compilerMode.usesPrimaryFileInputs
else { return nil }
return try mergeModuleJob(inputs: moduleInputs, inputsFromOutputs: moduleInputsFromJobOutputs)
}
private mutating func addVerifyJobs(mergeJob: Job, addJob: (Job) -> Void )
throws {
guard
parsedOptions.hasArgument(.enableLibraryEvolution),
parsedOptions.hasFlag(positive: .verifyEmittedModuleInterface,
negative: .noVerifyEmittedModuleInterface,
default: false)
else { return }
func addVerifyJob(forPrivate: Bool) throws {
let isNeeded =
forPrivate
? parsedOptions.hasArgument(.emitPrivateModuleInterfacePath)
: parsedOptions.hasArgument(.emitModuleInterface, .emitModuleInterfacePath)
guard isNeeded else { return }
let outputType: FileType =
forPrivate ? .privateSwiftInterface : .swiftInterface
let mergeInterfaceOutputs = mergeJob.outputs.filter { $0.type == outputType }
assert(mergeInterfaceOutputs.count == 1,
"Merge module job should only have one swiftinterface output")
let job = try verifyModuleInterfaceJob(interfaceInput: mergeInterfaceOutputs[0])
addJob(job)
}
try addVerifyJob(forPrivate: false)
try addVerifyJob(forPrivate: true )
}
private mutating func addAutolinkExtractJob(
linkerInputs: [TypedVirtualPath],
addLinkerInput: (TypedVirtualPath) -> Void,
addJob: (Job) -> Void)
throws
{
let autolinkInputs = linkerInputs.filter { $0.type == .object }
if let autolinkExtractJob = try autolinkExtractJob(inputs: autolinkInputs) {
addJob(autolinkExtractJob)
autolinkExtractJob.outputs.forEach(addLinkerInput)
}
}
private mutating func addWrapJobOrMergeOutputs(mergeJob: Job,
debugInfo: DebugInfo,
addJob: (Job) -> Void,
addLinkerInput: (TypedVirtualPath) -> Void)
throws {
guard case .astTypes = debugInfo.level
else { return }
if targetTriple.objectFormat != .macho {
// Module wrapping is required.
let mergeModuleOutputs = mergeJob.outputs.filter { $0.type == .swiftModule }
assert(mergeModuleOutputs.count == 1,
"Merge module job should only have one swiftmodule output")
let wrapJob = try moduleWrapJob(moduleInput: mergeModuleOutputs[0])
addJob(wrapJob)
wrapJob.outputs.forEach(addLinkerInput)
} else {
mergeJob.outputs.forEach(addLinkerInput)
}
}
private mutating func addLinkAndPostLinkJobs(
linkerInputs: [TypedVirtualPath],
debugInfo: DebugInfo,
addJob: (Job) -> Void)
throws {
guard linkerOutputType != nil && !linkerInputs.isEmpty
else { return }
let linkJ = try linkJob(inputs: linkerInputs)
addJob(linkJ)
guard targetTriple.isDarwin, debugInfo.level != nil
else {return }
let dsymJob = try generateDSYMJob(inputs: linkJ.outputs)
addJob(dsymJob)
if debugInfo.shouldVerify {
addJob(try verifyDebugInfoJob(inputs: dsymJob.outputs))
}
}
/// Prescan the source files to produce a module dependency graph and turn it into a set
/// of jobs required to build all dependencies.
/// Preprocess the graph by resolving placeholder dependencies, if any are present and
/// by re-scanning all Clang modules against all possible targets they will be built against.
public mutating func generateExplicitModuleBuildJobs() throws -> [Job] {
let dependencyGraph = try generateInterModuleDependencyGraph()
explicitModuleBuildHandler =
try ExplicitModuleBuildHandler(dependencyGraph: dependencyGraph,
toolchain: toolchain,
fileSystem: fileSystem)
return try explicitModuleBuildHandler!.generateExplicitModuleDependenciesBuildJobs()
}
private mutating func generateInterModuleDependencyGraph() throws -> InterModuleDependencyGraph {
let dependencyScannerJob = try dependencyScanningJob()
let forceResponseFiles = parsedOptions.hasArgument(.driverForceResponseFiles)
var dependencyGraph =
try self.executor.execute(job: dependencyScannerJob,
capturingJSONOutputAs: InterModuleDependencyGraph.self,
forceResponseFiles: forceResponseFiles,
recordedInputModificationDates: recordedInputModificationDates)
// Resolve placeholder dependencies in the dependency graph, if any.
if externalBuildArtifacts != nil, !externalBuildArtifacts!.0.isEmpty {
try dependencyGraph.resolvePlaceholderDependencies(using: externalBuildArtifacts!)
}
// Re-scan Clang modules at all the targets they will be built against.
try resolveVersionedClangDependencies(dependencyGraph: &dependencyGraph)
// Set dependency modules' paths to be saved in the module cache.
try updateDependencyModulesWithModuleCachePath(dependencyGraph: &dependencyGraph)
return dependencyGraph
}
/// Update the given inter-module dependency graph to set module paths to be within the module cache,
/// if one is present.
private mutating func updateDependencyModulesWithModuleCachePath(dependencyGraph:
inout InterModuleDependencyGraph)
throws {
let moduleCachePath = parsedOptions.getLastArgument(.moduleCachePath)?.asSingle
if moduleCachePath != nil {
for (moduleId, moduleInfo) in dependencyGraph.modules {
// Output path on the main module is determined by the invocation arguments.
guard moduleId.moduleName != dependencyGraph.mainModuleName else {
continue
}
let modulePath = moduleInfo.modulePath
// Only update paths on modules which do not already specify a path beyond their module name
// and a file extension.
if modulePath == moduleId.moduleName + ".swiftmodule" ||
modulePath == moduleId.moduleName + ".pcm" {
// Use VirtualPath to get the OS-specific path separators right.
let modulePathInCache =
try VirtualPath(path: moduleCachePath!).appending(component: modulePath).description
dependencyGraph.modules[moduleId]!.modulePath = modulePathInCache
}
}
}
}
}
/// MARK: Planning
extension Driver {
/// Create a job if needed for simple requests that can be immediately
/// forwarded to the frontend.
public mutating func immediateForwardingJob() throws -> Job? {
if parsedOptions.hasArgument(.printTargetInfo) {
let sdkPath = try parsedOptions.getLastArgument(.sdk).map { try VirtualPath(path: $0.asSingle) }
let resourceDirPath = try parsedOptions.getLastArgument(.resourceDir).map { try VirtualPath(path: $0.asSingle) }
var useStaticResourceDir = false
if parsedOptions.hasFlag(positive: .staticExecutable,
negative: .noStaticExecutable,
default: false) ||
parsedOptions.hasFlag(positive: .staticStdlib,
negative: .noStaticStdlib,
default: false) {
useStaticResourceDir = true
}
return try toolchain.printTargetInfoJob(target: targetTriple,
targetVariant: targetVariantTriple,
sdkPath: sdkPath,
resourceDirPath: resourceDirPath,
requiresInPlaceExecution: true,
useStaticResourceDir: useStaticResourceDir)
}
if parsedOptions.hasArgument(.version) || parsedOptions.hasArgument(.version_) {
return Job(
moduleName: moduleOutputInfo.name,
kind: .versionRequest,
tool: .absolute(try toolchain.getToolPath(.swiftCompiler)),
commandLine: [.flag("--version")],
inputs: [],
primaryInputs: [],
outputs: [],
requiresInPlaceExecution: true)
}
if parsedOptions.contains(.help) || parsedOptions.contains(.helpHidden) {
var commandLine: [Job.ArgTemplate] = [.flag("-tool=\(driverKind.rawValue)")]
if parsedOptions.contains(.helpHidden) {
commandLine.append(.flag("-show-hidden"))
}
return Job(
moduleName: moduleOutputInfo.name,
kind: .help,
tool: .absolute(try toolchain.getToolPath(.swiftHelp)),
commandLine: commandLine,
inputs: [],
primaryInputs: [],
outputs: [],
requiresInPlaceExecution: true)
}
return nil
}
/// Plan a build by producing a set of jobs to complete the build.
public mutating func planBuild() throws -> [Job] {
if let job = try immediateForwardingJob() {
return [job]
}
// The REPL doesn't require input files, but all other modes do.
guard !inputFiles.isEmpty || compilerMode == .repl else {
if parsedOptions.hasArgument(.v) {
// `swiftc -v` is allowed and prints version information.
return []
}
throw Error.noInputFiles
}
// Plan the build.
switch compilerMode {
case .repl:
if !inputFiles.isEmpty {
throw PlanningError.replReceivedInput
}
return [try replJob()]
case .immediate:
return [try interpretJob(inputs: inputFiles)]
case .standardCompile, .batchCompile, .singleCompile:
return try planStandardCompile()
case .compilePCM:
if inputFiles.count != 1 {
throw PlanningError.emitPCMWrongInputFiles
}
return [try generatePCMJob(input: inputFiles.first!)]
}
}
}
extension Diagnostic.Message {
static func error_unexpected_input_file(_ file: VirtualPath) -> Diagnostic.Message {
.error("unexpected input file: \(file.name)")
}
}
// MARK: Batch mode
extension Driver {
/// Determine the number of partitions we'll use for batch mode.
private func numberOfBatchPartitions(
_ info: BatchModeInfo,
swiftInputFiles: [TypedVirtualPath]
) -> Int {
// If the number of partitions was specified by the user, use it
if let fixedCount = info.count {
return fixedCount
}
// This is a long comment to justify a simple calculation.
//
// Because there is a secondary "outer" build system potentially also
// scheduling multiple drivers in parallel on separate build targets
// -- while we, the driver, schedule our own subprocesses -- we might
// be creating up to $NCPU^2 worth of _memory pressure_.
//
// Oversubscribing CPU is typically no problem these days, but
// oversubscribing memory can lead to paging, which on modern systems
// is quite bad.
//
// In practice, $NCPU^2 processes doesn't _quite_ happen: as core
// count rises, it usually exceeds the number of large targets
// without any dependencies between them (which are the only thing we
// have to worry about): you might have (say) 2 large independent
// modules * 2 architectures, but that's only an $NTARGET value of 4,
// which is much less than $NCPU if you're on a 24 or 36-way machine.
//
// So the actual number of concurrent processes is:
//
// NCONCUR := $NCPU * min($NCPU, $NTARGET)
//
// Empirically, a frontend uses about 512kb RAM per non-primary file
// and about 10mb per primary. The number of non-primaries per
// process is a constant in a given module, but the number of
// primaries -- the "batch size" -- is inversely proportional to the
// batch count (default: $NCPU). As a result, the memory pressure
// we can expect is:
//
// $NCONCUR * (($NONPRIMARYMEM * $NFILE) +
// ($PRIMARYMEM * ($NFILE/$NCPU)))
//
// If we tabulate this across some plausible values, we see
// unfortunate memory-pressure results:
//
// $NFILE
// +---------------------
// $NTARGET $NCPU | 100 500 1000
// ----------------+---------------------
// 2 2 | 2gb 11gb 22gb
// 4 4 | 4gb 24gb 48gb
// 4 8 | 5gb 28gb 56gb
// 4 16 | 7gb 36gb 72gb
// 4 36 | 11gb 56gb 112gb
//
// As it happens, the lower parts of the table are dominated by
// number of processes rather than the files-per-batch (the batches
// are already quite small due to the high core count) and the left
// side of the table is dealing with modules too small to worry
// about. But the middle and upper-right quadrant is problematic: 4
// and 8 core machines do not typically have 24-48gb of RAM, it'd be
// nice not to page on them when building a 4-target project with
// 500-file modules.
//
// Turns we can do that if we just cap the batch size statically at,
// say, 25 files per batch, we get a better formula:
//
// $NCONCUR * (($NONPRIMARYMEM * $NFILE) +
// ($PRIMARYMEM * min(25, ($NFILE/$NCPU))))
//
// $NFILE
// +---------------------
// $NTARGET $NCPU | 100 500 1000
// ----------------+---------------------
// 2 2 | 1gb 2gb 3gb
// 4 4 | 4gb 8gb 12gb
// 4 8 | 5gb 16gb 24gb
// 4 16 | 7gb 32gb 48gb
// 4 36 | 11gb 56gb 108gb
//
// This means that the "performance win" of batch mode diminishes
// slightly: the batching factor in the equation drops from
// ($NFILE/$NCPU) to min(25, $NFILE/$NCPU). In practice this seems to
// not cost too much: the additional factor in number of subprocesses
// run is the following:
//
// $NFILE
// +---------------------
// $NTARGET $NCPU | 100 500 1000
// ----------------+---------------------
// 2 2 | 2x 10x 20x
// 4 4 | - 5x 10x
// 4 8 | - 2.5x 5x
// 4 16 | - 1.25x 2.5x
// 4 36 | - - 1.1x
//
// Where - means "no difference" because the batches were already
// smaller than 25.
//
// Even in the worst case here, the 1000-file module on 2-core
// machine is being built with only 40 subprocesses, rather than the
// pre-batch-mode 1000. I.e. it's still running 96% fewer
// subprocesses than before. And significantly: it's doing so while
// not exceeding the RAM of a typical 2-core laptop.
// An explanation of why the partition calculation isn't integer
// division. Using an example, a module of 26 files exceeds the
// limit of 25 and must be compiled in 2 batches. Integer division
// yields 26/25 = 1 batch, but a single batch of 26 exceeds the
// limit. The calculation must round up, which can be calculated
// using: `(x + y - 1) / y`
let divideRoundingUp = { num, div in
return (num + div - 1) / div
}
let defaultSizeLimit = 25
let numInputFiles = swiftInputFiles.count
let sizeLimit = info.sizeLimit ?? defaultSizeLimit
let numTasks = numParallelJobs ?? 1
return max(numTasks, divideRoundingUp(numInputFiles, sizeLimit))
}
/// Describes the partitions used when batching.
private struct BatchPartitions {
/// Assignment of each Swift input file to a particular partition.
/// The values are indices into `partitions`.
let assignment: [TypedVirtualPath : Int]
/// The contents of each partition.
let partitions: [[TypedVirtualPath]]
}
/// Compute the partitions we'll use for batch mode.
private func batchPartitions() -> BatchPartitions? {
guard case let .batchCompile(info) = compilerMode
else { return nil }
let swiftInputFiles = inputFiles.filter { inputFile in
inputFile.type.isPartOfSwiftCompilation
}
let numPartitions = numberOfBatchPartitions(info, swiftInputFiles: swiftInputFiles)
if parsedOptions.hasArgument(.driverShowJobLifecycle) {
stdoutStream.write("Found \(swiftInputFiles.count) batchable jobs\n")
stdoutStream.write("Forming into \(numPartitions) batches\n")
stdoutStream.flush()
}
// If there is only one partition, fast path.
if numPartitions == 1 {
var assignment = [TypedVirtualPath: Int]()
for input in swiftInputFiles {
assignment[input] = 0
}
return BatchPartitions(assignment: assignment, partitions: [swiftInputFiles])
}
// Map each input file to a partition index. Ensure that we evenly
// distribute the remainder.
let numInputFiles = swiftInputFiles.count
let remainder = numInputFiles % numPartitions
let targetSize = numInputFiles / numPartitions
var partitionIndices: [Int] = []
for partitionIdx in 0..<numPartitions {
let fillCount = targetSize + (partitionIdx < remainder ? 1 : 0)
partitionIndices.append(contentsOf: Array(repeating: partitionIdx, count: fillCount))
}
assert(partitionIndices.count == numInputFiles)
if let seed = info.seed {
var generator = PredictableRandomNumberGenerator(seed: UInt64(seed))
partitionIndices.shuffle(using: &generator)
}
// Form the actual partitions.
var assignment: [TypedVirtualPath : Int] = [:]
var partitions = Array<[TypedVirtualPath]>(repeating: [], count: numPartitions)
for (fileIndex, file) in swiftInputFiles.enumerated() {
let partitionIdx = partitionIndices[fileIndex]
assignment[file] = partitionIdx
partitions[partitionIdx].append(file)
}
return BatchPartitions(assignment: assignment, partitions: partitions)
}
}