xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision ac664697c54cf2ffa9ebef0215f734bcca3b718f)
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Frontend/CompilerInstance.h"
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/DiagnosticOptions.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangStandard.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/Stack.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/Version.h"
22 #include "clang/Config/config.h"
23 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
24 #include "clang/Frontend/FrontendAction.h"
25 #include "clang/Frontend/FrontendActions.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Frontend/FrontendPluginRegistry.h"
28 #include "clang/Frontend/LogDiagnosticPrinter.h"
29 #include "clang/Frontend/SARIFDiagnosticPrinter.h"
30 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
31 #include "clang/Frontend/TextDiagnosticPrinter.h"
32 #include "clang/Frontend/Utils.h"
33 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Lex/PreprocessorOptions.h"
37 #include "clang/Sema/CodeCompleteConsumer.h"
38 #include "clang/Sema/Sema.h"
39 #include "clang/Serialization/ASTReader.h"
40 #include "clang/Serialization/GlobalModuleIndex.h"
41 #include "clang/Serialization/InMemoryModuleCache.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/ScopeExit.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Config/llvm-config.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CrashRecoveryContext.h"
48 #include "llvm/Support/Errc.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/LockFileManager.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/Signals.h"
55 #include "llvm/Support/TimeProfiler.h"
56 #include "llvm/Support/Timer.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/TargetParser/Host.h"
59 #include <optional>
60 #include <time.h>
61 #include <utility>
62 
63 using namespace clang;
64 
65 CompilerInstance::CompilerInstance(
66     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
67     InMemoryModuleCache *SharedModuleCache)
68     : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
69       Invocation(new CompilerInvocation()),
70       ModuleCache(SharedModuleCache ? SharedModuleCache
71                                     : new InMemoryModuleCache),
72       ThePCHContainerOperations(std::move(PCHContainerOps)) {}
73 
74 CompilerInstance::~CompilerInstance() {
75   assert(OutputFiles.empty() && "Still output files in flight?");
76 }
77 
78 void CompilerInstance::setInvocation(
79     std::shared_ptr<CompilerInvocation> Value) {
80   Invocation = std::move(Value);
81 }
82 
83 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
84   return (BuildGlobalModuleIndex ||
85           (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
86            getFrontendOpts().GenerateGlobalModuleIndex)) &&
87          !DisableGeneratingGlobalModuleIndex;
88 }
89 
90 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
91   Diagnostics = Value;
92 }
93 
94 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
95   OwnedVerboseOutputStream.reset();
96   VerboseOutputStream = &Value;
97 }
98 
99 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
100   OwnedVerboseOutputStream.swap(Value);
101   VerboseOutputStream = OwnedVerboseOutputStream.get();
102 }
103 
104 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
105 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
106 
107 bool CompilerInstance::createTarget() {
108   // Create the target instance.
109   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
110                                          getInvocation().TargetOpts));
111   if (!hasTarget())
112     return false;
113 
114   // Check whether AuxTarget exists, if not, then create TargetInfo for the
115   // other side of CUDA/OpenMP/SYCL compilation.
116   if (!getAuxTarget() &&
117       (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
118        getLangOpts().SYCLIsDevice) &&
119       !getFrontendOpts().AuxTriple.empty()) {
120     auto TO = std::make_shared<TargetOptions>();
121     TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
122     if (getFrontendOpts().AuxTargetCPU)
123       TO->CPU = *getFrontendOpts().AuxTargetCPU;
124     if (getFrontendOpts().AuxTargetFeatures)
125       TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
126     TO->HostTriple = getTarget().getTriple().str();
127     setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
128   }
129 
130   if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
131     if (getLangOpts().RoundingMath) {
132       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
133       getLangOpts().RoundingMath = false;
134     }
135     auto FPExc = getLangOpts().getFPExceptionMode();
136     if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
137       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
138       getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
139     }
140     // FIXME: can we disable FEnvAccess?
141   }
142 
143   // We should do it here because target knows nothing about
144   // language options when it's being created.
145   if (getLangOpts().OpenCL &&
146       !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
147     return false;
148 
149   // Inform the target of the language options.
150   // FIXME: We shouldn't need to do this, the target should be immutable once
151   // created. This complexity should be lifted elsewhere.
152   getTarget().adjust(getDiagnostics(), getLangOpts());
153 
154   if (auto *Aux = getAuxTarget())
155     getTarget().setAuxTarget(Aux);
156 
157   return true;
158 }
159 
160 llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
161   return getFileManager().getVirtualFileSystem();
162 }
163 
164 void CompilerInstance::setFileManager(FileManager *Value) {
165   FileMgr = Value;
166 }
167 
168 void CompilerInstance::setSourceManager(SourceManager *Value) {
169   SourceMgr = Value;
170 }
171 
172 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
173   PP = std::move(Value);
174 }
175 
176 void CompilerInstance::setASTContext(ASTContext *Value) {
177   Context = Value;
178 
179   if (Context && Consumer)
180     getASTConsumer().Initialize(getASTContext());
181 }
182 
183 void CompilerInstance::setSema(Sema *S) {
184   TheSema.reset(S);
185 }
186 
187 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
188   Consumer = std::move(Value);
189 
190   if (Context && Consumer)
191     getASTConsumer().Initialize(getASTContext());
192 }
193 
194 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
195   CompletionConsumer.reset(Value);
196 }
197 
198 std::unique_ptr<Sema> CompilerInstance::takeSema() {
199   return std::move(TheSema);
200 }
201 
202 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
203   return TheASTReader;
204 }
205 void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
206   assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
207          "Expected ASTReader to use the same PCM cache");
208   TheASTReader = std::move(Reader);
209 }
210 
211 std::shared_ptr<ModuleDependencyCollector>
212 CompilerInstance::getModuleDepCollector() const {
213   return ModuleDepCollector;
214 }
215 
216 void CompilerInstance::setModuleDepCollector(
217     std::shared_ptr<ModuleDependencyCollector> Collector) {
218   ModuleDepCollector = std::move(Collector);
219 }
220 
221 static void collectHeaderMaps(const HeaderSearch &HS,
222                               std::shared_ptr<ModuleDependencyCollector> MDC) {
223   SmallVector<std::string, 4> HeaderMapFileNames;
224   HS.getHeaderMapFileNames(HeaderMapFileNames);
225   for (auto &Name : HeaderMapFileNames)
226     MDC->addFile(Name);
227 }
228 
229 static void collectIncludePCH(CompilerInstance &CI,
230                               std::shared_ptr<ModuleDependencyCollector> MDC) {
231   const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
232   if (PPOpts.ImplicitPCHInclude.empty())
233     return;
234 
235   StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
236   FileManager &FileMgr = CI.getFileManager();
237   auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
238   if (!PCHDir) {
239     MDC->addFile(PCHInclude);
240     return;
241   }
242 
243   std::error_code EC;
244   SmallString<128> DirNative;
245   llvm::sys::path::native(PCHDir->getName(), DirNative);
246   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
247   SimpleASTReaderListener Validator(CI.getPreprocessor());
248   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
249        Dir != DirEnd && !EC; Dir.increment(EC)) {
250     // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
251     // used here since we're not interested in validating the PCH at this time,
252     // but only to check whether this is a file containing an AST.
253     if (!ASTReader::readASTFileControlBlock(
254             Dir->path(), FileMgr, CI.getModuleCache(),
255             CI.getPCHContainerReader(),
256             /*FindModuleFileExtensions=*/false, Validator,
257             /*ValidateDiagnosticOptions=*/false))
258       MDC->addFile(Dir->path());
259   }
260 }
261 
262 static void collectVFSEntries(CompilerInstance &CI,
263                               std::shared_ptr<ModuleDependencyCollector> MDC) {
264   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
265     return;
266 
267   // Collect all VFS found.
268   SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
269   for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
270     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
271         llvm::MemoryBuffer::getFile(VFSFile);
272     if (!Buffer)
273       return;
274     llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
275                                   /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
276   }
277 
278   for (auto &E : VFSEntries)
279     MDC->addFile(E.VPath, E.RPath);
280 }
281 
282 // Diagnostics
283 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
284                                const CodeGenOptions *CodeGenOpts,
285                                DiagnosticsEngine &Diags) {
286   std::error_code EC;
287   std::unique_ptr<raw_ostream> StreamOwner;
288   raw_ostream *OS = &llvm::errs();
289   if (DiagOpts->DiagnosticLogFile != "-") {
290     // Create the output stream.
291     auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
292         DiagOpts->DiagnosticLogFile, EC,
293         llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
294     if (EC) {
295       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
296           << DiagOpts->DiagnosticLogFile << EC.message();
297     } else {
298       FileOS->SetUnbuffered();
299       OS = FileOS.get();
300       StreamOwner = std::move(FileOS);
301     }
302   }
303 
304   // Chain in the diagnostic client which will log the diagnostics.
305   auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
306                                                         std::move(StreamOwner));
307   if (CodeGenOpts)
308     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
309   if (Diags.ownsClient()) {
310     Diags.setClient(
311         new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
312   } else {
313     Diags.setClient(
314         new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
315   }
316 }
317 
318 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
319                                        DiagnosticsEngine &Diags,
320                                        StringRef OutputFile) {
321   auto SerializedConsumer =
322       clang::serialized_diags::create(OutputFile, DiagOpts);
323 
324   if (Diags.ownsClient()) {
325     Diags.setClient(new ChainedDiagnosticConsumer(
326         Diags.takeClient(), std::move(SerializedConsumer)));
327   } else {
328     Diags.setClient(new ChainedDiagnosticConsumer(
329         Diags.getClient(), std::move(SerializedConsumer)));
330   }
331 }
332 
333 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
334                                          bool ShouldOwnClient) {
335   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
336                                   ShouldOwnClient, &getCodeGenOpts());
337 }
338 
339 IntrusiveRefCntPtr<DiagnosticsEngine>
340 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
341                                     DiagnosticConsumer *Client,
342                                     bool ShouldOwnClient,
343                                     const CodeGenOptions *CodeGenOpts) {
344   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
345   IntrusiveRefCntPtr<DiagnosticsEngine>
346       Diags(new DiagnosticsEngine(DiagID, Opts));
347 
348   // Create the diagnostic client for reporting errors or for
349   // implementing -verify.
350   if (Client) {
351     Diags->setClient(Client, ShouldOwnClient);
352   } else if (Opts->getFormat() == DiagnosticOptions::SARIF) {
353     Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
354   } else
355     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
356 
357   // Chain in -verify checker, if requested.
358   if (Opts->VerifyDiagnostics)
359     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
360 
361   // Chain in -diagnostic-log-file dumper, if requested.
362   if (!Opts->DiagnosticLogFile.empty())
363     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
364 
365   if (!Opts->DiagnosticSerializationFile.empty())
366     SetupSerializedDiagnostics(Opts, *Diags,
367                                Opts->DiagnosticSerializationFile);
368 
369   // Configure our handling of diagnostics.
370   ProcessWarningOptions(*Diags, *Opts);
371 
372   return Diags;
373 }
374 
375 // File Manager
376 
377 FileManager *CompilerInstance::createFileManager(
378     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
379   if (!VFS)
380     VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
381                   : createVFSFromCompilerInvocation(getInvocation(),
382                                                     getDiagnostics());
383   assert(VFS && "FileManager has no VFS?");
384   if (getFrontendOpts().ShowStats)
385     VFS =
386         llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
387   FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
388   return FileMgr.get();
389 }
390 
391 // Source Manager
392 
393 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
394   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
395 }
396 
397 // Initialize the remapping of files to alternative contents, e.g.,
398 // those specified through other files.
399 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
400                                     SourceManager &SourceMgr,
401                                     FileManager &FileMgr,
402                                     const PreprocessorOptions &InitOpts) {
403   // Remap files in the source manager (with buffers).
404   for (const auto &RB : InitOpts.RemappedFileBuffers) {
405     // Create the file entry for the file that we're mapping from.
406     FileEntryRef FromFile =
407         FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
408 
409     // Override the contents of the "from" file with the contents of the
410     // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
411     // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
412     // to the SourceManager.
413     if (InitOpts.RetainRemappedFileBuffers)
414       SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
415     else
416       SourceMgr.overrideFileContents(
417           FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
418   }
419 
420   // Remap files in the source manager (with other files).
421   for (const auto &RF : InitOpts.RemappedFiles) {
422     // Find the file that we're mapping to.
423     OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
424     if (!ToFile) {
425       Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
426       continue;
427     }
428 
429     // Create the file entry for the file that we're mapping from.
430     const FileEntry *FromFile =
431         FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
432     if (!FromFile) {
433       Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
434       continue;
435     }
436 
437     // Override the contents of the "from" file with the contents of
438     // the "to" file.
439     SourceMgr.overrideFileContents(FromFile, *ToFile);
440   }
441 
442   SourceMgr.setOverridenFilesKeepOriginalName(
443       InitOpts.RemappedFilesKeepOriginalName);
444 }
445 
446 // Preprocessor
447 
448 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
449   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
450 
451   // The AST reader holds a reference to the old preprocessor (if any).
452   TheASTReader.reset();
453 
454   // Create the Preprocessor.
455   HeaderSearch *HeaderInfo =
456       new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
457                        getDiagnostics(), getLangOpts(), &getTarget());
458   PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
459                                       getDiagnostics(), getLangOpts(),
460                                       getSourceManager(), *HeaderInfo, *this,
461                                       /*IdentifierInfoLookup=*/nullptr,
462                                       /*OwnsHeaderSearch=*/true, TUKind);
463   getTarget().adjust(getDiagnostics(), getLangOpts());
464   PP->Initialize(getTarget(), getAuxTarget());
465 
466   if (PPOpts.DetailedRecord)
467     PP->createPreprocessingRecord();
468 
469   // Apply remappings to the source manager.
470   InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
471                           PP->getFileManager(), PPOpts);
472 
473   // Predefine macros and configure the preprocessor.
474   InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
475                          getFrontendOpts(), getCodeGenOpts());
476 
477   // Initialize the header search object.  In CUDA compilations, we use the aux
478   // triple (the host triple) to initialize our header search, since we need to
479   // find the host headers in order to compile the CUDA code.
480   const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
481   if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
482       PP->getAuxTargetInfo())
483     HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
484 
485   ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
486                            PP->getLangOpts(), *HeaderSearchTriple);
487 
488   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
489 
490   if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
491     std::string ModuleHash = getInvocation().getModuleHash();
492     PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
493     PP->getHeaderSearchInfo().setModuleCachePath(
494         getSpecificModuleCachePath(ModuleHash));
495   }
496 
497   // Handle generating dependencies, if requested.
498   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
499   if (!DepOpts.OutputFile.empty())
500     addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
501   if (!DepOpts.DOTOutputFile.empty())
502     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
503                              getHeaderSearchOpts().Sysroot);
504 
505   // If we don't have a collector, but we are collecting module dependencies,
506   // then we're the top level compiler instance and need to create one.
507   if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
508     ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
509         DepOpts.ModuleDependencyOutputDir);
510   }
511 
512   // If there is a module dep collector, register with other dep collectors
513   // and also (a) collect header maps and (b) TODO: input vfs overlay files.
514   if (ModuleDepCollector) {
515     addDependencyCollector(ModuleDepCollector);
516     collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
517     collectIncludePCH(*this, ModuleDepCollector);
518     collectVFSEntries(*this, ModuleDepCollector);
519   }
520 
521   for (auto &Listener : DependencyCollectors)
522     Listener->attachToPreprocessor(*PP);
523 
524   // Handle generating header include information, if requested.
525   if (DepOpts.ShowHeaderIncludes)
526     AttachHeaderIncludeGen(*PP, DepOpts);
527   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
528     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
529     if (OutputPath == "-")
530       OutputPath = "";
531     AttachHeaderIncludeGen(*PP, DepOpts,
532                            /*ShowAllHeaders=*/true, OutputPath,
533                            /*ShowDepth=*/false);
534   }
535 
536   if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
537     AttachHeaderIncludeGen(*PP, DepOpts,
538                            /*ShowAllHeaders=*/true, /*OutputPath=*/"",
539                            /*ShowDepth=*/true, /*MSStyle=*/true);
540   }
541 }
542 
543 std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
544   // Set up the module path, including the hash for the module-creation options.
545   SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
546   if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
547     llvm::sys::path::append(SpecificModuleCache, ModuleHash);
548   return std::string(SpecificModuleCache);
549 }
550 
551 // ASTContext
552 
553 void CompilerInstance::createASTContext() {
554   Preprocessor &PP = getPreprocessor();
555   auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
556                                  PP.getIdentifierTable(), PP.getSelectorTable(),
557                                  PP.getBuiltinInfo(), PP.TUKind);
558   Context->InitBuiltinTypes(getTarget(), getAuxTarget());
559   setASTContext(Context);
560 }
561 
562 // ExternalASTSource
563 
564 namespace {
565 // Helper to recursively read the module names for all modules we're adding.
566 // We mark these as known and redirect any attempt to load that module to
567 // the files we were handed.
568 struct ReadModuleNames : ASTReaderListener {
569   Preprocessor &PP;
570   llvm::SmallVector<std::string, 8> LoadedModules;
571 
572   ReadModuleNames(Preprocessor &PP) : PP(PP) {}
573 
574   void ReadModuleName(StringRef ModuleName) override {
575     // Keep the module name as a string for now. It's not safe to create a new
576     // IdentifierInfo from an ASTReader callback.
577     LoadedModules.push_back(ModuleName.str());
578   }
579 
580   void registerAll() {
581     ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
582     for (const std::string &LoadedModule : LoadedModules)
583       MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
584                          MM.findModule(LoadedModule));
585     LoadedModules.clear();
586   }
587 
588   void markAllUnavailable() {
589     for (const std::string &LoadedModule : LoadedModules) {
590       if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
591               LoadedModule)) {
592         M->HasIncompatibleModuleFile = true;
593 
594         // Mark module as available if the only reason it was unavailable
595         // was missing headers.
596         SmallVector<Module *, 2> Stack;
597         Stack.push_back(M);
598         while (!Stack.empty()) {
599           Module *Current = Stack.pop_back_val();
600           if (Current->IsUnimportable) continue;
601           Current->IsAvailable = true;
602           auto SubmodulesRange = Current->submodules();
603           Stack.insert(Stack.end(), SubmodulesRange.begin(),
604                        SubmodulesRange.end());
605         }
606       }
607     }
608     LoadedModules.clear();
609   }
610 };
611 } // namespace
612 
613 void CompilerInstance::createPCHExternalASTSource(
614     StringRef Path, DisableValidationForModuleKind DisableValidation,
615     bool AllowPCHWithCompilerErrors, void *DeserializationListener,
616     bool OwnDeserializationListener) {
617   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
618   TheASTReader = createPCHExternalASTSource(
619       Path, getHeaderSearchOpts().Sysroot, DisableValidation,
620       AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
621       getASTContext(), getPCHContainerReader(),
622       getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
623       DeserializationListener, OwnDeserializationListener, Preamble,
624       getFrontendOpts().UseGlobalModuleIndex);
625 }
626 
627 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
628     StringRef Path, StringRef Sysroot,
629     DisableValidationForModuleKind DisableValidation,
630     bool AllowPCHWithCompilerErrors, Preprocessor &PP,
631     InMemoryModuleCache &ModuleCache, ASTContext &Context,
632     const PCHContainerReader &PCHContainerRdr,
633     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
634     ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
635     void *DeserializationListener, bool OwnDeserializationListener,
636     bool Preamble, bool UseGlobalModuleIndex) {
637   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
638 
639   IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
640       PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
641       Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
642       AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
643       HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
644       UseGlobalModuleIndex));
645 
646   // We need the external source to be set up before we read the AST, because
647   // eagerly-deserialized declarations may use it.
648   Context.setExternalSource(Reader.get());
649 
650   Reader->setDeserializationListener(
651       static_cast<ASTDeserializationListener *>(DeserializationListener),
652       /*TakeOwnership=*/OwnDeserializationListener);
653 
654   for (auto &Listener : DependencyCollectors)
655     Listener->attachToASTReader(*Reader);
656 
657   auto Listener = std::make_unique<ReadModuleNames>(PP);
658   auto &ListenerRef = *Listener;
659   ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
660                                                    std::move(Listener));
661 
662   switch (Reader->ReadAST(Path,
663                           Preamble ? serialization::MK_Preamble
664                                    : serialization::MK_PCH,
665                           SourceLocation(),
666                           ASTReader::ARR_None)) {
667   case ASTReader::Success:
668     // Set the predefines buffer as suggested by the PCH reader. Typically, the
669     // predefines buffer will be empty.
670     PP.setPredefines(Reader->getSuggestedPredefines());
671     ListenerRef.registerAll();
672     return Reader;
673 
674   case ASTReader::Failure:
675     // Unrecoverable failure: don't even try to process the input file.
676     break;
677 
678   case ASTReader::Missing:
679   case ASTReader::OutOfDate:
680   case ASTReader::VersionMismatch:
681   case ASTReader::ConfigurationMismatch:
682   case ASTReader::HadErrors:
683     // No suitable PCH file could be found. Return an error.
684     break;
685   }
686 
687   ListenerRef.markAllUnavailable();
688   Context.setExternalSource(nullptr);
689   return nullptr;
690 }
691 
692 // Code Completion
693 
694 static bool EnableCodeCompletion(Preprocessor &PP,
695                                  StringRef Filename,
696                                  unsigned Line,
697                                  unsigned Column) {
698   // Tell the source manager to chop off the given file at a specific
699   // line and column.
700   auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
701   if (!Entry) {
702     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
703       << Filename;
704     return true;
705   }
706 
707   // Truncate the named file at the given line/column.
708   PP.SetCodeCompletionPoint(*Entry, Line, Column);
709   return false;
710 }
711 
712 void CompilerInstance::createCodeCompletionConsumer() {
713   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
714   if (!CompletionConsumer) {
715     setCodeCompletionConsumer(createCodeCompletionConsumer(
716         getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
717         getFrontendOpts().CodeCompleteOpts, llvm::outs()));
718     return;
719   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
720                                   Loc.Line, Loc.Column)) {
721     setCodeCompletionConsumer(nullptr);
722     return;
723   }
724 }
725 
726 void CompilerInstance::createFrontendTimer() {
727   FrontendTimerGroup.reset(
728       new llvm::TimerGroup("frontend", "Clang front-end time report"));
729   FrontendTimer.reset(
730       new llvm::Timer("frontend", "Clang front-end timer",
731                       *FrontendTimerGroup));
732 }
733 
734 CodeCompleteConsumer *
735 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
736                                                StringRef Filename,
737                                                unsigned Line,
738                                                unsigned Column,
739                                                const CodeCompleteOptions &Opts,
740                                                raw_ostream &OS) {
741   if (EnableCodeCompletion(PP, Filename, Line, Column))
742     return nullptr;
743 
744   // Set up the creation routine for code-completion.
745   return new PrintingCodeCompleteConsumer(Opts, OS);
746 }
747 
748 void CompilerInstance::createSema(TranslationUnitKind TUKind,
749                                   CodeCompleteConsumer *CompletionConsumer) {
750   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
751                          TUKind, CompletionConsumer));
752 
753   // Set up API notes.
754   TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
755 
756   // Attach the external sema source if there is any.
757   if (ExternalSemaSrc) {
758     TheSema->addExternalSource(ExternalSemaSrc.get());
759     ExternalSemaSrc->InitializeSema(*TheSema);
760   }
761 
762   // If we're building a module and are supposed to load API notes,
763   // notify the API notes manager.
764   if (auto *currentModule = getPreprocessor().getCurrentModule()) {
765     (void)TheSema->APINotes.loadCurrentModuleAPINotes(
766         currentModule, getLangOpts().APINotesModules,
767         getAPINotesOpts().ModuleSearchPaths);
768   }
769 }
770 
771 // Output Files
772 
773 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
774   // The ASTConsumer can own streams that write to the output files.
775   assert(!hasASTConsumer() && "ASTConsumer should be reset");
776   // Ignore errors that occur when trying to discard the temp file.
777   for (OutputFile &OF : OutputFiles) {
778     if (EraseFiles) {
779       if (OF.File)
780         consumeError(OF.File->discard());
781       if (!OF.Filename.empty())
782         llvm::sys::fs::remove(OF.Filename);
783       continue;
784     }
785 
786     if (!OF.File)
787       continue;
788 
789     if (OF.File->TmpName.empty()) {
790       consumeError(OF.File->discard());
791       continue;
792     }
793 
794     llvm::Error E = OF.File->keep(OF.Filename);
795     if (!E)
796       continue;
797 
798     getDiagnostics().Report(diag::err_unable_to_rename_temp)
799         << OF.File->TmpName << OF.Filename << std::move(E);
800 
801     llvm::sys::fs::remove(OF.File->TmpName);
802   }
803   OutputFiles.clear();
804   if (DeleteBuiltModules) {
805     for (auto &Module : BuiltModules)
806       llvm::sys::fs::remove(Module.second);
807     BuiltModules.clear();
808   }
809 }
810 
811 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
812     bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
813     bool CreateMissingDirectories, bool ForceUseTemporary) {
814   StringRef OutputPath = getFrontendOpts().OutputFile;
815   std::optional<SmallString<128>> PathStorage;
816   if (OutputPath.empty()) {
817     if (InFile == "-" || Extension.empty()) {
818       OutputPath = "-";
819     } else {
820       PathStorage.emplace(InFile);
821       llvm::sys::path::replace_extension(*PathStorage, Extension);
822       OutputPath = *PathStorage;
823     }
824   }
825 
826   return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
827                           getFrontendOpts().UseTemporary || ForceUseTemporary,
828                           CreateMissingDirectories);
829 }
830 
831 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
832   return std::make_unique<llvm::raw_null_ostream>();
833 }
834 
835 std::unique_ptr<raw_pwrite_stream>
836 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
837                                    bool RemoveFileOnSignal, bool UseTemporary,
838                                    bool CreateMissingDirectories) {
839   Expected<std::unique_ptr<raw_pwrite_stream>> OS =
840       createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
841                            CreateMissingDirectories);
842   if (OS)
843     return std::move(*OS);
844   getDiagnostics().Report(diag::err_fe_unable_to_open_output)
845       << OutputPath << errorToErrorCode(OS.takeError()).message();
846   return nullptr;
847 }
848 
849 Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
850 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
851                                        bool RemoveFileOnSignal,
852                                        bool UseTemporary,
853                                        bool CreateMissingDirectories) {
854   assert((!CreateMissingDirectories || UseTemporary) &&
855          "CreateMissingDirectories is only allowed when using temporary files");
856 
857   // If '-working-directory' was passed, the output filename should be
858   // relative to that.
859   std::optional<SmallString<128>> AbsPath;
860   if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
861     assert(hasFileManager() &&
862            "File Manager is required to fix up relative path.\n");
863 
864     AbsPath.emplace(OutputPath);
865     FileMgr->FixupRelativePath(*AbsPath);
866     OutputPath = *AbsPath;
867   }
868 
869   std::unique_ptr<llvm::raw_fd_ostream> OS;
870   std::optional<StringRef> OSFile;
871 
872   if (UseTemporary) {
873     if (OutputPath == "-")
874       UseTemporary = false;
875     else {
876       llvm::sys::fs::file_status Status;
877       llvm::sys::fs::status(OutputPath, Status);
878       if (llvm::sys::fs::exists(Status)) {
879         // Fail early if we can't write to the final destination.
880         if (!llvm::sys::fs::can_write(OutputPath))
881           return llvm::errorCodeToError(
882               make_error_code(llvm::errc::operation_not_permitted));
883 
884         // Don't use a temporary if the output is a special file. This handles
885         // things like '-o /dev/null'
886         if (!llvm::sys::fs::is_regular_file(Status))
887           UseTemporary = false;
888       }
889     }
890   }
891 
892   std::optional<llvm::sys::fs::TempFile> Temp;
893   if (UseTemporary) {
894     // Create a temporary file.
895     // Insert -%%%%%%%% before the extension (if any), and because some tools
896     // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
897     // artifacts, also append .tmp.
898     StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
899     SmallString<128> TempPath =
900         StringRef(OutputPath).drop_back(OutputExtension.size());
901     TempPath += "-%%%%%%%%";
902     TempPath += OutputExtension;
903     TempPath += ".tmp";
904     llvm::sys::fs::OpenFlags BinaryFlags =
905         Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text;
906     Expected<llvm::sys::fs::TempFile> ExpectedFile =
907         llvm::sys::fs::TempFile::create(
908             TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
909             BinaryFlags);
910 
911     llvm::Error E = handleErrors(
912         ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error {
913           std::error_code EC = E.convertToErrorCode();
914           if (CreateMissingDirectories &&
915               EC == llvm::errc::no_such_file_or_directory) {
916             StringRef Parent = llvm::sys::path::parent_path(OutputPath);
917             EC = llvm::sys::fs::create_directories(Parent);
918             if (!EC) {
919               ExpectedFile = llvm::sys::fs::TempFile::create(
920                   TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
921                   BinaryFlags);
922               if (!ExpectedFile)
923                 return llvm::errorCodeToError(
924                     llvm::errc::no_such_file_or_directory);
925             }
926           }
927           return llvm::errorCodeToError(EC);
928         });
929 
930     if (E) {
931       consumeError(std::move(E));
932     } else {
933       Temp = std::move(ExpectedFile.get());
934       OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false));
935       OSFile = Temp->TmpName;
936     }
937     // If we failed to create the temporary, fallback to writing to the file
938     // directly. This handles the corner case where we cannot write to the
939     // directory, but can write to the file.
940   }
941 
942   if (!OS) {
943     OSFile = OutputPath;
944     std::error_code EC;
945     OS.reset(new llvm::raw_fd_ostream(
946         *OSFile, EC,
947         (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
948     if (EC)
949       return llvm::errorCodeToError(EC);
950   }
951 
952   // Add the output file -- but don't try to remove "-", since this means we are
953   // using stdin.
954   OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
955                            std::move(Temp));
956 
957   if (!Binary || OS->supportsSeeking())
958     return std::move(OS);
959 
960   return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
961 }
962 
963 // Initialization Utilities
964 
965 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
966   return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
967                                  getSourceManager());
968 }
969 
970 // static
971 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
972                                                DiagnosticsEngine &Diags,
973                                                FileManager &FileMgr,
974                                                SourceManager &SourceMgr) {
975   SrcMgr::CharacteristicKind Kind =
976       Input.getKind().getFormat() == InputKind::ModuleMap
977           ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
978                              : SrcMgr::C_User_ModuleMap
979           : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
980 
981   if (Input.isBuffer()) {
982     SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
983     assert(SourceMgr.getMainFileID().isValid() &&
984            "Couldn't establish MainFileID!");
985     return true;
986   }
987 
988   StringRef InputFile = Input.getFile();
989 
990   // Figure out where to get and map in the main file.
991   auto FileOrErr = InputFile == "-"
992                        ? FileMgr.getSTDIN()
993                        : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
994   if (!FileOrErr) {
995     auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
996     if (InputFile != "-")
997       Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
998     else
999       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
1000     return false;
1001   }
1002 
1003   SourceMgr.setMainFileID(
1004       SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
1005 
1006   assert(SourceMgr.getMainFileID().isValid() &&
1007          "Couldn't establish MainFileID!");
1008   return true;
1009 }
1010 
1011 // High-Level Operations
1012 
1013 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
1014   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
1015   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
1016   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
1017 
1018   // Mark this point as the bottom of the stack if we don't have somewhere
1019   // better. We generally expect frontend actions to be invoked with (nearly)
1020   // DesiredStackSpace available.
1021   noteBottomOfStack();
1022 
1023   auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
1024     // Notify the diagnostic client that all files were processed.
1025     getDiagnosticClient().finish();
1026   });
1027 
1028   raw_ostream &OS = getVerboseOutputStream();
1029 
1030   if (!Act.PrepareToExecute(*this))
1031     return false;
1032 
1033   if (!createTarget())
1034     return false;
1035 
1036   // rewriter project will change target built-in bool type from its default.
1037   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
1038     getTarget().noSignedCharForObjCBool();
1039 
1040   // Validate/process some options.
1041   if (getHeaderSearchOpts().Verbose)
1042     OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
1043        << LLVM_VERSION_STRING << " default target "
1044        << llvm::sys::getDefaultTargetTriple() << "\n";
1045 
1046   if (getCodeGenOpts().TimePasses)
1047     createFrontendTimer();
1048 
1049   if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
1050     llvm::EnableStatistics(false);
1051 
1052   // Sort vectors containing toc data and no toc data variables to facilitate
1053   // binary search later.
1054   llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified);
1055   llvm::sort(getCodeGenOpts().NoTocDataVars);
1056 
1057   for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
1058     // Reset the ID tables if we are reusing the SourceManager and parsing
1059     // regular files.
1060     if (hasSourceManager() && !Act.isModelParsingAction())
1061       getSourceManager().clearIDTables();
1062 
1063     if (Act.BeginSourceFile(*this, FIF)) {
1064       if (llvm::Error Err = Act.Execute()) {
1065         consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1066       }
1067       Act.EndSourceFile();
1068     }
1069   }
1070 
1071   printDiagnosticStats();
1072 
1073   if (getFrontendOpts().ShowStats) {
1074     if (hasFileManager()) {
1075       getFileManager().PrintStats();
1076       OS << '\n';
1077     }
1078     llvm::PrintStatistics(OS);
1079   }
1080   StringRef StatsFile = getFrontendOpts().StatsFile;
1081   if (!StatsFile.empty()) {
1082     llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1083     if (getFrontendOpts().AppendStats)
1084       FileFlags |= llvm::sys::fs::OF_Append;
1085     std::error_code EC;
1086     auto StatS =
1087         std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1088     if (EC) {
1089       getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1090           << StatsFile << EC.message();
1091     } else {
1092       llvm::PrintStatisticsJSON(*StatS);
1093     }
1094   }
1095 
1096   return !getDiagnostics().getClient()->getNumErrors();
1097 }
1098 
1099 void CompilerInstance::printDiagnosticStats() {
1100   if (!getDiagnosticOpts().ShowCarets)
1101     return;
1102 
1103   raw_ostream &OS = getVerboseOutputStream();
1104 
1105   // We can have multiple diagnostics sharing one diagnostic client.
1106   // Get the total number of warnings/errors from the client.
1107   unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1108   unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1109 
1110   if (NumWarnings)
1111     OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1112   if (NumWarnings && NumErrors)
1113     OS << " and ";
1114   if (NumErrors)
1115     OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1116   if (NumWarnings || NumErrors) {
1117     OS << " generated";
1118     if (getLangOpts().CUDA) {
1119       if (!getLangOpts().CUDAIsDevice) {
1120         OS << " when compiling for host";
1121       } else {
1122         OS << " when compiling for " << getTargetOpts().CPU;
1123       }
1124     }
1125     OS << ".\n";
1126   }
1127 }
1128 
1129 void CompilerInstance::LoadRequestedPlugins() {
1130   // Load any requested plugins.
1131   for (const std::string &Path : getFrontendOpts().Plugins) {
1132     std::string Error;
1133     if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1134       getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1135           << Path << Error;
1136   }
1137 
1138   // Check if any of the loaded plugins replaces the main AST action
1139   for (const FrontendPluginRegistry::entry &Plugin :
1140        FrontendPluginRegistry::entries()) {
1141     std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1142     if (P->getActionType() == PluginASTAction::ReplaceAction) {
1143       getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
1144       getFrontendOpts().ActionName = Plugin.getName().str();
1145       break;
1146     }
1147   }
1148 }
1149 
1150 /// Determine the appropriate source input kind based on language
1151 /// options.
1152 static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1153   if (LangOpts.OpenCL)
1154     return Language::OpenCL;
1155   if (LangOpts.CUDA)
1156     return Language::CUDA;
1157   if (LangOpts.ObjC)
1158     return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1159   return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1160 }
1161 
1162 /// Compile a module file for the given module, using the options
1163 /// provided by the importing compiler instance. Returns true if the module
1164 /// was built without errors.
1165 static bool
1166 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1167                   StringRef ModuleName, FrontendInputFile Input,
1168                   StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1169                   llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1170                       [](CompilerInstance &) {},
1171                   llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1172                       [](CompilerInstance &) {}) {
1173   llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1174 
1175   // Never compile a module that's already finalized - this would cause the
1176   // existing module to be freed, causing crashes if it is later referenced
1177   if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) {
1178     ImportingInstance.getDiagnostics().Report(
1179         ImportLoc, diag::err_module_rebuild_finalized)
1180         << ModuleName;
1181     return false;
1182   }
1183 
1184   // Construct a compiler invocation for creating this module.
1185   auto Invocation =
1186       std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
1187 
1188   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1189 
1190   // For any options that aren't intended to affect how a module is built,
1191   // reset them to their default values.
1192   Invocation->resetNonModularOptions();
1193 
1194   // Remove any macro definitions that are explicitly ignored by the module.
1195   // They aren't supposed to affect how the module is built anyway.
1196   HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1197   llvm::erase_if(PPOpts.Macros,
1198                  [&HSOpts](const std::pair<std::string, bool> &def) {
1199                    StringRef MacroDef = def.first;
1200                    return HSOpts.ModulesIgnoreMacros.contains(
1201                        llvm::CachedHashString(MacroDef.split('=').first));
1202                  });
1203 
1204   // If the original compiler invocation had -fmodule-name, pass it through.
1205   Invocation->getLangOpts().ModuleName =
1206       ImportingInstance.getInvocation().getLangOpts().ModuleName;
1207 
1208   // Note the name of the module we're building.
1209   Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1210 
1211   // If there is a module map file, build the module using the module map.
1212   // Set up the inputs/outputs so that we build the module from its umbrella
1213   // header.
1214   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1215   FrontendOpts.OutputFile = ModuleFileName.str();
1216   FrontendOpts.DisableFree = false;
1217   FrontendOpts.GenerateGlobalModuleIndex = false;
1218   FrontendOpts.BuildingImplicitModule = true;
1219   FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1220   // Force implicitly-built modules to hash the content of the module file.
1221   HSOpts.ModulesHashContent = true;
1222   FrontendOpts.Inputs = {Input};
1223 
1224   // Don't free the remapped file buffers; they are owned by our caller.
1225   PPOpts.RetainRemappedFileBuffers = true;
1226 
1227   DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1228 
1229   DiagOpts.VerifyDiagnostics = 0;
1230   assert(ImportingInstance.getInvocation().getModuleHash() ==
1231          Invocation->getModuleHash() && "Module hash mismatch!");
1232 
1233   // Construct a compiler instance that will be used to actually create the
1234   // module.  Since we're sharing an in-memory module cache,
1235   // CompilerInstance::CompilerInstance is responsible for finalizing the
1236   // buffers to prevent use-after-frees.
1237   CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1238                             &ImportingInstance.getModuleCache());
1239   auto &Inv = *Invocation;
1240   Instance.setInvocation(std::move(Invocation));
1241 
1242   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1243                                    ImportingInstance.getDiagnosticClient()),
1244                              /*ShouldOwnClient=*/true);
1245 
1246   if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1247     Instance.getDiagnostics().setSuppressSystemWarnings(false);
1248 
1249   if (FrontendOpts.ModulesShareFileManager) {
1250     Instance.setFileManager(&ImportingInstance.getFileManager());
1251   } else {
1252     Instance.createFileManager(&ImportingInstance.getVirtualFileSystem());
1253   }
1254   Instance.createSourceManager(Instance.getFileManager());
1255   SourceManager &SourceMgr = Instance.getSourceManager();
1256 
1257   // Note that this module is part of the module build stack, so that we
1258   // can detect cycles in the module graph.
1259   SourceMgr.setModuleBuildStack(
1260     ImportingInstance.getSourceManager().getModuleBuildStack());
1261   SourceMgr.pushModuleBuildStack(ModuleName,
1262     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1263 
1264   // Make sure that the failed-module structure has been allocated in
1265   // the importing instance, and propagate the pointer to the newly-created
1266   // instance.
1267   if (!ImportingInstance.hasFailedModulesSet())
1268     ImportingInstance.createFailedModulesSet();
1269   Instance.setFailedModulesSet(ImportingInstance.getFailedModulesSetPtr());
1270 
1271   // If we're collecting module dependencies, we need to share a collector
1272   // between all of the module CompilerInstances. Other than that, we don't
1273   // want to produce any dependency output from the module build.
1274   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1275   Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1276 
1277   ImportingInstance.getDiagnostics().Report(ImportLoc,
1278                                             diag::remark_module_build)
1279     << ModuleName << ModuleFileName;
1280 
1281   PreBuildStep(Instance);
1282 
1283   // Execute the action to actually build the module in-place. Use a separate
1284   // thread so that we get a stack large enough.
1285   bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread(
1286       [&]() {
1287         GenerateModuleFromModuleMapAction Action;
1288         Instance.ExecuteAction(Action);
1289       },
1290       DesiredStackSize);
1291 
1292   PostBuildStep(Instance);
1293 
1294   ImportingInstance.getDiagnostics().Report(ImportLoc,
1295                                             diag::remark_module_build_done)
1296     << ModuleName;
1297 
1298   // Propagate the statistics to the parent FileManager.
1299   if (!FrontendOpts.ModulesShareFileManager)
1300     ImportingInstance.getFileManager().AddStats(Instance.getFileManager());
1301 
1302   if (Crashed) {
1303     // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1304     // that must be closed before clearing output files.
1305     Instance.setSema(nullptr);
1306     Instance.setASTConsumer(nullptr);
1307 
1308     // Delete any remaining temporary files related to Instance.
1309     Instance.clearOutputFiles(/*EraseFiles=*/true);
1310   }
1311 
1312   // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1313   // occurred.
1314   return !Instance.getDiagnostics().hasErrorOccurred() ||
1315          Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1316 }
1317 
1318 static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File,
1319                                                FileManager &FileMgr) {
1320   StringRef Filename = llvm::sys::path::filename(File.getName());
1321   SmallString<128> PublicFilename(File.getDir().getName());
1322   if (Filename == "module_private.map")
1323     llvm::sys::path::append(PublicFilename, "module.map");
1324   else if (Filename == "module.private.modulemap")
1325     llvm::sys::path::append(PublicFilename, "module.modulemap");
1326   else
1327     return std::nullopt;
1328   return FileMgr.getOptionalFileRef(PublicFilename);
1329 }
1330 
1331 /// Compile a module file for the given module in a separate compiler instance,
1332 /// using the options provided by the importing compiler instance. Returns true
1333 /// if the module was built without errors.
1334 static bool compileModule(CompilerInstance &ImportingInstance,
1335                           SourceLocation ImportLoc, Module *Module,
1336                           StringRef ModuleFileName) {
1337   InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1338                InputKind::ModuleMap);
1339 
1340   // Get or create the module map that we'll use to build this module.
1341   ModuleMap &ModMap
1342     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1343   SourceManager &SourceMgr = ImportingInstance.getSourceManager();
1344   bool Result;
1345   if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1346       ModuleMapFID.isValid()) {
1347     // We want to use the top-level module map. If we don't, the compiling
1348     // instance may think the containing module map is a top-level one, while
1349     // the importing instance knows it's included from a parent module map via
1350     // the extern directive. This mismatch could bite us later.
1351     SourceLocation Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1352     while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1353       ModuleMapFID = SourceMgr.getFileID(Loc);
1354       Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1355     }
1356 
1357     OptionalFileEntryRef ModuleMapFile =
1358         SourceMgr.getFileEntryRefForID(ModuleMapFID);
1359     assert(ModuleMapFile && "Top-level module map with no FileID");
1360 
1361     // Canonicalize compilation to start with the public module map. This is
1362     // vital for submodules declarations in the private module maps to be
1363     // correctly parsed when depending on a top level module in the public one.
1364     if (OptionalFileEntryRef PublicMMFile = getPublicModuleMap(
1365             *ModuleMapFile, ImportingInstance.getFileManager()))
1366       ModuleMapFile = PublicMMFile;
1367 
1368     StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1369 
1370     // Use the module map where this module resides.
1371     Result = compileModuleImpl(
1372         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1373         FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem),
1374         ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName);
1375   } else {
1376     // FIXME: We only need to fake up an input file here as a way of
1377     // transporting the module's directory to the module map parser. We should
1378     // be able to do that more directly, and parse from a memory buffer without
1379     // inventing this file.
1380     SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1381     llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1382 
1383     std::string InferredModuleMapContent;
1384     llvm::raw_string_ostream OS(InferredModuleMapContent);
1385     Module->print(OS);
1386 
1387     Result = compileModuleImpl(
1388         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1389         FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1390         ModMap.getModuleMapFileForUniquing(Module)->getName(),
1391         ModuleFileName,
1392         [&](CompilerInstance &Instance) {
1393       std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1394           llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1395       FileEntryRef ModuleMapFile = Instance.getFileManager().getVirtualFileRef(
1396           FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1397       Instance.getSourceManager().overrideFileContents(
1398           ModuleMapFile, std::move(ModuleMapBuffer));
1399     });
1400   }
1401 
1402   // We've rebuilt a module. If we're allowed to generate or update the global
1403   // module index, record that fact in the importing compiler instance.
1404   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1405     ImportingInstance.setBuildGlobalModuleIndex(true);
1406   }
1407 
1408   return Result;
1409 }
1410 
1411 /// Read the AST right after compiling the module.
1412 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1413                                       SourceLocation ImportLoc,
1414                                       SourceLocation ModuleNameLoc,
1415                                       Module *Module, StringRef ModuleFileName,
1416                                       bool *OutOfDate) {
1417   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1418 
1419   unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1420   if (OutOfDate)
1421     ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1422 
1423   // Try to read the module file, now that we've compiled it.
1424   ASTReader::ASTReadResult ReadResult =
1425       ImportingInstance.getASTReader()->ReadAST(
1426           ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1427           ModuleLoadCapabilities);
1428   if (ReadResult == ASTReader::Success)
1429     return true;
1430 
1431   // The caller wants to handle out-of-date failures.
1432   if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1433     *OutOfDate = true;
1434     return false;
1435   }
1436 
1437   // The ASTReader didn't diagnose the error, so conservatively report it.
1438   if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1439     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1440       << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1441 
1442   return false;
1443 }
1444 
1445 /// Compile a module in a separate compiler instance and read the AST,
1446 /// returning true if the module compiles without errors.
1447 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
1448                                         SourceLocation ImportLoc,
1449                                         SourceLocation ModuleNameLoc,
1450                                         Module *Module,
1451                                         StringRef ModuleFileName) {
1452   if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
1453                      ModuleFileName)) {
1454     ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1455                                               diag::err_module_not_built)
1456         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1457     return false;
1458   }
1459 
1460   return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1461                                    Module, ModuleFileName,
1462                                    /*OutOfDate=*/nullptr);
1463 }
1464 
1465 /// Compile a module in a separate compiler instance and read the AST,
1466 /// returning true if the module compiles without errors, using a lock manager
1467 /// to avoid building the same module in multiple compiler instances.
1468 ///
1469 /// Uses a lock file manager and exponential backoff to reduce the chances that
1470 /// multiple instances will compete to create the same module.  On timeout,
1471 /// deletes the lock file in order to avoid deadlock from crashing processes or
1472 /// bugs in the lock file manager.
1473 static bool compileModuleAndReadASTBehindLock(
1474     CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1475     SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1476   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1477 
1478   Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1479       << ModuleFileName << Module->Name;
1480 
1481   // FIXME: have LockFileManager return an error_code so that we can
1482   // avoid the mkdir when the directory already exists.
1483   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1484   llvm::sys::fs::create_directories(Dir);
1485 
1486   while (true) {
1487     llvm::LockFileManager Locked(ModuleFileName);
1488     switch (Locked) {
1489     case llvm::LockFileManager::LFS_Error:
1490       // ModuleCache takes care of correctness and locks are only necessary for
1491       // performance. Fallback to building the module in case of any lock
1492       // related errors.
1493       Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1494           << Module->Name << Locked.getErrorMessage();
1495       // Clear out any potential leftover.
1496       Locked.unsafeRemoveLockFile();
1497       [[fallthrough]];
1498     case llvm::LockFileManager::LFS_Owned:
1499       // We're responsible for building the module ourselves.
1500       return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1501                                          ModuleNameLoc, Module, ModuleFileName);
1502 
1503     case llvm::LockFileManager::LFS_Shared:
1504       break; // The interesting case.
1505     }
1506 
1507     // Someone else is responsible for building the module. Wait for them to
1508     // finish.
1509     switch (Locked.waitForUnlock()) {
1510     case llvm::LockFileManager::Res_Success:
1511       break; // The interesting case.
1512     case llvm::LockFileManager::Res_OwnerDied:
1513       continue; // try again to get the lock.
1514     case llvm::LockFileManager::Res_Timeout:
1515       // Since ModuleCache takes care of correctness, we try waiting for
1516       // another process to complete the build so clang does not do it done
1517       // twice. If case of timeout, build it ourselves.
1518       Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1519           << Module->Name;
1520       // Clear the lock file so that future invocations can make progress.
1521       Locked.unsafeRemoveLockFile();
1522       continue;
1523     }
1524 
1525     // Read the module that was just written by someone else.
1526     bool OutOfDate = false;
1527     if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1528                                   Module, ModuleFileName, &OutOfDate))
1529       return true;
1530     if (!OutOfDate)
1531       return false;
1532 
1533     // The module may be out of date in the presence of file system races,
1534     // or if one of its imports depends on header search paths that are not
1535     // consistent with this ImportingInstance.  Try again...
1536   }
1537 }
1538 
1539 /// Compile a module in a separate compiler instance and read the AST,
1540 /// returning true if the module compiles without errors, potentially using a
1541 /// lock manager to avoid building the same module in multiple compiler
1542 /// instances.
1543 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1544                                     SourceLocation ImportLoc,
1545                                     SourceLocation ModuleNameLoc,
1546                                     Module *Module, StringRef ModuleFileName) {
1547   return ImportingInstance.getInvocation()
1548                  .getFrontendOpts()
1549                  .BuildingImplicitModuleUsesLock
1550              ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
1551                                                  ModuleNameLoc, Module,
1552                                                  ModuleFileName)
1553              : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1554                                            ModuleNameLoc, Module,
1555                                            ModuleFileName);
1556 }
1557 
1558 /// Diagnose differences between the current definition of the given
1559 /// configuration macro and the definition provided on the command line.
1560 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1561                              Module *Mod, SourceLocation ImportLoc) {
1562   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1563   SourceManager &SourceMgr = PP.getSourceManager();
1564 
1565   // If this identifier has never had a macro definition, then it could
1566   // not have changed.
1567   if (!Id->hadMacroDefinition())
1568     return;
1569   auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1570 
1571   // Find the macro definition from the command line.
1572   MacroInfo *CmdLineDefinition = nullptr;
1573   for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1574     // We only care about the predefines buffer.
1575     FileID FID = SourceMgr.getFileID(MD->getLocation());
1576     if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1577       continue;
1578     if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1579       CmdLineDefinition = DMD->getMacroInfo();
1580     break;
1581   }
1582 
1583   auto *CurrentDefinition = PP.getMacroInfo(Id);
1584   if (CurrentDefinition == CmdLineDefinition) {
1585     // Macro matches. Nothing to do.
1586   } else if (!CurrentDefinition) {
1587     // This macro was defined on the command line, then #undef'd later.
1588     // Complain.
1589     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1590       << true << ConfigMacro << Mod->getFullModuleName();
1591     auto LatestDef = LatestLocalMD->getDefinition();
1592     assert(LatestDef.isUndefined() &&
1593            "predefined macro went away with no #undef?");
1594     PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1595       << true;
1596     return;
1597   } else if (!CmdLineDefinition) {
1598     // There was no definition for this macro in the predefines buffer,
1599     // but there was a local definition. Complain.
1600     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1601       << false << ConfigMacro << Mod->getFullModuleName();
1602     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1603             diag::note_module_def_undef_here)
1604       << false;
1605   } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1606                                                /*Syntactically=*/true)) {
1607     // The macro definitions differ.
1608     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1609       << false << ConfigMacro << Mod->getFullModuleName();
1610     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1611             diag::note_module_def_undef_here)
1612       << false;
1613   }
1614 }
1615 
1616 static void checkConfigMacros(Preprocessor &PP, Module *M,
1617                               SourceLocation ImportLoc) {
1618   clang::Module *TopModule = M->getTopLevelModule();
1619   for (const StringRef ConMacro : TopModule->ConfigMacros) {
1620     checkConfigMacro(PP, ConMacro, M, ImportLoc);
1621   }
1622 }
1623 
1624 /// Write a new timestamp file with the given path.
1625 static void writeTimestampFile(StringRef TimestampFile) {
1626   std::error_code EC;
1627   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1628 }
1629 
1630 /// Prune the module cache of modules that haven't been accessed in
1631 /// a long time.
1632 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1633   llvm::sys::fs::file_status StatBuf;
1634   llvm::SmallString<128> TimestampFile;
1635   TimestampFile = HSOpts.ModuleCachePath;
1636   assert(!TimestampFile.empty());
1637   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1638 
1639   // Try to stat() the timestamp file.
1640   if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1641     // If the timestamp file wasn't there, create one now.
1642     if (EC == std::errc::no_such_file_or_directory) {
1643       writeTimestampFile(TimestampFile);
1644     }
1645     return;
1646   }
1647 
1648   // Check whether the time stamp is older than our pruning interval.
1649   // If not, do nothing.
1650   time_t TimeStampModTime =
1651       llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1652   time_t CurrentTime = time(nullptr);
1653   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1654     return;
1655 
1656   // Write a new timestamp file so that nobody else attempts to prune.
1657   // There is a benign race condition here, if two Clang instances happen to
1658   // notice at the same time that the timestamp is out-of-date.
1659   writeTimestampFile(TimestampFile);
1660 
1661   // Walk the entire module cache, looking for unused module files and module
1662   // indices.
1663   std::error_code EC;
1664   for (llvm::sys::fs::directory_iterator Dir(HSOpts.ModuleCachePath, EC),
1665        DirEnd;
1666        Dir != DirEnd && !EC; Dir.increment(EC)) {
1667     // If we don't have a directory, there's nothing to look into.
1668     if (!llvm::sys::fs::is_directory(Dir->path()))
1669       continue;
1670 
1671     // Walk all of the files within this directory.
1672     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1673          File != FileEnd && !EC; File.increment(EC)) {
1674       // We only care about module and global module index files.
1675       StringRef Extension = llvm::sys::path::extension(File->path());
1676       if (Extension != ".pcm" && Extension != ".timestamp" &&
1677           llvm::sys::path::filename(File->path()) != "modules.idx")
1678         continue;
1679 
1680       // Look at this file. If we can't stat it, there's nothing interesting
1681       // there.
1682       if (llvm::sys::fs::status(File->path(), StatBuf))
1683         continue;
1684 
1685       // If the file has been used recently enough, leave it there.
1686       time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1687       if (CurrentTime - FileAccessTime <=
1688               time_t(HSOpts.ModuleCachePruneAfter)) {
1689         continue;
1690       }
1691 
1692       // Remove the file.
1693       llvm::sys::fs::remove(File->path());
1694 
1695       // Remove the timestamp file.
1696       std::string TimpestampFilename = File->path() + ".timestamp";
1697       llvm::sys::fs::remove(TimpestampFilename);
1698     }
1699 
1700     // If we removed all of the files in the directory, remove the directory
1701     // itself.
1702     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1703             llvm::sys::fs::directory_iterator() && !EC)
1704       llvm::sys::fs::remove(Dir->path());
1705   }
1706 }
1707 
1708 void CompilerInstance::createASTReader() {
1709   if (TheASTReader)
1710     return;
1711 
1712   if (!hasASTContext())
1713     createASTContext();
1714 
1715   // If we're implicitly building modules but not currently recursively
1716   // building a module, check whether we need to prune the module cache.
1717   if (getSourceManager().getModuleBuildStack().empty() &&
1718       !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1719       getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1720       getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1721     pruneModuleCache(getHeaderSearchOpts());
1722   }
1723 
1724   HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1725   std::string Sysroot = HSOpts.Sysroot;
1726   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1727   const FrontendOptions &FEOpts = getFrontendOpts();
1728   std::unique_ptr<llvm::Timer> ReadTimer;
1729 
1730   if (FrontendTimerGroup)
1731     ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1732                                                 "Reading modules",
1733                                                 *FrontendTimerGroup);
1734   TheASTReader = new ASTReader(
1735       getPreprocessor(), getModuleCache(), &getASTContext(),
1736       getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1737       Sysroot.empty() ? "" : Sysroot.c_str(),
1738       PPOpts.DisablePCHOrModuleValidation,
1739       /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1740       /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
1741       HSOpts.ValidateASTInputFilesContent,
1742       getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1743   if (hasASTConsumer()) {
1744     TheASTReader->setDeserializationListener(
1745         getASTConsumer().GetASTDeserializationListener());
1746     getASTContext().setASTMutationListener(
1747       getASTConsumer().GetASTMutationListener());
1748   }
1749   getASTContext().setExternalSource(TheASTReader);
1750   if (hasSema())
1751     TheASTReader->InitializeSema(getSema());
1752   if (hasASTConsumer())
1753     TheASTReader->StartTranslationUnit(&getASTConsumer());
1754 
1755   for (auto &Listener : DependencyCollectors)
1756     Listener->attachToASTReader(*TheASTReader);
1757 }
1758 
1759 bool CompilerInstance::loadModuleFile(
1760     StringRef FileName, serialization::ModuleFile *&LoadedModuleFile) {
1761   llvm::Timer Timer;
1762   if (FrontendTimerGroup)
1763     Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1764                *FrontendTimerGroup);
1765   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1766 
1767   // If we don't already have an ASTReader, create one now.
1768   if (!TheASTReader)
1769     createASTReader();
1770 
1771   // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1772   // ASTReader to diagnose it, since it can produce better errors that we can.
1773   bool ConfigMismatchIsRecoverable =
1774       getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1775                                           SourceLocation())
1776         <= DiagnosticsEngine::Warning;
1777 
1778   auto Listener = std::make_unique<ReadModuleNames>(*PP);
1779   auto &ListenerRef = *Listener;
1780   ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1781                                                    std::move(Listener));
1782 
1783   // Try to load the module file.
1784   switch (TheASTReader->ReadAST(
1785       FileName, serialization::MK_ExplicitModule, SourceLocation(),
1786       ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1787       &LoadedModuleFile)) {
1788   case ASTReader::Success:
1789     // We successfully loaded the module file; remember the set of provided
1790     // modules so that we don't try to load implicit modules for them.
1791     ListenerRef.registerAll();
1792     return true;
1793 
1794   case ASTReader::ConfigurationMismatch:
1795     // Ignore unusable module files.
1796     getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1797         << FileName;
1798     // All modules provided by any files we tried and failed to load are now
1799     // unavailable; includes of those modules should now be handled textually.
1800     ListenerRef.markAllUnavailable();
1801     return true;
1802 
1803   default:
1804     return false;
1805   }
1806 }
1807 
1808 namespace {
1809 enum ModuleSource {
1810   MS_ModuleNotFound,
1811   MS_ModuleCache,
1812   MS_PrebuiltModulePath,
1813   MS_ModuleBuildPragma
1814 };
1815 } // end namespace
1816 
1817 /// Select a source for loading the named module and compute the filename to
1818 /// load it from.
1819 static ModuleSource selectModuleSource(
1820     Module *M, StringRef ModuleName, std::string &ModuleFilename,
1821     const std::map<std::string, std::string, std::less<>> &BuiltModules,
1822     HeaderSearch &HS) {
1823   assert(ModuleFilename.empty() && "Already has a module source?");
1824 
1825   // Check to see if the module has been built as part of this compilation
1826   // via a module build pragma.
1827   auto BuiltModuleIt = BuiltModules.find(ModuleName);
1828   if (BuiltModuleIt != BuiltModules.end()) {
1829     ModuleFilename = BuiltModuleIt->second;
1830     return MS_ModuleBuildPragma;
1831   }
1832 
1833   // Try to load the module from the prebuilt module path.
1834   const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1835   if (!HSOpts.PrebuiltModuleFiles.empty() ||
1836       !HSOpts.PrebuiltModulePaths.empty()) {
1837     ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1838     if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1839       ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1840     if (!ModuleFilename.empty())
1841       return MS_PrebuiltModulePath;
1842   }
1843 
1844   // Try to load the module from the module cache.
1845   if (M) {
1846     ModuleFilename = HS.getCachedModuleFileName(M);
1847     return MS_ModuleCache;
1848   }
1849 
1850   return MS_ModuleNotFound;
1851 }
1852 
1853 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1854     StringRef ModuleName, SourceLocation ImportLoc,
1855     SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1856   // Search for a module with the given name.
1857   HeaderSearch &HS = PP->getHeaderSearchInfo();
1858   Module *M =
1859       HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1860 
1861   // Check for any configuration macros that have changed. This is done
1862   // immediately before potentially building a module in case this module
1863   // depends on having one of its configuration macros defined to successfully
1864   // build. If this is not done the user will never see the warning.
1865   if (M)
1866     checkConfigMacros(getPreprocessor(), M, ImportLoc);
1867 
1868   // Select the source and filename for loading the named module.
1869   std::string ModuleFilename;
1870   ModuleSource Source =
1871       selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1872   if (Source == MS_ModuleNotFound) {
1873     // We can't find a module, error out here.
1874     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1875         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1876     return nullptr;
1877   }
1878   if (ModuleFilename.empty()) {
1879     if (M && M->HasIncompatibleModuleFile) {
1880       // We tried and failed to load a module file for this module. Fall
1881       // back to textual inclusion for its headers.
1882       return ModuleLoadResult::ConfigMismatch;
1883     }
1884 
1885     getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1886         << ModuleName;
1887     return nullptr;
1888   }
1889 
1890   // Create an ASTReader on demand.
1891   if (!getASTReader())
1892     createASTReader();
1893 
1894   // Time how long it takes to load the module.
1895   llvm::Timer Timer;
1896   if (FrontendTimerGroup)
1897     Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1898                *FrontendTimerGroup);
1899   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1900   llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1901 
1902   // Try to load the module file. If we are not trying to load from the
1903   // module cache, we don't know how to rebuild modules.
1904   unsigned ARRFlags = Source == MS_ModuleCache
1905                           ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
1906                                 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
1907                           : Source == MS_PrebuiltModulePath
1908                                 ? 0
1909                                 : ASTReader::ARR_ConfigurationMismatch;
1910   switch (getASTReader()->ReadAST(ModuleFilename,
1911                                   Source == MS_PrebuiltModulePath
1912                                       ? serialization::MK_PrebuiltModule
1913                                       : Source == MS_ModuleBuildPragma
1914                                             ? serialization::MK_ExplicitModule
1915                                             : serialization::MK_ImplicitModule,
1916                                   ImportLoc, ARRFlags)) {
1917   case ASTReader::Success: {
1918     if (M)
1919       return M;
1920     assert(Source != MS_ModuleCache &&
1921            "missing module, but file loaded from cache");
1922 
1923     // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1924     // until the first call to ReadAST.  Look it up now.
1925     M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1926 
1927     // Check whether M refers to the file in the prebuilt module path.
1928     if (M && M->getASTFile())
1929       if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
1930         if (*ModuleFile == M->getASTFile())
1931           return M;
1932 
1933     getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1934         << ModuleName;
1935     return ModuleLoadResult();
1936   }
1937 
1938   case ASTReader::OutOfDate:
1939   case ASTReader::Missing:
1940     // The most interesting case.
1941     break;
1942 
1943   case ASTReader::ConfigurationMismatch:
1944     if (Source == MS_PrebuiltModulePath)
1945       // FIXME: We shouldn't be setting HadFatalFailure below if we only
1946       // produce a warning here!
1947       getDiagnostics().Report(SourceLocation(),
1948                               diag::warn_module_config_mismatch)
1949           << ModuleFilename;
1950     // Fall through to error out.
1951     [[fallthrough]];
1952   case ASTReader::VersionMismatch:
1953   case ASTReader::HadErrors:
1954     ModuleLoader::HadFatalFailure = true;
1955     // FIXME: The ASTReader will already have complained, but can we shoehorn
1956     // that diagnostic information into a more useful form?
1957     return ModuleLoadResult();
1958 
1959   case ASTReader::Failure:
1960     ModuleLoader::HadFatalFailure = true;
1961     return ModuleLoadResult();
1962   }
1963 
1964   // ReadAST returned Missing or OutOfDate.
1965   if (Source != MS_ModuleCache) {
1966     // We don't know the desired configuration for this module and don't
1967     // necessarily even have a module map. Since ReadAST already produces
1968     // diagnostics for these two cases, we simply error out here.
1969     return ModuleLoadResult();
1970   }
1971 
1972   // The module file is missing or out-of-date. Build it.
1973   assert(M && "missing module, but trying to compile for cache");
1974 
1975   // Check whether there is a cycle in the module graph.
1976   ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1977   ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1978   for (; Pos != PosEnd; ++Pos) {
1979     if (Pos->first == ModuleName)
1980       break;
1981   }
1982 
1983   if (Pos != PosEnd) {
1984     SmallString<256> CyclePath;
1985     for (; Pos != PosEnd; ++Pos) {
1986       CyclePath += Pos->first;
1987       CyclePath += " -> ";
1988     }
1989     CyclePath += ModuleName;
1990 
1991     getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1992         << ModuleName << CyclePath;
1993     return nullptr;
1994   }
1995 
1996   // Check whether we have already attempted to build this module (but failed).
1997   if (FailedModules && FailedModules->hasAlreadyFailed(ModuleName)) {
1998     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1999         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
2000     return nullptr;
2001   }
2002 
2003   // Try to compile and then read the AST.
2004   if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
2005                                ModuleFilename)) {
2006     assert(getDiagnostics().hasErrorOccurred() &&
2007            "undiagnosed error in compileModuleAndReadAST");
2008     if (FailedModules)
2009       FailedModules->addFailed(ModuleName);
2010     return nullptr;
2011   }
2012 
2013   // Okay, we've rebuilt and now loaded the module.
2014   return M;
2015 }
2016 
2017 ModuleLoadResult
2018 CompilerInstance::loadModule(SourceLocation ImportLoc,
2019                              ModuleIdPath Path,
2020                              Module::NameVisibilityKind Visibility,
2021                              bool IsInclusionDirective) {
2022   // Determine what file we're searching from.
2023   StringRef ModuleName = Path[0].first->getName();
2024   SourceLocation ModuleNameLoc = Path[0].second;
2025 
2026   // If we've already handled this import, just return the cached result.
2027   // This one-element cache is important to eliminate redundant diagnostics
2028   // when both the preprocessor and parser see the same import declaration.
2029   if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
2030     // Make the named module visible.
2031     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
2032       TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
2033                                       ImportLoc);
2034     return LastModuleImportResult;
2035   }
2036 
2037   // If we don't already have information on this module, load the module now.
2038   Module *Module = nullptr;
2039   ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2040   if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
2041     // Use the cached result, which may be nullptr.
2042     Module = *MaybeModule;
2043     // Config macros are already checked before building a module, but they need
2044     // to be checked at each import location in case any of the config macros
2045     // have a new value at the current `ImportLoc`.
2046     if (Module)
2047       checkConfigMacros(getPreprocessor(), Module, ImportLoc);
2048   } else if (ModuleName == getLangOpts().CurrentModule) {
2049     // This is the module we're building.
2050     Module = PP->getHeaderSearchInfo().lookupModule(
2051         ModuleName, ImportLoc, /*AllowSearch*/ true,
2052         /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
2053 
2054     // Config macros do not need to be checked here for two reasons.
2055     // * This will always be textual inclusion, and thus the config macros
2056     //   actually do impact the content of the header.
2057     // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
2058     //   function as the `#include` or `#import` is textual.
2059 
2060     MM.cacheModuleLoad(*Path[0].first, Module);
2061   } else {
2062     ModuleLoadResult Result = findOrCompileModuleAndReadAST(
2063         ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
2064     if (!Result.isNormal())
2065       return Result;
2066     if (!Result)
2067       DisableGeneratingGlobalModuleIndex = true;
2068     Module = Result;
2069     MM.cacheModuleLoad(*Path[0].first, Module);
2070   }
2071 
2072   // If we never found the module, fail.  Otherwise, verify the module and link
2073   // it up.
2074   if (!Module)
2075     return ModuleLoadResult();
2076 
2077   // Verify that the rest of the module path actually corresponds to
2078   // a submodule.
2079   bool MapPrivateSubModToTopLevel = false;
2080   for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2081     StringRef Name = Path[I].first->getName();
2082     clang::Module *Sub = Module->findSubmodule(Name);
2083 
2084     // If the user is requesting Foo.Private and it doesn't exist, try to
2085     // match Foo_Private and emit a warning asking for the user to write
2086     // @import Foo_Private instead. FIXME: remove this when existing clients
2087     // migrate off of Foo.Private syntax.
2088     if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2089       SmallString<128> PrivateModule(Module->Name);
2090       PrivateModule.append("_Private");
2091 
2092       SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
2093       auto &II = PP->getIdentifierTable().get(
2094           PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2095       PrivPath.push_back(std::make_pair(&II, Path[0].second));
2096 
2097       std::string FileName;
2098       // If there is a modulemap module or prebuilt module, load it.
2099       if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2100                                                  !IsInclusionDirective) ||
2101           selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2102                              PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2103         Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2104       if (Sub) {
2105         MapPrivateSubModToTopLevel = true;
2106         PP->markClangModuleAsAffecting(Module);
2107         if (!getDiagnostics().isIgnored(
2108                 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2109           getDiagnostics().Report(Path[I].second,
2110                                   diag::warn_no_priv_submodule_use_toplevel)
2111               << Path[I].first << Module->getFullModuleName() << PrivateModule
2112               << SourceRange(Path[0].second, Path[I].second)
2113               << FixItHint::CreateReplacement(SourceRange(Path[0].second),
2114                                               PrivateModule);
2115           getDiagnostics().Report(Sub->DefinitionLoc,
2116                                   diag::note_private_top_level_defined);
2117         }
2118       }
2119     }
2120 
2121     if (!Sub) {
2122       // Attempt to perform typo correction to find a module name that works.
2123       SmallVector<StringRef, 2> Best;
2124       unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2125 
2126       for (class Module *SubModule : Module->submodules()) {
2127         unsigned ED =
2128             Name.edit_distance(SubModule->Name,
2129                                /*AllowReplacements=*/true, BestEditDistance);
2130         if (ED <= BestEditDistance) {
2131           if (ED < BestEditDistance) {
2132             Best.clear();
2133             BestEditDistance = ED;
2134           }
2135 
2136           Best.push_back(SubModule->Name);
2137         }
2138       }
2139 
2140       // If there was a clear winner, user it.
2141       if (Best.size() == 1) {
2142         getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest)
2143             << Path[I].first << Module->getFullModuleName() << Best[0]
2144             << SourceRange(Path[0].second, Path[I - 1].second)
2145             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
2146                                             Best[0]);
2147 
2148         Sub = Module->findSubmodule(Best[0]);
2149       }
2150     }
2151 
2152     if (!Sub) {
2153       // No submodule by this name. Complain, and don't look for further
2154       // submodules.
2155       getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
2156           << Path[I].first << Module->getFullModuleName()
2157           << SourceRange(Path[0].second, Path[I - 1].second);
2158       break;
2159     }
2160 
2161     Module = Sub;
2162   }
2163 
2164   // Make the named module visible, if it's not already part of the module
2165   // we are parsing.
2166   if (ModuleName != getLangOpts().CurrentModule) {
2167     if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2168       // We have an umbrella header or directory that doesn't actually include
2169       // all of the headers within the directory it covers. Complain about
2170       // this missing submodule and recover by forgetting that we ever saw
2171       // this submodule.
2172       // FIXME: Should we detect this at module load time? It seems fairly
2173       // expensive (and rare).
2174       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2175         << Module->getFullModuleName()
2176         << SourceRange(Path.front().second, Path.back().second);
2177 
2178       return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected);
2179     }
2180 
2181     // Check whether this module is available.
2182     if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
2183                                              *Module, getDiagnostics())) {
2184       getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2185         << SourceRange(Path.front().second, Path.back().second);
2186       LastModuleImportLoc = ImportLoc;
2187       LastModuleImportResult = ModuleLoadResult();
2188       return ModuleLoadResult();
2189     }
2190 
2191     TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2192   }
2193 
2194   // Resolve any remaining module using export_as for this one.
2195   getPreprocessor()
2196       .getHeaderSearchInfo()
2197       .getModuleMap()
2198       .resolveLinkAsDependencies(Module->getTopLevelModule());
2199 
2200   LastModuleImportLoc = ImportLoc;
2201   LastModuleImportResult = ModuleLoadResult(Module);
2202   return LastModuleImportResult;
2203 }
2204 
2205 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
2206                                               StringRef ModuleName,
2207                                               StringRef Source) {
2208   // Avoid creating filenames with special characters.
2209   SmallString<128> CleanModuleName(ModuleName);
2210   for (auto &C : CleanModuleName)
2211     if (!isAlphanumeric(C))
2212       C = '_';
2213 
2214   // FIXME: Using a randomized filename here means that our intermediate .pcm
2215   // output is nondeterministic (as .pcm files refer to each other by name).
2216   // Can this affect the output in any way?
2217   SmallString<128> ModuleFileName;
2218   if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2219           CleanModuleName, "pcm", ModuleFileName)) {
2220     getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2221         << ModuleFileName << EC.message();
2222     return;
2223   }
2224   std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2225 
2226   FrontendInputFile Input(
2227       ModuleMapFileName,
2228       InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2229                 InputKind::ModuleMap, /*Preprocessed*/true));
2230 
2231   std::string NullTerminatedSource(Source.str());
2232 
2233   auto PreBuildStep = [&](CompilerInstance &Other) {
2234     // Create a virtual file containing our desired source.
2235     // FIXME: We shouldn't need to do this.
2236     FileEntryRef ModuleMapFile = Other.getFileManager().getVirtualFileRef(
2237         ModuleMapFileName, NullTerminatedSource.size(), 0);
2238     Other.getSourceManager().overrideFileContents(
2239         ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2240 
2241     Other.BuiltModules = std::move(BuiltModules);
2242     Other.DeleteBuiltModules = false;
2243   };
2244 
2245   auto PostBuildStep = [this](CompilerInstance &Other) {
2246     BuiltModules = std::move(Other.BuiltModules);
2247   };
2248 
2249   // Build the module, inheriting any modules that we've built locally.
2250   if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2251                         ModuleFileName, PreBuildStep, PostBuildStep)) {
2252     BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2253     llvm::sys::RemoveFileOnSignal(ModuleFileName);
2254   }
2255 }
2256 
2257 void CompilerInstance::makeModuleVisible(Module *Mod,
2258                                          Module::NameVisibilityKind Visibility,
2259                                          SourceLocation ImportLoc) {
2260   if (!TheASTReader)
2261     createASTReader();
2262   if (!TheASTReader)
2263     return;
2264 
2265   TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2266 }
2267 
2268 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2269     SourceLocation TriggerLoc) {
2270   if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2271     return nullptr;
2272   if (!TheASTReader)
2273     createASTReader();
2274   // Can't do anything if we don't have the module manager.
2275   if (!TheASTReader)
2276     return nullptr;
2277   // Get an existing global index.  This loads it if not already
2278   // loaded.
2279   TheASTReader->loadGlobalIndex();
2280   GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2281   // If the global index doesn't exist, create it.
2282   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2283       hasPreprocessor()) {
2284     llvm::sys::fs::create_directories(
2285       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2286     if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2287             getFileManager(), getPCHContainerReader(),
2288             getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2289       // FIXME this drops the error on the floor. This code is only used for
2290       // typo correction and drops more than just this one source of errors
2291       // (such as the directory creation failure above). It should handle the
2292       // error.
2293       consumeError(std::move(Err));
2294       return nullptr;
2295     }
2296     TheASTReader->resetForReload();
2297     TheASTReader->loadGlobalIndex();
2298     GlobalIndex = TheASTReader->getGlobalIndex();
2299   }
2300   // For finding modules needing to be imported for fixit messages,
2301   // we need to make the global index cover all modules, so we do that here.
2302   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2303     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2304     bool RecreateIndex = false;
2305     for (ModuleMap::module_iterator I = MMap.module_begin(),
2306         E = MMap.module_end(); I != E; ++I) {
2307       Module *TheModule = I->second;
2308       OptionalFileEntryRef Entry = TheModule->getASTFile();
2309       if (!Entry) {
2310         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2311         Path.push_back(std::make_pair(
2312             getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
2313         std::reverse(Path.begin(), Path.end());
2314         // Load a module as hidden.  This also adds it to the global index.
2315         loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2316         RecreateIndex = true;
2317       }
2318     }
2319     if (RecreateIndex) {
2320       if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2321               getFileManager(), getPCHContainerReader(),
2322               getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2323         // FIXME As above, this drops the error on the floor.
2324         consumeError(std::move(Err));
2325         return nullptr;
2326       }
2327       TheASTReader->resetForReload();
2328       TheASTReader->loadGlobalIndex();
2329       GlobalIndex = TheASTReader->getGlobalIndex();
2330     }
2331     HaveFullGlobalModuleIndex = true;
2332   }
2333   return GlobalIndex;
2334 }
2335 
2336 // Check global module index for missing imports.
2337 bool
2338 CompilerInstance::lookupMissingImports(StringRef Name,
2339                                        SourceLocation TriggerLoc) {
2340   // Look for the symbol in non-imported modules, but only if an error
2341   // actually occurred.
2342   if (!buildingModule()) {
2343     // Load global module index, or retrieve a previously loaded one.
2344     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2345       TriggerLoc);
2346 
2347     // Only if we have a global index.
2348     if (GlobalIndex) {
2349       GlobalModuleIndex::HitSet FoundModules;
2350 
2351       // Find the modules that reference the identifier.
2352       // Note that this only finds top-level modules.
2353       // We'll let diagnoseTypo find the actual declaration module.
2354       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2355         return true;
2356     }
2357   }
2358 
2359   return false;
2360 }
2361 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2362 
2363 void CompilerInstance::setExternalSemaSource(
2364     IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2365   ExternalSemaSrc = std::move(ESS);
2366 }
2367