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