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