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