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