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   virtual void ReaderInitialized(ASTReader *Reader) {
47     if (Previous)
48       Previous->ReaderInitialized(Reader);
49   }
50   virtual void IdentifierRead(serialization::IdentID ID,
51                               IdentifierInfo *II) {
52     if (Previous)
53       Previous->IdentifierRead(ID, II);
54   }
55   virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {
56     if (Previous)
57       Previous->TypeRead(Idx, T);
58   }
59   virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
60     if (Previous)
61       Previous->DeclRead(ID, D);
62   }
63   virtual void SelectorRead(serialization::SelectorID ID, Selector Sel) {
64     if (Previous)
65       Previous->SelectorRead(ID, Sel);
66   }
67   virtual void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
68                                    MacroDefinition *MD) {
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   virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
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   virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
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         OwningPtr<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 
163 bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
164                                      const FrontendInputFile &Input) {
165   assert(!Instance && "Already processing a source file!");
166   assert(!Input.isEmpty() && "Unexpected empty filename!");
167   setCurrentInput(Input);
168   setCompilerInstance(&CI);
169 
170   StringRef InputFile = Input.getFile();
171   bool HasBegunSourceFile = false;
172   if (!BeginInvocation(CI))
173     goto failure;
174 
175   // AST files follow a very different path, since they share objects via the
176   // AST unit.
177   if (Input.getKind() == IK_AST) {
178     assert(!usesPreprocessorOnly() &&
179            "Attempt to pass AST file to preprocessor only action!");
180     assert(hasASTFileSupport() &&
181            "This action does not have AST file support!");
182 
183     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
184 
185     ASTUnit *AST = ASTUnit::LoadFromASTFile(InputFile, Diags,
186                                             CI.getFileSystemOpts());
187     if (!AST)
188       goto failure;
189 
190     setCurrentInput(Input, AST);
191 
192     // Inform the diagnostic client we are processing a source file.
193     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
194     HasBegunSourceFile = true;
195 
196     // Set the shared objects, these are reset when we finish processing the
197     // file, otherwise the CompilerInstance will happily destroy them.
198     CI.setFileManager(&AST->getFileManager());
199     CI.setSourceManager(&AST->getSourceManager());
200     CI.setPreprocessor(&AST->getPreprocessor());
201     CI.setASTContext(&AST->getASTContext());
202 
203     // Initialize the action.
204     if (!BeginSourceFileAction(CI, InputFile))
205       goto failure;
206 
207     // Create the AST consumer.
208     CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
209     if (!CI.hasASTConsumer())
210       goto failure;
211 
212     return true;
213   }
214 
215   // Set up the file and source managers, if needed.
216   if (!CI.hasFileManager())
217     CI.createFileManager();
218   if (!CI.hasSourceManager())
219     CI.createSourceManager(CI.getFileManager());
220 
221   // IR files bypass the rest of initialization.
222   if (Input.getKind() == IK_LLVM_IR) {
223     assert(hasIRSupport() &&
224            "This action does not have IR file support!");
225 
226     // Inform the diagnostic client we are processing a source file.
227     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
228     HasBegunSourceFile = true;
229 
230     // Initialize the action.
231     if (!BeginSourceFileAction(CI, InputFile))
232       goto failure;
233 
234     return true;
235   }
236 
237   // If the implicit PCH include is actually a directory, rather than
238   // a single file, search for a suitable PCH file in that directory.
239   if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
240     FileManager &FileMgr = CI.getFileManager();
241     PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
242     StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
243     if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
244       llvm::error_code EC;
245       SmallString<128> DirNative;
246       llvm::sys::path::native(PCHDir->getName(), DirNative);
247       bool Found = false;
248       for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
249            Dir != DirEnd && !EC; Dir.increment(EC)) {
250         // Check whether this is an acceptable AST file.
251         if (ASTReader::isAcceptableASTFile(Dir->path(), FileMgr,
252                                            CI.getLangOpts(),
253                                            CI.getTargetOpts(),
254                                            CI.getPreprocessorOpts())) {
255           PPOpts.ImplicitPCHInclude = Dir->path();
256           Found = true;
257           break;
258         }
259       }
260 
261       if (!Found) {
262         CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
263         return true;
264       }
265     }
266   }
267 
268   // Set up the preprocessor.
269   CI.createPreprocessor();
270 
271   // Inform the diagnostic client we are processing a source file.
272   CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
273                                            &CI.getPreprocessor());
274   HasBegunSourceFile = true;
275 
276   // Initialize the action.
277   if (!BeginSourceFileAction(CI, InputFile))
278     goto failure;
279 
280   // Create the AST context and consumer unless this is a preprocessor only
281   // action.
282   if (!usesPreprocessorOnly()) {
283     CI.createASTContext();
284 
285     OwningPtr<ASTConsumer> Consumer(
286                                    CreateWrappedASTConsumer(CI, InputFile));
287     if (!Consumer)
288       goto failure;
289 
290     CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
291 
292     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
293       // Convert headers to PCH and chain them.
294       OwningPtr<ExternalASTSource> source;
295       source.reset(ChainedIncludesSource::create(CI));
296       if (!source)
297         goto failure;
298       CI.setModuleManager(static_cast<ASTReader*>(
299          &static_cast<ChainedIncludesSource*>(source.get())->getFinalReader()));
300       CI.getASTContext().setExternalSource(source);
301 
302     } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
303       // Use PCH.
304       assert(hasPCHSupport() && "This action does not have PCH support!");
305       ASTDeserializationListener *DeserialListener =
306           Consumer->GetASTDeserializationListener();
307       if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
308         DeserialListener = new DeserializedDeclsDumper(DeserialListener);
309       if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
310         DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
311                          CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
312                                                         DeserialListener);
313       CI.createPCHExternalASTSource(
314                                 CI.getPreprocessorOpts().ImplicitPCHInclude,
315                                 CI.getPreprocessorOpts().DisablePCHValidation,
316                             CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
317                                 DeserialListener);
318       if (!CI.getASTContext().getExternalSource())
319         goto failure;
320     }
321 
322     CI.setASTConsumer(Consumer.take());
323     if (!CI.hasASTConsumer())
324       goto failure;
325   }
326 
327   // Initialize built-in info as long as we aren't using an external AST
328   // source.
329   if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
330     Preprocessor &PP = CI.getPreprocessor();
331     PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
332                                            PP.getLangOpts());
333   }
334 
335   // If there is a layout overrides file, attach an external AST source that
336   // provides the layouts from that file.
337   if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
338       CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
339     OwningPtr<ExternalASTSource>
340       Override(new LayoutOverrideSource(
341                      CI.getFrontendOpts().OverrideRecordLayoutsFile));
342     CI.getASTContext().setExternalSource(Override);
343   }
344 
345   return true;
346 
347   // If we failed, reset state since the client will not end up calling the
348   // matching EndSourceFile().
349   failure:
350   if (isCurrentFileAST()) {
351     CI.setASTContext(0);
352     CI.setPreprocessor(0);
353     CI.setSourceManager(0);
354     CI.setFileManager(0);
355   }
356 
357   if (HasBegunSourceFile)
358     CI.getDiagnosticClient().EndSourceFile();
359   CI.clearOutputFiles(/*EraseFiles=*/true);
360   setCurrentInput(FrontendInputFile());
361   setCompilerInstance(0);
362   return false;
363 }
364 
365 bool FrontendAction::Execute() {
366   CompilerInstance &CI = getCompilerInstance();
367 
368   // Initialize the main file entry. This needs to be delayed until after PCH
369   // has loaded.
370   if (!isCurrentFileAST()) {
371     if (!CI.InitializeSourceManager(getCurrentInput()))
372       return false;
373   }
374 
375   if (CI.hasFrontendTimer()) {
376     llvm::TimeRegion Timer(CI.getFrontendTimer());
377     ExecuteAction();
378   }
379   else ExecuteAction();
380 
381   // If we are supposed to rebuild the global module index, do so now unless
382   // there were any module-build failures.
383   if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
384       CI.hasPreprocessor()) {
385     GlobalModuleIndex::writeIndex(
386       CI.getFileManager(),
387       CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
388   }
389 
390   return true;
391 }
392 
393 void FrontendAction::EndSourceFile() {
394   CompilerInstance &CI = getCompilerInstance();
395 
396   // Inform the diagnostic client we are done with this source file.
397   CI.getDiagnosticClient().EndSourceFile();
398 
399   // Finalize the action.
400   EndSourceFileAction();
401 
402   // Release the consumer and the AST, in that order since the consumer may
403   // perform actions in its destructor which require the context.
404   //
405   // FIXME: There is more per-file stuff we could just drop here?
406   if (CI.getFrontendOpts().DisableFree) {
407     BuryPointer(CI.takeASTConsumer());
408     if (!isCurrentFileAST()) {
409       BuryPointer(CI.takeSema());
410       CI.resetAndLeakASTContext();
411     }
412   } else {
413     if (!isCurrentFileAST()) {
414       CI.setSema(0);
415       CI.setASTContext(0);
416     }
417     CI.setASTConsumer(0);
418   }
419 
420   // Inform the preprocessor we are done.
421   if (CI.hasPreprocessor())
422     CI.getPreprocessor().EndSourceFile();
423 
424   if (CI.getFrontendOpts().ShowStats) {
425     llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
426     CI.getPreprocessor().PrintStats();
427     CI.getPreprocessor().getIdentifierTable().PrintStats();
428     CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
429     CI.getSourceManager().PrintStats();
430     llvm::errs() << "\n";
431   }
432 
433   // Cleanup the output streams, and erase the output files if instructed by the
434   // FrontendAction.
435   CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
436 
437   if (isCurrentFileAST()) {
438     CI.takeSema();
439     CI.resetAndLeakASTContext();
440     CI.resetAndLeakPreprocessor();
441     CI.resetAndLeakSourceManager();
442     CI.resetAndLeakFileManager();
443   }
444 
445   setCompilerInstance(0);
446   setCurrentInput(FrontendInputFile());
447 }
448 
449 bool FrontendAction::shouldEraseOutputFiles() {
450   return getCompilerInstance().getDiagnostics().hasErrorOccurred();
451 }
452 
453 //===----------------------------------------------------------------------===//
454 // Utility Actions
455 //===----------------------------------------------------------------------===//
456 
457 void ASTFrontendAction::ExecuteAction() {
458   CompilerInstance &CI = getCompilerInstance();
459   if (!CI.hasPreprocessor())
460     return;
461 
462   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
463   // here so the source manager would be initialized.
464   if (hasCodeCompletionSupport() &&
465       !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
466     CI.createCodeCompletionConsumer();
467 
468   // Use a code completion consumer?
469   CodeCompleteConsumer *CompletionConsumer = 0;
470   if (CI.hasCodeCompletionConsumer())
471     CompletionConsumer = &CI.getCodeCompletionConsumer();
472 
473   if (!CI.hasSema())
474     CI.createSema(getTranslationUnitKind(), CompletionConsumer);
475 
476   ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
477            CI.getFrontendOpts().SkipFunctionBodies);
478 }
479 
480 void PluginASTAction::anchor() { }
481 
482 ASTConsumer *
483 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
484                                               StringRef InFile) {
485   llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
486 }
487 
488 ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
489                                                       StringRef InFile) {
490   return WrappedAction->CreateASTConsumer(CI, InFile);
491 }
492 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
493   return WrappedAction->BeginInvocation(CI);
494 }
495 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
496                                                   StringRef Filename) {
497   WrappedAction->setCurrentInput(getCurrentInput());
498   WrappedAction->setCompilerInstance(&CI);
499   return WrappedAction->BeginSourceFileAction(CI, Filename);
500 }
501 void WrapperFrontendAction::ExecuteAction() {
502   WrappedAction->ExecuteAction();
503 }
504 void WrapperFrontendAction::EndSourceFileAction() {
505   WrappedAction->EndSourceFileAction();
506 }
507 
508 bool WrapperFrontendAction::usesPreprocessorOnly() const {
509   return WrappedAction->usesPreprocessorOnly();
510 }
511 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
512   return WrappedAction->getTranslationUnitKind();
513 }
514 bool WrapperFrontendAction::hasPCHSupport() const {
515   return WrappedAction->hasPCHSupport();
516 }
517 bool WrapperFrontendAction::hasASTFileSupport() const {
518   return WrappedAction->hasASTFileSupport();
519 }
520 bool WrapperFrontendAction::hasIRSupport() const {
521   return WrappedAction->hasIRSupport();
522 }
523 bool WrapperFrontendAction::hasCodeCompletionSupport() const {
524   return WrappedAction->hasCodeCompletionSupport();
525 }
526 
527 WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
528   : WrappedAction(WrappedAction) {}
529 
530