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