xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision ee4e08ba94e2ee04ad7ad0e0e396147be417c79f)
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(), DeserializationListener,
412       OwnDeserializationListener, Preamble,
413       getFrontendOpts().UseGlobalModuleIndex);
414 }
415 
416 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
417     StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
418     bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
419     const PCHContainerReader &PCHContainerRdr,
420     void *DeserializationListener, bool OwnDeserializationListener,
421     bool Preamble, bool UseGlobalModuleIndex) {
422   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
423 
424   IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
425       PP, Context, PCHContainerRdr, Sysroot.empty() ? "" : Sysroot.data(),
426       DisablePCHValidation, AllowPCHWithCompilerErrors,
427       /*AllowConfigurationMismatch*/ false, HSOpts.ModulesValidateSystemHeaders,
428       UseGlobalModuleIndex));
429 
430   // We need the external source to be set up before we read the AST, because
431   // eagerly-deserialized declarations may use it.
432   Context.setExternalSource(Reader.get());
433 
434   Reader->setDeserializationListener(
435       static_cast<ASTDeserializationListener *>(DeserializationListener),
436       /*TakeOwnership=*/OwnDeserializationListener);
437   switch (Reader->ReadAST(Path,
438                           Preamble ? serialization::MK_Preamble
439                                    : serialization::MK_PCH,
440                           SourceLocation(),
441                           ASTReader::ARR_None)) {
442   case ASTReader::Success:
443     // Set the predefines buffer as suggested by the PCH reader. Typically, the
444     // predefines buffer will be empty.
445     PP.setPredefines(Reader->getSuggestedPredefines());
446     return Reader;
447 
448   case ASTReader::Failure:
449     // Unrecoverable failure: don't even try to process the input file.
450     break;
451 
452   case ASTReader::Missing:
453   case ASTReader::OutOfDate:
454   case ASTReader::VersionMismatch:
455   case ASTReader::ConfigurationMismatch:
456   case ASTReader::HadErrors:
457     // No suitable PCH file could be found. Return an error.
458     break;
459   }
460 
461   Context.setExternalSource(nullptr);
462   return nullptr;
463 }
464 
465 // Code Completion
466 
467 static bool EnableCodeCompletion(Preprocessor &PP,
468                                  const std::string &Filename,
469                                  unsigned Line,
470                                  unsigned Column) {
471   // Tell the source manager to chop off the given file at a specific
472   // line and column.
473   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
474   if (!Entry) {
475     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
476       << Filename;
477     return true;
478   }
479 
480   // Truncate the named file at the given line/column.
481   PP.SetCodeCompletionPoint(Entry, Line, Column);
482   return false;
483 }
484 
485 void CompilerInstance::createCodeCompletionConsumer() {
486   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
487   if (!CompletionConsumer) {
488     setCodeCompletionConsumer(
489       createCodeCompletionConsumer(getPreprocessor(),
490                                    Loc.FileName, Loc.Line, Loc.Column,
491                                    getFrontendOpts().CodeCompleteOpts,
492                                    llvm::outs()));
493     if (!CompletionConsumer)
494       return;
495   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
496                                   Loc.Line, Loc.Column)) {
497     setCodeCompletionConsumer(nullptr);
498     return;
499   }
500 
501   if (CompletionConsumer->isOutputBinary() &&
502       llvm::sys::ChangeStdoutToBinary()) {
503     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
504     setCodeCompletionConsumer(nullptr);
505   }
506 }
507 
508 void CompilerInstance::createFrontendTimer() {
509   FrontendTimerGroup.reset(new llvm::TimerGroup("Clang front-end time report"));
510   FrontendTimer.reset(
511       new llvm::Timer("Clang front-end timer", *FrontendTimerGroup));
512 }
513 
514 CodeCompleteConsumer *
515 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
516                                                StringRef Filename,
517                                                unsigned Line,
518                                                unsigned Column,
519                                                const CodeCompleteOptions &Opts,
520                                                raw_ostream &OS) {
521   if (EnableCodeCompletion(PP, Filename, Line, Column))
522     return nullptr;
523 
524   // Set up the creation routine for code-completion.
525   return new PrintingCodeCompleteConsumer(Opts, OS);
526 }
527 
528 void CompilerInstance::createSema(TranslationUnitKind TUKind,
529                                   CodeCompleteConsumer *CompletionConsumer) {
530   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
531                          TUKind, CompletionConsumer));
532 }
533 
534 // Output Files
535 
536 void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
537   assert(OutFile.OS && "Attempt to add empty stream to output list!");
538   OutputFiles.push_back(std::move(OutFile));
539 }
540 
541 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
542   for (OutputFile &OF : OutputFiles) {
543     // Manually close the stream before we rename it.
544     OF.OS.reset();
545 
546     if (!OF.TempFilename.empty()) {
547       if (EraseFiles) {
548         llvm::sys::fs::remove(OF.TempFilename);
549       } else {
550         SmallString<128> NewOutFile(OF.Filename);
551 
552         // If '-working-directory' was passed, the output filename should be
553         // relative to that.
554         FileMgr->FixupRelativePath(NewOutFile);
555         if (std::error_code ec =
556                 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
557           getDiagnostics().Report(diag::err_unable_to_rename_temp)
558             << OF.TempFilename << OF.Filename << ec.message();
559 
560           llvm::sys::fs::remove(OF.TempFilename);
561         }
562       }
563     } else if (!OF.Filename.empty() && EraseFiles)
564       llvm::sys::fs::remove(OF.Filename);
565 
566   }
567   OutputFiles.clear();
568   NonSeekStream.reset();
569 }
570 
571 raw_pwrite_stream *
572 CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
573                                           StringRef Extension) {
574   return createOutputFile(getFrontendOpts().OutputFile, Binary,
575                           /*RemoveFileOnSignal=*/true, InFile, Extension,
576                           /*UseTemporary=*/true);
577 }
578 
579 llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() {
580   auto OS = llvm::make_unique<llvm::raw_null_ostream>();
581   llvm::raw_null_ostream *Ret = OS.get();
582   addOutputFile(OutputFile("", "", std::move(OS)));
583   return Ret;
584 }
585 
586 raw_pwrite_stream *
587 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
588                                    bool RemoveFileOnSignal, StringRef InFile,
589                                    StringRef Extension, bool UseTemporary,
590                                    bool CreateMissingDirectories) {
591   std::string OutputPathName, TempPathName;
592   std::error_code EC;
593   std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
594       OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
595       UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
596   if (!OS) {
597     getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
598                                                                 << EC.message();
599     return nullptr;
600   }
601 
602   raw_pwrite_stream *Ret = OS.get();
603   // Add the output file -- but don't try to remove "-", since this means we are
604   // using stdin.
605   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
606                            TempPathName, std::move(OS)));
607 
608   return Ret;
609 }
610 
611 std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
612     StringRef OutputPath, std::error_code &Error, bool Binary,
613     bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
614     bool UseTemporary, bool CreateMissingDirectories,
615     std::string *ResultPathName, std::string *TempPathName) {
616   assert((!CreateMissingDirectories || UseTemporary) &&
617          "CreateMissingDirectories is only allowed when using temporary files");
618 
619   std::string OutFile, TempFile;
620   if (!OutputPath.empty()) {
621     OutFile = OutputPath;
622   } else if (InFile == "-") {
623     OutFile = "-";
624   } else if (!Extension.empty()) {
625     SmallString<128> Path(InFile);
626     llvm::sys::path::replace_extension(Path, Extension);
627     OutFile = Path.str();
628   } else {
629     OutFile = "-";
630   }
631 
632   std::unique_ptr<llvm::raw_fd_ostream> OS;
633   std::string OSFile;
634 
635   if (UseTemporary) {
636     if (OutFile == "-")
637       UseTemporary = false;
638     else {
639       llvm::sys::fs::file_status Status;
640       llvm::sys::fs::status(OutputPath, Status);
641       if (llvm::sys::fs::exists(Status)) {
642         // Fail early if we can't write to the final destination.
643         if (!llvm::sys::fs::can_write(OutputPath)) {
644           Error = make_error_code(llvm::errc::operation_not_permitted);
645           return nullptr;
646         }
647 
648         // Don't use a temporary if the output is a special file. This handles
649         // things like '-o /dev/null'
650         if (!llvm::sys::fs::is_regular_file(Status))
651           UseTemporary = false;
652       }
653     }
654   }
655 
656   if (UseTemporary) {
657     // Create a temporary file.
658     SmallString<128> TempPath;
659     TempPath = OutFile;
660     TempPath += "-%%%%%%%%";
661     int fd;
662     std::error_code EC =
663         llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
664 
665     if (CreateMissingDirectories &&
666         EC == llvm::errc::no_such_file_or_directory) {
667       StringRef Parent = llvm::sys::path::parent_path(OutputPath);
668       EC = llvm::sys::fs::create_directories(Parent);
669       if (!EC) {
670         EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
671       }
672     }
673 
674     if (!EC) {
675       OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
676       OSFile = TempFile = TempPath.str();
677     }
678     // If we failed to create the temporary, fallback to writing to the file
679     // directly. This handles the corner case where we cannot write to the
680     // directory, but can write to the file.
681   }
682 
683   if (!OS) {
684     OSFile = OutFile;
685     OS.reset(new llvm::raw_fd_ostream(
686         OSFile, Error,
687         (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
688     if (Error)
689       return nullptr;
690   }
691 
692   // Make sure the out stream file gets removed if we crash.
693   if (RemoveFileOnSignal)
694     llvm::sys::RemoveFileOnSignal(OSFile);
695 
696   if (ResultPathName)
697     *ResultPathName = OutFile;
698   if (TempPathName)
699     *TempPathName = TempFile;
700 
701   if (!Binary || OS->supportsSeeking())
702     return std::move(OS);
703 
704   auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
705   assert(!NonSeekStream);
706   NonSeekStream = std::move(OS);
707   return std::move(B);
708 }
709 
710 // Initialization Utilities
711 
712 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
713   return InitializeSourceManager(Input, getDiagnostics(),
714                                  getFileManager(), getSourceManager(),
715                                  getFrontendOpts());
716 }
717 
718 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
719                                                DiagnosticsEngine &Diags,
720                                                FileManager &FileMgr,
721                                                SourceManager &SourceMgr,
722                                                const FrontendOptions &Opts) {
723   SrcMgr::CharacteristicKind
724     Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
725 
726   if (Input.isBuffer()) {
727     SourceMgr.setMainFileID(SourceMgr.createFileID(
728         std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind));
729     assert(SourceMgr.getMainFileID().isValid() &&
730            "Couldn't establish MainFileID!");
731     return true;
732   }
733 
734   StringRef InputFile = Input.getFile();
735 
736   // Figure out where to get and map in the main file.
737   if (InputFile != "-") {
738     const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
739     if (!File) {
740       Diags.Report(diag::err_fe_error_reading) << InputFile;
741       return false;
742     }
743 
744     // The natural SourceManager infrastructure can't currently handle named
745     // pipes, but we would at least like to accept them for the main
746     // file. Detect them here, read them with the volatile flag so FileMgr will
747     // pick up the correct size, and simply override their contents as we do for
748     // STDIN.
749     if (File->isNamedPipe()) {
750       auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
751       if (MB) {
752         // Create a new virtual file that will have the correct size.
753         File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
754         SourceMgr.overrideFileContents(File, std::move(*MB));
755       } else {
756         Diags.Report(diag::err_cannot_open_file) << InputFile
757                                                  << MB.getError().message();
758         return false;
759       }
760     }
761 
762     SourceMgr.setMainFileID(
763         SourceMgr.createFileID(File, SourceLocation(), Kind));
764   } else {
765     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
766         llvm::MemoryBuffer::getSTDIN();
767     if (std::error_code EC = SBOrErr.getError()) {
768       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
769       return false;
770     }
771     std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
772 
773     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
774                                                    SB->getBufferSize(), 0);
775     SourceMgr.setMainFileID(
776         SourceMgr.createFileID(File, SourceLocation(), Kind));
777     SourceMgr.overrideFileContents(File, std::move(SB));
778   }
779 
780   assert(SourceMgr.getMainFileID().isValid() &&
781          "Couldn't establish MainFileID!");
782   return true;
783 }
784 
785 // High-Level Operations
786 
787 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
788   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
789   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
790   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
791 
792   // FIXME: Take this as an argument, once all the APIs we used have moved to
793   // taking it as an input instead of hard-coding llvm::errs.
794   raw_ostream &OS = llvm::errs();
795 
796   // Create the target instance.
797   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
798                                          getInvocation().TargetOpts));
799   if (!hasTarget())
800     return false;
801 
802   // Create TargetInfo for the other side of CUDA compilation.
803   if (getLangOpts().CUDA && !getFrontendOpts().AuxTriple.empty()) {
804     std::shared_ptr<TargetOptions> TO(new TargetOptions);
805     TO->Triple = getFrontendOpts().AuxTriple;
806     setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
807   }
808 
809   // Inform the target of the language options.
810   //
811   // FIXME: We shouldn't need to do this, the target should be immutable once
812   // created. This complexity should be lifted elsewhere.
813   getTarget().adjust(getLangOpts());
814 
815   // rewriter project will change target built-in bool type from its default.
816   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
817     getTarget().noSignedCharForObjCBool();
818 
819   // Validate/process some options.
820   if (getHeaderSearchOpts().Verbose)
821     OS << "clang -cc1 version " CLANG_VERSION_STRING
822        << " based upon " << BACKEND_PACKAGE_STRING
823        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
824 
825   if (getFrontendOpts().ShowTimers)
826     createFrontendTimer();
827 
828   if (getFrontendOpts().ShowStats)
829     llvm::EnableStatistics();
830 
831   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
832     // Reset the ID tables if we are reusing the SourceManager and parsing
833     // regular files.
834     if (hasSourceManager() && !Act.isModelParsingAction())
835       getSourceManager().clearIDTables();
836 
837     if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
838       Act.Execute();
839       Act.EndSourceFile();
840     }
841   }
842 
843   // Notify the diagnostic client that all files were processed.
844   getDiagnostics().getClient()->finish();
845 
846   if (getDiagnosticOpts().ShowCarets) {
847     // We can have multiple diagnostics sharing one diagnostic client.
848     // Get the total number of warnings/errors from the client.
849     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
850     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
851 
852     if (NumWarnings)
853       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
854     if (NumWarnings && NumErrors)
855       OS << " and ";
856     if (NumErrors)
857       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
858     if (NumWarnings || NumErrors)
859       OS << " generated.\n";
860   }
861 
862   if (getFrontendOpts().ShowStats && hasFileManager()) {
863     getFileManager().PrintStats();
864     OS << "\n";
865   }
866 
867   return !getDiagnostics().getClient()->getNumErrors();
868 }
869 
870 /// \brief Determine the appropriate source input kind based on language
871 /// options.
872 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
873   if (LangOpts.OpenCL)
874     return IK_OpenCL;
875   if (LangOpts.CUDA)
876     return IK_CUDA;
877   if (LangOpts.ObjC1)
878     return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
879   return LangOpts.CPlusPlus? IK_CXX : IK_C;
880 }
881 
882 /// \brief Compile a module file for the given module, using the options
883 /// provided by the importing compiler instance. Returns true if the module
884 /// was built without errors.
885 static bool compileModuleImpl(CompilerInstance &ImportingInstance,
886                               SourceLocation ImportLoc,
887                               Module *Module,
888                               StringRef ModuleFileName) {
889   ModuleMap &ModMap
890     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
891 
892   // Construct a compiler invocation for creating this module.
893   IntrusiveRefCntPtr<CompilerInvocation> Invocation
894     (new CompilerInvocation(ImportingInstance.getInvocation()));
895 
896   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
897 
898   // For any options that aren't intended to affect how a module is built,
899   // reset them to their default values.
900   Invocation->getLangOpts()->resetNonModularOptions();
901   PPOpts.resetNonModularOptions();
902 
903   // Remove any macro definitions that are explicitly ignored by the module.
904   // They aren't supposed to affect how the module is built anyway.
905   const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
906   PPOpts.Macros.erase(
907       std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
908                      [&HSOpts](const std::pair<std::string, bool> &def) {
909         StringRef MacroDef = def.first;
910         return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
911       }),
912       PPOpts.Macros.end());
913 
914   // Note the name of the module we're building.
915   Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
916 
917   // Make sure that the failed-module structure has been allocated in
918   // the importing instance, and propagate the pointer to the newly-created
919   // instance.
920   PreprocessorOptions &ImportingPPOpts
921     = ImportingInstance.getInvocation().getPreprocessorOpts();
922   if (!ImportingPPOpts.FailedModules)
923     ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
924   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
925 
926   // If there is a module map file, build the module using the module map.
927   // Set up the inputs/outputs so that we build the module from its umbrella
928   // header.
929   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
930   FrontendOpts.OutputFile = ModuleFileName.str();
931   FrontendOpts.DisableFree = false;
932   FrontendOpts.GenerateGlobalModuleIndex = false;
933   FrontendOpts.BuildingImplicitModule = true;
934   FrontendOpts.Inputs.clear();
935   InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
936 
937   // Don't free the remapped file buffers; they are owned by our caller.
938   PPOpts.RetainRemappedFileBuffers = true;
939 
940   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
941   assert(ImportingInstance.getInvocation().getModuleHash() ==
942          Invocation->getModuleHash() && "Module hash mismatch!");
943 
944   // Construct a compiler instance that will be used to actually create the
945   // module.
946   CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
947                             /*BuildingModule=*/true);
948   Instance.setInvocation(&*Invocation);
949 
950   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
951                                    ImportingInstance.getDiagnosticClient()),
952                              /*ShouldOwnClient=*/true);
953 
954   Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
955 
956   // Note that this module is part of the module build stack, so that we
957   // can detect cycles in the module graph.
958   Instance.setFileManager(&ImportingInstance.getFileManager());
959   Instance.createSourceManager(Instance.getFileManager());
960   SourceManager &SourceMgr = Instance.getSourceManager();
961   SourceMgr.setModuleBuildStack(
962     ImportingInstance.getSourceManager().getModuleBuildStack());
963   SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
964     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
965 
966   // If we're collecting module dependencies, we need to share a collector
967   // between all of the module CompilerInstances. Other than that, we don't
968   // want to produce any dependency output from the module build.
969   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
970   Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
971 
972   // Get or create the module map that we'll use to build this module.
973   std::string InferredModuleMapContent;
974   if (const FileEntry *ModuleMapFile =
975           ModMap.getContainingModuleMapFile(Module)) {
976     // Use the module map where this module resides.
977     FrontendOpts.Inputs.emplace_back(ModuleMapFile->getName(), IK);
978   } else {
979     SmallString<128> FakeModuleMapFile(Module->Directory->getName());
980     llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
981     FrontendOpts.Inputs.emplace_back(FakeModuleMapFile, IK);
982 
983     llvm::raw_string_ostream OS(InferredModuleMapContent);
984     Module->print(OS);
985     OS.flush();
986 
987     std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
988         llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
989     ModuleMapFile = Instance.getFileManager().getVirtualFile(
990         FakeModuleMapFile, InferredModuleMapContent.size(), 0);
991     SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer));
992   }
993 
994   // Construct a module-generating action. Passing through the module map is
995   // safe because the FileManager is shared between the compiler instances.
996   GenerateModuleAction CreateModuleAction(
997       ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
998 
999   ImportingInstance.getDiagnostics().Report(ImportLoc,
1000                                             diag::remark_module_build)
1001     << Module->Name << ModuleFileName;
1002 
1003   // Execute the action to actually build the module in-place. Use a separate
1004   // thread so that we get a stack large enough.
1005   const unsigned ThreadStackSize = 8 << 20;
1006   llvm::CrashRecoveryContext CRC;
1007   CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
1008                         ThreadStackSize);
1009 
1010   ImportingInstance.getDiagnostics().Report(ImportLoc,
1011                                             diag::remark_module_build_done)
1012     << Module->Name;
1013 
1014   // Delete the temporary module map file.
1015   // FIXME: Even though we're executing under crash protection, it would still
1016   // be nice to do this with RemoveFileOnSignal when we can. However, that
1017   // doesn't make sense for all clients, so clean this up manually.
1018   Instance.clearOutputFiles(/*EraseFiles=*/true);
1019 
1020   // We've rebuilt a module. If we're allowed to generate or update the global
1021   // module index, record that fact in the importing compiler instance.
1022   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1023     ImportingInstance.setBuildGlobalModuleIndex(true);
1024   }
1025 
1026   return !Instance.getDiagnostics().hasErrorOccurred();
1027 }
1028 
1029 static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
1030                                  SourceLocation ImportLoc,
1031                                  SourceLocation ModuleNameLoc, Module *Module,
1032                                  StringRef ModuleFileName) {
1033   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1034 
1035   auto diagnoseBuildFailure = [&] {
1036     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1037         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1038   };
1039 
1040   // FIXME: have LockFileManager return an error_code so that we can
1041   // avoid the mkdir when the directory already exists.
1042   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1043   llvm::sys::fs::create_directories(Dir);
1044 
1045   while (1) {
1046     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1047     llvm::LockFileManager Locked(ModuleFileName);
1048     switch (Locked) {
1049     case llvm::LockFileManager::LFS_Error:
1050       Diags.Report(ModuleNameLoc, diag::err_module_lock_failure)
1051           << Module->Name;
1052       return false;
1053 
1054     case llvm::LockFileManager::LFS_Owned:
1055       // We're responsible for building the module ourselves.
1056       if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
1057                              ModuleFileName)) {
1058         diagnoseBuildFailure();
1059         return false;
1060       }
1061       break;
1062 
1063     case llvm::LockFileManager::LFS_Shared:
1064       // Someone else is responsible for building the module. Wait for them to
1065       // finish.
1066       switch (Locked.waitForUnlock()) {
1067       case llvm::LockFileManager::Res_Success:
1068         ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1069         break;
1070       case llvm::LockFileManager::Res_OwnerDied:
1071         continue; // try again to get the lock.
1072       case llvm::LockFileManager::Res_Timeout:
1073         Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout)
1074             << Module->Name;
1075         // Clear the lock file so that future invokations can make progress.
1076         Locked.unsafeRemoveLockFile();
1077         return false;
1078       }
1079       break;
1080     }
1081 
1082     // Try to read the module file, now that we've compiled it.
1083     ASTReader::ASTReadResult ReadResult =
1084         ImportingInstance.getModuleManager()->ReadAST(
1085             ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1086             ModuleLoadCapabilities);
1087 
1088     if (ReadResult == ASTReader::OutOfDate &&
1089         Locked == llvm::LockFileManager::LFS_Shared) {
1090       // The module may be out of date in the presence of file system races,
1091       // or if one of its imports depends on header search paths that are not
1092       // consistent with this ImportingInstance.  Try again...
1093       continue;
1094     } else if (ReadResult == ASTReader::Missing) {
1095       diagnoseBuildFailure();
1096     } else if (ReadResult != ASTReader::Success &&
1097                !Diags.hasErrorOccurred()) {
1098       // The ASTReader didn't diagnose the error, so conservatively report it.
1099       diagnoseBuildFailure();
1100     }
1101     return ReadResult == ASTReader::Success;
1102   }
1103 }
1104 
1105 /// \brief Diagnose differences between the current definition of the given
1106 /// configuration macro and the definition provided on the command line.
1107 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1108                              Module *Mod, SourceLocation ImportLoc) {
1109   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1110   SourceManager &SourceMgr = PP.getSourceManager();
1111 
1112   // If this identifier has never had a macro definition, then it could
1113   // not have changed.
1114   if (!Id->hadMacroDefinition())
1115     return;
1116   auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1117 
1118   // Find the macro definition from the command line.
1119   MacroInfo *CmdLineDefinition = nullptr;
1120   for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1121     // We only care about the predefines buffer.
1122     FileID FID = SourceMgr.getFileID(MD->getLocation());
1123     if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1124       continue;
1125     if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1126       CmdLineDefinition = DMD->getMacroInfo();
1127     break;
1128   }
1129 
1130   auto *CurrentDefinition = PP.getMacroInfo(Id);
1131   if (CurrentDefinition == CmdLineDefinition) {
1132     // Macro matches. Nothing to do.
1133   } else if (!CurrentDefinition) {
1134     // This macro was defined on the command line, then #undef'd later.
1135     // Complain.
1136     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1137       << true << ConfigMacro << Mod->getFullModuleName();
1138     auto LatestDef = LatestLocalMD->getDefinition();
1139     assert(LatestDef.isUndefined() &&
1140            "predefined macro went away with no #undef?");
1141     PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1142       << true;
1143     return;
1144   } else if (!CmdLineDefinition) {
1145     // There was no definition for this macro in the predefines buffer,
1146     // but there was a local definition. Complain.
1147     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1148       << false << ConfigMacro << Mod->getFullModuleName();
1149     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1150             diag::note_module_def_undef_here)
1151       << false;
1152   } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1153                                                /*Syntactically=*/true)) {
1154     // The macro definitions differ.
1155     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1156       << false << ConfigMacro << Mod->getFullModuleName();
1157     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1158             diag::note_module_def_undef_here)
1159       << false;
1160   }
1161 }
1162 
1163 /// \brief Write a new timestamp file with the given path.
1164 static void writeTimestampFile(StringRef TimestampFile) {
1165   std::error_code EC;
1166   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1167 }
1168 
1169 /// \brief Prune the module cache of modules that haven't been accessed in
1170 /// a long time.
1171 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1172   struct stat StatBuf;
1173   llvm::SmallString<128> TimestampFile;
1174   TimestampFile = HSOpts.ModuleCachePath;
1175   assert(!TimestampFile.empty());
1176   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1177 
1178   // Try to stat() the timestamp file.
1179   if (::stat(TimestampFile.c_str(), &StatBuf)) {
1180     // If the timestamp file wasn't there, create one now.
1181     if (errno == ENOENT) {
1182       writeTimestampFile(TimestampFile);
1183     }
1184     return;
1185   }
1186 
1187   // Check whether the time stamp is older than our pruning interval.
1188   // If not, do nothing.
1189   time_t TimeStampModTime = StatBuf.st_mtime;
1190   time_t CurrentTime = time(nullptr);
1191   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1192     return;
1193 
1194   // Write a new timestamp file so that nobody else attempts to prune.
1195   // There is a benign race condition here, if two Clang instances happen to
1196   // notice at the same time that the timestamp is out-of-date.
1197   writeTimestampFile(TimestampFile);
1198 
1199   // Walk the entire module cache, looking for unused module files and module
1200   // indices.
1201   std::error_code EC;
1202   SmallString<128> ModuleCachePathNative;
1203   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1204   for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1205        Dir != DirEnd && !EC; Dir.increment(EC)) {
1206     // If we don't have a directory, there's nothing to look into.
1207     if (!llvm::sys::fs::is_directory(Dir->path()))
1208       continue;
1209 
1210     // Walk all of the files within this directory.
1211     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1212          File != FileEnd && !EC; File.increment(EC)) {
1213       // We only care about module and global module index files.
1214       StringRef Extension = llvm::sys::path::extension(File->path());
1215       if (Extension != ".pcm" && Extension != ".timestamp" &&
1216           llvm::sys::path::filename(File->path()) != "modules.idx")
1217         continue;
1218 
1219       // Look at this file. If we can't stat it, there's nothing interesting
1220       // there.
1221       if (::stat(File->path().c_str(), &StatBuf))
1222         continue;
1223 
1224       // If the file has been used recently enough, leave it there.
1225       time_t FileAccessTime = StatBuf.st_atime;
1226       if (CurrentTime - FileAccessTime <=
1227               time_t(HSOpts.ModuleCachePruneAfter)) {
1228         continue;
1229       }
1230 
1231       // Remove the file.
1232       llvm::sys::fs::remove(File->path());
1233 
1234       // Remove the timestamp file.
1235       std::string TimpestampFilename = File->path() + ".timestamp";
1236       llvm::sys::fs::remove(TimpestampFilename);
1237     }
1238 
1239     // If we removed all of the files in the directory, remove the directory
1240     // itself.
1241     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1242             llvm::sys::fs::directory_iterator() && !EC)
1243       llvm::sys::fs::remove(Dir->path());
1244   }
1245 }
1246 
1247 void CompilerInstance::createModuleManager() {
1248   if (!ModuleManager) {
1249     if (!hasASTContext())
1250       createASTContext();
1251 
1252     // If we're implicitly building modules but not currently recursively
1253     // building a module, check whether we need to prune the module cache.
1254     if (getSourceManager().getModuleBuildStack().empty() &&
1255         !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1256         getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1257         getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1258       pruneModuleCache(getHeaderSearchOpts());
1259     }
1260 
1261     HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1262     std::string Sysroot = HSOpts.Sysroot;
1263     const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1264     std::unique_ptr<llvm::Timer> ReadTimer;
1265     if (FrontendTimerGroup)
1266       ReadTimer = llvm::make_unique<llvm::Timer>("Reading modules",
1267                                                  *FrontendTimerGroup);
1268     ModuleManager = new ASTReader(
1269         getPreprocessor(), getASTContext(), getPCHContainerReader(),
1270         Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
1271         /*AllowASTWithCompilerErrors=*/false,
1272         /*AllowConfigurationMismatch=*/false,
1273         HSOpts.ModulesValidateSystemHeaders,
1274         getFrontendOpts().UseGlobalModuleIndex,
1275         std::move(ReadTimer));
1276     if (hasASTConsumer()) {
1277       ModuleManager->setDeserializationListener(
1278         getASTConsumer().GetASTDeserializationListener());
1279       getASTContext().setASTMutationListener(
1280         getASTConsumer().GetASTMutationListener());
1281     }
1282     getASTContext().setExternalSource(ModuleManager);
1283     if (hasSema())
1284       ModuleManager->InitializeSema(getSema());
1285     if (hasASTConsumer())
1286       ModuleManager->StartTranslationUnit(&getASTConsumer());
1287 
1288     if (TheDependencyFileGenerator)
1289       TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1290     if (ModuleDepCollector)
1291       ModuleDepCollector->attachToASTReader(*ModuleManager);
1292     for (auto &Listener : DependencyCollectors)
1293       Listener->attachToASTReader(*ModuleManager);
1294   }
1295 }
1296 
1297 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1298   llvm::Timer Timer;
1299   if (FrontendTimerGroup)
1300     Timer.init("Preloading " + FileName.str(), *FrontendTimerGroup);
1301   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1302 
1303   // Helper to recursively read the module names for all modules we're adding.
1304   // We mark these as known and redirect any attempt to load that module to
1305   // the files we were handed.
1306   struct ReadModuleNames : ASTReaderListener {
1307     CompilerInstance &CI;
1308     llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
1309 
1310     ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
1311 
1312     void ReadModuleName(StringRef ModuleName) override {
1313       LoadedModules.push_back(
1314           CI.getPreprocessor().getIdentifierInfo(ModuleName));
1315     }
1316 
1317     void registerAll() {
1318       for (auto *II : LoadedModules) {
1319         CI.KnownModules[II] = CI.getPreprocessor()
1320                                   .getHeaderSearchInfo()
1321                                   .getModuleMap()
1322                                   .findModule(II->getName());
1323       }
1324       LoadedModules.clear();
1325     }
1326   };
1327 
1328   // If we don't already have an ASTReader, create one now.
1329   if (!ModuleManager)
1330     createModuleManager();
1331 
1332   auto Listener = llvm::make_unique<ReadModuleNames>(*this);
1333   auto &ListenerRef = *Listener;
1334   ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
1335                                                    std::move(Listener));
1336 
1337   // Try to load the module file.
1338   if (ModuleManager->ReadAST(FileName, serialization::MK_ExplicitModule,
1339                              SourceLocation(), ASTReader::ARR_None)
1340           != ASTReader::Success)
1341     return false;
1342 
1343   // We successfully loaded the module file; remember the set of provided
1344   // modules so that we don't try to load implicit modules for them.
1345   ListenerRef.registerAll();
1346   return true;
1347 }
1348 
1349 ModuleLoadResult
1350 CompilerInstance::loadModule(SourceLocation ImportLoc,
1351                              ModuleIdPath Path,
1352                              Module::NameVisibilityKind Visibility,
1353                              bool IsInclusionDirective) {
1354   // Determine what file we're searching from.
1355   StringRef ModuleName = Path[0].first->getName();
1356   SourceLocation ModuleNameLoc = Path[0].second;
1357 
1358   // If we've already handled this import, just return the cached result.
1359   // This one-element cache is important to eliminate redundant diagnostics
1360   // when both the preprocessor and parser see the same import declaration.
1361   if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1362     // Make the named module visible.
1363     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule &&
1364         ModuleName != getLangOpts().ImplementationOfModule)
1365       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1366                                        ImportLoc);
1367     return LastModuleImportResult;
1368   }
1369 
1370   clang::Module *Module = nullptr;
1371 
1372   // If we don't already have information on this module, load the module now.
1373   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1374     = KnownModules.find(Path[0].first);
1375   if (Known != KnownModules.end()) {
1376     // Retrieve the cached top-level module.
1377     Module = Known->second;
1378   } else if (ModuleName == getLangOpts().CurrentModule ||
1379              ModuleName == getLangOpts().ImplementationOfModule) {
1380     // This is the module we're building.
1381     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1382     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1383   } else {
1384     // Search for a module with the given name.
1385     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1386     if (!Module) {
1387       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1388       << ModuleName
1389       << SourceRange(ImportLoc, ModuleNameLoc);
1390       ModuleBuildFailed = true;
1391       return ModuleLoadResult();
1392     }
1393 
1394     std::string ModuleFileName =
1395         PP->getHeaderSearchInfo().getModuleFileName(Module);
1396     if (ModuleFileName.empty()) {
1397       getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1398           << ModuleName;
1399       ModuleBuildFailed = true;
1400       return ModuleLoadResult();
1401     }
1402 
1403     // If we don't already have an ASTReader, create one now.
1404     if (!ModuleManager)
1405       createModuleManager();
1406 
1407     llvm::Timer Timer;
1408     if (FrontendTimerGroup)
1409       Timer.init("Loading " + ModuleFileName, *FrontendTimerGroup);
1410     llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1411 
1412     // Try to load the module file.
1413     unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
1414     switch (ModuleManager->ReadAST(ModuleFileName,
1415                                    serialization::MK_ImplicitModule,
1416                                    ImportLoc, ARRFlags)) {
1417     case ASTReader::Success:
1418       break;
1419 
1420     case ASTReader::OutOfDate:
1421     case ASTReader::Missing: {
1422       // The module file is missing or out-of-date. Build it.
1423       assert(Module && "missing module file");
1424       // Check whether there is a cycle in the module graph.
1425       ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1426       ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1427       for (; Pos != PosEnd; ++Pos) {
1428         if (Pos->first == ModuleName)
1429           break;
1430       }
1431 
1432       if (Pos != PosEnd) {
1433         SmallString<256> CyclePath;
1434         for (; Pos != PosEnd; ++Pos) {
1435           CyclePath += Pos->first;
1436           CyclePath += " -> ";
1437         }
1438         CyclePath += ModuleName;
1439 
1440         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1441           << ModuleName << CyclePath;
1442         return ModuleLoadResult();
1443       }
1444 
1445       // Check whether we have already attempted to build this module (but
1446       // failed).
1447       if (getPreprocessorOpts().FailedModules &&
1448           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1449         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1450           << ModuleName
1451           << SourceRange(ImportLoc, ModuleNameLoc);
1452         ModuleBuildFailed = true;
1453         return ModuleLoadResult();
1454       }
1455 
1456       // Try to compile and then load the module.
1457       if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1458                                 ModuleFileName)) {
1459         assert(getDiagnostics().hasErrorOccurred() &&
1460                "undiagnosed error in compileAndLoadModule");
1461         if (getPreprocessorOpts().FailedModules)
1462           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1463         KnownModules[Path[0].first] = nullptr;
1464         ModuleBuildFailed = true;
1465         return ModuleLoadResult();
1466       }
1467 
1468       // Okay, we've rebuilt and now loaded the module.
1469       break;
1470     }
1471 
1472     case ASTReader::VersionMismatch:
1473     case ASTReader::ConfigurationMismatch:
1474     case ASTReader::HadErrors:
1475       ModuleLoader::HadFatalFailure = true;
1476       // FIXME: The ASTReader will already have complained, but can we shoehorn
1477       // that diagnostic information into a more useful form?
1478       KnownModules[Path[0].first] = nullptr;
1479       return ModuleLoadResult();
1480 
1481     case ASTReader::Failure:
1482       ModuleLoader::HadFatalFailure = true;
1483       // Already complained, but note now that we failed.
1484       KnownModules[Path[0].first] = nullptr;
1485       ModuleBuildFailed = true;
1486       return ModuleLoadResult();
1487     }
1488 
1489     // Cache the result of this top-level module lookup for later.
1490     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1491   }
1492 
1493   // If we never found the module, fail.
1494   if (!Module)
1495     return ModuleLoadResult();
1496 
1497   // Verify that the rest of the module path actually corresponds to
1498   // a submodule.
1499   if (Path.size() > 1) {
1500     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1501       StringRef Name = Path[I].first->getName();
1502       clang::Module *Sub = Module->findSubmodule(Name);
1503 
1504       if (!Sub) {
1505         // Attempt to perform typo correction to find a module name that works.
1506         SmallVector<StringRef, 2> Best;
1507         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1508 
1509         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1510                                             JEnd = Module->submodule_end();
1511              J != JEnd; ++J) {
1512           unsigned ED = Name.edit_distance((*J)->Name,
1513                                            /*AllowReplacements=*/true,
1514                                            BestEditDistance);
1515           if (ED <= BestEditDistance) {
1516             if (ED < BestEditDistance) {
1517               Best.clear();
1518               BestEditDistance = ED;
1519             }
1520 
1521             Best.push_back((*J)->Name);
1522           }
1523         }
1524 
1525         // If there was a clear winner, user it.
1526         if (Best.size() == 1) {
1527           getDiagnostics().Report(Path[I].second,
1528                                   diag::err_no_submodule_suggest)
1529             << Path[I].first << Module->getFullModuleName() << Best[0]
1530             << SourceRange(Path[0].second, Path[I-1].second)
1531             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1532                                             Best[0]);
1533 
1534           Sub = Module->findSubmodule(Best[0]);
1535         }
1536       }
1537 
1538       if (!Sub) {
1539         // No submodule by this name. Complain, and don't look for further
1540         // submodules.
1541         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1542           << Path[I].first << Module->getFullModuleName()
1543           << SourceRange(Path[0].second, Path[I-1].second);
1544         break;
1545       }
1546 
1547       Module = Sub;
1548     }
1549   }
1550 
1551   // Don't make the module visible if we are in the implementation.
1552   if (ModuleName == getLangOpts().ImplementationOfModule)
1553     return ModuleLoadResult(Module, false);
1554 
1555   // Make the named module visible, if it's not already part of the module
1556   // we are parsing.
1557   if (ModuleName != getLangOpts().CurrentModule) {
1558     if (!Module->IsFromModuleFile) {
1559       // We have an umbrella header or directory that doesn't actually include
1560       // all of the headers within the directory it covers. Complain about
1561       // this missing submodule and recover by forgetting that we ever saw
1562       // this submodule.
1563       // FIXME: Should we detect this at module load time? It seems fairly
1564       // expensive (and rare).
1565       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1566         << Module->getFullModuleName()
1567         << SourceRange(Path.front().second, Path.back().second);
1568 
1569       return ModuleLoadResult(nullptr, true);
1570     }
1571 
1572     // Check whether this module is available.
1573     clang::Module::Requirement Requirement;
1574     clang::Module::UnresolvedHeaderDirective MissingHeader;
1575     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
1576                              MissingHeader)) {
1577       if (MissingHeader.FileNameLoc.isValid()) {
1578         getDiagnostics().Report(MissingHeader.FileNameLoc,
1579                                 diag::err_module_header_missing)
1580           << MissingHeader.IsUmbrella << MissingHeader.FileName;
1581       } else {
1582         getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1583           << Module->getFullModuleName()
1584           << Requirement.second << Requirement.first
1585           << SourceRange(Path.front().second, Path.back().second);
1586       }
1587       LastModuleImportLoc = ImportLoc;
1588       LastModuleImportResult = ModuleLoadResult();
1589       return ModuleLoadResult();
1590     }
1591 
1592     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1593   }
1594 
1595   // Check for any configuration macros that have changed.
1596   clang::Module *TopModule = Module->getTopLevelModule();
1597   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1598     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1599                      Module, ImportLoc);
1600   }
1601 
1602   LastModuleImportLoc = ImportLoc;
1603   LastModuleImportResult = ModuleLoadResult(Module, false);
1604   return LastModuleImportResult;
1605 }
1606 
1607 void CompilerInstance::makeModuleVisible(Module *Mod,
1608                                          Module::NameVisibilityKind Visibility,
1609                                          SourceLocation ImportLoc) {
1610   if (!ModuleManager)
1611     createModuleManager();
1612   if (!ModuleManager)
1613     return;
1614 
1615   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
1616 }
1617 
1618 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
1619     SourceLocation TriggerLoc) {
1620   if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
1621     return nullptr;
1622   if (!ModuleManager)
1623     createModuleManager();
1624   // Can't do anything if we don't have the module manager.
1625   if (!ModuleManager)
1626     return nullptr;
1627   // Get an existing global index.  This loads it if not already
1628   // loaded.
1629   ModuleManager->loadGlobalIndex();
1630   GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1631   // If the global index doesn't exist, create it.
1632   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
1633       hasPreprocessor()) {
1634     llvm::sys::fs::create_directories(
1635       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1636     GlobalModuleIndex::writeIndex(
1637         getFileManager(), getPCHContainerReader(),
1638         getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1639     ModuleManager->resetForReload();
1640     ModuleManager->loadGlobalIndex();
1641     GlobalIndex = ModuleManager->getGlobalIndex();
1642   }
1643   // For finding modules needing to be imported for fixit messages,
1644   // we need to make the global index cover all modules, so we do that here.
1645   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
1646     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1647     bool RecreateIndex = false;
1648     for (ModuleMap::module_iterator I = MMap.module_begin(),
1649         E = MMap.module_end(); I != E; ++I) {
1650       Module *TheModule = I->second;
1651       const FileEntry *Entry = TheModule->getASTFile();
1652       if (!Entry) {
1653         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1654         Path.push_back(std::make_pair(
1655             getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
1656         std::reverse(Path.begin(), Path.end());
1657         // Load a module as hidden.  This also adds it to the global index.
1658         loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
1659         RecreateIndex = true;
1660       }
1661     }
1662     if (RecreateIndex) {
1663       GlobalModuleIndex::writeIndex(
1664           getFileManager(), getPCHContainerReader(),
1665           getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1666       ModuleManager->resetForReload();
1667       ModuleManager->loadGlobalIndex();
1668       GlobalIndex = ModuleManager->getGlobalIndex();
1669     }
1670     HaveFullGlobalModuleIndex = true;
1671   }
1672   return GlobalIndex;
1673 }
1674 
1675 // Check global module index for missing imports.
1676 bool
1677 CompilerInstance::lookupMissingImports(StringRef Name,
1678                                        SourceLocation TriggerLoc) {
1679   // Look for the symbol in non-imported modules, but only if an error
1680   // actually occurred.
1681   if (!buildingModule()) {
1682     // Load global module index, or retrieve a previously loaded one.
1683     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
1684       TriggerLoc);
1685 
1686     // Only if we have a global index.
1687     if (GlobalIndex) {
1688       GlobalModuleIndex::HitSet FoundModules;
1689 
1690       // Find the modules that reference the identifier.
1691       // Note that this only finds top-level modules.
1692       // We'll let diagnoseTypo find the actual declaration module.
1693       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
1694         return true;
1695     }
1696   }
1697 
1698   return false;
1699 }
1700 void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }
1701