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