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