FrontendAction.cpp 18 KB

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