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