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