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