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