xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 2d2b420ab9452afe2b298418ceeb40096e72d935)
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     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
687         llvm::MemoryBuffer::getSTDIN();
688     if (std::error_code EC = SBOrErr.getError()) {
689       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
690       return false;
691     }
692     std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
693 
694     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
695                                                    SB->getBufferSize(), 0);
696     SourceMgr.setMainFileID(
697         SourceMgr.createFileID(File, SourceLocation(), Kind));
698     SourceMgr.overrideFileContents(File, SB.release());
699   }
700 
701   assert(!SourceMgr.getMainFileID().isInvalid() &&
702          "Couldn't establish MainFileID!");
703   return true;
704 }
705 
706 // High-Level Operations
707 
708 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
709   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
710   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
711   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
712 
713   // FIXME: Take this as an argument, once all the APIs we used have moved to
714   // taking it as an input instead of hard-coding llvm::errs.
715   raw_ostream &OS = llvm::errs();
716 
717   // Create the target instance.
718   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
719                                          getInvocation().TargetOpts));
720   if (!hasTarget())
721     return false;
722 
723   // Inform the target of the language options.
724   //
725   // FIXME: We shouldn't need to do this, the target should be immutable once
726   // created. This complexity should be lifted elsewhere.
727   getTarget().adjust(getLangOpts());
728 
729   // rewriter project will change target built-in bool type from its default.
730   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
731     getTarget().noSignedCharForObjCBool();
732 
733   // Validate/process some options.
734   if (getHeaderSearchOpts().Verbose)
735     OS << "clang -cc1 version " CLANG_VERSION_STRING
736        << " based upon " << BACKEND_PACKAGE_STRING
737        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
738 
739   if (getFrontendOpts().ShowTimers)
740     createFrontendTimer();
741 
742   if (getFrontendOpts().ShowStats)
743     llvm::EnableStatistics();
744 
745   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
746     // Reset the ID tables if we are reusing the SourceManager.
747     if (hasSourceManager())
748       getSourceManager().clearIDTables();
749 
750     if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
751       Act.Execute();
752       Act.EndSourceFile();
753     }
754   }
755 
756   // Notify the diagnostic client that all files were processed.
757   getDiagnostics().getClient()->finish();
758 
759   if (getDiagnosticOpts().ShowCarets) {
760     // We can have multiple diagnostics sharing one diagnostic client.
761     // Get the total number of warnings/errors from the client.
762     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
763     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
764 
765     if (NumWarnings)
766       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
767     if (NumWarnings && NumErrors)
768       OS << " and ";
769     if (NumErrors)
770       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
771     if (NumWarnings || NumErrors)
772       OS << " generated.\n";
773   }
774 
775   if (getFrontendOpts().ShowStats && hasFileManager()) {
776     getFileManager().PrintStats();
777     OS << "\n";
778   }
779 
780   return !getDiagnostics().getClient()->getNumErrors();
781 }
782 
783 /// \brief Determine the appropriate source input kind based on language
784 /// options.
785 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
786   if (LangOpts.OpenCL)
787     return IK_OpenCL;
788   if (LangOpts.CUDA)
789     return IK_CUDA;
790   if (LangOpts.ObjC1)
791     return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
792   return LangOpts.CPlusPlus? IK_CXX : IK_C;
793 }
794 
795 /// \brief Compile a module file for the given module, using the options
796 /// provided by the importing compiler instance.
797 static void compileModuleImpl(CompilerInstance &ImportingInstance,
798                           SourceLocation ImportLoc,
799                           Module *Module,
800                           StringRef ModuleFileName) {
801   ModuleMap &ModMap
802     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
803 
804   // Construct a compiler invocation for creating this module.
805   IntrusiveRefCntPtr<CompilerInvocation> Invocation
806     (new CompilerInvocation(ImportingInstance.getInvocation()));
807 
808   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
809 
810   // For any options that aren't intended to affect how a module is built,
811   // reset them to their default values.
812   Invocation->getLangOpts()->resetNonModularOptions();
813   PPOpts.resetNonModularOptions();
814 
815   // Remove any macro definitions that are explicitly ignored by the module.
816   // They aren't supposed to affect how the module is built anyway.
817   const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
818   PPOpts.Macros.erase(
819       std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
820                      [&HSOpts](const std::pair<std::string, bool> &def) {
821         StringRef MacroDef = def.first;
822         return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
823       }),
824       PPOpts.Macros.end());
825 
826   // Note the name of the module we're building.
827   Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
828 
829   // Make sure that the failed-module structure has been allocated in
830   // the importing instance, and propagate the pointer to the newly-created
831   // instance.
832   PreprocessorOptions &ImportingPPOpts
833     = ImportingInstance.getInvocation().getPreprocessorOpts();
834   if (!ImportingPPOpts.FailedModules)
835     ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
836   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
837 
838   // If there is a module map file, build the module using the module map.
839   // Set up the inputs/outputs so that we build the module from its umbrella
840   // header.
841   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
842   FrontendOpts.OutputFile = ModuleFileName.str();
843   FrontendOpts.DisableFree = false;
844   FrontendOpts.GenerateGlobalModuleIndex = false;
845   FrontendOpts.Inputs.clear();
846   InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
847 
848   // Don't free the remapped file buffers; they are owned by our caller.
849   PPOpts.RetainRemappedFileBuffers = true;
850 
851   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
852   assert(ImportingInstance.getInvocation().getModuleHash() ==
853          Invocation->getModuleHash() && "Module hash mismatch!");
854 
855   // Construct a compiler instance that will be used to actually create the
856   // module.
857   CompilerInstance Instance(/*BuildingModule=*/true);
858   Instance.setInvocation(&*Invocation);
859 
860   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
861                                    ImportingInstance.getDiagnosticClient()),
862                              /*ShouldOwnClient=*/true);
863 
864   Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
865 
866   // Note that this module is part of the module build stack, so that we
867   // can detect cycles in the module graph.
868   Instance.setFileManager(&ImportingInstance.getFileManager());
869   Instance.createSourceManager(Instance.getFileManager());
870   SourceManager &SourceMgr = Instance.getSourceManager();
871   SourceMgr.setModuleBuildStack(
872     ImportingInstance.getSourceManager().getModuleBuildStack());
873   SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
874     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
875 
876   // If we're collecting module dependencies, we need to share a collector
877   // between all of the module CompilerInstances.
878   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
879 
880   // Get or create the module map that we'll use to build this module.
881   std::string InferredModuleMapContent;
882   if (const FileEntry *ModuleMapFile =
883           ModMap.getContainingModuleMapFile(Module)) {
884     // Use the module map where this module resides.
885     FrontendOpts.Inputs.push_back(
886         FrontendInputFile(ModuleMapFile->getName(), IK));
887   } else {
888     llvm::raw_string_ostream OS(InferredModuleMapContent);
889     Module->print(OS);
890     OS.flush();
891     FrontendOpts.Inputs.push_back(
892         FrontendInputFile("__inferred_module.map", IK));
893 
894     llvm::MemoryBuffer *ModuleMapBuffer =
895         llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
896     ModuleMapFile = Instance.getFileManager().getVirtualFile(
897         "__inferred_module.map", InferredModuleMapContent.size(), 0);
898     SourceMgr.overrideFileContents(ModuleMapFile, ModuleMapBuffer);
899   }
900 
901   // Construct a module-generating action. Passing through Module->ModuleMap is
902   // safe because the FileManager is shared between the compiler instances.
903   GenerateModuleAction CreateModuleAction(Module->ModuleMap, Module->IsSystem);
904 
905   // Execute the action to actually build the module in-place. Use a separate
906   // thread so that we get a stack large enough.
907   const unsigned ThreadStackSize = 8 << 20;
908   llvm::CrashRecoveryContext CRC;
909   CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
910                         ThreadStackSize);
911 
912   // Delete the temporary module map file.
913   // FIXME: Even though we're executing under crash protection, it would still
914   // be nice to do this with RemoveFileOnSignal when we can. However, that
915   // doesn't make sense for all clients, so clean this up manually.
916   Instance.clearOutputFiles(/*EraseFiles=*/true);
917 
918   // We've rebuilt a module. If we're allowed to generate or update the global
919   // module index, record that fact in the importing compiler instance.
920   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
921     ImportingInstance.setBuildGlobalModuleIndex(true);
922   }
923 }
924 
925 static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
926                                  SourceLocation ImportLoc,
927                                  SourceLocation ModuleNameLoc,
928                                  Module *Module,
929                                  StringRef ModuleFileName) {
930   // FIXME: have LockFileManager return an error_code so that we can
931   // avoid the mkdir when the directory already exists.
932   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
933   llvm::sys::fs::create_directories(Dir);
934 
935   while (1) {
936     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
937     llvm::LockFileManager Locked(ModuleFileName);
938     switch (Locked) {
939     case llvm::LockFileManager::LFS_Error:
940       return false;
941 
942     case llvm::LockFileManager::LFS_Owned:
943       // We're responsible for building the module ourselves.
944       // FIXME: if there are errors, don't attempt to load the module.
945       compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
946                         ModuleFileName);
947       break;
948 
949     case llvm::LockFileManager::LFS_Shared:
950       // Someone else is responsible for building the module. Wait for them to
951       // finish.
952       if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
953         continue; // try again to get the lock.
954       ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
955       break;
956     }
957 
958     // Try to read the module file, now that we've compiled it.
959     ASTReader::ASTReadResult ReadResult =
960         ImportingInstance.getModuleManager()->ReadAST(
961             ModuleFileName, serialization::MK_Module, ImportLoc,
962             ModuleLoadCapabilities);
963 
964     if (ReadResult == ASTReader::OutOfDate &&
965         Locked == llvm::LockFileManager::LFS_Shared) {
966       // The module may be out of date in the presence of file system races,
967       // or if one of its imports depends on header search paths that are not
968       // consistent with this ImportingInstance.  Try again...
969       continue;
970     } else if (ReadResult == ASTReader::Missing) {
971       ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
972                                                 diag::err_module_not_built)
973           << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
974     }
975     return ReadResult == ASTReader::Success;
976   }
977 }
978 
979 /// \brief Diagnose differences between the current definition of the given
980 /// configuration macro and the definition provided on the command line.
981 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
982                              Module *Mod, SourceLocation ImportLoc) {
983   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
984   SourceManager &SourceMgr = PP.getSourceManager();
985 
986   // If this identifier has never had a macro definition, then it could
987   // not have changed.
988   if (!Id->hadMacroDefinition())
989     return;
990 
991   // If this identifier does not currently have a macro definition,
992   // check whether it had one on the command line.
993   if (!Id->hasMacroDefinition()) {
994     MacroDirective::DefInfo LatestDef =
995         PP.getMacroDirectiveHistory(Id)->getDefinition();
996     for (MacroDirective::DefInfo Def = LatestDef; Def;
997            Def = Def.getPreviousDefinition()) {
998       FileID FID = SourceMgr.getFileID(Def.getLocation());
999       if (FID.isInvalid())
1000         continue;
1001 
1002       // We only care about the predefines buffer.
1003       if (FID != PP.getPredefinesFileID())
1004         continue;
1005 
1006       // This macro was defined on the command line, then #undef'd later.
1007       // Complain.
1008       PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1009         << true << ConfigMacro << Mod->getFullModuleName();
1010       if (LatestDef.isUndefined())
1011         PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1012           << true;
1013       return;
1014     }
1015 
1016     // Okay: no definition in the predefines buffer.
1017     return;
1018   }
1019 
1020   // This identifier has a macro definition. Check whether we had a definition
1021   // on the command line.
1022   MacroDirective::DefInfo LatestDef =
1023       PP.getMacroDirectiveHistory(Id)->getDefinition();
1024   MacroDirective::DefInfo PredefinedDef;
1025   for (MacroDirective::DefInfo Def = LatestDef; Def;
1026          Def = Def.getPreviousDefinition()) {
1027     FileID FID = SourceMgr.getFileID(Def.getLocation());
1028     if (FID.isInvalid())
1029       continue;
1030 
1031     // We only care about the predefines buffer.
1032     if (FID != PP.getPredefinesFileID())
1033       continue;
1034 
1035     PredefinedDef = Def;
1036     break;
1037   }
1038 
1039   // If there was no definition for this macro in the predefines buffer,
1040   // complain.
1041   if (!PredefinedDef ||
1042       (!PredefinedDef.getLocation().isValid() &&
1043        PredefinedDef.getUndefLocation().isValid())) {
1044     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1045       << false << ConfigMacro << Mod->getFullModuleName();
1046     PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1047       << false;
1048     return;
1049   }
1050 
1051   // If the current macro definition is the same as the predefined macro
1052   // definition, it's okay.
1053   if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
1054       LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
1055                                               /*Syntactically=*/true))
1056     return;
1057 
1058   // The macro definitions differ.
1059   PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1060     << false << ConfigMacro << Mod->getFullModuleName();
1061   PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1062     << false;
1063 }
1064 
1065 /// \brief Write a new timestamp file with the given path.
1066 static void writeTimestampFile(StringRef TimestampFile) {
1067   std::string ErrorInfo;
1068   llvm::raw_fd_ostream Out(TimestampFile.str().c_str(), ErrorInfo,
1069                            llvm::sys::fs::F_None);
1070 }
1071 
1072 /// \brief Prune the module cache of modules that haven't been accessed in
1073 /// a long time.
1074 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1075   struct stat StatBuf;
1076   llvm::SmallString<128> TimestampFile;
1077   TimestampFile = HSOpts.ModuleCachePath;
1078   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1079 
1080   // Try to stat() the timestamp file.
1081   if (::stat(TimestampFile.c_str(), &StatBuf)) {
1082     // If the timestamp file wasn't there, create one now.
1083     if (errno == ENOENT) {
1084       writeTimestampFile(TimestampFile);
1085     }
1086     return;
1087   }
1088 
1089   // Check whether the time stamp is older than our pruning interval.
1090   // If not, do nothing.
1091   time_t TimeStampModTime = StatBuf.st_mtime;
1092   time_t CurrentTime = time(nullptr);
1093   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1094     return;
1095 
1096   // Write a new timestamp file so that nobody else attempts to prune.
1097   // There is a benign race condition here, if two Clang instances happen to
1098   // notice at the same time that the timestamp is out-of-date.
1099   writeTimestampFile(TimestampFile);
1100 
1101   // Walk the entire module cache, looking for unused module files and module
1102   // indices.
1103   std::error_code EC;
1104   SmallString<128> ModuleCachePathNative;
1105   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1106   for (llvm::sys::fs::directory_iterator
1107          Dir(ModuleCachePathNative.str(), EC), DirEnd;
1108        Dir != DirEnd && !EC; Dir.increment(EC)) {
1109     // If we don't have a directory, there's nothing to look into.
1110     if (!llvm::sys::fs::is_directory(Dir->path()))
1111       continue;
1112 
1113     // Walk all of the files within this directory.
1114     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1115          File != FileEnd && !EC; File.increment(EC)) {
1116       // We only care about module and global module index files.
1117       StringRef Extension = llvm::sys::path::extension(File->path());
1118       if (Extension != ".pcm" && Extension != ".timestamp" &&
1119           llvm::sys::path::filename(File->path()) != "modules.idx")
1120         continue;
1121 
1122       // Look at this file. If we can't stat it, there's nothing interesting
1123       // there.
1124       if (::stat(File->path().c_str(), &StatBuf))
1125         continue;
1126 
1127       // If the file has been used recently enough, leave it there.
1128       time_t FileAccessTime = StatBuf.st_atime;
1129       if (CurrentTime - FileAccessTime <=
1130               time_t(HSOpts.ModuleCachePruneAfter)) {
1131         continue;
1132       }
1133 
1134       // Remove the file.
1135       llvm::sys::fs::remove(File->path());
1136 
1137       // Remove the timestamp file.
1138       std::string TimpestampFilename = File->path() + ".timestamp";
1139       llvm::sys::fs::remove(TimpestampFilename);
1140     }
1141 
1142     // If we removed all of the files in the directory, remove the directory
1143     // itself.
1144     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1145             llvm::sys::fs::directory_iterator() && !EC)
1146       llvm::sys::fs::remove(Dir->path());
1147   }
1148 }
1149 
1150 void CompilerInstance::createModuleManager() {
1151   if (!ModuleManager) {
1152     if (!hasASTContext())
1153       createASTContext();
1154 
1155     // If we're not recursively building a module, check whether we
1156     // need to prune the module cache.
1157     if (getSourceManager().getModuleBuildStack().empty() &&
1158         getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1159         getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1160       pruneModuleCache(getHeaderSearchOpts());
1161     }
1162 
1163     HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1164     std::string Sysroot = HSOpts.Sysroot;
1165     const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1166     ModuleManager = new ASTReader(getPreprocessor(), *Context,
1167                                   Sysroot.empty() ? "" : Sysroot.c_str(),
1168                                   PPOpts.DisablePCHValidation,
1169                                   /*AllowASTWithCompilerErrors=*/false,
1170                                   /*AllowConfigurationMismatch=*/false,
1171                                   HSOpts.ModulesValidateSystemHeaders,
1172                                   getFrontendOpts().UseGlobalModuleIndex);
1173     if (hasASTConsumer()) {
1174       ModuleManager->setDeserializationListener(
1175         getASTConsumer().GetASTDeserializationListener());
1176       getASTContext().setASTMutationListener(
1177         getASTConsumer().GetASTMutationListener());
1178     }
1179     getASTContext().setExternalSource(ModuleManager);
1180     if (hasSema())
1181       ModuleManager->InitializeSema(getSema());
1182     if (hasASTConsumer())
1183       ModuleManager->StartTranslationUnit(&getASTConsumer());
1184   }
1185 }
1186 
1187 ModuleLoadResult
1188 CompilerInstance::loadModule(SourceLocation ImportLoc,
1189                              ModuleIdPath Path,
1190                              Module::NameVisibilityKind Visibility,
1191                              bool IsInclusionDirective) {
1192   // Determine what file we're searching from.
1193   StringRef ModuleName = Path[0].first->getName();
1194   SourceLocation ModuleNameLoc = Path[0].second;
1195 
1196   // If we've already handled this import, just return the cached result.
1197   // This one-element cache is important to eliminate redundant diagnostics
1198   // when both the preprocessor and parser see the same import declaration.
1199   if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
1200     // Make the named module visible.
1201     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1202       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1203                                        ImportLoc, /*Complain=*/false);
1204     return LastModuleImportResult;
1205   }
1206 
1207   clang::Module *Module = nullptr;
1208 
1209   // If we don't already have information on this module, load the module now.
1210   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1211     = KnownModules.find(Path[0].first);
1212   if (Known != KnownModules.end()) {
1213     // Retrieve the cached top-level module.
1214     Module = Known->second;
1215   } else if (ModuleName == getLangOpts().CurrentModule) {
1216     // This is the module we're building.
1217     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1218     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1219   } else {
1220     // Search for a module with the given name.
1221     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1222     if (!Module) {
1223       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1224       << ModuleName
1225       << SourceRange(ImportLoc, ModuleNameLoc);
1226       ModuleBuildFailed = true;
1227       return ModuleLoadResult();
1228     }
1229 
1230     std::string ModuleFileName =
1231         PP->getHeaderSearchInfo().getModuleFileName(Module);
1232 
1233     // If we don't already have an ASTReader, create one now.
1234     if (!ModuleManager)
1235       createModuleManager();
1236 
1237     if (TheDependencyFileGenerator)
1238       TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1239 
1240     if (ModuleDepCollector)
1241       ModuleDepCollector->attachToASTReader(*ModuleManager);
1242 
1243     for (auto &Listener : DependencyCollectors)
1244       Listener->attachToASTReader(*ModuleManager);
1245 
1246     // Try to load the module file.
1247     unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
1248     switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module,
1249                                    ImportLoc, ARRFlags)) {
1250     case ASTReader::Success:
1251       break;
1252 
1253     case ASTReader::OutOfDate:
1254     case ASTReader::Missing: {
1255       // The module file is missing or out-of-date. Build it.
1256       assert(Module && "missing module file");
1257       // Check whether there is a cycle in the module graph.
1258       ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1259       ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1260       for (; Pos != PosEnd; ++Pos) {
1261         if (Pos->first == ModuleName)
1262           break;
1263       }
1264 
1265       if (Pos != PosEnd) {
1266         SmallString<256> CyclePath;
1267         for (; Pos != PosEnd; ++Pos) {
1268           CyclePath += Pos->first;
1269           CyclePath += " -> ";
1270         }
1271         CyclePath += ModuleName;
1272 
1273         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1274           << ModuleName << CyclePath;
1275         return ModuleLoadResult();
1276       }
1277 
1278       getDiagnostics().Report(ImportLoc, diag::remark_module_build)
1279           << ModuleName << ModuleFileName;
1280 
1281       // Check whether we have already attempted to build this module (but
1282       // failed).
1283       if (getPreprocessorOpts().FailedModules &&
1284           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1285         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1286           << ModuleName
1287           << SourceRange(ImportLoc, ModuleNameLoc);
1288         ModuleBuildFailed = true;
1289         return ModuleLoadResult();
1290       }
1291 
1292       // Try to compile and then load the module.
1293       if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1294                                 ModuleFileName)) {
1295         if (getPreprocessorOpts().FailedModules)
1296           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1297         KnownModules[Path[0].first] = nullptr;
1298         ModuleBuildFailed = true;
1299         return ModuleLoadResult();
1300       }
1301 
1302       // Okay, we've rebuilt and now loaded the module.
1303       break;
1304     }
1305 
1306     case ASTReader::VersionMismatch:
1307     case ASTReader::ConfigurationMismatch:
1308     case ASTReader::HadErrors:
1309       ModuleLoader::HadFatalFailure = true;
1310       // FIXME: The ASTReader will already have complained, but can we showhorn
1311       // that diagnostic information into a more useful form?
1312       KnownModules[Path[0].first] = nullptr;
1313       return ModuleLoadResult();
1314 
1315     case ASTReader::Failure:
1316       ModuleLoader::HadFatalFailure = true;
1317       // Already complained, but note now that we failed.
1318       KnownModules[Path[0].first] = nullptr;
1319       ModuleBuildFailed = true;
1320       return ModuleLoadResult();
1321     }
1322 
1323     // Cache the result of this top-level module lookup for later.
1324     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1325   }
1326 
1327   // If we never found the module, fail.
1328   if (!Module)
1329     return ModuleLoadResult();
1330 
1331   // Verify that the rest of the module path actually corresponds to
1332   // a submodule.
1333   if (Path.size() > 1) {
1334     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1335       StringRef Name = Path[I].first->getName();
1336       clang::Module *Sub = Module->findSubmodule(Name);
1337 
1338       if (!Sub) {
1339         // Attempt to perform typo correction to find a module name that works.
1340         SmallVector<StringRef, 2> Best;
1341         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1342 
1343         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1344                                             JEnd = Module->submodule_end();
1345              J != JEnd; ++J) {
1346           unsigned ED = Name.edit_distance((*J)->Name,
1347                                            /*AllowReplacements=*/true,
1348                                            BestEditDistance);
1349           if (ED <= BestEditDistance) {
1350             if (ED < BestEditDistance) {
1351               Best.clear();
1352               BestEditDistance = ED;
1353             }
1354 
1355             Best.push_back((*J)->Name);
1356           }
1357         }
1358 
1359         // If there was a clear winner, user it.
1360         if (Best.size() == 1) {
1361           getDiagnostics().Report(Path[I].second,
1362                                   diag::err_no_submodule_suggest)
1363             << Path[I].first << Module->getFullModuleName() << Best[0]
1364             << SourceRange(Path[0].second, Path[I-1].second)
1365             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1366                                             Best[0]);
1367 
1368           Sub = Module->findSubmodule(Best[0]);
1369         }
1370       }
1371 
1372       if (!Sub) {
1373         // No submodule by this name. Complain, and don't look for further
1374         // submodules.
1375         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1376           << Path[I].first << Module->getFullModuleName()
1377           << SourceRange(Path[0].second, Path[I-1].second);
1378         break;
1379       }
1380 
1381       Module = Sub;
1382     }
1383   }
1384 
1385   // Make the named module visible, if it's not already part of the module
1386   // we are parsing.
1387   if (ModuleName != getLangOpts().CurrentModule) {
1388     if (!Module->IsFromModuleFile) {
1389       // We have an umbrella header or directory that doesn't actually include
1390       // all of the headers within the directory it covers. Complain about
1391       // this missing submodule and recover by forgetting that we ever saw
1392       // this submodule.
1393       // FIXME: Should we detect this at module load time? It seems fairly
1394       // expensive (and rare).
1395       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1396         << Module->getFullModuleName()
1397         << SourceRange(Path.front().second, Path.back().second);
1398 
1399       return ModuleLoadResult(nullptr, true);
1400     }
1401 
1402     // Check whether this module is available.
1403     clang::Module::Requirement Requirement;
1404     clang::Module::HeaderDirective MissingHeader;
1405     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
1406                              MissingHeader)) {
1407       if (MissingHeader.FileNameLoc.isValid()) {
1408         getDiagnostics().Report(MissingHeader.FileNameLoc,
1409                                 diag::err_module_header_missing)
1410           << MissingHeader.IsUmbrella << MissingHeader.FileName;
1411       } else {
1412         getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1413           << Module->getFullModuleName()
1414           << Requirement.second << Requirement.first
1415           << SourceRange(Path.front().second, Path.back().second);
1416       }
1417       LastModuleImportLoc = ImportLoc;
1418       LastModuleImportResult = ModuleLoadResult();
1419       return ModuleLoadResult();
1420     }
1421 
1422     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
1423                                      /*Complain=*/true);
1424   }
1425 
1426   // Check for any configuration macros that have changed.
1427   clang::Module *TopModule = Module->getTopLevelModule();
1428   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1429     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1430                      Module, ImportLoc);
1431   }
1432 
1433   // If this module import was due to an inclusion directive, create an
1434   // implicit import declaration to capture it in the AST.
1435   if (IsInclusionDirective && hasASTContext()) {
1436     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1437     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1438                                                      ImportLoc, Module,
1439                                                      Path.back().second);
1440     TU->addDecl(ImportD);
1441     if (Consumer)
1442       Consumer->HandleImplicitImportDecl(ImportD);
1443   }
1444 
1445   LastModuleImportLoc = ImportLoc;
1446   LastModuleImportResult = ModuleLoadResult(Module, false);
1447   return LastModuleImportResult;
1448 }
1449 
1450 void CompilerInstance::makeModuleVisible(Module *Mod,
1451                                          Module::NameVisibilityKind Visibility,
1452                                          SourceLocation ImportLoc,
1453                                          bool Complain){
1454   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
1455 }
1456 
1457 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
1458     SourceLocation TriggerLoc) {
1459   if (!ModuleManager)
1460     createModuleManager();
1461   // Can't do anything if we don't have the module manager.
1462   if (!ModuleManager)
1463     return nullptr;
1464   // Get an existing global index.  This loads it if not already
1465   // loaded.
1466   ModuleManager->loadGlobalIndex();
1467   GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1468   // If the global index doesn't exist, create it.
1469   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
1470       hasPreprocessor()) {
1471     llvm::sys::fs::create_directories(
1472       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1473     GlobalModuleIndex::writeIndex(
1474       getFileManager(),
1475       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1476     ModuleManager->resetForReload();
1477     ModuleManager->loadGlobalIndex();
1478     GlobalIndex = ModuleManager->getGlobalIndex();
1479   }
1480   // For finding modules needing to be imported for fixit messages,
1481   // we need to make the global index cover all modules, so we do that here.
1482   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
1483     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1484     bool RecreateIndex = false;
1485     for (ModuleMap::module_iterator I = MMap.module_begin(),
1486         E = MMap.module_end(); I != E; ++I) {
1487       Module *TheModule = I->second;
1488       const FileEntry *Entry = TheModule->getASTFile();
1489       if (!Entry) {
1490         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1491         Path.push_back(std::make_pair(
1492 				  getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
1493         std::reverse(Path.begin(), Path.end());
1494 		    // Load a module as hidden.  This also adds it to the global index.
1495         loadModule(TheModule->DefinitionLoc, Path,
1496                                              Module::Hidden, false);
1497         RecreateIndex = true;
1498       }
1499     }
1500     if (RecreateIndex) {
1501       GlobalModuleIndex::writeIndex(
1502         getFileManager(),
1503         getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1504       ModuleManager->resetForReload();
1505       ModuleManager->loadGlobalIndex();
1506       GlobalIndex = ModuleManager->getGlobalIndex();
1507     }
1508     HaveFullGlobalModuleIndex = true;
1509   }
1510   return GlobalIndex;
1511 }
1512 
1513 // Check global module index for missing imports.
1514 bool
1515 CompilerInstance::lookupMissingImports(StringRef Name,
1516                                        SourceLocation TriggerLoc) {
1517   // Look for the symbol in non-imported modules, but only if an error
1518   // actually occurred.
1519   if (!buildingModule()) {
1520     // Load global module index, or retrieve a previously loaded one.
1521     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
1522       TriggerLoc);
1523 
1524     // Only if we have a global index.
1525     if (GlobalIndex) {
1526       GlobalModuleIndex::HitSet FoundModules;
1527 
1528       // Find the modules that reference the identifier.
1529       // Note that this only finds top-level modules.
1530       // We'll let diagnoseTypo find the actual declaration module.
1531       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
1532         return true;
1533     }
1534   }
1535 
1536   return false;
1537 }
1538