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