xref: /freebsd/contrib/llvm-project/clang/lib/Frontend/FrontendAction.cpp (revision fe75646a0234a261c0013bf1840fdac4acaf0cec)
1 //===--- FrontendAction.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Frontend/FrontendAction.h"
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/DeclGroup.h"
13 #include "clang/Basic/Builtins.h"
14 #include "clang/Basic/DiagnosticOptions.h"
15 #include "clang/Basic/FileEntry.h"
16 #include "clang/Basic/LangStandard.h"
17 #include "clang/Basic/Sarif.h"
18 #include "clang/Basic/Stack.h"
19 #include "clang/Frontend/ASTUnit.h"
20 #include "clang/Frontend/CompilerInstance.h"
21 #include "clang/Frontend/FrontendDiagnostic.h"
22 #include "clang/Frontend/FrontendPluginRegistry.h"
23 #include "clang/Frontend/LayoutOverrideSource.h"
24 #include "clang/Frontend/MultiplexConsumer.h"
25 #include "clang/Frontend/SARIFDiagnosticPrinter.h"
26 #include "clang/Frontend/Utils.h"
27 #include "clang/Lex/HeaderSearch.h"
28 #include "clang/Lex/LiteralSupport.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Lex/PreprocessorOptions.h"
31 #include "clang/Parse/ParseAST.h"
32 #include "clang/Sema/HLSLExternalSemaSource.h"
33 #include "clang/Sema/MultiplexExternalSemaSource.h"
34 #include "clang/Serialization/ASTDeserializationListener.h"
35 #include "clang/Serialization/ASTReader.h"
36 #include "clang/Serialization/GlobalModuleIndex.h"
37 #include "llvm/ADT/ScopeExit.h"
38 #include "llvm/Support/BuryPointer.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include <memory>
45 #include <system_error>
46 using namespace clang;
47 
48 LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
49 
50 namespace {
51 
52 class DelegatingDeserializationListener : public ASTDeserializationListener {
53   ASTDeserializationListener *Previous;
54   bool DeletePrevious;
55 
56 public:
57   explicit DelegatingDeserializationListener(
58       ASTDeserializationListener *Previous, bool DeletePrevious)
59       : Previous(Previous), DeletePrevious(DeletePrevious) {}
60   ~DelegatingDeserializationListener() override {
61     if (DeletePrevious)
62       delete Previous;
63   }
64 
65   void ReaderInitialized(ASTReader *Reader) override {
66     if (Previous)
67       Previous->ReaderInitialized(Reader);
68   }
69   void IdentifierRead(serialization::IdentID ID,
70                       IdentifierInfo *II) override {
71     if (Previous)
72       Previous->IdentifierRead(ID, II);
73   }
74   void TypeRead(serialization::TypeIdx Idx, QualType T) override {
75     if (Previous)
76       Previous->TypeRead(Idx, T);
77   }
78   void DeclRead(serialization::DeclID ID, const Decl *D) override {
79     if (Previous)
80       Previous->DeclRead(ID, D);
81   }
82   void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
83     if (Previous)
84       Previous->SelectorRead(ID, Sel);
85   }
86   void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
87                            MacroDefinitionRecord *MD) override {
88     if (Previous)
89       Previous->MacroDefinitionRead(PPID, MD);
90   }
91 };
92 
93 /// Dumps deserialized declarations.
94 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
95 public:
96   explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
97                                    bool DeletePrevious)
98       : DelegatingDeserializationListener(Previous, DeletePrevious) {}
99 
100   void DeclRead(serialization::DeclID ID, const Decl *D) override {
101     llvm::outs() << "PCH DECL: " << D->getDeclKindName();
102     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
103       llvm::outs() << " - ";
104       ND->printQualifiedName(llvm::outs());
105     }
106     llvm::outs() << "\n";
107 
108     DelegatingDeserializationListener::DeclRead(ID, D);
109   }
110 };
111 
112 /// Checks deserialized declarations and emits error if a name
113 /// matches one given in command-line using -error-on-deserialized-decl.
114 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
115   ASTContext &Ctx;
116   std::set<std::string> NamesToCheck;
117 
118 public:
119   DeserializedDeclsChecker(ASTContext &Ctx,
120                            const std::set<std::string> &NamesToCheck,
121                            ASTDeserializationListener *Previous,
122                            bool DeletePrevious)
123       : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
124         NamesToCheck(NamesToCheck) {}
125 
126   void DeclRead(serialization::DeclID ID, const Decl *D) override {
127     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
128       if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
129         unsigned DiagID
130           = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
131                                                  "%0 was deserialized");
132         Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
133             << ND;
134       }
135 
136     DelegatingDeserializationListener::DeclRead(ID, D);
137   }
138 };
139 
140 } // end anonymous namespace
141 
142 FrontendAction::FrontendAction() : Instance(nullptr) {}
143 
144 FrontendAction::~FrontendAction() {}
145 
146 void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
147                                      std::unique_ptr<ASTUnit> AST) {
148   this->CurrentInput = CurrentInput;
149   CurrentASTUnit = std::move(AST);
150 }
151 
152 Module *FrontendAction::getCurrentModule() const {
153   CompilerInstance &CI = getCompilerInstance();
154   return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
155       CI.getLangOpts().CurrentModule, SourceLocation(), /*AllowSearch*/false);
156 }
157 
158 std::unique_ptr<ASTConsumer>
159 FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
160                                          StringRef InFile) {
161   std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
162   if (!Consumer)
163     return nullptr;
164 
165   // Validate -add-plugin args.
166   bool FoundAllPlugins = true;
167   for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) {
168     bool Found = false;
169     for (const FrontendPluginRegistry::entry &Plugin :
170          FrontendPluginRegistry::entries()) {
171       if (Plugin.getName() == Arg)
172         Found = true;
173     }
174     if (!Found) {
175       CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name) << Arg;
176       FoundAllPlugins = false;
177     }
178   }
179   if (!FoundAllPlugins)
180     return nullptr;
181 
182   // If there are no registered plugins we don't need to wrap the consumer
183   if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
184     return Consumer;
185 
186   // If this is a code completion run, avoid invoking the plugin consumers
187   if (CI.hasCodeCompletionConsumer())
188     return Consumer;
189 
190   // Collect the list of plugins that go before the main action (in Consumers)
191   // or after it (in AfterConsumers)
192   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
193   std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
194   for (const FrontendPluginRegistry::entry &Plugin :
195        FrontendPluginRegistry::entries()) {
196     std::unique_ptr<PluginASTAction> P = Plugin.instantiate();
197     PluginASTAction::ActionType ActionType = P->getActionType();
198     if (ActionType == PluginASTAction::CmdlineAfterMainAction ||
199         ActionType == PluginASTAction::CmdlineBeforeMainAction) {
200       // This is O(|plugins| * |add_plugins|), but since both numbers are
201       // way below 50 in practice, that's ok.
202       if (llvm::is_contained(CI.getFrontendOpts().AddPluginActions,
203                              Plugin.getName())) {
204         if (ActionType == PluginASTAction::CmdlineBeforeMainAction)
205           ActionType = PluginASTAction::AddBeforeMainAction;
206         else
207           ActionType = PluginASTAction::AddAfterMainAction;
208       }
209     }
210     if ((ActionType == PluginASTAction::AddBeforeMainAction ||
211          ActionType == PluginASTAction::AddAfterMainAction) &&
212         P->ParseArgs(
213             CI,
214             CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())])) {
215       std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
216       if (ActionType == PluginASTAction::AddBeforeMainAction) {
217         Consumers.push_back(std::move(PluginConsumer));
218       } else {
219         AfterConsumers.push_back(std::move(PluginConsumer));
220       }
221     }
222   }
223 
224   // Add to Consumers the main consumer, then all the plugins that go after it
225   Consumers.push_back(std::move(Consumer));
226   if (!AfterConsumers.empty()) {
227     // If we have plugins after the main consumer, which may be the codegen
228     // action, they likely will need the ASTContext, so don't clear it in the
229     // codegen action.
230     CI.getCodeGenOpts().ClearASTBeforeBackend = false;
231     for (auto &C : AfterConsumers)
232       Consumers.push_back(std::move(C));
233   }
234 
235   return std::make_unique<MultiplexConsumer>(std::move(Consumers));
236 }
237 
238 /// For preprocessed files, if the first line is the linemarker and specifies
239 /// the original source file name, use that name as the input file name.
240 /// Returns the location of the first token after the line marker directive.
241 ///
242 /// \param CI The compiler instance.
243 /// \param InputFile Populated with the filename from the line marker.
244 /// \param IsModuleMap If \c true, add a line note corresponding to this line
245 ///        directive. (We need to do this because the directive will not be
246 ///        visited by the preprocessor.)
247 static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
248                                            std::string &InputFile,
249                                            bool IsModuleMap = false) {
250   auto &SourceMgr = CI.getSourceManager();
251   auto MainFileID = SourceMgr.getMainFileID();
252 
253   auto MainFileBuf = SourceMgr.getBufferOrNone(MainFileID);
254   if (!MainFileBuf)
255     return SourceLocation();
256 
257   std::unique_ptr<Lexer> RawLexer(
258       new Lexer(MainFileID, *MainFileBuf, SourceMgr, CI.getLangOpts()));
259 
260   // If the first line has the syntax of
261   //
262   // # NUM "FILENAME"
263   //
264   // we use FILENAME as the input file name.
265   Token T;
266   if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
267     return SourceLocation();
268   if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
269       T.getKind() != tok::numeric_constant)
270     return SourceLocation();
271 
272   unsigned LineNo;
273   SourceLocation LineNoLoc = T.getLocation();
274   if (IsModuleMap) {
275     llvm::SmallString<16> Buffer;
276     if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
277             .getAsInteger(10, LineNo))
278       return SourceLocation();
279   }
280 
281   RawLexer->LexFromRawLexer(T);
282   if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
283     return SourceLocation();
284 
285   StringLiteralParser Literal(T, CI.getPreprocessor());
286   if (Literal.hadError)
287     return SourceLocation();
288   RawLexer->LexFromRawLexer(T);
289   if (T.isNot(tok::eof) && !T.isAtStartOfLine())
290     return SourceLocation();
291   InputFile = Literal.GetString().str();
292 
293   if (IsModuleMap)
294     CI.getSourceManager().AddLineNote(
295         LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
296         false, SrcMgr::C_User_ModuleMap);
297 
298   return T.getLocation();
299 }
300 
301 static SmallVectorImpl<char> &
302 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
303   Includes.append(RHS.begin(), RHS.end());
304   return Includes;
305 }
306 
307 static void addHeaderInclude(StringRef HeaderName,
308                              SmallVectorImpl<char> &Includes,
309                              const LangOptions &LangOpts,
310                              bool IsExternC) {
311   if (IsExternC && LangOpts.CPlusPlus)
312     Includes += "extern \"C\" {\n";
313   if (LangOpts.ObjC)
314     Includes += "#import \"";
315   else
316     Includes += "#include \"";
317 
318   Includes += HeaderName;
319 
320   Includes += "\"\n";
321   if (IsExternC && LangOpts.CPlusPlus)
322     Includes += "}\n";
323 }
324 
325 /// Collect the set of header includes needed to construct the given
326 /// module and update the TopHeaders file set of the module.
327 ///
328 /// \param Module The module we're collecting includes from.
329 ///
330 /// \param Includes Will be augmented with the set of \#includes or \#imports
331 /// needed to load all of the named headers.
332 static std::error_code collectModuleHeaderIncludes(
333     const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
334     ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
335   // Don't collect any headers for unavailable modules.
336   if (!Module->isAvailable())
337     return std::error_code();
338 
339   // Resolve all lazy header directives to header files.
340   ModMap.resolveHeaderDirectives(Module, /*File=*/std::nullopt);
341 
342   // If any headers are missing, we can't build this module. In most cases,
343   // diagnostics for this should have already been produced; we only get here
344   // if explicit stat information was provided.
345   // FIXME: If the name resolves to a file with different stat information,
346   // produce a better diagnostic.
347   if (!Module->MissingHeaders.empty()) {
348     auto &MissingHeader = Module->MissingHeaders.front();
349     Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
350       << MissingHeader.IsUmbrella << MissingHeader.FileName;
351     return std::error_code();
352   }
353 
354   // Add includes for each of these headers.
355   for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
356     for (Module::Header &H : Module->Headers[HK]) {
357       Module->addTopHeader(H.Entry);
358       // Use the path as specified in the module map file. We'll look for this
359       // file relative to the module build directory (the directory containing
360       // the module map file) so this will find the same file that we found
361       // while parsing the module map.
362       addHeaderInclude(H.PathRelativeToRootModuleDirectory, Includes, LangOpts,
363                        Module->IsExternC);
364     }
365   }
366   // Note that Module->PrivateHeaders will not be a TopHeader.
367 
368   if (std::optional<Module::Header> UmbrellaHeader =
369           Module->getUmbrellaHeaderAsWritten()) {
370     Module->addTopHeader(UmbrellaHeader->Entry);
371     if (Module->Parent)
372       // Include the umbrella header for submodules.
373       addHeaderInclude(UmbrellaHeader->PathRelativeToRootModuleDirectory,
374                        Includes, LangOpts, Module->IsExternC);
375   } else if (std::optional<Module::DirectoryName> UmbrellaDir =
376                  Module->getUmbrellaDirAsWritten()) {
377     // Add all of the headers we find in this subdirectory.
378     std::error_code EC;
379     SmallString<128> DirNative;
380     llvm::sys::path::native(UmbrellaDir->Entry.getName(), DirNative);
381 
382     llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
383     SmallVector<std::pair<std::string, FileEntryRef>, 8> Headers;
384     for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
385          Dir != End && !EC; Dir.increment(EC)) {
386       // Check whether this entry has an extension typically associated with
387       // headers.
388       if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
389                .Cases(".h", ".H", ".hh", ".hpp", true)
390                .Default(false))
391         continue;
392 
393       auto Header = FileMgr.getOptionalFileRef(Dir->path());
394       // FIXME: This shouldn't happen unless there is a file system race. Is
395       // that worth diagnosing?
396       if (!Header)
397         continue;
398 
399       // If this header is marked 'unavailable' in this module, don't include
400       // it.
401       if (ModMap.isHeaderUnavailableInModule(*Header, Module))
402         continue;
403 
404       // Compute the relative path from the directory to this file.
405       SmallVector<StringRef, 16> Components;
406       auto PathIt = llvm::sys::path::rbegin(Dir->path());
407       for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
408         Components.push_back(*PathIt);
409       SmallString<128> RelativeHeader(
410           UmbrellaDir->PathRelativeToRootModuleDirectory);
411       for (auto It = Components.rbegin(), End = Components.rend(); It != End;
412            ++It)
413         llvm::sys::path::append(RelativeHeader, *It);
414 
415       std::string RelName = RelativeHeader.c_str();
416       Headers.push_back(std::make_pair(RelName, *Header));
417     }
418 
419     if (EC)
420       return EC;
421 
422     // Sort header paths and make the header inclusion order deterministic
423     // across different OSs and filesystems.
424     llvm::sort(Headers, llvm::less_first());
425     for (auto &H : Headers) {
426       // Include this header as part of the umbrella directory.
427       Module->addTopHeader(H.second);
428       addHeaderInclude(H.first, Includes, LangOpts, Module->IsExternC);
429     }
430   }
431 
432   // Recurse into submodules.
433   for (auto *Submodule : Module->submodules())
434     if (std::error_code Err = collectModuleHeaderIncludes(
435             LangOpts, FileMgr, Diag, ModMap, Submodule, Includes))
436       return Err;
437 
438   return std::error_code();
439 }
440 
441 static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
442                                         bool IsPreprocessed,
443                                         std::string &PresumedModuleMapFile,
444                                         unsigned &Offset) {
445   auto &SrcMgr = CI.getSourceManager();
446   HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
447 
448   // Map the current input to a file.
449   FileID ModuleMapID = SrcMgr.getMainFileID();
450   OptionalFileEntryRef ModuleMap = SrcMgr.getFileEntryRefForID(ModuleMapID);
451   assert(ModuleMap && "MainFileID without FileEntry");
452 
453   // If the module map is preprocessed, handle the initial line marker;
454   // line directives are not part of the module map syntax in general.
455   Offset = 0;
456   if (IsPreprocessed) {
457     SourceLocation EndOfLineMarker =
458         ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
459     if (EndOfLineMarker.isValid())
460       Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
461   }
462 
463   // Load the module map file.
464   if (HS.loadModuleMapFile(*ModuleMap, IsSystem, ModuleMapID, &Offset,
465                            PresumedModuleMapFile))
466     return true;
467 
468   if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
469     Offset = 0;
470 
471   // Infer framework module if possible.
472   if (HS.getModuleMap().canInferFrameworkModule(ModuleMap->getDir())) {
473     SmallString<128> InferredFrameworkPath = ModuleMap->getDir().getName();
474     llvm::sys::path::append(InferredFrameworkPath,
475                             CI.getLangOpts().ModuleName + ".framework");
476     if (auto Dir =
477             CI.getFileManager().getOptionalDirectoryRef(InferredFrameworkPath))
478       (void)HS.getModuleMap().inferFrameworkModule(*Dir, IsSystem, nullptr);
479   }
480 
481   return false;
482 }
483 
484 static Module *prepareToBuildModule(CompilerInstance &CI,
485                                     StringRef ModuleMapFilename) {
486   if (CI.getLangOpts().CurrentModule.empty()) {
487     CI.getDiagnostics().Report(diag::err_missing_module_name);
488 
489     // FIXME: Eventually, we could consider asking whether there was just
490     // a single module described in the module map, and use that as a
491     // default. Then it would be fairly trivial to just "compile" a module
492     // map with a single module (the common case).
493     return nullptr;
494   }
495 
496   // Dig out the module definition.
497   HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
498   Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule, SourceLocation(),
499                               /*AllowSearch=*/true);
500   if (!M) {
501     CI.getDiagnostics().Report(diag::err_missing_module)
502       << CI.getLangOpts().CurrentModule << ModuleMapFilename;
503 
504     return nullptr;
505   }
506 
507   // Check whether we can build this module at all.
508   if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(),
509                                            CI.getDiagnostics(), M))
510     return nullptr;
511 
512   // Inform the preprocessor that includes from within the input buffer should
513   // be resolved relative to the build directory of the module map file.
514   CI.getPreprocessor().setMainFileDir(*M->Directory);
515 
516   // If the module was inferred from a different module map (via an expanded
517   // umbrella module definition), track that fact.
518   // FIXME: It would be preferable to fill this in as part of processing
519   // the module map, rather than adding it after the fact.
520   StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
521   if (!OriginalModuleMapName.empty()) {
522     auto OriginalModuleMap =
523         CI.getFileManager().getFile(OriginalModuleMapName,
524                                     /*openFile*/ true);
525     if (!OriginalModuleMap) {
526       CI.getDiagnostics().Report(diag::err_module_map_not_found)
527         << OriginalModuleMapName;
528       return nullptr;
529     }
530     if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
531                                  CI.getSourceManager().getMainFileID())) {
532       M->IsInferred = true;
533       CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
534         .setInferredModuleAllowedBy(M, *OriginalModuleMap);
535     }
536   }
537 
538   // If we're being run from the command-line, the module build stack will not
539   // have been filled in yet, so complete it now in order to allow us to detect
540   // module cycles.
541   SourceManager &SourceMgr = CI.getSourceManager();
542   if (SourceMgr.getModuleBuildStack().empty())
543     SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
544                                    FullSourceLoc(SourceLocation(), SourceMgr));
545   return M;
546 }
547 
548 /// Compute the input buffer that should be used to build the specified module.
549 static std::unique_ptr<llvm::MemoryBuffer>
550 getInputBufferForModule(CompilerInstance &CI, Module *M) {
551   FileManager &FileMgr = CI.getFileManager();
552 
553   // Collect the set of #includes we need to build the module.
554   SmallString<256> HeaderContents;
555   std::error_code Err = std::error_code();
556   if (std::optional<Module::Header> UmbrellaHeader =
557           M->getUmbrellaHeaderAsWritten())
558     addHeaderInclude(UmbrellaHeader->PathRelativeToRootModuleDirectory,
559                      HeaderContents, CI.getLangOpts(), M->IsExternC);
560   Err = collectModuleHeaderIncludes(
561       CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
562       CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
563       HeaderContents);
564 
565   if (Err) {
566     CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
567       << M->getFullModuleName() << Err.message();
568     return nullptr;
569   }
570 
571   return llvm::MemoryBuffer::getMemBufferCopy(
572       HeaderContents, Module::getModuleInputBufferName());
573 }
574 
575 bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
576                                      const FrontendInputFile &RealInput) {
577   FrontendInputFile Input(RealInput);
578   assert(!Instance && "Already processing a source file!");
579   assert(!Input.isEmpty() && "Unexpected empty filename!");
580   setCurrentInput(Input);
581   setCompilerInstance(&CI);
582 
583   bool HasBegunSourceFile = false;
584   bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
585                        usesPreprocessorOnly();
586 
587   // If we fail, reset state since the client will not end up calling the
588   // matching EndSourceFile(). All paths that return true should release this.
589   auto FailureCleanup = llvm::make_scope_exit([&]() {
590     if (HasBegunSourceFile)
591       CI.getDiagnosticClient().EndSourceFile();
592     CI.setASTConsumer(nullptr);
593     CI.clearOutputFiles(/*EraseFiles=*/true);
594     CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
595     setCurrentInput(FrontendInputFile());
596     setCompilerInstance(nullptr);
597   });
598 
599   if (!BeginInvocation(CI))
600     return false;
601 
602   // If we're replaying the build of an AST file, import it and set up
603   // the initial state from its build.
604   if (ReplayASTFile) {
605     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
606 
607     // The AST unit populates its own diagnostics engine rather than ours.
608     IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
609         new DiagnosticsEngine(Diags->getDiagnosticIDs(),
610                               &Diags->getDiagnosticOptions()));
611     ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
612 
613     // FIXME: What if the input is a memory buffer?
614     StringRef InputFile = Input.getFile();
615 
616     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
617         std::string(InputFile), CI.getPCHContainerReader(),
618         ASTUnit::LoadPreprocessorOnly, ASTDiags, CI.getFileSystemOpts(),
619         /*HeaderSearchOptions=*/nullptr, CI.getCodeGenOpts().DebugTypeExtRefs);
620     if (!AST)
621       return false;
622 
623     // Options relating to how we treat the input (but not what we do with it)
624     // are inherited from the AST unit.
625     CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
626     CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
627     CI.getLangOpts() = AST->getLangOpts();
628 
629     // Set the shared objects, these are reset when we finish processing the
630     // file, otherwise the CompilerInstance will happily destroy them.
631     CI.setFileManager(&AST->getFileManager());
632     CI.createSourceManager(CI.getFileManager());
633     CI.getSourceManager().initializeForReplay(AST->getSourceManager());
634 
635     // Preload all the module files loaded transitively by the AST unit. Also
636     // load all module map files that were parsed as part of building the AST
637     // unit.
638     if (auto ASTReader = AST->getASTReader()) {
639       auto &MM = ASTReader->getModuleManager();
640       auto &PrimaryModule = MM.getPrimaryModule();
641 
642       for (serialization::ModuleFile &MF : MM)
643         if (&MF != &PrimaryModule)
644           CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
645 
646       ASTReader->visitTopLevelModuleMaps(PrimaryModule, [&](FileEntryRef FE) {
647         CI.getFrontendOpts().ModuleMapFiles.push_back(
648             std::string(FE.getName()));
649       });
650     }
651 
652     // Set up the input file for replay purposes.
653     auto Kind = AST->getInputKind();
654     if (Kind.getFormat() == InputKind::ModuleMap) {
655       Module *ASTModule =
656           AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
657               AST->getLangOpts().CurrentModule, SourceLocation(),
658               /*AllowSearch*/ false);
659       assert(ASTModule && "module file does not define its own module");
660       Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
661     } else {
662       auto &OldSM = AST->getSourceManager();
663       FileID ID = OldSM.getMainFileID();
664       if (auto *File = OldSM.getFileEntryForID(ID))
665         Input = FrontendInputFile(File->getName(), Kind);
666       else
667         Input = FrontendInputFile(OldSM.getBufferOrFake(ID), Kind);
668     }
669     setCurrentInput(Input, std::move(AST));
670   }
671 
672   // AST files follow a very different path, since they share objects via the
673   // AST unit.
674   if (Input.getKind().getFormat() == InputKind::Precompiled) {
675     assert(!usesPreprocessorOnly() && "this case was handled above");
676     assert(hasASTFileSupport() &&
677            "This action does not have AST file support!");
678 
679     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
680 
681     // FIXME: What if the input is a memory buffer?
682     StringRef InputFile = Input.getFile();
683 
684     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
685         std::string(InputFile), CI.getPCHContainerReader(),
686         ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts(),
687         CI.getHeaderSearchOptsPtr(),
688         CI.getCodeGenOpts().DebugTypeExtRefs);
689 
690     if (!AST)
691       return false;
692 
693     // Inform the diagnostic client we are processing a source file.
694     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
695     HasBegunSourceFile = true;
696 
697     // Set the shared objects, these are reset when we finish processing the
698     // file, otherwise the CompilerInstance will happily destroy them.
699     CI.setFileManager(&AST->getFileManager());
700     CI.setSourceManager(&AST->getSourceManager());
701     CI.setPreprocessor(AST->getPreprocessorPtr());
702     Preprocessor &PP = CI.getPreprocessor();
703     PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
704                                            PP.getLangOpts());
705     CI.setASTContext(&AST->getASTContext());
706 
707     setCurrentInput(Input, std::move(AST));
708 
709     // Initialize the action.
710     if (!BeginSourceFileAction(CI))
711       return false;
712 
713     // Create the AST consumer.
714     CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
715     if (!CI.hasASTConsumer())
716       return false;
717 
718     FailureCleanup.release();
719     return true;
720   }
721 
722   // Set up the file and source managers, if needed.
723   if (!CI.hasFileManager()) {
724     if (!CI.createFileManager()) {
725       return false;
726     }
727   }
728   if (!CI.hasSourceManager()) {
729     CI.createSourceManager(CI.getFileManager());
730     if (CI.getDiagnosticOpts().getFormat() == DiagnosticOptions::SARIF) {
731       static_cast<SARIFDiagnosticPrinter *>(&CI.getDiagnosticClient())
732           ->setSarifWriter(
733               std::make_unique<SarifDocumentWriter>(CI.getSourceManager()));
734     }
735   }
736 
737   // Set up embedding for any specified files. Do this before we load any
738   // source files, including the primary module map for the compilation.
739   for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
740     if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
741       CI.getSourceManager().setFileIsTransient(*FE);
742     else
743       CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
744   }
745   if (CI.getFrontendOpts().ModulesEmbedAllFiles)
746     CI.getSourceManager().setAllFilesAreTransient(true);
747 
748   // IR files bypass the rest of initialization.
749   if (Input.getKind().getLanguage() == Language::LLVM_IR) {
750     assert(hasIRSupport() &&
751            "This action does not have IR file support!");
752 
753     // Inform the diagnostic client we are processing a source file.
754     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
755     HasBegunSourceFile = true;
756 
757     // Initialize the action.
758     if (!BeginSourceFileAction(CI))
759       return false;
760 
761     // Initialize the main file entry.
762     if (!CI.InitializeSourceManager(CurrentInput))
763       return false;
764 
765     FailureCleanup.release();
766     return true;
767   }
768 
769   // If the implicit PCH include is actually a directory, rather than
770   // a single file, search for a suitable PCH file in that directory.
771   if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
772     FileManager &FileMgr = CI.getFileManager();
773     PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
774     StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
775     std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
776     if (auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude)) {
777       std::error_code EC;
778       SmallString<128> DirNative;
779       llvm::sys::path::native(PCHDir->getName(), DirNative);
780       bool Found = false;
781       llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
782       for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
783                                          DirEnd;
784            Dir != DirEnd && !EC; Dir.increment(EC)) {
785         // Check whether this is an acceptable AST file.
786         if (ASTReader::isAcceptableASTFile(
787                 Dir->path(), FileMgr, CI.getModuleCache(),
788                 CI.getPCHContainerReader(), CI.getLangOpts(),
789                 CI.getTargetOpts(), CI.getPreprocessorOpts(),
790                 SpecificModuleCachePath, /*RequireStrictOptionMatches=*/true)) {
791           PPOpts.ImplicitPCHInclude = std::string(Dir->path());
792           Found = true;
793           break;
794         }
795       }
796 
797       if (!Found) {
798         CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
799         return false;
800       }
801     }
802   }
803 
804   // Set up the preprocessor if needed. When parsing model files the
805   // preprocessor of the original source is reused.
806   if (!isModelParsingAction())
807     CI.createPreprocessor(getTranslationUnitKind());
808 
809   // Inform the diagnostic client we are processing a source file.
810   CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
811                                            &CI.getPreprocessor());
812   HasBegunSourceFile = true;
813 
814   // Handle C++20 header units.
815   // Here, the user has the option to specify that the header name should be
816   // looked up in the pre-processor search paths (and the main filename as
817   // passed by the driver might therefore be incomplete until that look-up).
818   if (CI.getLangOpts().CPlusPlusModules && Input.getKind().isHeaderUnit() &&
819       !Input.getKind().isPreprocessed()) {
820     StringRef FileName = Input.getFile();
821     InputKind Kind = Input.getKind();
822     if (Kind.getHeaderUnitKind() != InputKind::HeaderUnit_Abs) {
823       assert(CI.hasPreprocessor() &&
824              "trying to build a header unit without a Pre-processor?");
825       HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
826       // Relative searches begin from CWD.
827       auto Dir = CI.getFileManager().getOptionalDirectoryRef(".");
828       SmallVector<std::pair<const FileEntry *, DirectoryEntryRef>, 1> CWD;
829       CWD.push_back({nullptr, *Dir});
830       OptionalFileEntryRef FE =
831           HS.LookupFile(FileName, SourceLocation(),
832                         /*Angled*/ Input.getKind().getHeaderUnitKind() ==
833                             InputKind::HeaderUnit_System,
834                         nullptr, nullptr, CWD, nullptr, nullptr, nullptr,
835                         nullptr, nullptr, nullptr);
836       if (!FE) {
837         CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
838             << FileName;
839         return false;
840       }
841       // We now have the filename...
842       FileName = FE->getFileEntry().getName();
843       // ... still a header unit, but now use the path as written.
844       Kind = Input.getKind().withHeaderUnit(InputKind::HeaderUnit_Abs);
845       Input = FrontendInputFile(FileName, Kind, Input.isSystem());
846     }
847     // Unless the user has overridden the name, the header unit module name is
848     // the pathname for the file.
849     if (CI.getLangOpts().ModuleName.empty())
850       CI.getLangOpts().ModuleName = std::string(FileName);
851     CI.getLangOpts().CurrentModule = CI.getLangOpts().ModuleName;
852   }
853 
854   if (!CI.InitializeSourceManager(Input))
855     return false;
856 
857   if (CI.getLangOpts().CPlusPlusModules && Input.getKind().isHeaderUnit() &&
858       Input.getKind().isPreprocessed() && !usesPreprocessorOnly()) {
859     // We have an input filename like foo.iih, but we want to find the right
860     // module name (and original file, to build the map entry).
861     // Check if the first line specifies the original source file name with a
862     // linemarker.
863     std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
864     ReadOriginalFileName(CI, PresumedInputFile);
865     // Unless the user overrides this, the module name is the name by which the
866     // original file was known.
867     if (CI.getLangOpts().ModuleName.empty())
868       CI.getLangOpts().ModuleName = std::string(PresumedInputFile);
869     CI.getLangOpts().CurrentModule = CI.getLangOpts().ModuleName;
870   }
871 
872   // For module map files, we first parse the module map and synthesize a
873   // "<module-includes>" buffer before more conventional processing.
874   if (Input.getKind().getFormat() == InputKind::ModuleMap) {
875     CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
876 
877     std::string PresumedModuleMapFile;
878     unsigned OffsetToContents;
879     if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
880                                     Input.isPreprocessed(),
881                                     PresumedModuleMapFile, OffsetToContents))
882       return false;
883 
884     auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
885     if (!CurrentModule)
886       return false;
887 
888     CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
889 
890     if (OffsetToContents)
891       // If the module contents are in the same file, skip to them.
892       CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
893     else {
894       // Otherwise, convert the module description to a suitable input buffer.
895       auto Buffer = getInputBufferForModule(CI, CurrentModule);
896       if (!Buffer)
897         return false;
898 
899       // Reinitialize the main file entry to refer to the new input.
900       auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
901       auto &SourceMgr = CI.getSourceManager();
902       auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
903       assert(BufferID.isValid() && "couldn't create module buffer ID");
904       SourceMgr.setMainFileID(BufferID);
905     }
906   }
907 
908   // Initialize the action.
909   if (!BeginSourceFileAction(CI))
910     return false;
911 
912   // If we were asked to load any module map files, do so now.
913   for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
914     if (auto File = CI.getFileManager().getOptionalFileRef(Filename))
915       CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
916           *File, /*IsSystem*/false);
917     else
918       CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
919   }
920 
921   // If compiling implementation of a module, load its module map file now.
922   (void)CI.getPreprocessor().getCurrentModuleImplementation();
923 
924   // Add a module declaration scope so that modules from -fmodule-map-file
925   // arguments may shadow modules found implicitly in search paths.
926   CI.getPreprocessor()
927       .getHeaderSearchInfo()
928       .getModuleMap()
929       .finishModuleDeclarationScope();
930 
931   // Create the AST context and consumer unless this is a preprocessor only
932   // action.
933   if (!usesPreprocessorOnly()) {
934     // Parsing a model file should reuse the existing ASTContext.
935     if (!isModelParsingAction())
936       CI.createASTContext();
937 
938     // For preprocessed files, check if the first line specifies the original
939     // source file name with a linemarker.
940     std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
941     if (Input.isPreprocessed())
942       ReadOriginalFileName(CI, PresumedInputFile);
943 
944     std::unique_ptr<ASTConsumer> Consumer =
945         CreateWrappedASTConsumer(CI, PresumedInputFile);
946     if (!Consumer)
947       return false;
948 
949     // FIXME: should not overwrite ASTMutationListener when parsing model files?
950     if (!isModelParsingAction())
951       CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
952 
953     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
954       // Convert headers to PCH and chain them.
955       IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
956       source = createChainedIncludesSource(CI, FinalReader);
957       if (!source)
958         return false;
959       CI.setASTReader(static_cast<ASTReader *>(FinalReader.get()));
960       CI.getASTContext().setExternalSource(source);
961     } else if (CI.getLangOpts().Modules ||
962                !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
963       // Use PCM or PCH.
964       assert(hasPCHSupport() && "This action does not have PCH support!");
965       ASTDeserializationListener *DeserialListener =
966           Consumer->GetASTDeserializationListener();
967       bool DeleteDeserialListener = false;
968       if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
969         DeserialListener = new DeserializedDeclsDumper(DeserialListener,
970                                                        DeleteDeserialListener);
971         DeleteDeserialListener = true;
972       }
973       if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
974         DeserialListener = new DeserializedDeclsChecker(
975             CI.getASTContext(),
976             CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
977             DeserialListener, DeleteDeserialListener);
978         DeleteDeserialListener = true;
979       }
980       if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
981         CI.createPCHExternalASTSource(
982             CI.getPreprocessorOpts().ImplicitPCHInclude,
983             CI.getPreprocessorOpts().DisablePCHOrModuleValidation,
984             CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
985             DeserialListener, DeleteDeserialListener);
986         if (!CI.getASTContext().getExternalSource())
987           return false;
988       }
989       // If modules are enabled, create the AST reader before creating
990       // any builtins, so that all declarations know that they might be
991       // extended by an external source.
992       if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
993           !CI.getASTContext().getExternalSource()) {
994         CI.createASTReader();
995         CI.getASTReader()->setDeserializationListener(DeserialListener,
996                                                       DeleteDeserialListener);
997       }
998     }
999 
1000     CI.setASTConsumer(std::move(Consumer));
1001     if (!CI.hasASTConsumer())
1002       return false;
1003   }
1004 
1005   // Initialize built-in info as long as we aren't using an external AST
1006   // source.
1007   if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
1008       !CI.getASTContext().getExternalSource()) {
1009     Preprocessor &PP = CI.getPreprocessor();
1010     PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
1011                                            PP.getLangOpts());
1012   } else {
1013     // FIXME: If this is a problem, recover from it by creating a multiplex
1014     // source.
1015     assert((!CI.getLangOpts().Modules || CI.getASTReader()) &&
1016            "modules enabled but created an external source that "
1017            "doesn't support modules");
1018   }
1019 
1020   // If we were asked to load any module files, do so now.
1021   for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
1022     if (!CI.loadModuleFile(ModuleFile))
1023       return false;
1024 
1025   // If there is a layout overrides file, attach an external AST source that
1026   // provides the layouts from that file.
1027   if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
1028       CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
1029     IntrusiveRefCntPtr<ExternalASTSource>
1030       Override(new LayoutOverrideSource(
1031                      CI.getFrontendOpts().OverrideRecordLayoutsFile));
1032     CI.getASTContext().setExternalSource(Override);
1033   }
1034 
1035   // Setup HLSL External Sema Source
1036   if (CI.getLangOpts().HLSL && CI.hasASTContext()) {
1037     IntrusiveRefCntPtr<ExternalSemaSource> HLSLSema(
1038         new HLSLExternalSemaSource());
1039     if (auto *SemaSource = dyn_cast_if_present<ExternalSemaSource>(
1040             CI.getASTContext().getExternalSource())) {
1041       IntrusiveRefCntPtr<ExternalSemaSource> MultiSema(
1042           new MultiplexExternalSemaSource(SemaSource, HLSLSema.get()));
1043       CI.getASTContext().setExternalSource(MultiSema);
1044     } else
1045       CI.getASTContext().setExternalSource(HLSLSema);
1046   }
1047 
1048   FailureCleanup.release();
1049   return true;
1050 }
1051 
1052 llvm::Error FrontendAction::Execute() {
1053   CompilerInstance &CI = getCompilerInstance();
1054 
1055   if (CI.hasFrontendTimer()) {
1056     llvm::TimeRegion Timer(CI.getFrontendTimer());
1057     ExecuteAction();
1058   }
1059   else ExecuteAction();
1060 
1061   // If we are supposed to rebuild the global module index, do so now unless
1062   // there were any module-build failures.
1063   if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
1064       CI.hasPreprocessor()) {
1065     StringRef Cache =
1066         CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
1067     if (!Cache.empty()) {
1068       if (llvm::Error Err = GlobalModuleIndex::writeIndex(
1069               CI.getFileManager(), CI.getPCHContainerReader(), Cache)) {
1070         // FIXME this drops the error on the floor, but
1071         // Index/pch-from-libclang.c seems to rely on dropping at least some of
1072         // the error conditions!
1073         consumeError(std::move(Err));
1074       }
1075     }
1076   }
1077 
1078   return llvm::Error::success();
1079 }
1080 
1081 void FrontendAction::EndSourceFile() {
1082   CompilerInstance &CI = getCompilerInstance();
1083 
1084   // Inform the diagnostic client we are done with this source file.
1085   CI.getDiagnosticClient().EndSourceFile();
1086 
1087   // Inform the preprocessor we are done.
1088   if (CI.hasPreprocessor())
1089     CI.getPreprocessor().EndSourceFile();
1090 
1091   // Finalize the action.
1092   EndSourceFileAction();
1093 
1094   // Sema references the ast consumer, so reset sema first.
1095   //
1096   // FIXME: There is more per-file stuff we could just drop here?
1097   bool DisableFree = CI.getFrontendOpts().DisableFree;
1098   if (DisableFree) {
1099     CI.resetAndLeakSema();
1100     CI.resetAndLeakASTContext();
1101     llvm::BuryPointer(CI.takeASTConsumer().get());
1102   } else {
1103     CI.setSema(nullptr);
1104     CI.setASTContext(nullptr);
1105     CI.setASTConsumer(nullptr);
1106   }
1107 
1108   if (CI.getFrontendOpts().ShowStats) {
1109     llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFileOrBufferName() << "':\n";
1110     CI.getPreprocessor().PrintStats();
1111     CI.getPreprocessor().getIdentifierTable().PrintStats();
1112     CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
1113     CI.getSourceManager().PrintStats();
1114     llvm::errs() << "\n";
1115   }
1116 
1117   // Cleanup the output streams, and erase the output files if instructed by the
1118   // FrontendAction.
1119   CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
1120 
1121   // The resources are owned by AST when the current file is AST.
1122   // So we reset the resources here to avoid users accessing it
1123   // accidently.
1124   if (isCurrentFileAST()) {
1125     if (DisableFree) {
1126       CI.resetAndLeakPreprocessor();
1127       CI.resetAndLeakSourceManager();
1128       CI.resetAndLeakFileManager();
1129       llvm::BuryPointer(std::move(CurrentASTUnit));
1130     } else {
1131       CI.setPreprocessor(nullptr);
1132       CI.setSourceManager(nullptr);
1133       CI.setFileManager(nullptr);
1134     }
1135   }
1136 
1137   setCompilerInstance(nullptr);
1138   setCurrentInput(FrontendInputFile());
1139   CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
1140 }
1141 
1142 bool FrontendAction::shouldEraseOutputFiles() {
1143   return getCompilerInstance().getDiagnostics().hasErrorOccurred();
1144 }
1145 
1146 //===----------------------------------------------------------------------===//
1147 // Utility Actions
1148 //===----------------------------------------------------------------------===//
1149 
1150 void ASTFrontendAction::ExecuteAction() {
1151   CompilerInstance &CI = getCompilerInstance();
1152   if (!CI.hasPreprocessor())
1153     return;
1154   // This is a fallback: If the client forgets to invoke this, we mark the
1155   // current stack as the bottom. Though not optimal, this could help prevent
1156   // stack overflow during deep recursion.
1157   clang::noteBottomOfStack();
1158 
1159   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1160   // here so the source manager would be initialized.
1161   if (hasCodeCompletionSupport() &&
1162       !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
1163     CI.createCodeCompletionConsumer();
1164 
1165   // Use a code completion consumer?
1166   CodeCompleteConsumer *CompletionConsumer = nullptr;
1167   if (CI.hasCodeCompletionConsumer())
1168     CompletionConsumer = &CI.getCodeCompletionConsumer();
1169 
1170   if (!CI.hasSema())
1171     CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1172 
1173   ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1174            CI.getFrontendOpts().SkipFunctionBodies);
1175 }
1176 
1177 void PluginASTAction::anchor() { }
1178 
1179 std::unique_ptr<ASTConsumer>
1180 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1181                                               StringRef InFile) {
1182   llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1183 }
1184 
1185 bool WrapperFrontendAction::PrepareToExecuteAction(CompilerInstance &CI) {
1186   return WrappedAction->PrepareToExecuteAction(CI);
1187 }
1188 std::unique_ptr<ASTConsumer>
1189 WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1190                                          StringRef InFile) {
1191   return WrappedAction->CreateASTConsumer(CI, InFile);
1192 }
1193 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1194   return WrappedAction->BeginInvocation(CI);
1195 }
1196 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
1197   WrappedAction->setCurrentInput(getCurrentInput());
1198   WrappedAction->setCompilerInstance(&CI);
1199   auto Ret = WrappedAction->BeginSourceFileAction(CI);
1200   // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1201   setCurrentInput(WrappedAction->getCurrentInput());
1202   return Ret;
1203 }
1204 void WrapperFrontendAction::ExecuteAction() {
1205   WrappedAction->ExecuteAction();
1206 }
1207 void WrapperFrontendAction::EndSourceFile() { WrappedAction->EndSourceFile(); }
1208 void WrapperFrontendAction::EndSourceFileAction() {
1209   WrappedAction->EndSourceFileAction();
1210 }
1211 bool WrapperFrontendAction::shouldEraseOutputFiles() {
1212   return WrappedAction->shouldEraseOutputFiles();
1213 }
1214 
1215 bool WrapperFrontendAction::usesPreprocessorOnly() const {
1216   return WrappedAction->usesPreprocessorOnly();
1217 }
1218 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1219   return WrappedAction->getTranslationUnitKind();
1220 }
1221 bool WrapperFrontendAction::hasPCHSupport() const {
1222   return WrappedAction->hasPCHSupport();
1223 }
1224 bool WrapperFrontendAction::hasASTFileSupport() const {
1225   return WrappedAction->hasASTFileSupport();
1226 }
1227 bool WrapperFrontendAction::hasIRSupport() const {
1228   return WrappedAction->hasIRSupport();
1229 }
1230 bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1231   return WrappedAction->hasCodeCompletionSupport();
1232 }
1233 
1234 WrapperFrontendAction::WrapperFrontendAction(
1235     std::unique_ptr<FrontendAction> WrappedAction)
1236   : WrappedAction(std::move(WrappedAction)) {}
1237