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