FrontendAction.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. //===--- FrontendAction.cpp -----------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/Frontend/FrontendAction.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/DeclGroup.h"
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/Frontend/ChainedIncludesSource.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/Preprocessor.h"
  23. #include "clang/Parse/ParseAST.h"
  24. #include "clang/Serialization/ASTDeserializationListener.h"
  25. #include "clang/Serialization/ASTReader.h"
  26. #include "clang/Serialization/GlobalModuleIndex.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/FileSystem.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/Timer.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Support/system_error.h"
  33. using namespace clang;
  34. namespace {
  35. class DelegatingDeserializationListener : public ASTDeserializationListener {
  36. ASTDeserializationListener *Previous;
  37. public:
  38. explicit DelegatingDeserializationListener(
  39. ASTDeserializationListener *Previous)
  40. : Previous(Previous) { }
  41. void ReaderInitialized(ASTReader *Reader) override {
  42. if (Previous)
  43. Previous->ReaderInitialized(Reader);
  44. }
  45. void IdentifierRead(serialization::IdentID ID,
  46. IdentifierInfo *II) override {
  47. if (Previous)
  48. Previous->IdentifierRead(ID, II);
  49. }
  50. void TypeRead(serialization::TypeIdx Idx, QualType T) override {
  51. if (Previous)
  52. Previous->TypeRead(Idx, T);
  53. }
  54. void DeclRead(serialization::DeclID ID, const Decl *D) override {
  55. if (Previous)
  56. Previous->DeclRead(ID, D);
  57. }
  58. void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
  59. if (Previous)
  60. Previous->SelectorRead(ID, Sel);
  61. }
  62. void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
  63. MacroDefinition *MD) override {
  64. if (Previous)
  65. Previous->MacroDefinitionRead(PPID, MD);
  66. }
  67. };
  68. /// \brief Dumps deserialized declarations.
  69. class DeserializedDeclsDumper : public DelegatingDeserializationListener {
  70. public:
  71. explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous)
  72. : DelegatingDeserializationListener(Previous) { }
  73. void DeclRead(serialization::DeclID ID, const Decl *D) override {
  74. llvm::outs() << "PCH DECL: " << D->getDeclKindName();
  75. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  76. llvm::outs() << " - " << *ND;
  77. llvm::outs() << "\n";
  78. DelegatingDeserializationListener::DeclRead(ID, D);
  79. }
  80. };
  81. /// \brief Checks deserialized declarations and emits error if a name
  82. /// matches one given in command-line using -error-on-deserialized-decl.
  83. class DeserializedDeclsChecker : public DelegatingDeserializationListener {
  84. ASTContext &Ctx;
  85. std::set<std::string> NamesToCheck;
  86. public:
  87. DeserializedDeclsChecker(ASTContext &Ctx,
  88. const std::set<std::string> &NamesToCheck,
  89. ASTDeserializationListener *Previous)
  90. : DelegatingDeserializationListener(Previous),
  91. Ctx(Ctx), NamesToCheck(NamesToCheck) { }
  92. void DeclRead(serialization::DeclID ID, const Decl *D) override {
  93. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  94. if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
  95. unsigned DiagID
  96. = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
  97. "%0 was deserialized");
  98. Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
  99. << ND->getNameAsString();
  100. }
  101. DelegatingDeserializationListener::DeclRead(ID, D);
  102. }
  103. };
  104. } // end anonymous namespace
  105. FrontendAction::FrontendAction() : Instance(0) {}
  106. FrontendAction::~FrontendAction() {}
  107. void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
  108. ASTUnit *AST) {
  109. this->CurrentInput = CurrentInput;
  110. CurrentASTUnit.reset(AST);
  111. }
  112. ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
  113. StringRef InFile) {
  114. ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
  115. if (!Consumer)
  116. return 0;
  117. if (CI.getFrontendOpts().AddPluginActions.size() == 0)
  118. return Consumer;
  119. // Make sure the non-plugin consumer is first, so that plugins can't
  120. // modifiy the AST.
  121. std::vector<ASTConsumer*> Consumers(1, Consumer);
  122. for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
  123. i != e; ++i) {
  124. // This is O(|plugins| * |add_plugins|), but since both numbers are
  125. // way below 50 in practice, that's ok.
  126. for (FrontendPluginRegistry::iterator
  127. it = FrontendPluginRegistry::begin(),
  128. ie = FrontendPluginRegistry::end();
  129. it != ie; ++it) {
  130. if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
  131. std::unique_ptr<PluginASTAction> P(it->instantiate());
  132. FrontendAction* c = P.get();
  133. if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
  134. Consumers.push_back(c->CreateASTConsumer(CI, InFile));
  135. }
  136. }
  137. }
  138. return new MultiplexConsumer(Consumers);
  139. }
  140. bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
  141. const FrontendInputFile &Input) {
  142. assert(!Instance && "Already processing a source file!");
  143. assert(!Input.isEmpty() && "Unexpected empty filename!");
  144. setCurrentInput(Input);
  145. setCompilerInstance(&CI);
  146. StringRef InputFile = Input.getFile();
  147. bool HasBegunSourceFile = false;
  148. if (!BeginInvocation(CI))
  149. goto failure;
  150. // AST files follow a very different path, since they share objects via the
  151. // AST unit.
  152. if (Input.getKind() == IK_AST) {
  153. assert(!usesPreprocessorOnly() &&
  154. "Attempt to pass AST file to preprocessor only action!");
  155. assert(hasASTFileSupport() &&
  156. "This action does not have AST file support!");
  157. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
  158. ASTUnit *AST = ASTUnit::LoadFromASTFile(InputFile, Diags,
  159. CI.getFileSystemOpts());
  160. if (!AST)
  161. goto failure;
  162. setCurrentInput(Input, AST);
  163. // Inform the diagnostic client we are processing a source file.
  164. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
  165. HasBegunSourceFile = true;
  166. // Set the shared objects, these are reset when we finish processing the
  167. // file, otherwise the CompilerInstance will happily destroy them.
  168. CI.setFileManager(&AST->getFileManager());
  169. CI.setSourceManager(&AST->getSourceManager());
  170. CI.setPreprocessor(&AST->getPreprocessor());
  171. CI.setASTContext(&AST->getASTContext());
  172. // Initialize the action.
  173. if (!BeginSourceFileAction(CI, InputFile))
  174. goto failure;
  175. // Create the AST consumer.
  176. CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
  177. if (!CI.hasASTConsumer())
  178. goto failure;
  179. return true;
  180. }
  181. if (!CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) {
  182. IntrusiveRefCntPtr<vfs::OverlayFileSystem>
  183. Overlay(new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
  184. // earlier vfs files are on the bottom
  185. const std::vector<std::string> &Files =
  186. CI.getHeaderSearchOpts().VFSOverlayFiles;
  187. for (std::vector<std::string>::const_iterator I = Files.begin(),
  188. E = Files.end();
  189. I != E; ++I) {
  190. std::unique_ptr<llvm::MemoryBuffer> Buffer;
  191. if (llvm::errc::success != llvm::MemoryBuffer::getFile(*I, Buffer)) {
  192. CI.getDiagnostics().Report(diag::err_missing_vfs_overlay_file) << *I;
  193. goto failure;
  194. }
  195. IntrusiveRefCntPtr<vfs::FileSystem> FS =
  196. vfs::getVFSFromYAML(Buffer.release(), /*DiagHandler*/ 0);
  197. if (!FS.getPtr()) {
  198. CI.getDiagnostics().Report(diag::err_invalid_vfs_overlay) << *I;
  199. goto failure;
  200. }
  201. Overlay->pushOverlay(FS);
  202. }
  203. CI.setVirtualFileSystem(Overlay);
  204. }
  205. // Set up the file and source managers, if needed.
  206. if (!CI.hasFileManager())
  207. CI.createFileManager();
  208. if (!CI.hasSourceManager())
  209. CI.createSourceManager(CI.getFileManager());
  210. // IR files bypass the rest of initialization.
  211. if (Input.getKind() == IK_LLVM_IR) {
  212. assert(hasIRSupport() &&
  213. "This action does not have IR file support!");
  214. // Inform the diagnostic client we are processing a source file.
  215. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
  216. HasBegunSourceFile = true;
  217. // Initialize the action.
  218. if (!BeginSourceFileAction(CI, InputFile))
  219. goto failure;
  220. return true;
  221. }
  222. // If the implicit PCH include is actually a directory, rather than
  223. // a single file, search for a suitable PCH file in that directory.
  224. if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  225. FileManager &FileMgr = CI.getFileManager();
  226. PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
  227. StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
  228. if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
  229. llvm::error_code EC;
  230. SmallString<128> DirNative;
  231. llvm::sys::path::native(PCHDir->getName(), DirNative);
  232. bool Found = false;
  233. for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
  234. Dir != DirEnd && !EC; Dir.increment(EC)) {
  235. // Check whether this is an acceptable AST file.
  236. if (ASTReader::isAcceptableASTFile(Dir->path(), FileMgr,
  237. CI.getLangOpts(),
  238. CI.getTargetOpts(),
  239. CI.getPreprocessorOpts())) {
  240. PPOpts.ImplicitPCHInclude = Dir->path();
  241. Found = true;
  242. break;
  243. }
  244. }
  245. if (!Found) {
  246. CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
  247. return true;
  248. }
  249. }
  250. }
  251. // Set up the preprocessor.
  252. CI.createPreprocessor(getTranslationUnitKind());
  253. // Inform the diagnostic client we are processing a source file.
  254. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
  255. &CI.getPreprocessor());
  256. HasBegunSourceFile = true;
  257. // Initialize the action.
  258. if (!BeginSourceFileAction(CI, InputFile))
  259. goto failure;
  260. // Create the AST context and consumer unless this is a preprocessor only
  261. // action.
  262. if (!usesPreprocessorOnly()) {
  263. CI.createASTContext();
  264. std::unique_ptr<ASTConsumer> Consumer(
  265. CreateWrappedASTConsumer(CI, InputFile));
  266. if (!Consumer)
  267. goto failure;
  268. CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
  269. if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
  270. // Convert headers to PCH and chain them.
  271. IntrusiveRefCntPtr<ChainedIncludesSource> source;
  272. source = ChainedIncludesSource::create(CI);
  273. if (!source)
  274. goto failure;
  275. CI.setModuleManager(static_cast<ASTReader*>(&source->getFinalReader()));
  276. CI.getASTContext().setExternalSource(source);
  277. } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  278. // Use PCH.
  279. assert(hasPCHSupport() && "This action does not have PCH support!");
  280. ASTDeserializationListener *DeserialListener =
  281. Consumer->GetASTDeserializationListener();
  282. if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
  283. DeserialListener = new DeserializedDeclsDumper(DeserialListener);
  284. if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
  285. DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
  286. CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
  287. DeserialListener);
  288. CI.createPCHExternalASTSource(
  289. CI.getPreprocessorOpts().ImplicitPCHInclude,
  290. CI.getPreprocessorOpts().DisablePCHValidation,
  291. CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  292. DeserialListener);
  293. if (!CI.getASTContext().getExternalSource())
  294. goto failure;
  295. }
  296. CI.setASTConsumer(Consumer.release());
  297. if (!CI.hasASTConsumer())
  298. goto failure;
  299. }
  300. // Initialize built-in info as long as we aren't using an external AST
  301. // source.
  302. if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
  303. Preprocessor &PP = CI.getPreprocessor();
  304. PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
  305. PP.getLangOpts());
  306. }
  307. // If there is a layout overrides file, attach an external AST source that
  308. // provides the layouts from that file.
  309. if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
  310. CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
  311. IntrusiveRefCntPtr<ExternalASTSource>
  312. Override(new LayoutOverrideSource(
  313. CI.getFrontendOpts().OverrideRecordLayoutsFile));
  314. CI.getASTContext().setExternalSource(Override);
  315. }
  316. return true;
  317. // If we failed, reset state since the client will not end up calling the
  318. // matching EndSourceFile().
  319. failure:
  320. if (isCurrentFileAST()) {
  321. CI.setASTContext(0);
  322. CI.setPreprocessor(0);
  323. CI.setSourceManager(0);
  324. CI.setFileManager(0);
  325. }
  326. if (HasBegunSourceFile)
  327. CI.getDiagnosticClient().EndSourceFile();
  328. CI.clearOutputFiles(/*EraseFiles=*/true);
  329. setCurrentInput(FrontendInputFile());
  330. setCompilerInstance(0);
  331. return false;
  332. }
  333. bool FrontendAction::Execute() {
  334. CompilerInstance &CI = getCompilerInstance();
  335. // Initialize the main file entry. This needs to be delayed until after PCH
  336. // has loaded.
  337. if (!isCurrentFileAST()) {
  338. if (!CI.InitializeSourceManager(getCurrentInput()))
  339. return false;
  340. }
  341. if (CI.hasFrontendTimer()) {
  342. llvm::TimeRegion Timer(CI.getFrontendTimer());
  343. ExecuteAction();
  344. }
  345. else ExecuteAction();
  346. // If we are supposed to rebuild the global module index, do so now unless
  347. // there were any module-build failures.
  348. if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
  349. CI.hasPreprocessor()) {
  350. GlobalModuleIndex::writeIndex(
  351. CI.getFileManager(),
  352. CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  353. }
  354. return true;
  355. }
  356. void FrontendAction::EndSourceFile() {
  357. CompilerInstance &CI = getCompilerInstance();
  358. // Inform the diagnostic client we are done with this source file.
  359. CI.getDiagnosticClient().EndSourceFile();
  360. // Finalize the action.
  361. EndSourceFileAction();
  362. // Release the consumer and the AST, in that order since the consumer may
  363. // perform actions in its destructor which require the context.
  364. //
  365. // FIXME: There is more per-file stuff we could just drop here?
  366. if (CI.getFrontendOpts().DisableFree) {
  367. BuryPointer(CI.takeASTConsumer());
  368. if (!isCurrentFileAST()) {
  369. BuryPointer(CI.takeSema());
  370. CI.resetAndLeakASTContext();
  371. }
  372. } else {
  373. if (!isCurrentFileAST()) {
  374. CI.setSema(0);
  375. CI.setASTContext(0);
  376. }
  377. CI.setASTConsumer(0);
  378. }
  379. // Inform the preprocessor we are done.
  380. if (CI.hasPreprocessor())
  381. CI.getPreprocessor().EndSourceFile();
  382. if (CI.getFrontendOpts().ShowStats) {
  383. llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
  384. CI.getPreprocessor().PrintStats();
  385. CI.getPreprocessor().getIdentifierTable().PrintStats();
  386. CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
  387. CI.getSourceManager().PrintStats();
  388. llvm::errs() << "\n";
  389. }
  390. // Cleanup the output streams, and erase the output files if instructed by the
  391. // FrontendAction.
  392. CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
  393. if (isCurrentFileAST()) {
  394. CI.takeSema();
  395. CI.resetAndLeakASTContext();
  396. CI.resetAndLeakPreprocessor();
  397. CI.resetAndLeakSourceManager();
  398. CI.resetAndLeakFileManager();
  399. }
  400. setCompilerInstance(0);
  401. setCurrentInput(FrontendInputFile());
  402. }
  403. bool FrontendAction::shouldEraseOutputFiles() {
  404. return getCompilerInstance().getDiagnostics().hasErrorOccurred();
  405. }
  406. //===----------------------------------------------------------------------===//
  407. // Utility Actions
  408. //===----------------------------------------------------------------------===//
  409. void ASTFrontendAction::ExecuteAction() {
  410. CompilerInstance &CI = getCompilerInstance();
  411. if (!CI.hasPreprocessor())
  412. return;
  413. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  414. // here so the source manager would be initialized.
  415. if (hasCodeCompletionSupport() &&
  416. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  417. CI.createCodeCompletionConsumer();
  418. // Use a code completion consumer?
  419. CodeCompleteConsumer *CompletionConsumer = 0;
  420. if (CI.hasCodeCompletionConsumer())
  421. CompletionConsumer = &CI.getCodeCompletionConsumer();
  422. if (!CI.hasSema())
  423. CI.createSema(getTranslationUnitKind(), CompletionConsumer);
  424. ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
  425. CI.getFrontendOpts().SkipFunctionBodies);
  426. }
  427. void PluginASTAction::anchor() { }
  428. ASTConsumer *
  429. PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  430. StringRef InFile) {
  431. llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
  432. }
  433. ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  434. StringRef InFile) {
  435. return WrappedAction->CreateASTConsumer(CI, InFile);
  436. }
  437. bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
  438. return WrappedAction->BeginInvocation(CI);
  439. }
  440. bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
  441. StringRef Filename) {
  442. WrappedAction->setCurrentInput(getCurrentInput());
  443. WrappedAction->setCompilerInstance(&CI);
  444. return WrappedAction->BeginSourceFileAction(CI, Filename);
  445. }
  446. void WrapperFrontendAction::ExecuteAction() {
  447. WrappedAction->ExecuteAction();
  448. }
  449. void WrapperFrontendAction::EndSourceFileAction() {
  450. WrappedAction->EndSourceFileAction();
  451. }
  452. bool WrapperFrontendAction::usesPreprocessorOnly() const {
  453. return WrappedAction->usesPreprocessorOnly();
  454. }
  455. TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
  456. return WrappedAction->getTranslationUnitKind();
  457. }
  458. bool WrapperFrontendAction::hasPCHSupport() const {
  459. return WrappedAction->hasPCHSupport();
  460. }
  461. bool WrapperFrontendAction::hasASTFileSupport() const {
  462. return WrappedAction->hasASTFileSupport();
  463. }
  464. bool WrapperFrontendAction::hasIRSupport() const {
  465. return WrappedAction->hasIRSupport();
  466. }
  467. bool WrapperFrontendAction::hasCodeCompletionSupport() const {
  468. return WrappedAction->hasCodeCompletionSupport();
  469. }
  470. WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
  471. : WrappedAction(WrappedAction) {}