File: Frontend.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (1831 lines) | stat: -rw-r--r-- 70,776 bytes parent folder | download
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
//===--- Frontend.cpp - frontend utility methods --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
//
// This file contains utility methods for parsing and performing semantic
// on modules.
//
//===----------------------------------------------------------------------===//

#include "swift/Frontend/Frontend.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleDependencies.h"
#include "swift/AST/PluginLoader.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/FileTypes.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Frontend/CachingUtils.h"
#include "swift/Frontend/CompileJobCacheKey.h"
#include "swift/Frontend/ModuleInterfaceLoader.h"
#include "swift/Parse/Lexer.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/Utils/Generics.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Serialization/ScanningLoaders.h"
#include "swift/DependencyScan/ModuleDependencyScanner.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/TargetParser/Triple.h"
#include "llvm/CAS/ActionCache.h"
#include "llvm/CAS/BuiltinUnifiedCASDatabases.h"
#include "llvm/CAS/CASFileSystem.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/VirtualOutputBackends.h"
#include "llvm/Support/ThreadPool.h"
#include <llvm/ADT/StringExtras.h>

using namespace swift;

CompilerInstance::CompilerInstance() = default;
CompilerInstance::~CompilerInstance() = default;

std::string CompilerInvocation::getPCHHash() const {
  using llvm::hash_combine;

  auto Code = hash_combine(LangOpts.getPCHHashComponents(),
                           FrontendOpts.getPCHHashComponents(),
                           ClangImporterOpts.getPCHHashComponents(),
                           SearchPathOpts.getPCHHashComponents(),
                           DiagnosticOpts.getPCHHashComponents(),
                           SILOpts.getPCHHashComponents(),
                           IRGenOpts.getPCHHashComponents(),
                           CASOpts.getPCHHashComponents());

  return llvm::toString(llvm::APInt(64, Code), 36, /*Signed=*/false);
}

std::string CompilerInvocation::getModuleScanningHash() const {
  using llvm::hash_combine;

  auto Code = hash_combine(LangOpts.getModuleScanningHashComponents(),
                           FrontendOpts.getModuleScanningHashComponents(),
                           ClangImporterOpts.getModuleScanningHashComponents(),
                           SearchPathOpts.getModuleScanningHashComponents(),
                           DiagnosticOpts.getModuleScanningHashComponents(),
                           SILOpts.getModuleScanningHashComponents(),
                           IRGenOpts.getModuleScanningHashComponents(),
                           CASOpts.getModuleScanningHashComponents());

  return llvm::toString(llvm::APInt(64, Code), 36, /*Signed=*/false);
}

const PrimarySpecificPaths &
CompilerInvocation::getPrimarySpecificPathsForAtMostOnePrimary() const {
  return getFrontendOptions().getPrimarySpecificPathsForAtMostOnePrimary();
}

const PrimarySpecificPaths &
CompilerInvocation::getPrimarySpecificPathsForPrimary(
    StringRef filename) const {
  return getFrontendOptions().getPrimarySpecificPathsForPrimary(filename);
}

const PrimarySpecificPaths &
CompilerInvocation::getPrimarySpecificPathsForSourceFile(
    const SourceFile &SF) const {
  return getPrimarySpecificPathsForPrimary(SF.getFilename());
}

std::string CompilerInvocation::getOutputFilenameForAtMostOnePrimary() const {
  return getPrimarySpecificPathsForAtMostOnePrimary().OutputFilename;
}
std::string
CompilerInvocation::getMainInputFilenameForDebugInfoForAtMostOnePrimary()
    const {
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .MainInputFilenameForDebugInfo;
}
std::string
CompilerInvocation::getClangHeaderOutputPathForAtMostOnePrimary() const {
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.ClangHeaderOutputPath;
}
std::string CompilerInvocation::getModuleOutputPathForAtMostOnePrimary() const {
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.ModuleOutputPath;
}
std::string CompilerInvocation::getReferenceDependenciesFilePathForPrimary(
    StringRef filename) const {
  return getPrimarySpecificPathsForPrimary(filename)
      .SupplementaryOutputs.ReferenceDependenciesFilePath;
}
std::string CompilerInvocation::getConstValuesFilePathForPrimary(
    StringRef filename) const {
  return getPrimarySpecificPathsForPrimary(filename)
      .SupplementaryOutputs.ConstValuesOutputPath;
}
std::string
CompilerInvocation::getSerializedDiagnosticsPathForAtMostOnePrimary() const {
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.SerializedDiagnosticsPath;
}
std::string CompilerInvocation::getTBDPathForWholeModule() const {
  assert(getFrontendOptions().InputsAndOutputs.isWholeModule() &&
         "TBDPath only makes sense when the whole module can be seen");
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.TBDPath;
}

std::string
CompilerInvocation::getModuleInterfaceOutputPathForWholeModule() const {
  assert(getFrontendOptions().InputsAndOutputs.isWholeModule() &&
         "ModuleInterfaceOutputPath only makes sense when the whole module "
         "can be seen");
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.ModuleInterfaceOutputPath;
}

std::string
CompilerInvocation::getPrivateModuleInterfaceOutputPathForWholeModule() const {
  assert(getFrontendOptions().InputsAndOutputs.isWholeModule() &&
         "PrivateModuleInterfaceOutputPath only makes sense when the whole "
         "module can be seen");
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.PrivateModuleInterfaceOutputPath;
}

std::string
CompilerInvocation::getPackageModuleInterfaceOutputPathForWholeModule() const {
  assert(getFrontendOptions().InputsAndOutputs.isWholeModule() &&
         "PackageModuleInterfaceOutputPath only makes sense when the whole "
         "module can be seen");
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.PackageModuleInterfaceOutputPath;
}

std::string CompilerInvocation::getAPIDescriptorPathForWholeModule() const {
  assert(
      getFrontendOptions().InputsAndOutputs.isWholeModule() &&
      "APIDescriptorPath only makes sense when the whole module can be seen");
  return getPrimarySpecificPathsForAtMostOnePrimary()
      .SupplementaryOutputs.APIDescriptorOutputPath;
}

SerializationOptions CompilerInvocation::computeSerializationOptions(
    const SupplementaryOutputPaths &outs, const ModuleDecl *module) const {
  const FrontendOptions &opts = getFrontendOptions();

  SerializationOptions serializationOpts;
  serializationOpts.OutputPath = outs.ModuleOutputPath;
  serializationOpts.DocOutputPath = outs.ModuleDocOutputPath;
  serializationOpts.SourceInfoOutputPath = outs.ModuleSourceInfoOutputPath;
  serializationOpts.GroupInfoPath = opts.GroupInfoPath.c_str();
  if (opts.SerializeBridgingHeader && !outs.ModuleOutputPath.empty())
    serializationOpts.ImportedHeader = opts.ImplicitObjCHeaderPath;
  serializationOpts.ModuleLinkName = opts.ModuleLinkName;
  serializationOpts.UserModuleVersion = opts.UserModuleVersion;
  serializationOpts.AllowableClients = opts.AllowableClients;

  serializationOpts.PublicDependentLibraries =
      getIRGenOptions().PublicLinkLibraries;
  serializationOpts.SDKName = getLangOptions().SDKName;
  serializationOpts.ABIDescriptorPath = outs.ABIDescriptorOutputPath.c_str();
  serializationOpts.emptyABIDescriptor = opts.emptyABIDescriptor;

  if (!getIRGenOptions().ForceLoadSymbolName.empty())
    serializationOpts.AutolinkForceLoad = true;

  // Options contain information about the developer's computer,
  // so only serialize them if the module isn't going to be shipped to
  // the public.
  serializationOpts.SerializeOptionsForDebugging =
      opts.SerializeOptionsForDebugging.value_or(
          !module->isExternallyConsumed());

  serializationOpts.PathObfuscator = opts.serializedPathObfuscator;
  if (serializationOpts.SerializeOptionsForDebugging &&
      opts.DebugPrefixSerializedDebuggingOptions) {
    serializationOpts.DebuggingOptionsPrefixMap =
        getIRGenOptions().DebugPrefixMap;
    auto &remapper = serializationOpts.DebuggingOptionsPrefixMap;
    auto remapClangPaths = [&remapper](StringRef path) {
      return remapper.remapPath(path);
    };
    serializationOpts.ExtraClangOptions =
        getClangImporterOptions().getRemappedExtraArgs(remapClangPaths);
  } else {
    serializationOpts.ExtraClangOptions = getClangImporterOptions().ExtraArgs;
  }
  if (LangOpts.ClangTarget) {
    serializationOpts.ExtraClangOptions.push_back("--target=" +
                                                  LangOpts.ClangTarget->str());
  }

  serializationOpts.PluginSearchOptions =
      getSearchPathOptions().PluginSearchOpts;

  serializationOpts.DisableCrossModuleIncrementalInfo =
      opts.DisableCrossModuleIncrementalBuild;

  serializationOpts.StaticLibrary = opts.Static;

  serializationOpts.HermeticSealAtLink = opts.HermeticSealAtLink;

  serializationOpts.EmbeddedSwiftModule =
      LangOpts.hasFeature(Feature::Embedded);

  serializationOpts.IsOSSA = getSILOptions().EnableOSSAModules;

  serializationOpts.SkipNonExportableDecls =
      getLangOptions().SkipNonExportableDecls;

  serializationOpts.ExplicitModuleBuild = FrontendOpts.DisableImplicitModules;

  serializationOpts.EnableSerializationRemarks =
      getLangOptions().EnableModuleSerializationRemarks;

  return serializationOpts;
}

Lowering::TypeConverter &CompilerInstance::getSILTypes() {
  if (auto *tc = TheSILTypes.get())
    return *tc;

  auto *tc = new Lowering::TypeConverter(
      *getMainModule(),
      /*loweredAddresses=*/!Context->SILOpts.EnableSILOpaqueValues);
  TheSILTypes.reset(tc);
  return *tc;
}

void CompilerInstance::recordPrimaryInputBuffer(unsigned BufID) {
  PrimaryBufferIDs.insert(BufID);
}

bool CompilerInstance::setUpASTContextIfNeeded() {
  if (FrontendOptions::doesActionBuildModuleFromInterface(
          Invocation.getFrontendOptions().RequestedAction) &&
      !Invocation.getFrontendOptions().ExplicitInterfaceBuild) {
    // Compiling a module interface from source uses its own CompilerInstance
    // with options read from the input file. Don't bother setting up an
    // ASTContext at this level.
    return false;
  }

  // For the time being, we only need to record dependencies in batch mode
  // and single file builds.
  Invocation.getLangOptions().RecordRequestReferences
    = !isWholeModuleCompilation();

  Context.reset(ASTContext::get(
      Invocation.getLangOptions(), Invocation.getTypeCheckerOptions(),
      Invocation.getSILOptions(), Invocation.getSearchPathOptions(),
      Invocation.getClangImporterOptions(), Invocation.getSymbolGraphOptions(),
      Invocation.getCASOptions(), SourceMgr, Diagnostics, OutputBackend));
  if (!Invocation.getFrontendOptions().ModuleAliasMap.empty())
    Context->setModuleAliases(Invocation.getFrontendOptions().ModuleAliasMap);

  registerParseRequestFunctions(Context->evaluator);
  registerTypeCheckerRequestFunctions(Context->evaluator);
  registerClangImporterRequestFunctions(Context->evaluator);
  registerConstExtractRequestFunctions(Context->evaluator);
  registerSILGenRequestFunctions(Context->evaluator);
  registerSILOptimizerRequestFunctions(Context->evaluator);
  registerTBDGenRequestFunctions(Context->evaluator);
  registerIRGenRequestFunctions(Context->evaluator);
  
  // Migrator, indexing and typo correction need some IDE requests.
  // The integrated REPL needs IDE requests for completion.
  if (Invocation.getMigratorOptions().shouldRunMigrator() ||
      !Invocation.getFrontendOptions().IndexStorePath.empty() ||
      Invocation.getLangOptions().TypoCorrectionLimit ||
      Invocation.getFrontendOptions().RequestedAction ==
          FrontendOptions::ActionType::REPL) {
    registerIDERequestFunctions(Context->evaluator);
  }

  registerIRGenSILTransforms(*Context);

  if (Invocation.getFrontendOptions().RequestedAction ==
        FrontendOptions::ActionType::MergeModules ||
      Invocation.getLangOptions().DebuggerSupport)
    Invocation.getLangOptions().EnableDeserializationSafety = false;

  if (setUpModuleLoaders())
    return true;
  if (setUpPluginLoader())
    return true;

  return false;
}

void CompilerInstance::setupStatsReporter() {
  const auto &Invoke = getInvocation();
  const std::string &StatsOutputDir =
      Invoke.getFrontendOptions().StatsOutputDir;
  if (StatsOutputDir.empty())
    return;

  auto silOptModeArgStr = [](OptimizationMode mode) -> StringRef {
    switch (mode) {
    case OptimizationMode::ForSpeed:
      return "O";
    case OptimizationMode::ForSize:
      return "Osize";
    default:
      return "Onone";
    }
  };

  auto getClangSourceManager = [](ASTContext &Ctx) -> clang::SourceManager * {
    if (auto *clangImporter = static_cast<ClangImporter *>(
            Ctx.getClangModuleLoader())) {
      return &clangImporter->getClangASTContext().getSourceManager();
    }
    return nullptr;
  };

  const auto &FEOpts = Invoke.getFrontendOptions();
  const auto &LangOpts = Invoke.getLangOptions();
  const auto &SILOpts = Invoke.getSILOptions();
  const std::string &OutFile =
      FEOpts.InputsAndOutputs.lastInputProducingOutput().outputFilename();
  auto Reporter = std::make_unique<UnifiedStatsReporter>(
      "swift-frontend",
      FEOpts.ModuleName,
      FEOpts.InputsAndOutputs.getStatsFileMangledInputName(),
      LangOpts.Target.normalize(),
      llvm::sys::path::extension(OutFile),
      silOptModeArgStr(SILOpts.OptMode),
      StatsOutputDir,
      &getSourceMgr(),
      getClangSourceManager(getASTContext()),
      Invoke.getFrontendOptions().TraceStats,
      Invoke.getFrontendOptions().ProfileEvents,
      Invoke.getFrontendOptions().ProfileEntities);
  // Hand the stats reporter down to the ASTContext so the rest of the compiler
  // can use it.
  getASTContext().setStatsReporter(Reporter.get());
  Diagnostics.setStatsReporter(Reporter.get());
  Stats = std::move(Reporter);
}

bool CompilerInstance::setupDiagnosticVerifierIfNeeded() {
  auto &diagOpts = Invocation.getDiagnosticOptions();
  bool hadError = false;

  if (diagOpts.VerifyMode != DiagnosticOptions::NoVerify) {
    DiagVerifier = std::make_unique<DiagnosticVerifier>(
        SourceMgr, InputSourceCodeBufferIDs,
        diagOpts.VerifyMode == DiagnosticOptions::VerifyAndApplyFixes,
        diagOpts.VerifyIgnoreUnknown, diagOpts.UseColor,
        diagOpts.AdditionalDiagnosticVerifierPrefixes);
    for (const auto &filename : diagOpts.AdditionalVerifierFiles) {
      auto result = getFileSystem().getBufferForFile(filename);
      if (!result) {
        Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file,
                             filename, result.getError().message());
        hadError |= true;
        continue;
      }

      auto bufferID = SourceMgr.addNewSourceBuffer(std::move(result.get()));
      DiagVerifier->appendAdditionalBufferID(bufferID);
    }

    addDiagnosticConsumer(DiagVerifier.get());
  }

  return hadError;
}

void CompilerInstance::setupDependencyTrackerIfNeeded() {
  assert(!Context && "Must be called before the ASTContext is created");

  const auto &Invocation = getInvocation();
  const auto &opts = Invocation.getFrontendOptions();

  // Note that we may track dependencies even when we don't need to write them
  // directly; in particular, -track-system-dependencies affects how module
  // interfaces get loaded, and so we need to be consistently tracking system
  // dependencies throughout the compiler.
  auto collectionMode = opts.IntermoduleDependencyTracking;
  if (!collectionMode) {
    // If we have an output path specified, but no other tracking options,
    // default to non-system dependency tracking.
    if (opts.InputsAndOutputs.hasDependencyTrackerPath() ||
        !opts.IndexStorePath.empty()) {
      collectionMode = IntermoduleDepTrackingMode::ExcludeSystem;
    }
  }
  if (!collectionMode)
    return;

  DepTracker = std::make_unique<DependencyTracker>(*collectionMode);
}

bool CompilerInstance::setupCASIfNeeded(ArrayRef<const char *> Args) {
  if (!getInvocation().requiresCAS())
    return false;

  const auto &Opts = getInvocation().getCASOptions();
  auto MaybeDB= Opts.CASOpts.getOrCreateDatabases();
  if (!MaybeDB) {
    Diagnostics.diagnose(SourceLoc(), diag::error_cas,
                         toString(MaybeDB.takeError()));
    return true;
  }
  std::tie(CAS, ResultCache) = *MaybeDB;

  // create baseline key.
  auto BaseKey = createCompileJobBaseCacheKey(*CAS, Args);
  if (!BaseKey) {
    Diagnostics.diagnose(SourceLoc(), diag::error_cas,
                         toString(BaseKey.takeError()));
    return true;
  }
  CompileJobBaseKey = *BaseKey;
  return false;
}

void CompilerInstance::setupOutputBackend() {
  // Skip if output backend is not setup, default to OnDiskOutputBackend.
  if (OutputBackend)
    return;

  OutputBackend =
      llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();

  // Mirror the output into CAS.
  if (supportCaching()) {
    CASOutputBackend = createSwiftCachingOutputBackend(
        *CAS, *ResultCache, *CompileJobBaseKey,
        Invocation.getFrontendOptions().InputsAndOutputs,
        Invocation.getFrontendOptions().RequestedAction);
    OutputBackend =
        llvm::vfs::makeMirroringOutputBackend(OutputBackend, CASOutputBackend);
  }

  // Setup verification backend.
  // Create a mirroring outputbackend to produce hash for output files.
  // We cannot skip disk here since swift compiler is expecting to read back
  // some output file in later stages.
  if (Invocation.getFrontendOptions().DeterministicCheck) {
    HashBackend = llvm::makeIntrusiveRefCnt<HashBackendTy>();
    OutputBackend =
        llvm::vfs::makeMirroringOutputBackend(OutputBackend, HashBackend);
  }
}

void CompilerInstance::setupCachingDiagnosticsProcessorIfNeeded() {
  if (!supportCaching())
    return;

  // Only setup if using CAS.
  CDP = std::make_unique<CachingDiagnosticsProcessor>(*this);
  CDP->startDiagnosticCapture();
}

bool CompilerInstance::setup(const CompilerInvocation &Invoke,
                             std::string &Error, ArrayRef<const char *> Args) {
  Invocation = Invoke;

  if (setupCASIfNeeded(Args)) {
    Error = "Setting up CAS failed";
    return true;
  }

  setupDependencyTrackerIfNeeded();
  setupOutputBackend();

  // If initializing the overlay file system fails there's no sense in
  // continuing because the compiler will read the wrong files.
  if (setUpVirtualFileSystemOverlays()) {
    Error = "Setting up virtual file system overlays failed";
    return true;
  }
  setUpLLVMArguments();
  setUpDiagnosticOptions();

  assert(Lexer::isIdentifier(Invocation.getModuleName()));

  if (setUpInputs()) {
    Error = "Setting up inputs failed";
    return true;
  }

  if (setUpASTContextIfNeeded()) {
    Error = "Setting up ASTContext failed";
    return true;
  }

  setupStatsReporter();

  if (setupDiagnosticVerifierIfNeeded()) {
    Error = "Setting up diagnostics verified failed";
    return true;
  }

  // Setup caching diagnostics processor. It should be setup after all other
  // DiagConsumers are added.
  setupCachingDiagnosticsProcessorIfNeeded();

  // Dump module search paths if -Rmodule-loading is on.
  const auto &LangOpts = Invocation.getLangOptions();
  if (LangOpts.EnableModuleLoadingRemarks) {
    Invocation.getSearchPathOptions().dump(LangOpts.Target.isOSDarwin());
  }

  // If we expect an implicit stdlib import, load in the standard library. If we
  // either fail to find it or encounter an error while loading it, bail early. Continuing will at best
  // trigger a bunch of other errors due to the stdlib being missing, or at
  // worst crash downstream as many call sites don't currently handle a missing
  // stdlib.
  if (loadStdlibIfNeeded()) {
    Error = "Loading the standard library failed";
    return true;
  }

  return false;
}

bool CompilerInstance::setupForReplay(const CompilerInvocation &Invoke,
                                      std::string &Error,
                                      ArrayRef<const char *> Args) {
  // This is the fast path for setup an instance for replay but cannot run
  // regular compilation.
  Invocation = Invoke;

  if (setupCASIfNeeded(Args)) {
    Error = "Setting up CAS failed";
    return true;
  }

  setupOutputBackend();
  setupCachingDiagnosticsProcessorIfNeeded();
  return false;
}

bool CompilerInstance::setUpVirtualFileSystemOverlays() {
  if (Invocation.getCASOptions().requireCASFS()) {
    const auto &Opts = getInvocation().getCASOptions();
    if (!Opts.CASFSRootIDs.empty() || !Opts.ClangIncludeTrees.empty()) {
      // Set up CASFS as BaseFS.
      auto FS =
          createCASFileSystem(*CAS, Opts.CASFSRootIDs, Opts.ClangIncludeTrees);
      if (!FS) {
        Diagnostics.diagnose(SourceLoc(), diag::error_cas,
                             toString(FS.takeError()));
        return true;
      }
      SourceMgr.setFileSystem(std::move(*FS));
    }

    // If we need to load any files from CAS, try load it now and overlay it.
    llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> MemFS =
        new llvm::vfs::InMemoryFileSystem();
    const auto &ClangOpts = getInvocation().getClangImporterOptions();

    if (!Opts.BridgingHeaderPCHCacheKey.empty()) {
      if (auto loadedBuffer = loadCachedCompileResultFromCacheKey(
              getObjectStore(), getActionCache(), Diagnostics,
              Opts.BridgingHeaderPCHCacheKey, file_types::ID::TY_PCH,
              ClangOpts.BridgingHeader))
        MemFS->addFile(Invocation.getClangImporterOptions().BridgingHeader, 0,
                       std::move(loadedBuffer));
      else
        Diagnostics.diagnose(
            SourceLoc(), diag::error_load_input_from_cas,
            Invocation.getClangImporterOptions().BridgingHeader);
    }
    if (!Opts.InputFileKey.empty()) {
      if (Invocation.getFrontendOptions()
              .InputsAndOutputs.getAllInputs()
              .size() != 1)
        Diagnostics.diagnose(SourceLoc(),
                             diag::error_wrong_input_num_for_input_file_key);
      else {
        auto InputPath = Invocation.getFrontendOptions()
                             .InputsAndOutputs.getFilenameOfFirstInput();
        auto Type = file_types::lookupTypeFromFilename(
            llvm::sys::path::filename(InputPath));
        if (auto loadedBuffer = loadCachedCompileResultFromCacheKey(
                getObjectStore(), getActionCache(), Diagnostics,
                Opts.InputFileKey, Type, InputPath))
          MemFS->addFile(InputPath, 0, std::move(loadedBuffer));
        else
          Diagnostics.diagnose(SourceLoc(), diag::error_load_input_from_cas,
                               InputPath);
      }
    }
    llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayVFS =
        new llvm::vfs::OverlayFileSystem(SourceMgr.getFileSystem());
    OverlayVFS->pushOverlay(MemFS);
    SourceMgr.setFileSystem(std::move(OverlayVFS));
  }

  auto ExpectedOverlay =
      Invocation.getSearchPathOptions().makeOverlayFileSystem(
          SourceMgr.getFileSystem());
  if (!ExpectedOverlay) {
    llvm::handleAllErrors(
        ExpectedOverlay.takeError(), [&](const llvm::FileError &FE) {
          if (FE.convertToErrorCode() == std::errc::no_such_file_or_directory) {
            Diagnostics.diagnose(SourceLoc(), diag::cannot_open_file,
                                 FE.getFileName(), FE.messageWithoutFileInfo());
          } else {
            Diagnostics.diagnose(SourceLoc(), diag::invalid_vfs_overlay_file,
                                 FE.getFileName());
          }
        });
    return true;
  }

  SourceMgr.setFileSystem(*ExpectedOverlay);
  return false;
}

void CompilerInstance::setUpLLVMArguments() {
  // Dependency scanning has no need for LLVM options, and
  // must not use `llvm::cl::` utilities operating on global state
  // since dependency scanning is multi-threaded.
  if (Invocation.getFrontendOptions().RequestedAction !=
      FrontendOptions::ActionType::ScanDependencies) {
    // Honor -Xllvm.
    if (!Invocation.getFrontendOptions().LLVMArgs.empty()) {
      llvm::SmallVector<const char *, 4> Args;
      Args.push_back("swift (LLVM option parsing)");
      for (unsigned i = 0, e = Invocation.getFrontendOptions().LLVMArgs.size();
           i != e; ++i)
        Args.push_back(Invocation.getFrontendOptions().LLVMArgs[i].c_str());
      Args.push_back(nullptr);
      llvm::cl::ParseCommandLineOptions(Args.size()-1, Args.data());
    }
  }
}

void CompilerInstance::setUpDiagnosticOptions() {
  if (Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) {
    Diagnostics.setShowDiagnosticsAfterFatalError();
  }
  if (Invocation.getDiagnosticOptions().SuppressWarnings) {
    Diagnostics.setSuppressWarnings(true);
  }
  if (Invocation.getDiagnosticOptions().SuppressRemarks) {
    Diagnostics.setSuppressRemarks(true);
  }
  if (Invocation.getDiagnosticOptions().WarningsAsErrors) {
    Diagnostics.setWarningsAsErrors(true);
  }
  if (Invocation.getDiagnosticOptions().PrintDiagnosticNames) {
    Diagnostics.setPrintDiagnosticNames(true);
  }
  Diagnostics.setDiagnosticDocumentationPath(
      Invocation.getDiagnosticOptions().DiagnosticDocumentationPath);
  Diagnostics.setLanguageVersion(
      Invocation.getLangOptions().EffectiveLanguageVersion);
  if (!Invocation.getDiagnosticOptions().LocalizationCode.empty()) {
    Diagnostics.setLocalization(
        Invocation.getDiagnosticOptions().LocalizationCode,
        Invocation.getDiagnosticOptions().LocalizationPath);
  }
}

// The ordering of ModuleLoaders is important!
//
// 1. SourceLoader: This is a hack and only the compiler's tests are using it,
//    to avoid writing repetitive code involving generating modules/interfaces.
//    Ideally, we'd get rid of it.
// 2. MemoryBufferSerializedModuleLoader: This is used by LLDB, because it might
//    already have the module available in memory.
// 3. ExplicitSwiftModuleLoader: Loads a serialized module if it can, provided
//    this modules was specified as an explicit input to the compiler.
// 4. ModuleInterfaceLoader: Tries to find an up-to-date swiftmodule. If it
//    succeeds, it issues a particular "error" (see
//    [NOTE: ModuleInterfaceLoader-defer-to-ImplicitSerializedModuleLoader]),
//    which is interpreted by the overarching loader as a command to use the
//    ImplicitSerializedModuleLoader. If we failed to find a .swiftmodule,
//    this falls back to using an interface. Actual errors lead to diagnostics.
// 5. ImplicitSerializedModuleLoader: Loads a serialized module if it can.
//    Used for implicit loading of modules from the compiler's search paths.
// 6. ClangImporter: This must come after all the Swift module loaders because
//    in the presence of overlays and mixed-source frameworks, we want to prefer
//    the overlay or framework module over the underlying Clang module.
bool CompilerInstance::setUpModuleLoaders() {
  if (hasSourceImport()) {
    bool enableLibraryEvolution =
      Invocation.getFrontendOptions().EnableLibraryEvolution;
    Context->addModuleLoader(SourceLoader::create(*Context,
                                                  enableLibraryEvolution,
                                                  getDependencyTracker()));
  }
  auto MLM = Invocation.getSearchPathOptions().ModuleLoadMode;
  auto IgnoreSourceInfoFile =
    Invocation.getFrontendOptions().IgnoreSwiftSourceInfo;
  if (Invocation.getLangOptions().EnableMemoryBufferImporter) {
    auto MemoryBufferLoader = MemoryBufferSerializedModuleLoader::create(
        *Context, getDependencyTracker(), MLM, IgnoreSourceInfoFile);
    this->MemoryBufferLoader = MemoryBufferLoader.get();
    Context->addModuleLoader(std::move(MemoryBufferLoader));
  }

  // If using `-explicit-swift-module-map-file`, create the explicit loader
  // before creating `ClangImporter` because the entries in the map influence
  // the Clang flags. The loader is added to the context below.
  std::unique_ptr<SerializedModuleLoaderBase> ESML = nullptr;
  bool ExplicitModuleBuild =
      Invocation.getFrontendOptions().DisableImplicitModules;
  if (ExplicitModuleBuild ||
      !Invocation.getSearchPathOptions().ExplicitSwiftModuleMapPath.empty() ||
      !Invocation.getSearchPathOptions().ExplicitSwiftModuleInputs.empty()) {
    if (Invocation.getCASOptions().EnableCaching)
      ESML = ExplicitCASModuleLoader::create(
          *Context, getObjectStore(), getActionCache(), getDependencyTracker(),
          MLM, Invocation.getSearchPathOptions().ExplicitSwiftModuleMapPath,
          Invocation.getSearchPathOptions().ExplicitSwiftModuleInputs,
          IgnoreSourceInfoFile);
    else
      ESML = ExplicitSwiftModuleLoader::create(
          *Context, getDependencyTracker(), MLM,
          Invocation.getSearchPathOptions().ExplicitSwiftModuleMapPath,
          Invocation.getSearchPathOptions().ExplicitSwiftModuleInputs,
          IgnoreSourceInfoFile);
  }

  // Wire up the Clang importer. If the user has specified an SDK, use it.
  // Otherwise, we just keep it around as our interface to Clang's ABI
  // knowledge.
  std::unique_ptr<ClangImporter> clangImporter =
    ClangImporter::create(*Context, Invocation.getPCHHash(),
                          getDependencyTracker());
  if (!clangImporter) {
    Diagnostics.diagnose(SourceLoc(), diag::error_clang_importer_create_fail);
    return true;
  }

  // Configure ModuleInterfaceChecker for the ASTContext.
  auto const &Clang = clangImporter->getClangInstance();
  std::string ModuleCachePath = getModuleCachePathFromClang(Clang);
  auto &FEOpts = Invocation.getFrontendOptions();
  ModuleInterfaceLoaderOptions LoaderOpts(FEOpts);
  Context->addModuleInterfaceChecker(
      std::make_unique<ModuleInterfaceCheckerImpl>(
          *Context, ModuleCachePath, FEOpts.PrebuiltModuleCachePath,
          FEOpts.BackupModuleInterfaceDir, LoaderOpts,
          RequireOSSAModules_t(Invocation.getSILOptions())));

  // Install an explicit module loader if it was created earlier.
  if (ESML) {
    this->DefaultSerializedLoader = ESML.get();
    Context->addModuleLoader(std::move(ESML));
  }

  if (!ExplicitModuleBuild) {
    if (MLM != ModuleLoadingMode::OnlySerialized) {
      // We only need ModuleInterfaceLoader for implicit modules.
      auto PIML = ModuleInterfaceLoader::create(
          *Context, *static_cast<ModuleInterfaceCheckerImpl*>(Context
            ->getModuleInterfaceChecker()), getDependencyTracker(), MLM,
          FEOpts.PreferInterfaceForModules, IgnoreSourceInfoFile);
      Context->addModuleLoader(std::move(PIML), false, false, true);
    }
    std::unique_ptr<ImplicitSerializedModuleLoader> ISML =
    ImplicitSerializedModuleLoader::create(*Context, getDependencyTracker(), MLM,
                                   IgnoreSourceInfoFile);
    this->DefaultSerializedLoader = ISML.get();
    Context->addModuleLoader(std::move(ISML));
  }

  Context->addModuleLoader(std::move(clangImporter), /*isClang*/ true);

  // When scanning for dependencies, we must add the scanner placeholder loader in order to
  // handle ASTContext operations such as canImportModule
  if (Invocation.getFrontendOptions().RequestedAction ==
      FrontendOptions::ActionType::ScanDependencies) {
    auto ClangModuleCachePath = getModuleCachePathFromClang(
        Context->getClangModuleLoader()->getClangInstance());
    auto &FEOpts = Invocation.getFrontendOptions();
    ModuleInterfaceLoaderOptions LoaderOpts(FEOpts);
    InterfaceSubContextDelegateImpl ASTDelegate(
        Context->SourceMgr, &Context->Diags, Context->SearchPathOpts,
        Context->LangOpts, Context->ClangImporterOpts, Context->CASOpts,
        LoaderOpts,
        /*buildModuleCacheDirIfAbsent*/ false, ClangModuleCachePath,
        FEOpts.PrebuiltModuleCachePath, FEOpts.BackupModuleInterfaceDir,
        FEOpts.SerializeModuleInterfaceDependencyHashes,
        FEOpts.shouldTrackSystemDependencies(),
        RequireOSSAModules_t(Invocation.getSILOptions()));
    auto mainModuleName = Context->getIdentifier(FEOpts.ModuleName);
    std::unique_ptr<PlaceholderSwiftModuleScanner> PSMS =
        std::make_unique<PlaceholderSwiftModuleScanner>(
            *Context, MLM, mainModuleName,
            Context->SearchPathOpts.PlaceholderDependencyModuleMap, ASTDelegate,
            getInvocation().getFrontendOptions().ExplicitModulesOutputPath);
    Context->addModuleLoader(std::move(PSMS));
  }

  return false;
}

bool CompilerInstance::setUpPluginLoader() {
  /// FIXME: If Invocation has 'PluginRegistry', we can set it. But should we?
  auto loader = std::make_unique<PluginLoader>(
      *Context, getDependencyTracker(),
      Invocation.getFrontendOptions().DisableSandbox);
  Context->setPluginLoader(std::move(loader));
  return false;
}

std::optional<unsigned> CompilerInstance::setUpIDEInspectionTargetBuffer() {
  std::optional<unsigned> ideInspectionTargetBufferID;
  auto ideInspectionTarget = Invocation.getIDEInspectionTarget();
  if (ideInspectionTarget.first) {
    auto memBuf = ideInspectionTarget.first;
    // CompilerInvocation doesn't own the buffers, copy to a new buffer.
    ideInspectionTargetBufferID = SourceMgr.addMemBufferCopy(memBuf);
    InputSourceCodeBufferIDs.push_back(*ideInspectionTargetBufferID);
    SourceMgr.setIDEInspectionTarget(*ideInspectionTargetBufferID,
                                    ideInspectionTarget.second);
  }
  return ideInspectionTargetBufferID;
}

SourceFile *CompilerInstance::getIDEInspectionFile() const {
  auto *mod = getMainModule();
  auto &eval = mod->getASTContext().evaluator;
  return evaluateOrDefault(eval, IDEInspectionFileRequest{mod}, nullptr);
}

static inline bool isPCHFilenameExtension(StringRef path) {
  return llvm::sys::path::extension(path)
    .endswith(file_types::getExtension(file_types::TY_PCH));
}

std::string CompilerInstance::getBridgingHeaderPath() const {
  const FrontendOptions &opts = Invocation.getFrontendOptions();
  if (!isPCHFilenameExtension(opts.ImplicitObjCHeaderPath))
    return opts.ImplicitObjCHeaderPath;

  auto clangImporter =
      static_cast<ClangImporter *>(getASTContext().getClangModuleLoader());

  // No clang importer created. Report error?
  if (!clangImporter)
    return std::string();

  return clangImporter->getOriginalSourceFile(opts.ImplicitObjCHeaderPath);
}

bool CompilerInstance::setUpInputs() {
  // There is no input file when building PCM using ClangIncludeTree.
  if (Invocation.getFrontendOptions().RequestedAction ==
          FrontendOptions::ActionType::EmitPCM &&
      Invocation.getClangImporterOptions().HasClangIncludeTreeRoot)
    return false;

  // Adds to InputSourceCodeBufferIDs, so may need to happen before the
  // per-input setup.
  const std::optional<unsigned> ideInspectionTargetBufferID =
      setUpIDEInspectionTargetBuffer();

  const auto &Inputs =
      Invocation.getFrontendOptions().InputsAndOutputs.getAllInputs();
  const bool shouldRecover = Invocation.getFrontendOptions()
                                 .InputsAndOutputs.shouldRecoverMissingInputs();

  bool hasFailed = false;
  for (const InputFile &input : Inputs) {
    bool failed = false;
    std::optional<unsigned> bufferID =
        getRecordedBufferID(input, shouldRecover, failed);
    hasFailed |= failed;

    if (!bufferID.has_value() || !input.isPrimary())
      continue;

    recordPrimaryInputBuffer(*bufferID);
  }
  if (hasFailed)
    return true;

  // Set the primary file to the IDE inspection point if one exists.
  if (ideInspectionTargetBufferID.has_value() &&
      !isPrimaryInput(*ideInspectionTargetBufferID)) {
    assert(PrimaryBufferIDs.empty() && "re-setting PrimaryBufferID");
    recordPrimaryInputBuffer(*ideInspectionTargetBufferID);
  }

  return false;
}

std::optional<unsigned>
CompilerInstance::getRecordedBufferID(const InputFile &input,
                                      const bool shouldRecover, bool &failed) {
  if (!input.getBuffer()) {
    if (std::optional<unsigned> existingBufferID =
            SourceMgr.getIDForBufferIdentifier(input.getFileName())) {
      return existingBufferID;
    }
  }
  auto buffers = getInputBuffersIfPresent(input);

  // Recover by dummy buffer if requested.
  if (!buffers.has_value() && shouldRecover &&
      input.getType() == file_types::TY_Swift) {
    buffers = ModuleBuffers(llvm::MemoryBuffer::getMemBuffer(
        "// missing file\n", input.getFileName()));
  }

  if (!buffers.has_value()) {
    failed = true;
    return std::nullopt;
  }

  // FIXME: The fact that this test happens twice, for some cases,
  // suggests that setupInputs could use another round of refactoring.
  if (serialization::isSerializedAST(buffers->ModuleBuffer->getBuffer())) {
    PartialModules.push_back(std::move(*buffers));
    return std::nullopt;
  }
  assert(buffers->ModuleDocBuffer.get() == nullptr);
  assert(buffers->ModuleSourceInfoBuffer.get() == nullptr);
  // Transfer ownership of the MemoryBuffer to the SourceMgr.
  unsigned bufferID = SourceMgr.addNewSourceBuffer(std::move(buffers->ModuleBuffer));

  InputSourceCodeBufferIDs.push_back(bufferID);
  return bufferID;
}

std::optional<ModuleBuffers>
CompilerInstance::getInputBuffersIfPresent(const InputFile &input) {
  if (auto b = input.getBuffer()) {
    return ModuleBuffers(llvm::MemoryBuffer::getMemBufferCopy(b->getBuffer(),
                                                              b->getBufferIdentifier()));
  }
  // FIXME: Working with filenames is fragile, maybe use the real path
  // or have some kind of FileManager.
  using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
  // Avoid memory-mapping when the compiler is run for IDE inspection,
  // since that would prevent the user from saving the file.
  FileOrError inputFileOrErr =
    swift::vfs::getFileOrSTDIN(getFileSystem(), input.getFileName(),
                              /*FileSize*/-1,
                              /*RequiresNullTerminator*/true,
                              /*IsVolatile*/getInvocation().isIDEInspection(),
      /*Bad File Descriptor Retry*/getInvocation().getFrontendOptions()
                               .BadFileDescriptorRetryCount);
  if (!inputFileOrErr) {
    Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file,
                         input.getFileName(),
                         inputFileOrErr.getError().message());
    return std::nullopt;
  }
  if (!serialization::isSerializedAST((*inputFileOrErr)->getBuffer()))
    return ModuleBuffers(std::move(*inputFileOrErr));

  auto swiftdoc = openModuleDoc(input);
  auto sourceinfo = openModuleSourceInfo(input);
  return ModuleBuffers(std::move(*inputFileOrErr),
                       swiftdoc.has_value() ? std::move(swiftdoc.value()) : nullptr,
                       sourceinfo.has_value() ? std::move(sourceinfo.value()) : nullptr);
}

std::optional<std::unique_ptr<llvm::MemoryBuffer>>
CompilerInstance::openModuleSourceInfo(const InputFile &input) {
  llvm::SmallString<128> pathWithoutProjectDir(input.getFileName());
  llvm::sys::path::replace_extension(pathWithoutProjectDir,
                  file_types::getExtension(file_types::TY_SwiftSourceInfoFile));
  llvm::SmallString<128> pathWithProjectDir = pathWithoutProjectDir.str();
  StringRef fileName = llvm::sys::path::filename(pathWithoutProjectDir);
  llvm::sys::path::remove_filename(pathWithProjectDir);
  llvm::sys::path::append(pathWithProjectDir, "Project");
  llvm::sys::path::append(pathWithProjectDir, fileName);
  if (auto sourceInfoFileOrErr = swift::vfs::getFileOrSTDIN(getFileSystem(),
                                                            pathWithProjectDir))
    return std::move(*sourceInfoFileOrErr);
  if (auto sourceInfoFileOrErr = swift::vfs::getFileOrSTDIN(getFileSystem(),
                                                            pathWithoutProjectDir))
    return std::move(*sourceInfoFileOrErr);
  return std::nullopt;
}

std::optional<std::unique_ptr<llvm::MemoryBuffer>>
CompilerInstance::openModuleDoc(const InputFile &input) {
  llvm::SmallString<128> moduleDocFilePath(input.getFileName());
  llvm::sys::path::replace_extension(
      moduleDocFilePath,
      file_types::getExtension(file_types::TY_SwiftModuleDocFile));
  using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
  FileOrError moduleDocFileOrErr =
      swift::vfs::getFileOrSTDIN(getFileSystem(), moduleDocFilePath);
  if (moduleDocFileOrErr)
    return std::move(*moduleDocFileOrErr);

  if (moduleDocFileOrErr.getError() == std::errc::no_such_file_or_directory)
    return std::unique_ptr<llvm::MemoryBuffer>();

  Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file,
                       moduleDocFilePath,
                       moduleDocFileOrErr.getError().message());
  return std::nullopt;
}

/// Enable Swift concurrency on a per-target basis
static bool shouldImportConcurrencyByDefault(const llvm::Triple &target) {
  if (target.isOSDarwin())
    return true;
  if (target.isOSWindows())
    return true;
  if (target.isOSLinux())
    return true;
#if SWIFT_IMPLICIT_CONCURRENCY_IMPORT
  if (target.isOSWASI())
    return true;
  if (target.isOSOpenBSD())
    return true;
  if (target.isOSFreeBSD())
    return true;
#endif
  return false;
}

bool CompilerInvocation::shouldImportSwiftConcurrency() const {
  return shouldImportConcurrencyByDefault(getLangOptions().Target) &&
      !getLangOptions().DisableImplicitConcurrencyModuleImport &&
      getFrontendOptions().InputMode !=
        FrontendOptions::ParseInputMode::SwiftModuleInterface;
}

bool CompilerInvocation::shouldImportSwiftStringProcessing() const {
  return getLangOptions().EnableExperimentalStringProcessing &&
      !getLangOptions().DisableImplicitStringProcessingModuleImport &&
      getFrontendOptions().InputMode !=
        FrontendOptions::ParseInputMode::SwiftModuleInterface;
}

/// Enable Swift backtracing on a per-target basis
static bool shouldImportSwiftBacktracingByDefault(const llvm::Triple &target) {
  if (target.isOSDarwin() || target.isOSWindows() || target.isOSLinux())
    return true;
  return false;
}

bool CompilerInvocation::shouldImportSwiftBacktracing() const {
  return shouldImportSwiftBacktracingByDefault(getLangOptions().Target) &&
    !getLangOptions().DisableImplicitBacktracingModuleImport &&
    getFrontendOptions().InputMode !=
      FrontendOptions::ParseInputMode::SwiftModuleInterface;
}

bool CompilerInvocation::shouldImportCxx() const {
  // C++ Interop is disabled
  if (!getLangOptions().EnableCXXInterop)
    return false;
  // Avoid C++ stdlib when building Swift stdlib
  if (getImplicitStdlibKind() == ImplicitStdlibKind::Builtin)
    return false;
  // Avoid importing Cxx when building Cxx itself
  if (getFrontendOptions().ModuleName == CXX_MODULE_NAME)
    return false;
  // Cxx cannot be imported when Library evolution is enabled
  if (getFrontendOptions().EnableLibraryEvolution)
    return false;
  // Implicit import of Cxx is disabled
  if (getLangOptions().DisableImplicitCxxModuleImport)
    return false;

  return true;
}

/// Implicitly import the SwiftOnoneSupport module in non-optimized
/// builds. This allows for use of popular specialized functions
/// from the standard library, which makes the non-optimized builds
/// execute much faster.
bool CompilerInvocation::shouldImportSwiftONoneSupport() const {
  if (getImplicitStdlibKind() != ImplicitStdlibKind::Stdlib)
    return false;
  if (getSILOptions().shouldOptimize())
    return false;
  if (LangOpts.hasFeature(Feature::Embedded))
    return false;

  // If we are not executing an action that has a dependency on
  // SwiftOnoneSupport, don't load it.
  //
  // FIXME: Knowledge of SwiftOnoneSupport loading in the Frontend is a layering
  // violation. However, SIL currently does not have a way to express this
  // dependency itself for the benefit of autolinking.  In the mean time, we
  // will be conservative and say that actions like -emit-silgen and
  // -emit-sibgen - that don't really involve the optimizer - have a
  // strict dependency on SwiftOnoneSupport.
  //
  // This optimization is disabled by -track-system-dependencies to preserve
  // the explicit dependency.
  const auto &options = getFrontendOptions();
  return options.shouldTrackSystemDependencies() ||
         FrontendOptions::doesActionGenerateSIL(options.RequestedAction);
}

void CompilerInstance::verifyImplicitConcurrencyImport() {
  if (Invocation.shouldImportSwiftConcurrency() &&
      !canImportSwiftConcurrency()) {
    Diagnostics.diagnose(SourceLoc(),
                         diag::warn_implicit_concurrency_import_failed);
  }
}

bool CompilerInstance::canImportSwiftConcurrency() const {
  ImportPath::Module::Builder builder(
      getASTContext().getIdentifier(SWIFT_CONCURRENCY_NAME));
  auto modulePath = builder.get();
  return getASTContext().testImportModule(modulePath);
}

bool CompilerInstance::canImportSwiftConcurrencyShims() const {
  ImportPath::Module::Builder builder(
      getASTContext().getIdentifier(SWIFT_CONCURRENCY_SHIMS_NAME));
  auto modulePath = builder.get();
  return getASTContext().testImportModule(modulePath);
}

void CompilerInstance::verifyImplicitStringProcessingImport() {
  if (Invocation.shouldImportSwiftStringProcessing() &&
      !canImportSwiftStringProcessing()) {
    Diagnostics.diagnose(SourceLoc(),
                         diag::warn_implicit_string_processing_import_failed);
  }
}

bool CompilerInstance::canImportSwiftStringProcessing() const {
  ImportPath::Module::Builder builder(
      getASTContext().getIdentifier(SWIFT_STRING_PROCESSING_NAME));
  auto modulePath = builder.get();
  return getASTContext().testImportModule(modulePath);
}

void CompilerInstance::verifyImplicitBacktracingImport() {
  if (Invocation.shouldImportSwiftBacktracing() &&
      !canImportSwiftBacktracing()) {
    Diagnostics.diagnose(SourceLoc(),
                         diag::warn_implicit_backtracing_import_failed);
  }
}

bool CompilerInstance::canImportSwiftBacktracing() const {
  ImportPath::Module::Builder builder(
      getASTContext().getIdentifier(SWIFT_BACKTRACING_NAME));
  auto modulePath = builder.get();
  return getASTContext().testImportModule(modulePath);
}

bool CompilerInstance::canImportCxx() const {
  ImportPath::Module::Builder builder(
      getASTContext().getIdentifier(CXX_MODULE_NAME));
  auto modulePath = builder.get();
  return getASTContext().testImportModule(modulePath);
}

bool CompilerInstance::canImportCxxShim() const {
  ImportPath::Module::Builder builder(
      getASTContext().getIdentifier(CXX_SHIM_NAME));
  auto modulePath = builder.get();
  // Currently, Swift interfaces are not to expose their
  // C++ dependencies. Which means that when scanning them we should not
  // bring in such dependencies, including CxxShims.
  return getASTContext().testImportModule(modulePath) &&
         !Invocation.getFrontendOptions()
              .InputsAndOutputs.hasModuleInterfaceOutputPath() &&
         !Invocation.getFrontendOptions()
              .DependencyScanningSubInvocation;
}

bool CompilerInstance::supportCaching() const {
  if (!Invocation.getCASOptions().EnableCaching)
    return false;

  return FrontendOptions::supportCompilationCaching(
      Invocation.getFrontendOptions().RequestedAction);
}

bool CompilerInstance::downgradeInterfaceVerificationErrors() const {
  auto &FrontendOpts = Invocation.getFrontendOptions();
  if (Context->blockListConfig.hasBlockListAction(FrontendOpts.ModuleName,
                                             BlockListKeyKind::ModuleName,
                        BlockListAction::DowngradeInterfaceVerificationFailure)) {
    Context->Diags.diagnose(SourceLoc(), diag::interface_block_listed_broken,
                            FrontendOpts.ModuleName);
    return true;
  }
  return FrontendOpts.DowngradeInterfaceVerificationError;
}

ImplicitImportInfo CompilerInstance::getImplicitImportInfo() const {
  auto &frontendOpts = Invocation.getFrontendOptions();

  ImplicitImportInfo imports;
  imports.StdlibKind = Invocation.getImplicitStdlibKind();

  auto pushImport = [&](StringRef moduleStr,
                        ImportOptions options = ImportOptions()) {
    ImportPath::Builder importPath(Context->getIdentifier(moduleStr));
    UnloadedImportedModule import(importPath.copyTo(*Context),
                                  /*isScoped=*/false);
    imports.AdditionalUnloadedImports.emplace_back(
        import, SourceLoc(), options);
  };

  for (auto &moduleStrAndTestable : frontendOpts.getImplicitImportModuleNames()) {
    pushImport(moduleStrAndTestable.first,
               moduleStrAndTestable.second ? ImportFlags::Testable
                                           : ImportOptions());
  }

  if (Invocation.shouldImportSwiftONoneSupport()) {
    pushImport(SWIFT_ONONE_SUPPORT);
  }

  // FIXME: The canImport check is required for compatibility
  // with older SDKs. Longer term solution is to have the driver make
  // the decision on the implicit import: rdar://76996377
  if (Invocation.shouldImportSwiftConcurrency()) {
    switch (imports.StdlibKind) {
    case ImplicitStdlibKind::Builtin:
    case ImplicitStdlibKind::None:
      break;

    case ImplicitStdlibKind::Stdlib:
      if (canImportSwiftConcurrency())
        pushImport(SWIFT_CONCURRENCY_NAME);
      if (canImportSwiftConcurrencyShims())
        pushImport(SWIFT_CONCURRENCY_SHIMS_NAME);
      break;
    }
  }

  if (Invocation.shouldImportSwiftStringProcessing()) {
    switch (imports.StdlibKind) {
    case ImplicitStdlibKind::Builtin:
    case ImplicitStdlibKind::None:
      break;

    case ImplicitStdlibKind::Stdlib:
      if (canImportSwiftStringProcessing())
        pushImport(SWIFT_STRING_PROCESSING_NAME);
      break;
    }
  }

  if (Invocation.shouldImportSwiftBacktracing()) {
    switch (imports.StdlibKind) {
    case ImplicitStdlibKind::Builtin:
    case ImplicitStdlibKind::None:
      break;

    case ImplicitStdlibKind::Stdlib:
      if (canImportSwiftBacktracing())
        pushImport(SWIFT_BACKTRACING_NAME);
      break;
    }
  }

  if (Invocation.getLangOptions().EnableCXXInterop) {
    if (Invocation.shouldImportCxx() && canImportCxx())
      pushImport(CXX_MODULE_NAME);
    if (canImportCxxShim())
      pushImport(CXX_SHIM_NAME, {ImportFlags::ImplementationOnly});
  }

  imports.ShouldImportUnderlyingModule = frontendOpts.ImportUnderlyingModule;
  imports.BridgingHeaderPath = frontendOpts.ImplicitObjCHeaderPath;
  return imports;
}

static std::optional<SourceFileKind>
tryMatchInputModeToSourceFileKind(FrontendOptions::ParseInputMode mode) {
  switch (mode) {
  case FrontendOptions::ParseInputMode::SwiftLibrary:
      // A Swift file in -parse-as-library mode is a library file.
    return SourceFileKind::Library;
  case FrontendOptions::ParseInputMode::SIL:
      // A Swift file in -parse-sil mode is a SIL file.
    return SourceFileKind::SIL;
  case FrontendOptions::ParseInputMode::SwiftModuleInterface:
    return SourceFileKind::Interface;
  case FrontendOptions::ParseInputMode::Swift:
    return SourceFileKind::Main;
  }
  llvm::outs() << (unsigned)mode;
  llvm_unreachable("Unhandled input parsing mode!");
}

SourceFile *
CompilerInstance::computeMainSourceFileForModule(ModuleDecl *mod) const {
  // Swift libraries cannot have a 'main'.
  const auto &FOpts = getInvocation().getFrontendOptions();
  const auto &Inputs = FOpts.InputsAndOutputs.getAllInputs();
  if (FOpts.InputMode == FrontendOptions::ParseInputMode::SwiftLibrary) {
    return nullptr;
  }

  // Try to pull out a file called 'main.swift'.
  auto MainInputIter =
      std::find_if(Inputs.begin(), Inputs.end(), [](const InputFile &input) {
        return input.getType() == file_types::TY_Swift &&
               llvm::sys::path::filename(input.getFileName()) == "main.swift";
      });

  std::optional<unsigned> MainBufferID = std::nullopt;
  if (MainInputIter != Inputs.end()) {
    MainBufferID =
        getSourceMgr().getIDForBufferIdentifier(MainInputIter->getFileName());
  } else if (InputSourceCodeBufferIDs.size() == 1) {
    // Barring that, just nominate a single Swift file as the main file.
    MainBufferID.emplace(InputSourceCodeBufferIDs.front());
  }

  if (!MainBufferID.has_value()) {
    return nullptr;
  }

  auto SFK = tryMatchInputModeToSourceFileKind(FOpts.InputMode);
  if (!SFK.has_value()) {
    return nullptr;
  }

  return createSourceFileForMainModule(mod, *SFK,
                                       *MainBufferID, /*isMainBuffer*/true);
}

bool CompilerInstance::createFilesForMainModule(
    ModuleDecl *mod, SmallVectorImpl<FileUnit *> &files) const {
  // Try to pull out the main source file, if any. This ensures that it
  // is at the start of the list of files.
  std::optional<unsigned> MainBufferID = std::nullopt;
  if (SourceFile *mainSourceFile = computeMainSourceFileForModule(mod)) {
    MainBufferID = mainSourceFile->getBufferID();
    files.push_back(mainSourceFile);
  }

  // If we have partial modules to load, do so now, bailing if any failed to
  // load.
  if (!PartialModules.empty()) {
    if (loadPartialModulesAndImplicitImports(mod, files))
      return true;
  }

  // Finally add the library files.
  // FIXME: This is the only demand point for InputSourceCodeBufferIDs. We
  // should compute this list of source files lazily.
  for (auto BufferID : InputSourceCodeBufferIDs) {
    // Skip the main buffer, we've already handled it.
    if (BufferID == MainBufferID)
      continue;

    auto *libraryFile =
        createSourceFileForMainModule(mod, SourceFileKind::Library, BufferID);
    files.push_back(libraryFile);
  }
  return false;
}

ModuleDecl *CompilerInstance::getMainModule() const {
  if (!MainModule) {
    Identifier ID = Context->getIdentifier(Invocation.getModuleName());
    MainModule = ModuleDecl::createMainModule(*Context, ID,
                                              getImplicitImportInfo());
    if (Invocation.getFrontendOptions().EnableTesting)
      MainModule->setTestingEnabled();
    if (Invocation.getFrontendOptions().EnablePrivateImports)
      MainModule->setPrivateImportsEnabled();
    if (Invocation.getFrontendOptions().EnableImplicitDynamic)
      MainModule->setImplicitDynamicEnabled();
    if (Invocation.getLangOptions().BypassResilienceChecks)
      MainModule->setBypassResilience();
    if (!Invocation.getFrontendOptions().ModuleABIName.empty()) {
      MainModule->setABIName(getASTContext().getIdentifier(
          Invocation.getFrontendOptions().ModuleABIName));
    }
    if (!Invocation.getLangOptions().PackageName.empty()) {
      auto pkgName = Invocation.getLangOptions().PackageName;
      MainModule->setPackageName(getASTContext().getIdentifier(pkgName));
    }
    if (!Invocation.getFrontendOptions().ExportAsName.empty()) {
      MainModule->setExportAsName(getASTContext().getIdentifier(
          Invocation.getFrontendOptions().ExportAsName));
    }
    if (Invocation.getFrontendOptions().EnableLibraryEvolution)
      MainModule->setResilienceStrategy(ResilienceStrategy::Resilient);
    if (Invocation.getLangOptions().isSwiftVersionAtLeast(6))
      MainModule->setIsConcurrencyChecked(true);
    if (Invocation.getLangOptions().EnableCXXInterop &&
        Invocation.getLangOptions().RequireCxxInteropToImportCxxInteropModule)
      MainModule->setHasCxxInteroperability();
    if (Invocation.getLangOptions().AllowNonResilientAccess)
      MainModule->setAllowNonResilientAccess();
    if (Invocation.getSILOptions().EnableSerializePackage)
      MainModule->setSerializePackageEnabled();

    // Register the main module with the AST context.
    Context->addLoadedModule(MainModule);
    Context->MainModule = MainModule;

    // Create and add the module's files.
    SmallVector<FileUnit *, 16> files;
    if (!createFilesForMainModule(MainModule, files)) {
      for (auto *file : files)
        MainModule->addFile(*file);
    } else {
      // If we failed to load a partial module, mark the main module as having
      // "failed to load", as it will contain no files. Note that we don't try
      // to add any of the successfully loaded partial modules. This ensures
      // that we don't encounter cases where we try to resolve a cross-reference
      // into a partial module that failed to load.
      MainModule->setFailedToLoad();
    }
  }
  return MainModule;
}

void CompilerInstance::setMainModule(ModuleDecl *newMod) {
  assert(newMod->isMainModule());
  MainModule = newMod;
  Context->addLoadedModule(newMod);
  Context->MainModule = newMod;
}

bool CompilerInstance::performParseAndResolveImportsOnly() {
  FrontendStatsTracer tracer(getStatsReporter(), "parse-and-resolve-imports");

  auto *mainModule = getMainModule();

  // Load access notes.
  if (!Invocation.getFrontendOptions().AccessNotesPath.empty()) {
    auto accessNotesPath = Invocation.getFrontendOptions().AccessNotesPath;

    auto bufferOrError =
        swift::vfs::getFileOrSTDIN(getFileSystem(), accessNotesPath);
    if (bufferOrError) {
      int sourceID =
          SourceMgr.addNewSourceBuffer(std::move(bufferOrError.get()));
      auto buffer =
          SourceMgr.getLLVMSourceMgr().getMemoryBuffer(sourceID);

      if (auto accessNotesFile = AccessNotesFile::load(*Context, buffer))
        mainModule->getAccessNotes() = *accessNotesFile;
    }
    else {
      Diagnostics.diagnose(SourceLoc(), diag::access_notes_file_io_error,
                           accessNotesPath, bufferOrError.getError().message());
    }
  }

  // Resolve imports for all the source files.
  for (auto *file : mainModule->getFiles()) {
    if (auto *SF = dyn_cast<SourceFile>(file))
      performImportResolution(*SF);
  }

  assert(llvm::all_of(mainModule->getFiles(), [](const FileUnit *File) -> bool {
    auto *SF = dyn_cast<SourceFile>(File);
    if (!SF)
      return true;
    return SF->ASTStage >= SourceFile::ImportsResolved;
  }) && "some files have not yet had their imports resolved");
  mainModule->setHasResolvedImports();

  bindExtensions(*mainModule);
  return Context->hadError();
}

void CompilerInstance::performSema() {
  performParseAndResolveImportsOnly();

  FrontendStatsTracer tracer(getStatsReporter(), "perform-sema");

  forEachFileToTypeCheck([&](SourceFile &SF) {
    performTypeChecking(SF);
    return false;
  });

  finishTypeChecking();
}

bool CompilerInstance::loadStdlibIfNeeded() {
  if (!FrontendOptions::doesActionRequireSwiftStandardLibrary(
          Invocation.getFrontendOptions().RequestedAction)) {
    return false;
  }
  // If we aren't expecting an implicit stdlib import, there's nothing to do.
  if (getImplicitImportInfo().StdlibKind != ImplicitStdlibKind::Stdlib)
    return false;

  FrontendStatsTracer tracer(getStatsReporter(), "load-stdlib");
  ModuleDecl *M = Context->getStdlibModule(/*loadIfAbsent*/ true);

  if (!M) {
    Diagnostics.diagnose(SourceLoc(), diag::error_stdlib_not_found,
                         Invocation.getTargetTriple());
    return true;
  }

  verifyImplicitConcurrencyImport();
  verifyImplicitStringProcessingImport();

  // If we failed to load, we should have already diagnosed.
  if (M->failedToLoad()) {
    assert(Diagnostics.hadAnyError() &&
           "stdlib module failed to load but nothing was diagnosed?");
    return true;
  }
  return false;
}

bool CompilerInstance::loadPartialModulesAndImplicitImports(
    ModuleDecl *mod, SmallVectorImpl<FileUnit *> &partialModules) const {
  assert(DefaultSerializedLoader && "Expected module loader in Compiler Instance");
  FrontendStatsTracer tracer(getStatsReporter(),
                             "load-partial-modules-and-implicit-imports");
  // Force loading implicit imports. This is currently needed to allow
  // deserialization to resolve cross references into bridging headers.
  // FIXME: Once deserialization loads all the modules it needs for cross
  // references, this can be removed.
  (void)mod->getImplicitImports();

  // Load in the partial modules.
  bool hadLoadError = false;
  for (auto &PM : PartialModules) {
    assert(PM.ModuleBuffer);
    auto *file = DefaultSerializedLoader->loadAST(
        *mod, /*diagLoc=*/SourceLoc(), /*moduleInterfacePath*/ "",
        /*moduleInterfaceSourcePath=*/"", std::move(PM.ModuleBuffer),
        std::move(PM.ModuleDocBuffer), std::move(PM.ModuleSourceInfoBuffer),
        /*isFramework*/ false);
    if (file) {
      partialModules.push_back(file);
    } else {
      hadLoadError = true;
    }
  }
  return hadLoadError;
}

bool CompilerInstance::forEachFileToTypeCheck(
    llvm::function_ref<bool(SourceFile &)> fn) {
  if (isWholeModuleCompilation()) {
    for (auto fileName : getMainModule()->getFiles()) {
      auto *SF = dyn_cast<SourceFile>(fileName);
      if (!SF) {
        continue;
      }
      if (fn(*SF))
        return true;
    }
  } else {
    for (auto *SF : getPrimarySourceFiles()) {
      if (fn(*SF))
        return true;
    }
  }
  return false;
}

bool CompilerInstance::forEachSourceFile(
    llvm::function_ref<bool(SourceFile &)> fn) {
  for (auto fileName : getMainModule()->getFiles()) {
    auto *SF = dyn_cast<SourceFile>(fileName);
    if (!SF) {
      continue;
    }
    if (fn(*SF))
      return true;
    ;
  }

  return false;
}

void CompilerInstance::finishTypeChecking() {
  forEachFileToTypeCheck([](SourceFile &SF) {
    performWholeModuleTypeChecking(SF);
    return false;
  });

  forEachSourceFile([](SourceFile &SF) {
    loadDerivativeConfigurations(SF);
    return false;
  });
}

SourceFile::ParsingOptions
CompilerInstance::getSourceFileParsingOptions(bool forPrimary) const {
  using ActionType = FrontendOptions::ActionType;
  using ParsingFlags = SourceFile::ParsingFlags;

  const auto &frontendOpts = Invocation.getFrontendOptions();
  const auto action = frontendOpts.RequestedAction;

  auto opts = SourceFile::getDefaultParsingOptions(getASTContext().LangOpts);
  if (FrontendOptions::shouldActionOnlyParse(action)) {
    // Generally in a parse-only invocation, we want to disable #if evaluation.
    // However, there are a couple of modes where we need to know which clauses
    // are active.
    if (action != ActionType::EmitImportedModules &&
        action != ActionType::ScanDependencies) {
      opts |= ParsingFlags::DisablePoundIfEvaluation;
    }

    // If we need to dump the parse tree, disable delayed bodies as we want to
    // show everything.
    if (action == ActionType::DumpParse)
      opts |= ParsingFlags::DisableDelayedBodies;
  }

  const auto &typeOpts = getASTContext().TypeCheckerOpts;
  const auto isEffectivelyPrimary = forPrimary || isWholeModuleCompilation();
  if (isEffectivelyPrimary) {
    // Disable delayed body parsing for primaries and in WMO, unless
    // forcefully skipping function bodies
    if (typeOpts.SkipFunctionBodies == FunctionBodySkipping::None)
      opts |= ParsingFlags::DisableDelayedBodies;
  } else {
    // Suppress parse warnings for non-primaries, as they'll get parsed multiple
    // times.
    opts |= ParsingFlags::SuppressWarnings;
  }

  // Turn off new parser round-trip and diagnostics checking for
  //   - secondary files
  //     - Only want to verify on primary files, no point checking more than
  //       once
  //   - IDE inspection
  //     - We don't want to pay the cost of verification for simple IDE
  //       functionality (eg. completion and cursor info)
  //   - dependency scanning
  //     - Same as IDE inspection, this is meant to be a very fast operation.
  //       Don't slow it down
  //   - skipped function bodies
  //     - Swift parser doesn't support function body skipping yet, so this
  //       would result in verification failures when bodies have errors
  if (!isEffectivelyPrimary || SourceMgr.hasIDEInspectionTargetBuffer() ||
      frontendOpts.RequestedAction == ActionType::ScanDependencies ||
      typeOpts.SkipFunctionBodies != FunctionBodySkipping::None) {
    opts -= ParsingFlags::RoundTrip;
    opts -= ParsingFlags::ValidateNewParserDiagnostics;
  }

  // Enable interface hash computation for primaries or emit-module-separately,
  // but not in WMO, as it's only currently needed for incremental mode.
  if (forPrimary ||
      typeOpts.SkipFunctionBodies ==
          FunctionBodySkipping::NonInlinableWithoutTypes ||
      frontendOpts.ReuseFrontendForMultipleCompilations) {
    opts |= ParsingFlags::EnableInterfaceHash;
  }
  const auto &LangOpts = Invocation.getLangOptions();
  if (action == ActionType::Immediate &&
      LangOpts.hasFeature(Feature::LazyImmediate)) {
    opts -= ParsingFlags::DisableDelayedBodies;
    opts -= ParsingFlags::ValidateNewParserDiagnostics;
  }
  return opts;
}

SourceFile *CompilerInstance::createSourceFileForMainModule(
    ModuleDecl *mod, SourceFileKind fileKind, std::optional<unsigned> bufferID,
    bool isMainBuffer) const {
  auto isPrimary = bufferID && isPrimaryInput(*bufferID);
  auto opts = getSourceFileParsingOptions(isPrimary);

  auto *inputFile = new (*Context)
      SourceFile(*mod, fileKind, bufferID, opts, isPrimary);

  return inputFile;
}

void CompilerInstance::freeASTContext() {
  TheSILTypes.reset();
  Context.reset();
  MainModule = nullptr;
  DefaultSerializedLoader = nullptr;
  MemoryBufferLoader = nullptr;
  PrimaryBufferIDs.clear();
}

/// Perform "stable" optimizations that are invariant across compiler versions.
static bool performMandatorySILPasses(CompilerInvocation &Invocation,
                                      SILModule *SM) {
  // Don't run diagnostic passes at all when merging modules.
  if (Invocation.getFrontendOptions().RequestedAction ==
      FrontendOptions::ActionType::MergeModules) {
    return false;
  }
  if (Invocation.getDiagnosticOptions().SkipDiagnosticPasses) {
    // Even if we are not supposed to run the diagnostic passes, we still need
    // to run the ownership evaluator.
    return runSILOwnershipEliminatorPass(*SM);
  }
  return runSILDiagnosticPasses(*SM);
}

/// Perform SIL optimization passes if optimizations haven't been disabled.
/// These may change across compiler versions.
static void performSILOptimizations(CompilerInvocation &Invocation,
                                    SILModule *SM) {
  FrontendStatsTracer tracer(SM->getASTContext().Stats,
                             "SIL optimization");
  if (Invocation.getFrontendOptions().RequestedAction ==
      FrontendOptions::ActionType::MergeModules ||
      !Invocation.getSILOptions().shouldOptimize()) {
    runSILPassesForOnone(*SM);
    return;
  }
  StringRef CustomPipelinePath =
  Invocation.getSILOptions().ExternalPassPipelineFilename;
  if (!CustomPipelinePath.empty()) {
    runSILOptimizationPassesWithFileSpecification(*SM, CustomPipelinePath);
  } else {
    runSILOptimizationPasses(*SM);
  }
  // When building SwiftOnoneSupport.o verify all expected ABI symbols.
  if (Invocation.getFrontendOptions().CheckOnoneSupportCompleteness
       // TODO: handle non-ObjC based stdlib builds, e.g. on linux.
      && Invocation.getLangOptions().EnableObjCInterop
      && Invocation.getFrontendOptions().RequestedAction
             == FrontendOptions::ActionType::EmitObject) {
    checkCompletenessOfPrespecializations(*SM);
  }
}

static void countStatsPostSILOpt(UnifiedStatsReporter &Stats,
                                 const SILModule& Module) {
  auto &C = Stats.getFrontendCounters();
  // FIXME: calculate these in constant time, via the dense maps.
  C.NumSILOptFunctions += Module.getFunctionList().size();
  C.NumSILOptVtables += Module.getVTables().size();
  C.NumSILOptWitnessTables += Module.getWitnessTableList().size();
  C.NumSILOptDefaultWitnessTables += Module.getDefaultWitnessTableList().size();
  C.NumSILOptGlobalVariables += Module.getSILGlobalList().size();
}

bool CompilerInstance::performSILProcessing(SILModule *silModule) {
  if (performMandatorySILPasses(Invocation, silModule) &&
      !Invocation.getFrontendOptions().AllowModuleWithCompilerErrors)
    return true;

  {
    FrontendStatsTracer tracer(silModule->getASTContext().Stats,
                               "SIL verification, pre-optimization");
    silModule->verify();
  }

  performSILOptimizations(Invocation, silModule);

  if (auto *stats = getStatsReporter())
    countStatsPostSILOpt(*stats, *silModule);

  {
    FrontendStatsTracer tracer(silModule->getASTContext().Stats,
                               "SIL verification, post-optimization");
    silModule->verify();
  }

  performSILInstCountIfNeeded(silModule);
  return false;
}

bool CompilerInstance::isCancellationRequested() const {
  auto flag = getASTContext().CancellationFlag;
  return flag && flag->load(std::memory_order_relaxed);
}

const PrimarySpecificPaths &
CompilerInstance::getPrimarySpecificPathsForWholeModuleOptimizationMode()
    const {
  return getPrimarySpecificPathsForAtMostOnePrimary();
}
const PrimarySpecificPaths &
CompilerInstance::getPrimarySpecificPathsForAtMostOnePrimary() const {
  return Invocation.getPrimarySpecificPathsForAtMostOnePrimary();
}
const PrimarySpecificPaths &
CompilerInstance::getPrimarySpecificPathsForPrimary(StringRef filename) const {
  return Invocation.getPrimarySpecificPathsForPrimary(filename);
}
const PrimarySpecificPaths &
CompilerInstance::getPrimarySpecificPathsForSourceFile(
    const SourceFile &SF) const {
  return Invocation.getPrimarySpecificPathsForSourceFile(SF);
}