xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 81d08294384d968ebbc2d0584d1b987f1a8a01b3)
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Frontend/CompilerInstance.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/Version.h"
19 #include "clang/Config/config.h"
20 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
21 #include "clang/Frontend/FrontendAction.h"
22 #include "clang/Frontend/FrontendActions.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Frontend/LogDiagnosticPrinter.h"
25 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
26 #include "clang/Frontend/TextDiagnosticPrinter.h"
27 #include "clang/Frontend/Utils.h"
28 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
29 #include "clang/Lex/HeaderSearch.h"
30 #include "clang/Lex/PTHManager.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "clang/Sema/CodeCompleteConsumer.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Serialization/ASTReader.h"
36 #include "clang/Serialization/GlobalModuleIndex.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/CrashRecoveryContext.h"
39 #include "llvm/Support/Errc.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/LockFileManager.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Program.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <sys/stat.h>
50 #include <system_error>
51 #include <time.h>
52 #include <utility>
53 
54 using namespace clang;
55 
56 CompilerInstance::CompilerInstance(
57     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
58     bool BuildingModule)
59     : ModuleLoader(BuildingModule), Invocation(new CompilerInvocation()),
60       ModuleManager(nullptr),
61       ThePCHContainerOperations(std::move(PCHContainerOps)),
62       BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
63       ModuleBuildFailed(false) {}
64 
65 CompilerInstance::~CompilerInstance() {
66   assert(OutputFiles.empty() && "Still output files in flight?");
67 }
68 
69 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
70   Invocation = Value;
71 }
72 
73 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
74   return (BuildGlobalModuleIndex ||
75           (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
76            getFrontendOpts().GenerateGlobalModuleIndex)) &&
77          !ModuleBuildFailed;
78 }
79 
80 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
81   Diagnostics = Value;
82 }
83 
84 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
85 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
86 
87 void CompilerInstance::setFileManager(FileManager *Value) {
88   FileMgr = Value;
89   if (Value)
90     VirtualFileSystem = Value->getVirtualFileSystem();
91   else
92     VirtualFileSystem.reset();
93 }
94 
95 void CompilerInstance::setSourceManager(SourceManager *Value) {
96   SourceMgr = Value;
97 }
98 
99 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
100   PP = std::move(Value);
101 }
102 
103 void CompilerInstance::setASTContext(ASTContext *Value) {
104   Context = Value;
105 
106   if (Context && Consumer)
107     getASTConsumer().Initialize(getASTContext());
108 }
109 
110 void CompilerInstance::setSema(Sema *S) {
111   TheSema.reset(S);
112 }
113 
114 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
115   Consumer = std::move(Value);
116 
117   if (Context && Consumer)
118     getASTConsumer().Initialize(getASTContext());
119 }
120 
121 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
122   CompletionConsumer.reset(Value);
123 }
124 
125 std::unique_ptr<Sema> CompilerInstance::takeSema() {
126   return std::move(TheSema);
127 }
128 
129 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
130   return ModuleManager;
131 }
132 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
133   ModuleManager = std::move(Reader);
134 }
135 
136 std::shared_ptr<ModuleDependencyCollector>
137 CompilerInstance::getModuleDepCollector() const {
138   return ModuleDepCollector;
139 }
140 
141 void CompilerInstance::setModuleDepCollector(
142     std::shared_ptr<ModuleDependencyCollector> Collector) {
143   ModuleDepCollector = std::move(Collector);
144 }
145 
146 static void collectHeaderMaps(const HeaderSearch &HS,
147                               std::shared_ptr<ModuleDependencyCollector> MDC) {
148   SmallVector<std::string, 4> HeaderMapFileNames;
149   HS.getHeaderMapFileNames(HeaderMapFileNames);
150   for (auto &Name : HeaderMapFileNames)
151     MDC->addFile(Name);
152 }
153 
154 static void collectIncludePCH(CompilerInstance &CI,
155                               std::shared_ptr<ModuleDependencyCollector> MDC) {
156   const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
157   if (PPOpts.ImplicitPCHInclude.empty())
158     return;
159 
160   StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
161   FileManager &FileMgr = CI.getFileManager();
162   const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude);
163   if (!PCHDir) {
164     MDC->addFile(PCHInclude);
165     return;
166   }
167 
168   std::error_code EC;
169   SmallString<128> DirNative;
170   llvm::sys::path::native(PCHDir->getName(), DirNative);
171   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
172   SimpleASTReaderListener Validator(CI.getPreprocessor());
173   for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
174        Dir != DirEnd && !EC; Dir.increment(EC)) {
175     // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
176     // used here since we're not interested in validating the PCH at this time,
177     // but only to check whether this is a file containing an AST.
178     if (!ASTReader::readASTFileControlBlock(
179             Dir->getName(), FileMgr, CI.getPCHContainerReader(),
180             /*FindModuleFileExtensions=*/false, Validator,
181             /*ValidateDiagnosticOptions=*/false))
182       MDC->addFile(Dir->getName());
183   }
184 }
185 
186 static void collectVFSEntries(CompilerInstance &CI,
187                               std::shared_ptr<ModuleDependencyCollector> MDC) {
188   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
189     return;
190 
191   // Collect all VFS found.
192   SmallVector<vfs::YAMLVFSEntry, 16> VFSEntries;
193   for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
194     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
195         llvm::MemoryBuffer::getFile(VFSFile);
196     if (!Buffer)
197       return;
198     vfs::collectVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr,
199                             VFSFile, VFSEntries);
200   }
201 
202   for (auto &E : VFSEntries)
203     MDC->addFile(E.VPath, E.RPath);
204 }
205 
206 // Diagnostics
207 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
208                                const CodeGenOptions *CodeGenOpts,
209                                DiagnosticsEngine &Diags) {
210   std::error_code EC;
211   std::unique_ptr<raw_ostream> StreamOwner;
212   raw_ostream *OS = &llvm::errs();
213   if (DiagOpts->DiagnosticLogFile != "-") {
214     // Create the output stream.
215     auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
216         DiagOpts->DiagnosticLogFile, EC,
217         llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
218     if (EC) {
219       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
220           << DiagOpts->DiagnosticLogFile << EC.message();
221     } else {
222       FileOS->SetUnbuffered();
223       OS = FileOS.get();
224       StreamOwner = std::move(FileOS);
225     }
226   }
227 
228   // Chain in the diagnostic client which will log the diagnostics.
229   auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
230                                                         std::move(StreamOwner));
231   if (CodeGenOpts)
232     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
233   assert(Diags.ownsClient());
234   Diags.setClient(
235       new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
236 }
237 
238 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
239                                        DiagnosticsEngine &Diags,
240                                        StringRef OutputFile) {
241   auto SerializedConsumer =
242       clang::serialized_diags::create(OutputFile, DiagOpts);
243 
244   if (Diags.ownsClient()) {
245     Diags.setClient(new ChainedDiagnosticConsumer(
246         Diags.takeClient(), std::move(SerializedConsumer)));
247   } else {
248     Diags.setClient(new ChainedDiagnosticConsumer(
249         Diags.getClient(), std::move(SerializedConsumer)));
250   }
251 }
252 
253 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
254                                          bool ShouldOwnClient) {
255   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
256                                   ShouldOwnClient, &getCodeGenOpts());
257 }
258 
259 IntrusiveRefCntPtr<DiagnosticsEngine>
260 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
261                                     DiagnosticConsumer *Client,
262                                     bool ShouldOwnClient,
263                                     const CodeGenOptions *CodeGenOpts) {
264   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
265   IntrusiveRefCntPtr<DiagnosticsEngine>
266       Diags(new DiagnosticsEngine(DiagID, Opts));
267 
268   // Create the diagnostic client for reporting errors or for
269   // implementing -verify.
270   if (Client) {
271     Diags->setClient(Client, ShouldOwnClient);
272   } else
273     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
274 
275   // Chain in -verify checker, if requested.
276   if (Opts->VerifyDiagnostics)
277     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
278 
279   // Chain in -diagnostic-log-file dumper, if requested.
280   if (!Opts->DiagnosticLogFile.empty())
281     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
282 
283   if (!Opts->DiagnosticSerializationFile.empty())
284     SetupSerializedDiagnostics(Opts, *Diags,
285                                Opts->DiagnosticSerializationFile);
286 
287   // Configure our handling of diagnostics.
288   ProcessWarningOptions(*Diags, *Opts);
289 
290   return Diags;
291 }
292 
293 // File Manager
294 
295 void CompilerInstance::createFileManager() {
296   if (!hasVirtualFileSystem()) {
297     // TODO: choose the virtual file system based on the CompilerInvocation.
298     setVirtualFileSystem(vfs::getRealFileSystem());
299   }
300   FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
301 }
302 
303 // Source Manager
304 
305 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
306   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
307 }
308 
309 // Initialize the remapping of files to alternative contents, e.g.,
310 // those specified through other files.
311 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
312                                     SourceManager &SourceMgr,
313                                     FileManager &FileMgr,
314                                     const PreprocessorOptions &InitOpts) {
315   // Remap files in the source manager (with buffers).
316   for (const auto &RB : InitOpts.RemappedFileBuffers) {
317     // Create the file entry for the file that we're mapping from.
318     const FileEntry *FromFile =
319         FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
320     if (!FromFile) {
321       Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
322       if (!InitOpts.RetainRemappedFileBuffers)
323         delete RB.second;
324       continue;
325     }
326 
327     // Override the contents of the "from" file with the contents of
328     // the "to" file.
329     SourceMgr.overrideFileContents(FromFile, RB.second,
330                                    InitOpts.RetainRemappedFileBuffers);
331   }
332 
333   // Remap files in the source manager (with other files).
334   for (const auto &RF : InitOpts.RemappedFiles) {
335     // Find the file that we're mapping to.
336     const FileEntry *ToFile = FileMgr.getFile(RF.second);
337     if (!ToFile) {
338       Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
339       continue;
340     }
341 
342     // Create the file entry for the file that we're mapping from.
343     const FileEntry *FromFile =
344         FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
345     if (!FromFile) {
346       Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
347       continue;
348     }
349 
350     // Override the contents of the "from" file with the contents of
351     // the "to" file.
352     SourceMgr.overrideFileContents(FromFile, ToFile);
353   }
354 
355   SourceMgr.setOverridenFilesKeepOriginalName(
356       InitOpts.RemappedFilesKeepOriginalName);
357 }
358 
359 // Preprocessor
360 
361 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
362   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
363 
364   // Create a PTH manager if we are using some form of a token cache.
365   PTHManager *PTHMgr = nullptr;
366   if (!PPOpts.TokenCache.empty())
367     PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
368 
369   // Create the Preprocessor.
370   HeaderSearch *HeaderInfo =
371       new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
372                        getDiagnostics(), getLangOpts(), &getTarget());
373   PP = std::make_shared<Preprocessor>(
374       Invocation->getPreprocessorOptsPtr(), getDiagnostics(), getLangOpts(),
375       getSourceManager(), *HeaderInfo, *this, PTHMgr,
376       /*OwnsHeaderSearch=*/true, TUKind);
377   PP->Initialize(getTarget(), getAuxTarget());
378 
379   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
380   // That argument is used as the IdentifierInfoLookup argument to
381   // IdentifierTable's ctor.
382   if (PTHMgr) {
383     PTHMgr->setPreprocessor(&*PP);
384     PP->setPTHManager(PTHMgr);
385   }
386 
387   if (PPOpts.DetailedRecord)
388     PP->createPreprocessingRecord();
389 
390   // Apply remappings to the source manager.
391   InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
392                           PP->getFileManager(), PPOpts);
393 
394   // Predefine macros and configure the preprocessor.
395   InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
396                          getFrontendOpts());
397 
398   // Initialize the header search object.  In CUDA compilations, we use the aux
399   // triple (the host triple) to initialize our header search, since we need to
400   // find the host headers in order to compile the CUDA code.
401   const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
402   if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
403       PP->getAuxTargetInfo())
404     HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
405 
406   ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
407                            PP->getLangOpts(), *HeaderSearchTriple);
408 
409   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
410 
411   if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
412     PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
413 
414   // Handle generating dependencies, if requested.
415   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
416   if (!DepOpts.OutputFile.empty())
417     TheDependencyFileGenerator.reset(
418         DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
419   if (!DepOpts.DOTOutputFile.empty())
420     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
421                              getHeaderSearchOpts().Sysroot);
422 
423   // If we don't have a collector, but we are collecting module dependencies,
424   // then we're the top level compiler instance and need to create one.
425   if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
426     ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
427         DepOpts.ModuleDependencyOutputDir);
428   }
429 
430   // If there is a module dep collector, register with other dep collectors
431   // and also (a) collect header maps and (b) TODO: input vfs overlay files.
432   if (ModuleDepCollector) {
433     addDependencyCollector(ModuleDepCollector);
434     collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
435     collectIncludePCH(*this, ModuleDepCollector);
436     collectVFSEntries(*this, ModuleDepCollector);
437   }
438 
439   for (auto &Listener : DependencyCollectors)
440     Listener->attachToPreprocessor(*PP);
441 
442   // Handle generating header include information, if requested.
443   if (DepOpts.ShowHeaderIncludes)
444     AttachHeaderIncludeGen(*PP, DepOpts);
445   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
446     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
447     if (OutputPath == "-")
448       OutputPath = "";
449     AttachHeaderIncludeGen(*PP, DepOpts,
450                            /*ShowAllHeaders=*/true, OutputPath,
451                            /*ShowDepth=*/false);
452   }
453 
454   if (DepOpts.PrintShowIncludes) {
455     AttachHeaderIncludeGen(*PP, DepOpts,
456                            /*ShowAllHeaders=*/true, /*OutputPath=*/"",
457                            /*ShowDepth=*/true, /*MSStyle=*/true);
458   }
459 }
460 
461 std::string CompilerInstance::getSpecificModuleCachePath() {
462   // Set up the module path, including the hash for the
463   // module-creation options.
464   SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
465   if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
466     llvm::sys::path::append(SpecificModuleCache,
467                             getInvocation().getModuleHash());
468   return SpecificModuleCache.str();
469 }
470 
471 // ASTContext
472 
473 void CompilerInstance::createASTContext() {
474   Preprocessor &PP = getPreprocessor();
475   auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
476                                  PP.getIdentifierTable(), PP.getSelectorTable(),
477                                  PP.getBuiltinInfo());
478   Context->InitBuiltinTypes(getTarget(), getAuxTarget());
479   setASTContext(Context);
480 }
481 
482 // ExternalASTSource
483 
484 void CompilerInstance::createPCHExternalASTSource(
485     StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
486     void *DeserializationListener, bool OwnDeserializationListener) {
487   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
488   ModuleManager = createPCHExternalASTSource(
489       Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
490       AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
491       getPCHContainerReader(),
492       getFrontendOpts().ModuleFileExtensions,
493       DeserializationListener,
494       OwnDeserializationListener, Preamble,
495       getFrontendOpts().UseGlobalModuleIndex);
496 }
497 
498 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
499     StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
500     bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
501     const PCHContainerReader &PCHContainerRdr,
502     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
503     void *DeserializationListener, bool OwnDeserializationListener,
504     bool Preamble, bool UseGlobalModuleIndex) {
505   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
506 
507   IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
508       PP, Context, PCHContainerRdr, Extensions,
509       Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation,
510       AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
511       HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
512 
513   // We need the external source to be set up before we read the AST, because
514   // eagerly-deserialized declarations may use it.
515   Context.setExternalSource(Reader.get());
516 
517   Reader->setDeserializationListener(
518       static_cast<ASTDeserializationListener *>(DeserializationListener),
519       /*TakeOwnership=*/OwnDeserializationListener);
520   switch (Reader->ReadAST(Path,
521                           Preamble ? serialization::MK_Preamble
522                                    : serialization::MK_PCH,
523                           SourceLocation(),
524                           ASTReader::ARR_None)) {
525   case ASTReader::Success:
526     // Set the predefines buffer as suggested by the PCH reader. Typically, the
527     // predefines buffer will be empty.
528     PP.setPredefines(Reader->getSuggestedPredefines());
529     return Reader;
530 
531   case ASTReader::Failure:
532     // Unrecoverable failure: don't even try to process the input file.
533     break;
534 
535   case ASTReader::Missing:
536   case ASTReader::OutOfDate:
537   case ASTReader::VersionMismatch:
538   case ASTReader::ConfigurationMismatch:
539   case ASTReader::HadErrors:
540     // No suitable PCH file could be found. Return an error.
541     break;
542   }
543 
544   Context.setExternalSource(nullptr);
545   return nullptr;
546 }
547 
548 // Code Completion
549 
550 static bool EnableCodeCompletion(Preprocessor &PP,
551                                  StringRef Filename,
552                                  unsigned Line,
553                                  unsigned Column) {
554   // Tell the source manager to chop off the given file at a specific
555   // line and column.
556   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
557   if (!Entry) {
558     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
559       << Filename;
560     return true;
561   }
562 
563   // Truncate the named file at the given line/column.
564   PP.SetCodeCompletionPoint(Entry, Line, Column);
565   return false;
566 }
567 
568 void CompilerInstance::createCodeCompletionConsumer() {
569   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
570   if (!CompletionConsumer) {
571     setCodeCompletionConsumer(
572       createCodeCompletionConsumer(getPreprocessor(),
573                                    Loc.FileName, Loc.Line, Loc.Column,
574                                    getFrontendOpts().CodeCompleteOpts,
575                                    llvm::outs()));
576     if (!CompletionConsumer)
577       return;
578   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
579                                   Loc.Line, Loc.Column)) {
580     setCodeCompletionConsumer(nullptr);
581     return;
582   }
583 
584   if (CompletionConsumer->isOutputBinary() &&
585       llvm::sys::ChangeStdoutToBinary()) {
586     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
587     setCodeCompletionConsumer(nullptr);
588   }
589 }
590 
591 void CompilerInstance::createFrontendTimer() {
592   FrontendTimerGroup.reset(
593       new llvm::TimerGroup("frontend", "Clang front-end time report"));
594   FrontendTimer.reset(
595       new llvm::Timer("frontend", "Clang front-end timer",
596                       *FrontendTimerGroup));
597 }
598 
599 CodeCompleteConsumer *
600 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
601                                                StringRef Filename,
602                                                unsigned Line,
603                                                unsigned Column,
604                                                const CodeCompleteOptions &Opts,
605                                                raw_ostream &OS) {
606   if (EnableCodeCompletion(PP, Filename, Line, Column))
607     return nullptr;
608 
609   // Set up the creation routine for code-completion.
610   return new PrintingCodeCompleteConsumer(Opts, OS);
611 }
612 
613 void CompilerInstance::createSema(TranslationUnitKind TUKind,
614                                   CodeCompleteConsumer *CompletionConsumer) {
615   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
616                          TUKind, CompletionConsumer));
617   // Attach the external sema source if there is any.
618   if (ExternalSemaSrc) {
619     TheSema->addExternalSource(ExternalSemaSrc.get());
620     ExternalSemaSrc->InitializeSema(*TheSema);
621   }
622 }
623 
624 // Output Files
625 
626 void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
627   OutputFiles.push_back(std::move(OutFile));
628 }
629 
630 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
631   for (OutputFile &OF : OutputFiles) {
632     if (!OF.TempFilename.empty()) {
633       if (EraseFiles) {
634         llvm::sys::fs::remove(OF.TempFilename);
635       } else {
636         SmallString<128> NewOutFile(OF.Filename);
637 
638         // If '-working-directory' was passed, the output filename should be
639         // relative to that.
640         FileMgr->FixupRelativePath(NewOutFile);
641         if (std::error_code ec =
642                 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
643           getDiagnostics().Report(diag::err_unable_to_rename_temp)
644             << OF.TempFilename << OF.Filename << ec.message();
645 
646           llvm::sys::fs::remove(OF.TempFilename);
647         }
648       }
649     } else if (!OF.Filename.empty() && EraseFiles)
650       llvm::sys::fs::remove(OF.Filename);
651   }
652   OutputFiles.clear();
653   NonSeekStream.reset();
654 }
655 
656 std::unique_ptr<raw_pwrite_stream>
657 CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
658                                           StringRef Extension) {
659   return createOutputFile(getFrontendOpts().OutputFile, Binary,
660                           /*RemoveFileOnSignal=*/true, InFile, Extension,
661                           /*UseTemporary=*/true);
662 }
663 
664 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
665   return llvm::make_unique<llvm::raw_null_ostream>();
666 }
667 
668 std::unique_ptr<raw_pwrite_stream>
669 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
670                                    bool RemoveFileOnSignal, StringRef InFile,
671                                    StringRef Extension, bool UseTemporary,
672                                    bool CreateMissingDirectories) {
673   std::string OutputPathName, TempPathName;
674   std::error_code EC;
675   std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
676       OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
677       UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
678   if (!OS) {
679     getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
680                                                                 << EC.message();
681     return nullptr;
682   }
683 
684   // Add the output file -- but don't try to remove "-", since this means we are
685   // using stdin.
686   addOutputFile(
687       OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName));
688 
689   return OS;
690 }
691 
692 std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
693     StringRef OutputPath, std::error_code &Error, bool Binary,
694     bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
695     bool UseTemporary, bool CreateMissingDirectories,
696     std::string *ResultPathName, std::string *TempPathName) {
697   assert((!CreateMissingDirectories || UseTemporary) &&
698          "CreateMissingDirectories is only allowed when using temporary files");
699 
700   std::string OutFile, TempFile;
701   if (!OutputPath.empty()) {
702     OutFile = OutputPath;
703   } else if (InFile == "-") {
704     OutFile = "-";
705   } else if (!Extension.empty()) {
706     SmallString<128> Path(InFile);
707     llvm::sys::path::replace_extension(Path, Extension);
708     OutFile = Path.str();
709   } else {
710     OutFile = "-";
711   }
712 
713   std::unique_ptr<llvm::raw_fd_ostream> OS;
714   std::string OSFile;
715 
716   if (UseTemporary) {
717     if (OutFile == "-")
718       UseTemporary = false;
719     else {
720       llvm::sys::fs::file_status Status;
721       llvm::sys::fs::status(OutputPath, Status);
722       if (llvm::sys::fs::exists(Status)) {
723         // Fail early if we can't write to the final destination.
724         if (!llvm::sys::fs::can_write(OutputPath)) {
725           Error = make_error_code(llvm::errc::operation_not_permitted);
726           return nullptr;
727         }
728 
729         // Don't use a temporary if the output is a special file. This handles
730         // things like '-o /dev/null'
731         if (!llvm::sys::fs::is_regular_file(Status))
732           UseTemporary = false;
733       }
734     }
735   }
736 
737   if (UseTemporary) {
738     // Create a temporary file.
739     SmallString<128> TempPath;
740     TempPath = OutFile;
741     TempPath += "-%%%%%%%%";
742     int fd;
743     std::error_code EC =
744         llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
745 
746     if (CreateMissingDirectories &&
747         EC == llvm::errc::no_such_file_or_directory) {
748       StringRef Parent = llvm::sys::path::parent_path(OutputPath);
749       EC = llvm::sys::fs::create_directories(Parent);
750       if (!EC) {
751         EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
752       }
753     }
754 
755     if (!EC) {
756       OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
757       OSFile = TempFile = TempPath.str();
758     }
759     // If we failed to create the temporary, fallback to writing to the file
760     // directly. This handles the corner case where we cannot write to the
761     // directory, but can write to the file.
762   }
763 
764   if (!OS) {
765     OSFile = OutFile;
766     OS.reset(new llvm::raw_fd_ostream(
767         OSFile, Error,
768         (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
769     if (Error)
770       return nullptr;
771   }
772 
773   // Make sure the out stream file gets removed if we crash.
774   if (RemoveFileOnSignal)
775     llvm::sys::RemoveFileOnSignal(OSFile);
776 
777   if (ResultPathName)
778     *ResultPathName = OutFile;
779   if (TempPathName)
780     *TempPathName = TempFile;
781 
782   if (!Binary || OS->supportsSeeking())
783     return std::move(OS);
784 
785   auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
786   assert(!NonSeekStream);
787   NonSeekStream = std::move(OS);
788   return std::move(B);
789 }
790 
791 // Initialization Utilities
792 
793 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
794   return InitializeSourceManager(
795       Input, getDiagnostics(), getFileManager(), getSourceManager(),
796       hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr,
797       getDependencyOutputOpts(), getFrontendOpts());
798 }
799 
800 // static
801 bool CompilerInstance::InitializeSourceManager(
802     const FrontendInputFile &Input, DiagnosticsEngine &Diags,
803     FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS,
804     DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) {
805   SrcMgr::CharacteristicKind
806     Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
807 
808   if (Input.isBuffer()) {
809     SourceMgr.setMainFileID(SourceMgr.createFileID(
810         std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind));
811     assert(SourceMgr.getMainFileID().isValid() &&
812            "Couldn't establish MainFileID!");
813     return true;
814   }
815 
816   StringRef InputFile = Input.getFile();
817 
818   // Figure out where to get and map in the main file.
819   if (InputFile != "-") {
820     const FileEntry *File;
821     if (Opts.FindPchSource.empty()) {
822       File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
823     } else {
824       // When building a pch file in clang-cl mode, the .h file is built as if
825       // it was included by a cc file.  Since the driver doesn't know about
826       // all include search directories, the frontend must search the input
827       // file through HeaderSearch here, as if it had been included by the
828       // cc file at Opts.FindPchSource.
829       const FileEntry *FindFile = FileMgr.getFile(Opts.FindPchSource);
830       if (!FindFile) {
831         Diags.Report(diag::err_fe_error_reading) << Opts.FindPchSource;
832         return false;
833       }
834       const DirectoryLookup *UnusedCurDir;
835       SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
836           Includers;
837       Includers.push_back(std::make_pair(FindFile, FindFile->getDir()));
838       File = HS->LookupFile(InputFile, SourceLocation(), /*isAngled=*/false,
839                             /*FromDir=*/nullptr,
840                             /*CurDir=*/UnusedCurDir, Includers,
841                             /*SearchPath=*/nullptr,
842                             /*RelativePath=*/nullptr,
843                             /*RequestingModule=*/nullptr,
844                             /*SuggestedModule=*/nullptr, /*SkipCache=*/true);
845       // Also add the header to /showIncludes output.
846       if (File)
847         DepOpts.ShowIncludesPretendHeader = File->getName();
848     }
849     if (!File) {
850       Diags.Report(diag::err_fe_error_reading) << InputFile;
851       return false;
852     }
853 
854     // The natural SourceManager infrastructure can't currently handle named
855     // pipes, but we would at least like to accept them for the main
856     // file. Detect them here, read them with the volatile flag so FileMgr will
857     // pick up the correct size, and simply override their contents as we do for
858     // STDIN.
859     if (File->isNamedPipe()) {
860       auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
861       if (MB) {
862         // Create a new virtual file that will have the correct size.
863         File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
864         SourceMgr.overrideFileContents(File, std::move(*MB));
865       } else {
866         Diags.Report(diag::err_cannot_open_file) << InputFile
867                                                  << MB.getError().message();
868         return false;
869       }
870     }
871 
872     SourceMgr.setMainFileID(
873         SourceMgr.createFileID(File, SourceLocation(), Kind));
874   } else {
875     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
876         llvm::MemoryBuffer::getSTDIN();
877     if (std::error_code EC = SBOrErr.getError()) {
878       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
879       return false;
880     }
881     std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
882 
883     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
884                                                    SB->getBufferSize(), 0);
885     SourceMgr.setMainFileID(
886         SourceMgr.createFileID(File, SourceLocation(), Kind));
887     SourceMgr.overrideFileContents(File, std::move(SB));
888   }
889 
890   assert(SourceMgr.getMainFileID().isValid() &&
891          "Couldn't establish MainFileID!");
892   return true;
893 }
894 
895 // High-Level Operations
896 
897 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
898   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
899   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
900   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
901 
902   // FIXME: Take this as an argument, once all the APIs we used have moved to
903   // taking it as an input instead of hard-coding llvm::errs.
904   raw_ostream &OS = llvm::errs();
905 
906   // Create the target instance.
907   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
908                                          getInvocation().TargetOpts));
909   if (!hasTarget())
910     return false;
911 
912   // Create TargetInfo for the other side of CUDA compilation.
913   if (getLangOpts().CUDA && !getFrontendOpts().AuxTriple.empty()) {
914     auto TO = std::make_shared<TargetOptions>();
915     TO->Triple = getFrontendOpts().AuxTriple;
916     TO->HostTriple = getTarget().getTriple().str();
917     setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
918   }
919 
920   // Inform the target of the language options.
921   //
922   // FIXME: We shouldn't need to do this, the target should be immutable once
923   // created. This complexity should be lifted elsewhere.
924   getTarget().adjust(getLangOpts());
925 
926   // Adjust target options based on codegen options.
927   getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
928 
929   // rewriter project will change target built-in bool type from its default.
930   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
931     getTarget().noSignedCharForObjCBool();
932 
933   // Validate/process some options.
934   if (getHeaderSearchOpts().Verbose)
935     OS << "clang -cc1 version " CLANG_VERSION_STRING
936        << " based upon " << BACKEND_PACKAGE_STRING
937        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
938 
939   if (getFrontendOpts().ShowTimers)
940     createFrontendTimer();
941 
942   if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
943     llvm::EnableStatistics(false);
944 
945   for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
946     // Reset the ID tables if we are reusing the SourceManager and parsing
947     // regular files.
948     if (hasSourceManager() && !Act.isModelParsingAction())
949       getSourceManager().clearIDTables();
950 
951     if (Act.BeginSourceFile(*this, FIF)) {
952       Act.Execute();
953       Act.EndSourceFile();
954     }
955   }
956 
957   // Notify the diagnostic client that all files were processed.
958   getDiagnostics().getClient()->finish();
959 
960   if (getDiagnosticOpts().ShowCarets) {
961     // We can have multiple diagnostics sharing one diagnostic client.
962     // Get the total number of warnings/errors from the client.
963     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
964     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
965 
966     if (NumWarnings)
967       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
968     if (NumWarnings && NumErrors)
969       OS << " and ";
970     if (NumErrors)
971       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
972     if (NumWarnings || NumErrors)
973       OS << " generated.\n";
974   }
975 
976   if (getFrontendOpts().ShowStats) {
977     if (hasFileManager()) {
978       getFileManager().PrintStats();
979       OS << '\n';
980     }
981     llvm::PrintStatistics(OS);
982   }
983   StringRef StatsFile = getFrontendOpts().StatsFile;
984   if (!StatsFile.empty()) {
985     std::error_code EC;
986     auto StatS = llvm::make_unique<llvm::raw_fd_ostream>(StatsFile, EC,
987                                                          llvm::sys::fs::F_Text);
988     if (EC) {
989       getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
990           << StatsFile << EC.message();
991     } else {
992       llvm::PrintStatisticsJSON(*StatS);
993     }
994   }
995 
996   return !getDiagnostics().getClient()->getNumErrors();
997 }
998 
999 /// \brief Determine the appropriate source input kind based on language
1000 /// options.
1001 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
1002   if (LangOpts.OpenCL)
1003     return IK_OpenCL;
1004   if (LangOpts.CUDA)
1005     return IK_CUDA;
1006   if (LangOpts.ObjC1)
1007     return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
1008   return LangOpts.CPlusPlus? IK_CXX : IK_C;
1009 }
1010 
1011 /// \brief Compile a module file for the given module, using the options
1012 /// provided by the importing compiler instance. Returns true if the module
1013 /// was built without errors.
1014 static bool compileModuleImpl(CompilerInstance &ImportingInstance,
1015                               SourceLocation ImportLoc,
1016                               Module *Module,
1017                               StringRef ModuleFileName) {
1018   ModuleMap &ModMap
1019     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1020 
1021   // Construct a compiler invocation for creating this module.
1022   IntrusiveRefCntPtr<CompilerInvocation> Invocation
1023     (new CompilerInvocation(ImportingInstance.getInvocation()));
1024 
1025   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1026 
1027   // For any options that aren't intended to affect how a module is built,
1028   // reset them to their default values.
1029   Invocation->getLangOpts()->resetNonModularOptions();
1030   PPOpts.resetNonModularOptions();
1031 
1032   // Remove any macro definitions that are explicitly ignored by the module.
1033   // They aren't supposed to affect how the module is built anyway.
1034   const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1035   PPOpts.Macros.erase(
1036       std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1037                      [&HSOpts](const std::pair<std::string, bool> &def) {
1038         StringRef MacroDef = def.first;
1039         return HSOpts.ModulesIgnoreMacros.count(
1040                    llvm::CachedHashString(MacroDef.split('=').first)) > 0;
1041       }),
1042       PPOpts.Macros.end());
1043 
1044   // Note the name of the module we're building.
1045   Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
1046 
1047   // Make sure that the failed-module structure has been allocated in
1048   // the importing instance, and propagate the pointer to the newly-created
1049   // instance.
1050   PreprocessorOptions &ImportingPPOpts
1051     = ImportingInstance.getInvocation().getPreprocessorOpts();
1052   if (!ImportingPPOpts.FailedModules)
1053     ImportingPPOpts.FailedModules =
1054         std::make_shared<PreprocessorOptions::FailedModulesSet>();
1055   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
1056 
1057   // If there is a module map file, build the module using the module map.
1058   // Set up the inputs/outputs so that we build the module from its umbrella
1059   // header.
1060   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1061   FrontendOpts.OutputFile = ModuleFileName.str();
1062   FrontendOpts.DisableFree = false;
1063   FrontendOpts.GenerateGlobalModuleIndex = false;
1064   FrontendOpts.BuildingImplicitModule = true;
1065   FrontendOpts.Inputs.clear();
1066   InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
1067 
1068   // Don't free the remapped file buffers; they are owned by our caller.
1069   PPOpts.RetainRemappedFileBuffers = true;
1070 
1071   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1072   assert(ImportingInstance.getInvocation().getModuleHash() ==
1073          Invocation->getModuleHash() && "Module hash mismatch!");
1074 
1075   // Construct a compiler instance that will be used to actually create the
1076   // module.
1077   CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1078                             /*BuildingModule=*/true);
1079   Instance.setInvocation(&*Invocation);
1080 
1081   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1082                                    ImportingInstance.getDiagnosticClient()),
1083                              /*ShouldOwnClient=*/true);
1084 
1085   Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
1086 
1087   // Note that this module is part of the module build stack, so that we
1088   // can detect cycles in the module graph.
1089   Instance.setFileManager(&ImportingInstance.getFileManager());
1090   Instance.createSourceManager(Instance.getFileManager());
1091   SourceManager &SourceMgr = Instance.getSourceManager();
1092   SourceMgr.setModuleBuildStack(
1093     ImportingInstance.getSourceManager().getModuleBuildStack());
1094   SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
1095     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1096 
1097   // If we're collecting module dependencies, we need to share a collector
1098   // between all of the module CompilerInstances. Other than that, we don't
1099   // want to produce any dependency output from the module build.
1100   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1101   Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
1102 
1103   // Get or create the module map that we'll use to build this module.
1104   std::string InferredModuleMapContent;
1105   if (const FileEntry *ModuleMapFile =
1106           ModMap.getContainingModuleMapFile(Module)) {
1107     // Use the module map where this module resides.
1108     FrontendOpts.Inputs.emplace_back(ModuleMapFile->getName(), IK);
1109   } else {
1110     SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1111     llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1112     FrontendOpts.Inputs.emplace_back(FakeModuleMapFile, IK);
1113 
1114     llvm::raw_string_ostream OS(InferredModuleMapContent);
1115     Module->print(OS);
1116     OS.flush();
1117 
1118     std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1119         llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1120     ModuleMapFile = Instance.getFileManager().getVirtualFile(
1121         FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1122     SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer));
1123   }
1124 
1125   // Construct a module-generating action. Passing through the module map is
1126   // safe because the FileManager is shared between the compiler instances.
1127   GenerateModuleFromModuleMapAction CreateModuleAction(
1128       ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
1129 
1130   ImportingInstance.getDiagnostics().Report(ImportLoc,
1131                                             diag::remark_module_build)
1132     << Module->Name << ModuleFileName;
1133 
1134   // Execute the action to actually build the module in-place. Use a separate
1135   // thread so that we get a stack large enough.
1136   const unsigned ThreadStackSize = 8 << 20;
1137   llvm::CrashRecoveryContext CRC;
1138   CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
1139                         ThreadStackSize);
1140 
1141   ImportingInstance.getDiagnostics().Report(ImportLoc,
1142                                             diag::remark_module_build_done)
1143     << Module->Name;
1144 
1145   // Delete the temporary module map file.
1146   // FIXME: Even though we're executing under crash protection, it would still
1147   // be nice to do this with RemoveFileOnSignal when we can. However, that
1148   // doesn't make sense for all clients, so clean this up manually.
1149   Instance.clearOutputFiles(/*EraseFiles=*/true);
1150 
1151   // We've rebuilt a module. If we're allowed to generate or update the global
1152   // module index, record that fact in the importing compiler instance.
1153   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1154     ImportingInstance.setBuildGlobalModuleIndex(true);
1155   }
1156 
1157   return !Instance.getDiagnostics().hasErrorOccurred();
1158 }
1159 
1160 static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
1161                                  SourceLocation ImportLoc,
1162                                  SourceLocation ModuleNameLoc, Module *Module,
1163                                  StringRef ModuleFileName) {
1164   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1165 
1166   auto diagnoseBuildFailure = [&] {
1167     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1168         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1169   };
1170 
1171   // FIXME: have LockFileManager return an error_code so that we can
1172   // avoid the mkdir when the directory already exists.
1173   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1174   llvm::sys::fs::create_directories(Dir);
1175 
1176   while (1) {
1177     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1178     llvm::LockFileManager Locked(ModuleFileName);
1179     switch (Locked) {
1180     case llvm::LockFileManager::LFS_Error:
1181       Diags.Report(ModuleNameLoc, diag::err_module_lock_failure)
1182           << Module->Name << Locked.getErrorMessage();
1183       return false;
1184 
1185     case llvm::LockFileManager::LFS_Owned:
1186       // We're responsible for building the module ourselves.
1187       if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
1188                              ModuleFileName)) {
1189         diagnoseBuildFailure();
1190         return false;
1191       }
1192       break;
1193 
1194     case llvm::LockFileManager::LFS_Shared:
1195       // Someone else is responsible for building the module. Wait for them to
1196       // finish.
1197       switch (Locked.waitForUnlock()) {
1198       case llvm::LockFileManager::Res_Success:
1199         ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1200         break;
1201       case llvm::LockFileManager::Res_OwnerDied:
1202         continue; // try again to get the lock.
1203       case llvm::LockFileManager::Res_Timeout:
1204         Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout)
1205             << Module->Name;
1206         // Clear the lock file so that future invokations can make progress.
1207         Locked.unsafeRemoveLockFile();
1208         return false;
1209       }
1210       break;
1211     }
1212 
1213     // Try to read the module file, now that we've compiled it.
1214     ASTReader::ASTReadResult ReadResult =
1215         ImportingInstance.getModuleManager()->ReadAST(
1216             ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1217             ModuleLoadCapabilities);
1218 
1219     if (ReadResult == ASTReader::OutOfDate &&
1220         Locked == llvm::LockFileManager::LFS_Shared) {
1221       // The module may be out of date in the presence of file system races,
1222       // or if one of its imports depends on header search paths that are not
1223       // consistent with this ImportingInstance.  Try again...
1224       continue;
1225     } else if (ReadResult == ASTReader::Missing) {
1226       diagnoseBuildFailure();
1227     } else if (ReadResult != ASTReader::Success &&
1228                !Diags.hasErrorOccurred()) {
1229       // The ASTReader didn't diagnose the error, so conservatively report it.
1230       diagnoseBuildFailure();
1231     }
1232     return ReadResult == ASTReader::Success;
1233   }
1234 }
1235 
1236 /// \brief Diagnose differences between the current definition of the given
1237 /// configuration macro and the definition provided on the command line.
1238 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1239                              Module *Mod, SourceLocation ImportLoc) {
1240   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1241   SourceManager &SourceMgr = PP.getSourceManager();
1242 
1243   // If this identifier has never had a macro definition, then it could
1244   // not have changed.
1245   if (!Id->hadMacroDefinition())
1246     return;
1247   auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1248 
1249   // Find the macro definition from the command line.
1250   MacroInfo *CmdLineDefinition = nullptr;
1251   for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1252     // We only care about the predefines buffer.
1253     FileID FID = SourceMgr.getFileID(MD->getLocation());
1254     if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1255       continue;
1256     if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1257       CmdLineDefinition = DMD->getMacroInfo();
1258     break;
1259   }
1260 
1261   auto *CurrentDefinition = PP.getMacroInfo(Id);
1262   if (CurrentDefinition == CmdLineDefinition) {
1263     // Macro matches. Nothing to do.
1264   } else if (!CurrentDefinition) {
1265     // This macro was defined on the command line, then #undef'd later.
1266     // Complain.
1267     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1268       << true << ConfigMacro << Mod->getFullModuleName();
1269     auto LatestDef = LatestLocalMD->getDefinition();
1270     assert(LatestDef.isUndefined() &&
1271            "predefined macro went away with no #undef?");
1272     PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1273       << true;
1274     return;
1275   } else if (!CmdLineDefinition) {
1276     // There was no definition for this macro in the predefines buffer,
1277     // but there was a local definition. Complain.
1278     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1279       << false << ConfigMacro << Mod->getFullModuleName();
1280     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1281             diag::note_module_def_undef_here)
1282       << false;
1283   } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1284                                                /*Syntactically=*/true)) {
1285     // The macro definitions differ.
1286     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1287       << false << ConfigMacro << Mod->getFullModuleName();
1288     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1289             diag::note_module_def_undef_here)
1290       << false;
1291   }
1292 }
1293 
1294 /// \brief Write a new timestamp file with the given path.
1295 static void writeTimestampFile(StringRef TimestampFile) {
1296   std::error_code EC;
1297   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1298 }
1299 
1300 /// \brief Prune the module cache of modules that haven't been accessed in
1301 /// a long time.
1302 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1303   struct stat StatBuf;
1304   llvm::SmallString<128> TimestampFile;
1305   TimestampFile = HSOpts.ModuleCachePath;
1306   assert(!TimestampFile.empty());
1307   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1308 
1309   // Try to stat() the timestamp file.
1310   if (::stat(TimestampFile.c_str(), &StatBuf)) {
1311     // If the timestamp file wasn't there, create one now.
1312     if (errno == ENOENT) {
1313       writeTimestampFile(TimestampFile);
1314     }
1315     return;
1316   }
1317 
1318   // Check whether the time stamp is older than our pruning interval.
1319   // If not, do nothing.
1320   time_t TimeStampModTime = StatBuf.st_mtime;
1321   time_t CurrentTime = time(nullptr);
1322   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1323     return;
1324 
1325   // Write a new timestamp file so that nobody else attempts to prune.
1326   // There is a benign race condition here, if two Clang instances happen to
1327   // notice at the same time that the timestamp is out-of-date.
1328   writeTimestampFile(TimestampFile);
1329 
1330   // Walk the entire module cache, looking for unused module files and module
1331   // indices.
1332   std::error_code EC;
1333   SmallString<128> ModuleCachePathNative;
1334   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1335   for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1336        Dir != DirEnd && !EC; Dir.increment(EC)) {
1337     // If we don't have a directory, there's nothing to look into.
1338     if (!llvm::sys::fs::is_directory(Dir->path()))
1339       continue;
1340 
1341     // Walk all of the files within this directory.
1342     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1343          File != FileEnd && !EC; File.increment(EC)) {
1344       // We only care about module and global module index files.
1345       StringRef Extension = llvm::sys::path::extension(File->path());
1346       if (Extension != ".pcm" && Extension != ".timestamp" &&
1347           llvm::sys::path::filename(File->path()) != "modules.idx")
1348         continue;
1349 
1350       // Look at this file. If we can't stat it, there's nothing interesting
1351       // there.
1352       if (::stat(File->path().c_str(), &StatBuf))
1353         continue;
1354 
1355       // If the file has been used recently enough, leave it there.
1356       time_t FileAccessTime = StatBuf.st_atime;
1357       if (CurrentTime - FileAccessTime <=
1358               time_t(HSOpts.ModuleCachePruneAfter)) {
1359         continue;
1360       }
1361 
1362       // Remove the file.
1363       llvm::sys::fs::remove(File->path());
1364 
1365       // Remove the timestamp file.
1366       std::string TimpestampFilename = File->path() + ".timestamp";
1367       llvm::sys::fs::remove(TimpestampFilename);
1368     }
1369 
1370     // If we removed all of the files in the directory, remove the directory
1371     // itself.
1372     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1373             llvm::sys::fs::directory_iterator() && !EC)
1374       llvm::sys::fs::remove(Dir->path());
1375   }
1376 }
1377 
1378 void CompilerInstance::createModuleManager() {
1379   if (!ModuleManager) {
1380     if (!hasASTContext())
1381       createASTContext();
1382 
1383     // If we're implicitly building modules but not currently recursively
1384     // building a module, check whether we need to prune the module cache.
1385     if (getSourceManager().getModuleBuildStack().empty() &&
1386         !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1387         getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1388         getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1389       pruneModuleCache(getHeaderSearchOpts());
1390     }
1391 
1392     HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1393     std::string Sysroot = HSOpts.Sysroot;
1394     const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1395     std::unique_ptr<llvm::Timer> ReadTimer;
1396     if (FrontendTimerGroup)
1397       ReadTimer = llvm::make_unique<llvm::Timer>("reading_modules",
1398                                                  "Reading modules",
1399                                                  *FrontendTimerGroup);
1400     ModuleManager = new ASTReader(
1401         getPreprocessor(), getASTContext(), getPCHContainerReader(),
1402         getFrontendOpts().ModuleFileExtensions,
1403         Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
1404         /*AllowASTWithCompilerErrors=*/false,
1405         /*AllowConfigurationMismatch=*/false,
1406         HSOpts.ModulesValidateSystemHeaders,
1407         getFrontendOpts().UseGlobalModuleIndex,
1408         std::move(ReadTimer));
1409     if (hasASTConsumer()) {
1410       ModuleManager->setDeserializationListener(
1411         getASTConsumer().GetASTDeserializationListener());
1412       getASTContext().setASTMutationListener(
1413         getASTConsumer().GetASTMutationListener());
1414     }
1415     getASTContext().setExternalSource(ModuleManager);
1416     if (hasSema())
1417       ModuleManager->InitializeSema(getSema());
1418     if (hasASTConsumer())
1419       ModuleManager->StartTranslationUnit(&getASTConsumer());
1420 
1421     if (TheDependencyFileGenerator)
1422       TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1423     for (auto &Listener : DependencyCollectors)
1424       Listener->attachToASTReader(*ModuleManager);
1425   }
1426 }
1427 
1428 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1429   llvm::Timer Timer;
1430   if (FrontendTimerGroup)
1431     Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1432                *FrontendTimerGroup);
1433   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1434 
1435   // Helper to recursively read the module names for all modules we're adding.
1436   // We mark these as known and redirect any attempt to load that module to
1437   // the files we were handed.
1438   struct ReadModuleNames : ASTReaderListener {
1439     CompilerInstance &CI;
1440     llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
1441 
1442     ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
1443 
1444     void ReadModuleName(StringRef ModuleName) override {
1445       LoadedModules.push_back(
1446           CI.getPreprocessor().getIdentifierInfo(ModuleName));
1447     }
1448 
1449     void registerAll() {
1450       for (auto *II : LoadedModules) {
1451         CI.KnownModules[II] = CI.getPreprocessor()
1452                                   .getHeaderSearchInfo()
1453                                   .getModuleMap()
1454                                   .findModule(II->getName());
1455       }
1456       LoadedModules.clear();
1457     }
1458 
1459     void markAllUnavailable() {
1460       for (auto *II : LoadedModules) {
1461         if (Module *M = CI.getPreprocessor()
1462                             .getHeaderSearchInfo()
1463                             .getModuleMap()
1464                             .findModule(II->getName())) {
1465           M->HasIncompatibleModuleFile = true;
1466 
1467           // Mark module as available if the only reason it was unavailable
1468           // was missing headers.
1469           SmallVector<Module *, 2> Stack;
1470           Stack.push_back(M);
1471           while (!Stack.empty()) {
1472             Module *Current = Stack.pop_back_val();
1473             if (Current->IsMissingRequirement) continue;
1474             Current->IsAvailable = true;
1475             Stack.insert(Stack.end(),
1476                          Current->submodule_begin(), Current->submodule_end());
1477           }
1478         }
1479       }
1480       LoadedModules.clear();
1481     }
1482   };
1483 
1484   // If we don't already have an ASTReader, create one now.
1485   if (!ModuleManager)
1486     createModuleManager();
1487 
1488   auto Listener = llvm::make_unique<ReadModuleNames>(*this);
1489   auto &ListenerRef = *Listener;
1490   ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
1491                                                    std::move(Listener));
1492 
1493   // Try to load the module file.
1494   switch (ModuleManager->ReadAST(FileName, serialization::MK_ExplicitModule,
1495                                  SourceLocation(),
1496                                  ASTReader::ARR_ConfigurationMismatch)) {
1497   case ASTReader::Success:
1498     // We successfully loaded the module file; remember the set of provided
1499     // modules so that we don't try to load implicit modules for them.
1500     ListenerRef.registerAll();
1501     return true;
1502 
1503   case ASTReader::ConfigurationMismatch:
1504     // Ignore unusable module files.
1505     getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1506         << FileName;
1507     // All modules provided by any files we tried and failed to load are now
1508     // unavailable; includes of those modules should now be handled textually.
1509     ListenerRef.markAllUnavailable();
1510     return true;
1511 
1512   default:
1513     return false;
1514   }
1515 }
1516 
1517 ModuleLoadResult
1518 CompilerInstance::loadModule(SourceLocation ImportLoc,
1519                              ModuleIdPath Path,
1520                              Module::NameVisibilityKind Visibility,
1521                              bool IsInclusionDirective) {
1522   // Determine what file we're searching from.
1523   StringRef ModuleName = Path[0].first->getName();
1524   SourceLocation ModuleNameLoc = Path[0].second;
1525 
1526   // If we've already handled this import, just return the cached result.
1527   // This one-element cache is important to eliminate redundant diagnostics
1528   // when both the preprocessor and parser see the same import declaration.
1529   if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1530     // Make the named module visible.
1531     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1532       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1533                                        ImportLoc);
1534     return LastModuleImportResult;
1535   }
1536 
1537   clang::Module *Module = nullptr;
1538 
1539   // If we don't already have information on this module, load the module now.
1540   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1541     = KnownModules.find(Path[0].first);
1542   if (Known != KnownModules.end()) {
1543     // Retrieve the cached top-level module.
1544     Module = Known->second;
1545   } else if (ModuleName == getLangOpts().CurrentModule) {
1546     // This is the module we're building.
1547     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1548     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1549   } else {
1550     // Search for a module with the given name.
1551     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1552     HeaderSearchOptions &HSOpts =
1553         PP->getHeaderSearchInfo().getHeaderSearchOpts();
1554 
1555     std::string ModuleFileName;
1556     bool LoadFromPrebuiltModulePath = false;
1557     // We try to load the module from the prebuilt module paths. If not
1558     // successful, we then try to find it in the module cache.
1559     if (!HSOpts.PrebuiltModulePaths.empty()) {
1560       // Load the module from the prebuilt module path.
1561       ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(
1562           ModuleName, "", /*UsePrebuiltPath*/ true);
1563       if (!ModuleFileName.empty())
1564         LoadFromPrebuiltModulePath = true;
1565     }
1566     if (!LoadFromPrebuiltModulePath && Module) {
1567       // Load the module from the module cache.
1568       ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module);
1569     } else if (!LoadFromPrebuiltModulePath) {
1570       // We can't find a module, error out here.
1571       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1572       << ModuleName
1573       << SourceRange(ImportLoc, ModuleNameLoc);
1574       ModuleBuildFailed = true;
1575       return ModuleLoadResult();
1576     }
1577 
1578     if (ModuleFileName.empty()) {
1579       if (Module && Module->HasIncompatibleModuleFile) {
1580         // We tried and failed to load a module file for this module. Fall
1581         // back to textual inclusion for its headers.
1582         return ModuleLoadResult::ConfigMismatch;
1583       }
1584 
1585       getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1586           << ModuleName;
1587       ModuleBuildFailed = true;
1588       return ModuleLoadResult();
1589     }
1590 
1591     // If we don't already have an ASTReader, create one now.
1592     if (!ModuleManager)
1593       createModuleManager();
1594 
1595     llvm::Timer Timer;
1596     if (FrontendTimerGroup)
1597       Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName,
1598                  *FrontendTimerGroup);
1599     llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1600 
1601     // Try to load the module file. If we are trying to load from the prebuilt
1602     // module path, we don't have the module map files and don't know how to
1603     // rebuild modules.
1604     unsigned ARRFlags = LoadFromPrebuiltModulePath ?
1605                         ASTReader::ARR_ConfigurationMismatch :
1606                         ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
1607     switch (ModuleManager->ReadAST(ModuleFileName,
1608                                    LoadFromPrebuiltModulePath ?
1609                                    serialization::MK_PrebuiltModule :
1610                                    serialization::MK_ImplicitModule,
1611                                    ImportLoc,
1612                                    ARRFlags)) {
1613     case ASTReader::Success: {
1614       if (LoadFromPrebuiltModulePath && !Module) {
1615         Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1616         if (!Module || !Module->getASTFile() ||
1617             FileMgr->getFile(ModuleFileName) != Module->getASTFile()) {
1618           // Error out if Module does not refer to the file in the prebuilt
1619           // module path.
1620           getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1621               << ModuleName;
1622           ModuleBuildFailed = true;
1623           KnownModules[Path[0].first] = nullptr;
1624           return ModuleLoadResult();
1625         }
1626       }
1627       break;
1628     }
1629 
1630     case ASTReader::OutOfDate:
1631     case ASTReader::Missing: {
1632       if (LoadFromPrebuiltModulePath) {
1633         // We can't rebuild the module without a module map. Since ReadAST
1634         // already produces diagnostics for these two cases, we simply
1635         // error out here.
1636         ModuleBuildFailed = true;
1637         KnownModules[Path[0].first] = nullptr;
1638         return ModuleLoadResult();
1639       }
1640 
1641       // The module file is missing or out-of-date. Build it.
1642       assert(Module && "missing module file");
1643       // Check whether there is a cycle in the module graph.
1644       ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1645       ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1646       for (; Pos != PosEnd; ++Pos) {
1647         if (Pos->first == ModuleName)
1648           break;
1649       }
1650 
1651       if (Pos != PosEnd) {
1652         SmallString<256> CyclePath;
1653         for (; Pos != PosEnd; ++Pos) {
1654           CyclePath += Pos->first;
1655           CyclePath += " -> ";
1656         }
1657         CyclePath += ModuleName;
1658 
1659         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1660           << ModuleName << CyclePath;
1661         return ModuleLoadResult();
1662       }
1663 
1664       // Check whether we have already attempted to build this module (but
1665       // failed).
1666       if (getPreprocessorOpts().FailedModules &&
1667           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1668         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1669           << ModuleName
1670           << SourceRange(ImportLoc, ModuleNameLoc);
1671         ModuleBuildFailed = true;
1672         return ModuleLoadResult();
1673       }
1674 
1675       // Try to compile and then load the module.
1676       if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1677                                 ModuleFileName)) {
1678         assert(getDiagnostics().hasErrorOccurred() &&
1679                "undiagnosed error in compileAndLoadModule");
1680         if (getPreprocessorOpts().FailedModules)
1681           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1682         KnownModules[Path[0].first] = nullptr;
1683         ModuleBuildFailed = true;
1684         return ModuleLoadResult();
1685       }
1686 
1687       // Okay, we've rebuilt and now loaded the module.
1688       break;
1689     }
1690 
1691     case ASTReader::ConfigurationMismatch:
1692       if (LoadFromPrebuiltModulePath)
1693         getDiagnostics().Report(SourceLocation(),
1694                                 diag::warn_module_config_mismatch)
1695             << ModuleFileName;
1696       // Fall through to error out.
1697     case ASTReader::VersionMismatch:
1698     case ASTReader::HadErrors:
1699       ModuleLoader::HadFatalFailure = true;
1700       // FIXME: The ASTReader will already have complained, but can we shoehorn
1701       // that diagnostic information into a more useful form?
1702       KnownModules[Path[0].first] = nullptr;
1703       return ModuleLoadResult();
1704 
1705     case ASTReader::Failure:
1706       ModuleLoader::HadFatalFailure = true;
1707       // Already complained, but note now that we failed.
1708       KnownModules[Path[0].first] = nullptr;
1709       ModuleBuildFailed = true;
1710       return ModuleLoadResult();
1711     }
1712 
1713     // Cache the result of this top-level module lookup for later.
1714     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1715   }
1716 
1717   // If we never found the module, fail.
1718   if (!Module)
1719     return ModuleLoadResult();
1720 
1721   // Verify that the rest of the module path actually corresponds to
1722   // a submodule.
1723   if (Path.size() > 1) {
1724     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1725       StringRef Name = Path[I].first->getName();
1726       clang::Module *Sub = Module->findSubmodule(Name);
1727 
1728       if (!Sub) {
1729         // Attempt to perform typo correction to find a module name that works.
1730         SmallVector<StringRef, 2> Best;
1731         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1732 
1733         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1734                                             JEnd = Module->submodule_end();
1735              J != JEnd; ++J) {
1736           unsigned ED = Name.edit_distance((*J)->Name,
1737                                            /*AllowReplacements=*/true,
1738                                            BestEditDistance);
1739           if (ED <= BestEditDistance) {
1740             if (ED < BestEditDistance) {
1741               Best.clear();
1742               BestEditDistance = ED;
1743             }
1744 
1745             Best.push_back((*J)->Name);
1746           }
1747         }
1748 
1749         // If there was a clear winner, user it.
1750         if (Best.size() == 1) {
1751           getDiagnostics().Report(Path[I].second,
1752                                   diag::err_no_submodule_suggest)
1753             << Path[I].first << Module->getFullModuleName() << Best[0]
1754             << SourceRange(Path[0].second, Path[I-1].second)
1755             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1756                                             Best[0]);
1757 
1758           Sub = Module->findSubmodule(Best[0]);
1759         }
1760       }
1761 
1762       if (!Sub) {
1763         // No submodule by this name. Complain, and don't look for further
1764         // submodules.
1765         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1766           << Path[I].first << Module->getFullModuleName()
1767           << SourceRange(Path[0].second, Path[I-1].second);
1768         break;
1769       }
1770 
1771       Module = Sub;
1772     }
1773   }
1774 
1775   // Make the named module visible, if it's not already part of the module
1776   // we are parsing.
1777   if (ModuleName != getLangOpts().CurrentModule) {
1778     if (!Module->IsFromModuleFile) {
1779       // We have an umbrella header or directory that doesn't actually include
1780       // all of the headers within the directory it covers. Complain about
1781       // this missing submodule and recover by forgetting that we ever saw
1782       // this submodule.
1783       // FIXME: Should we detect this at module load time? It seems fairly
1784       // expensive (and rare).
1785       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1786         << Module->getFullModuleName()
1787         << SourceRange(Path.front().second, Path.back().second);
1788 
1789       return ModuleLoadResult::MissingExpected;
1790     }
1791 
1792     // Check whether this module is available.
1793     clang::Module::Requirement Requirement;
1794     clang::Module::UnresolvedHeaderDirective MissingHeader;
1795     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
1796                              MissingHeader)) {
1797       if (MissingHeader.FileNameLoc.isValid()) {
1798         getDiagnostics().Report(MissingHeader.FileNameLoc,
1799                                 diag::err_module_header_missing)
1800           << MissingHeader.IsUmbrella << MissingHeader.FileName;
1801       } else {
1802         getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1803           << Module->getFullModuleName()
1804           << Requirement.second << Requirement.first
1805           << SourceRange(Path.front().second, Path.back().second);
1806       }
1807       LastModuleImportLoc = ImportLoc;
1808       LastModuleImportResult = ModuleLoadResult();
1809       return ModuleLoadResult();
1810     }
1811 
1812     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1813   }
1814 
1815   // Check for any configuration macros that have changed.
1816   clang::Module *TopModule = Module->getTopLevelModule();
1817   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1818     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1819                      Module, ImportLoc);
1820   }
1821 
1822   LastModuleImportLoc = ImportLoc;
1823   LastModuleImportResult = ModuleLoadResult(Module);
1824   return LastModuleImportResult;
1825 }
1826 
1827 void CompilerInstance::makeModuleVisible(Module *Mod,
1828                                          Module::NameVisibilityKind Visibility,
1829                                          SourceLocation ImportLoc) {
1830   if (!ModuleManager)
1831     createModuleManager();
1832   if (!ModuleManager)
1833     return;
1834 
1835   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
1836 }
1837 
1838 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
1839     SourceLocation TriggerLoc) {
1840   if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
1841     return nullptr;
1842   if (!ModuleManager)
1843     createModuleManager();
1844   // Can't do anything if we don't have the module manager.
1845   if (!ModuleManager)
1846     return nullptr;
1847   // Get an existing global index.  This loads it if not already
1848   // loaded.
1849   ModuleManager->loadGlobalIndex();
1850   GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1851   // If the global index doesn't exist, create it.
1852   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
1853       hasPreprocessor()) {
1854     llvm::sys::fs::create_directories(
1855       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1856     GlobalModuleIndex::writeIndex(
1857         getFileManager(), getPCHContainerReader(),
1858         getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1859     ModuleManager->resetForReload();
1860     ModuleManager->loadGlobalIndex();
1861     GlobalIndex = ModuleManager->getGlobalIndex();
1862   }
1863   // For finding modules needing to be imported for fixit messages,
1864   // we need to make the global index cover all modules, so we do that here.
1865   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
1866     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1867     bool RecreateIndex = false;
1868     for (ModuleMap::module_iterator I = MMap.module_begin(),
1869         E = MMap.module_end(); I != E; ++I) {
1870       Module *TheModule = I->second;
1871       const FileEntry *Entry = TheModule->getASTFile();
1872       if (!Entry) {
1873         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1874         Path.push_back(std::make_pair(
1875             getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
1876         std::reverse(Path.begin(), Path.end());
1877         // Load a module as hidden.  This also adds it to the global index.
1878         loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
1879         RecreateIndex = true;
1880       }
1881     }
1882     if (RecreateIndex) {
1883       GlobalModuleIndex::writeIndex(
1884           getFileManager(), getPCHContainerReader(),
1885           getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1886       ModuleManager->resetForReload();
1887       ModuleManager->loadGlobalIndex();
1888       GlobalIndex = ModuleManager->getGlobalIndex();
1889     }
1890     HaveFullGlobalModuleIndex = true;
1891   }
1892   return GlobalIndex;
1893 }
1894 
1895 // Check global module index for missing imports.
1896 bool
1897 CompilerInstance::lookupMissingImports(StringRef Name,
1898                                        SourceLocation TriggerLoc) {
1899   // Look for the symbol in non-imported modules, but only if an error
1900   // actually occurred.
1901   if (!buildingModule()) {
1902     // Load global module index, or retrieve a previously loaded one.
1903     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
1904       TriggerLoc);
1905 
1906     // Only if we have a global index.
1907     if (GlobalIndex) {
1908       GlobalModuleIndex::HitSet FoundModules;
1909 
1910       // Find the modules that reference the identifier.
1911       // Note that this only finds top-level modules.
1912       // We'll let diagnoseTypo find the actual declaration module.
1913       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
1914         return true;
1915     }
1916   }
1917 
1918   return false;
1919 }
1920 void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }
1921 
1922 void CompilerInstance::setExternalSemaSource(
1923     IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
1924   ExternalSemaSrc = std::move(ESS);
1925 }
1926