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