FrontendAction.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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/Lex/HeaderSearch.h"
  14. #include "clang/Lex/Preprocessor.h"
  15. #include "clang/Frontend/ASTUnit.h"
  16. #include "clang/Frontend/ChainedIncludesSource.h"
  17. #include "clang/Frontend/CompilerInstance.h"
  18. #include "clang/Frontend/FrontendDiagnostic.h"
  19. #include "clang/Frontend/FrontendPluginRegistry.h"
  20. #include "clang/Frontend/LayoutOverrideSource.h"
  21. #include "clang/Frontend/MultiplexConsumer.h"
  22. #include "clang/Parse/ParseAST.h"
  23. #include "clang/Serialization/ASTDeserializationListener.h"
  24. #include "clang/Serialization/ASTReader.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/Support/Timer.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace clang;
  30. namespace {
  31. class DelegatingDeserializationListener : public ASTDeserializationListener {
  32. ASTDeserializationListener *Previous;
  33. public:
  34. explicit DelegatingDeserializationListener(
  35. ASTDeserializationListener *Previous)
  36. : Previous(Previous) { }
  37. virtual void ReaderInitialized(ASTReader *Reader) {
  38. if (Previous)
  39. Previous->ReaderInitialized(Reader);
  40. }
  41. virtual void IdentifierRead(serialization::IdentID ID,
  42. IdentifierInfo *II) {
  43. if (Previous)
  44. Previous->IdentifierRead(ID, II);
  45. }
  46. virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {
  47. if (Previous)
  48. Previous->TypeRead(Idx, T);
  49. }
  50. virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
  51. if (Previous)
  52. Previous->DeclRead(ID, D);
  53. }
  54. virtual void SelectorRead(serialization::SelectorID ID, Selector Sel) {
  55. if (Previous)
  56. Previous->SelectorRead(ID, Sel);
  57. }
  58. virtual void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
  59. MacroDefinition *MD) {
  60. if (Previous)
  61. Previous->MacroDefinitionRead(PPID, MD);
  62. }
  63. };
  64. /// \brief Dumps deserialized declarations.
  65. class DeserializedDeclsDumper : public DelegatingDeserializationListener {
  66. public:
  67. explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous)
  68. : DelegatingDeserializationListener(Previous) { }
  69. virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
  70. llvm::outs() << "PCH DECL: " << D->getDeclKindName();
  71. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  72. llvm::outs() << " - " << *ND;
  73. llvm::outs() << "\n";
  74. DelegatingDeserializationListener::DeclRead(ID, D);
  75. }
  76. };
  77. /// \brief Checks deserialized declarations and emits error if a name
  78. /// matches one given in command-line using -error-on-deserialized-decl.
  79. class DeserializedDeclsChecker : public DelegatingDeserializationListener {
  80. ASTContext &Ctx;
  81. std::set<std::string> NamesToCheck;
  82. public:
  83. DeserializedDeclsChecker(ASTContext &Ctx,
  84. const std::set<std::string> &NamesToCheck,
  85. ASTDeserializationListener *Previous)
  86. : DelegatingDeserializationListener(Previous),
  87. Ctx(Ctx), NamesToCheck(NamesToCheck) { }
  88. virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
  89. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  90. if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
  91. unsigned DiagID
  92. = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
  93. "%0 was deserialized");
  94. Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
  95. << ND->getNameAsString();
  96. }
  97. DelegatingDeserializationListener::DeclRead(ID, D);
  98. }
  99. };
  100. } // end anonymous namespace
  101. FrontendAction::FrontendAction() : Instance(0) {}
  102. FrontendAction::~FrontendAction() {}
  103. void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
  104. ASTUnit *AST) {
  105. this->CurrentInput = CurrentInput;
  106. CurrentASTUnit.reset(AST);
  107. }
  108. ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
  109. StringRef InFile) {
  110. ASTConsumer* Consumer = CreateASTConsumer(CI, InFile);
  111. if (!Consumer)
  112. return 0;
  113. if (CI.getFrontendOpts().AddPluginActions.size() == 0)
  114. return Consumer;
  115. // Make sure the non-plugin consumer is first, so that plugins can't
  116. // modifiy the AST.
  117. std::vector<ASTConsumer*> Consumers(1, Consumer);
  118. for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
  119. i != e; ++i) {
  120. // This is O(|plugins| * |add_plugins|), but since both numbers are
  121. // way below 50 in practice, that's ok.
  122. for (FrontendPluginRegistry::iterator
  123. it = FrontendPluginRegistry::begin(),
  124. ie = FrontendPluginRegistry::end();
  125. it != ie; ++it) {
  126. if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
  127. OwningPtr<PluginASTAction> P(it->instantiate());
  128. FrontendAction* c = P.get();
  129. if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
  130. Consumers.push_back(c->CreateASTConsumer(CI, InFile));
  131. }
  132. }
  133. }
  134. return new MultiplexConsumer(Consumers);
  135. }
  136. bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
  137. const FrontendInputFile &Input) {
  138. assert(!Instance && "Already processing a source file!");
  139. assert(!Input.File.empty() && "Unexpected empty filename!");
  140. setCurrentInput(Input);
  141. setCompilerInstance(&CI);
  142. bool HasBegunSourceFile = false;
  143. if (!BeginInvocation(CI))
  144. goto failure;
  145. // AST files follow a very different path, since they share objects via the
  146. // AST unit.
  147. if (Input.Kind == IK_AST) {
  148. assert(!usesPreprocessorOnly() &&
  149. "Attempt to pass AST file to preprocessor only action!");
  150. assert(hasASTFileSupport() &&
  151. "This action does not have AST file support!");
  152. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
  153. std::string Error;
  154. ASTUnit *AST = ASTUnit::LoadFromASTFile(Input.File, Diags,
  155. CI.getFileSystemOpts());
  156. if (!AST)
  157. goto failure;
  158. setCurrentInput(Input, AST);
  159. // Set the shared objects, these are reset when we finish processing the
  160. // file, otherwise the CompilerInstance will happily destroy them.
  161. CI.setFileManager(&AST->getFileManager());
  162. CI.setSourceManager(&AST->getSourceManager());
  163. CI.setPreprocessor(&AST->getPreprocessor());
  164. CI.setASTContext(&AST->getASTContext());
  165. // Initialize the action.
  166. if (!BeginSourceFileAction(CI, Input.File))
  167. goto failure;
  168. /// Create the AST consumer.
  169. CI.setASTConsumer(CreateWrappedASTConsumer(CI, Input.File));
  170. if (!CI.hasASTConsumer())
  171. goto failure;
  172. return true;
  173. }
  174. // Set up the file and source managers, if needed.
  175. if (!CI.hasFileManager())
  176. CI.createFileManager();
  177. if (!CI.hasSourceManager())
  178. CI.createSourceManager(CI.getFileManager());
  179. // IR files bypass the rest of initialization.
  180. if (Input.Kind == IK_LLVM_IR) {
  181. assert(hasIRSupport() &&
  182. "This action does not have IR file support!");
  183. // Inform the diagnostic client we are processing a source file.
  184. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
  185. HasBegunSourceFile = true;
  186. // Initialize the action.
  187. if (!BeginSourceFileAction(CI, Input.File))
  188. goto failure;
  189. return true;
  190. }
  191. // Set up the preprocessor.
  192. CI.createPreprocessor();
  193. // Inform the diagnostic client we are processing a source file.
  194. CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
  195. &CI.getPreprocessor());
  196. HasBegunSourceFile = true;
  197. // Initialize the action.
  198. if (!BeginSourceFileAction(CI, Input.File))
  199. goto failure;
  200. /// Create the AST context and consumer unless this is a preprocessor only
  201. /// action.
  202. if (!usesPreprocessorOnly()) {
  203. CI.createASTContext();
  204. OwningPtr<ASTConsumer> Consumer(
  205. CreateWrappedASTConsumer(CI, Input.File));
  206. if (!Consumer)
  207. goto failure;
  208. CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
  209. if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
  210. // Convert headers to PCH and chain them.
  211. OwningPtr<ExternalASTSource> source;
  212. source.reset(ChainedIncludesSource::create(CI));
  213. if (!source)
  214. goto failure;
  215. CI.getASTContext().setExternalSource(source);
  216. } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
  217. // Use PCH.
  218. assert(hasPCHSupport() && "This action does not have PCH support!");
  219. ASTDeserializationListener *DeserialListener =
  220. Consumer->GetASTDeserializationListener();
  221. if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
  222. DeserialListener = new DeserializedDeclsDumper(DeserialListener);
  223. if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
  224. DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
  225. CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
  226. DeserialListener);
  227. CI.createPCHExternalASTSource(
  228. CI.getPreprocessorOpts().ImplicitPCHInclude,
  229. CI.getPreprocessorOpts().DisablePCHValidation,
  230. CI.getPreprocessorOpts().DisableStatCache,
  231. CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  232. DeserialListener);
  233. if (!CI.getASTContext().getExternalSource())
  234. goto failure;
  235. }
  236. CI.setASTConsumer(Consumer.take());
  237. if (!CI.hasASTConsumer())
  238. goto failure;
  239. }
  240. // Initialize built-in info as long as we aren't using an external AST
  241. // source.
  242. if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
  243. Preprocessor &PP = CI.getPreprocessor();
  244. PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
  245. PP.getLangOpts());
  246. }
  247. // If there is a layout overrides file, attach an external AST source that
  248. // provides the layouts from that file.
  249. if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
  250. CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
  251. OwningPtr<ExternalASTSource>
  252. Override(new LayoutOverrideSource(
  253. CI.getFrontendOpts().OverrideRecordLayoutsFile));
  254. CI.getASTContext().setExternalSource(Override);
  255. }
  256. return true;
  257. // If we failed, reset state since the client will not end up calling the
  258. // matching EndSourceFile().
  259. failure:
  260. if (isCurrentFileAST()) {
  261. CI.setASTContext(0);
  262. CI.setPreprocessor(0);
  263. CI.setSourceManager(0);
  264. CI.setFileManager(0);
  265. }
  266. if (HasBegunSourceFile)
  267. CI.getDiagnosticClient().EndSourceFile();
  268. setCurrentInput(FrontendInputFile());
  269. setCompilerInstance(0);
  270. return false;
  271. }
  272. bool FrontendAction::Execute() {
  273. CompilerInstance &CI = getCompilerInstance();
  274. // Initialize the main file entry. This needs to be delayed until after PCH
  275. // has loaded.
  276. if (!isCurrentFileAST()) {
  277. if (!CI.InitializeSourceManager(getCurrentFile(),
  278. getCurrentInput().IsSystem
  279. ? SrcMgr::C_System
  280. : SrcMgr::C_User))
  281. return false;
  282. }
  283. if (CI.hasFrontendTimer()) {
  284. llvm::TimeRegion Timer(CI.getFrontendTimer());
  285. ExecuteAction();
  286. }
  287. else ExecuteAction();
  288. return true;
  289. }
  290. void FrontendAction::EndSourceFile() {
  291. CompilerInstance &CI = getCompilerInstance();
  292. // Inform the diagnostic client we are done with this source file.
  293. CI.getDiagnosticClient().EndSourceFile();
  294. // Finalize the action.
  295. EndSourceFileAction();
  296. // Release the consumer and the AST, in that order since the consumer may
  297. // perform actions in its destructor which require the context.
  298. //
  299. // FIXME: There is more per-file stuff we could just drop here?
  300. if (CI.getFrontendOpts().DisableFree) {
  301. CI.takeASTConsumer();
  302. if (!isCurrentFileAST()) {
  303. CI.takeSema();
  304. CI.resetAndLeakASTContext();
  305. }
  306. } else {
  307. if (!isCurrentFileAST()) {
  308. CI.setSema(0);
  309. CI.setASTContext(0);
  310. }
  311. CI.setASTConsumer(0);
  312. }
  313. // Inform the preprocessor we are done.
  314. if (CI.hasPreprocessor())
  315. CI.getPreprocessor().EndSourceFile();
  316. if (CI.getFrontendOpts().ShowStats) {
  317. llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
  318. CI.getPreprocessor().PrintStats();
  319. CI.getPreprocessor().getIdentifierTable().PrintStats();
  320. CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
  321. CI.getSourceManager().PrintStats();
  322. llvm::errs() << "\n";
  323. }
  324. // Cleanup the output streams, and erase the output files if we encountered
  325. // an error.
  326. CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred());
  327. if (isCurrentFileAST()) {
  328. CI.takeSema();
  329. CI.resetAndLeakASTContext();
  330. CI.resetAndLeakPreprocessor();
  331. CI.resetAndLeakSourceManager();
  332. CI.resetAndLeakFileManager();
  333. }
  334. setCompilerInstance(0);
  335. setCurrentInput(FrontendInputFile());
  336. }
  337. //===----------------------------------------------------------------------===//
  338. // Utility Actions
  339. //===----------------------------------------------------------------------===//
  340. void ASTFrontendAction::ExecuteAction() {
  341. CompilerInstance &CI = getCompilerInstance();
  342. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  343. // here so the source manager would be initialized.
  344. if (hasCodeCompletionSupport() &&
  345. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  346. CI.createCodeCompletionConsumer();
  347. // Use a code completion consumer?
  348. CodeCompleteConsumer *CompletionConsumer = 0;
  349. if (CI.hasCodeCompletionConsumer())
  350. CompletionConsumer = &CI.getCodeCompletionConsumer();
  351. if (!CI.hasSema())
  352. CI.createSema(getTranslationUnitKind(), CompletionConsumer);
  353. ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
  354. CI.getFrontendOpts().SkipFunctionBodies);
  355. }
  356. void PluginASTAction::anchor() { }
  357. ASTConsumer *
  358. PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  359. StringRef InFile) {
  360. llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
  361. }
  362. ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
  363. StringRef InFile) {
  364. return WrappedAction->CreateASTConsumer(CI, InFile);
  365. }
  366. bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
  367. return WrappedAction->BeginInvocation(CI);
  368. }
  369. bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
  370. StringRef Filename) {
  371. WrappedAction->setCurrentInput(getCurrentInput());
  372. WrappedAction->setCompilerInstance(&CI);
  373. return WrappedAction->BeginSourceFileAction(CI, Filename);
  374. }
  375. void WrapperFrontendAction::ExecuteAction() {
  376. WrappedAction->ExecuteAction();
  377. }
  378. void WrapperFrontendAction::EndSourceFileAction() {
  379. WrappedAction->EndSourceFileAction();
  380. }
  381. bool WrapperFrontendAction::usesPreprocessorOnly() const {
  382. return WrappedAction->usesPreprocessorOnly();
  383. }
  384. TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
  385. return WrappedAction->getTranslationUnitKind();
  386. }
  387. bool WrapperFrontendAction::hasPCHSupport() const {
  388. return WrappedAction->hasPCHSupport();
  389. }
  390. bool WrapperFrontendAction::hasASTFileSupport() const {
  391. return WrappedAction->hasASTFileSupport();
  392. }
  393. bool WrapperFrontendAction::hasIRSupport() const {
  394. return WrappedAction->hasIRSupport();
  395. }
  396. bool WrapperFrontendAction::hasCodeCompletionSupport() const {
  397. return WrappedAction->hasCodeCompletionSupport();
  398. }
  399. WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
  400. : WrappedAction(WrappedAction) {}