FrontendAction.cpp 43 KB

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