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