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