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