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