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