FrontendAction.cpp 41 KB

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