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