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.getHeaderSearchOpts().VFSOverlayFiles.empty()) {
215     IntrusiveRefCntPtr<vfs::OverlayFileSystem>
216         Overlay(new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
217     // earlier vfs files are on the bottom
218     const std::vector<std::string> &Files =
219         CI.getHeaderSearchOpts().VFSOverlayFiles;
220     for (std::vector<std::string>::const_iterator I = Files.begin(),
221                                                   E = Files.end();
222          I != E; ++I) {
223       std::unique_ptr<llvm::MemoryBuffer> Buffer;
224       if (llvm::errc::success != llvm::MemoryBuffer::getFile(*I, Buffer)) {
225         CI.getDiagnostics().Report(diag::err_missing_vfs_overlay_file) << *I;
226         goto failure;
227       }
228 
229       IntrusiveRefCntPtr<vfs::FileSystem> FS =
230           vfs::getVFSFromYAML(Buffer.release(), /*DiagHandler*/ 0);
231       if (!FS.getPtr()) {
232         CI.getDiagnostics().Report(diag::err_invalid_vfs_overlay) << *I;
233         goto failure;
234       }
235       Overlay->pushOverlay(FS);
236     }
237     CI.setVirtualFileSystem(Overlay);
238   }
239 
240   // Set up the file and source managers, if needed.
241   if (!CI.hasFileManager())
242     CI.createFileManager();
243   if (!CI.hasSourceManager())
244     CI.createSourceManager(CI.getFileManager());
245 
246   // IR files bypass the rest of initialization.
247   if (Input.getKind() == IK_LLVM_IR) {
248     assert(hasIRSupport() &&
249            "This action does not have IR file support!");
250 
251     // Inform the diagnostic client we are processing a source file.
252     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
253     HasBegunSourceFile = true;
254 
255     // Initialize the action.
256     if (!BeginSourceFileAction(CI, InputFile))
257       goto failure;
258 
259     // Initialize the main file entry.
260     if (!CI.InitializeSourceManager(CurrentInput))
261       goto failure;
262 
263     return true;
264   }
265 
266   // If the implicit PCH include is actually a directory, rather than
267   // a single file, search for a suitable PCH file in that directory.
268   if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
269     FileManager &FileMgr = CI.getFileManager();
270     PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
271     StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
272     if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
273       llvm::error_code EC;
274       SmallString<128> DirNative;
275       llvm::sys::path::native(PCHDir->getName(), DirNative);
276       bool Found = false;
277       for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEnd;
278            Dir != DirEnd && !EC; Dir.increment(EC)) {
279         // Check whether this is an acceptable AST file.
280         if (ASTReader::isAcceptableASTFile(Dir->path(), FileMgr,
281                                            CI.getLangOpts(),
282                                            CI.getTargetOpts(),
283                                            CI.getPreprocessorOpts())) {
284           PPOpts.ImplicitPCHInclude = Dir->path();
285           Found = true;
286           break;
287         }
288       }
289 
290       if (!Found) {
291         CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
292         return true;
293       }
294     }
295   }
296 
297   // Set up the preprocessor.
298   CI.createPreprocessor(getTranslationUnitKind());
299 
300   // Inform the diagnostic client we are processing a source file.
301   CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
302                                            &CI.getPreprocessor());
303   HasBegunSourceFile = true;
304 
305   // Initialize the action.
306   if (!BeginSourceFileAction(CI, InputFile))
307     goto failure;
308 
309   // Initialize the main file entry. It is important that this occurs after
310   // BeginSourceFileAction, which may change CurrentInput during module builds.
311   if (!CI.InitializeSourceManager(CurrentInput))
312     goto failure;
313 
314   // Create the AST context and consumer unless this is a preprocessor only
315   // action.
316   if (!usesPreprocessorOnly()) {
317     CI.createASTContext();
318 
319     std::unique_ptr<ASTConsumer> Consumer(
320         CreateWrappedASTConsumer(CI, InputFile));
321     if (!Consumer)
322       goto failure;
323 
324     CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
325 
326     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
327       // Convert headers to PCH and chain them.
328       IntrusiveRefCntPtr<ChainedIncludesSource> source;
329       source = ChainedIncludesSource::create(CI);
330       if (!source)
331         goto failure;
332       CI.setModuleManager(static_cast<ASTReader*>(&source->getFinalReader()));
333       CI.getASTContext().setExternalSource(source);
334 
335     } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
336       // Use PCH.
337       assert(hasPCHSupport() && "This action does not have PCH support!");
338       ASTDeserializationListener *DeserialListener =
339           Consumer->GetASTDeserializationListener();
340       if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls)
341         DeserialListener = new DeserializedDeclsDumper(DeserialListener);
342       if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty())
343         DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(),
344                          CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
345                                                         DeserialListener);
346       CI.createPCHExternalASTSource(
347                                 CI.getPreprocessorOpts().ImplicitPCHInclude,
348                                 CI.getPreprocessorOpts().DisablePCHValidation,
349                             CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
350                                 DeserialListener);
351       if (!CI.getASTContext().getExternalSource())
352         goto failure;
353     }
354 
355     CI.setASTConsumer(Consumer.release());
356     if (!CI.hasASTConsumer())
357       goto failure;
358   }
359 
360   // Initialize built-in info as long as we aren't using an external AST
361   // source.
362   if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
363     Preprocessor &PP = CI.getPreprocessor();
364     PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
365                                            PP.getLangOpts());
366   }
367 
368   // If there is a layout overrides file, attach an external AST source that
369   // provides the layouts from that file.
370   if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
371       CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
372     IntrusiveRefCntPtr<ExternalASTSource>
373       Override(new LayoutOverrideSource(
374                      CI.getFrontendOpts().OverrideRecordLayoutsFile));
375     CI.getASTContext().setExternalSource(Override);
376   }
377 
378   return true;
379 
380   // If we failed, reset state since the client will not end up calling the
381   // matching EndSourceFile().
382   failure:
383   if (isCurrentFileAST()) {
384     CI.setASTContext(0);
385     CI.setPreprocessor(0);
386     CI.setSourceManager(0);
387     CI.setFileManager(0);
388   }
389 
390   if (HasBegunSourceFile)
391     CI.getDiagnosticClient().EndSourceFile();
392   CI.clearOutputFiles(/*EraseFiles=*/true);
393   setCurrentInput(FrontendInputFile());
394   setCompilerInstance(0);
395   return false;
396 }
397 
398 bool FrontendAction::Execute() {
399   CompilerInstance &CI = getCompilerInstance();
400 
401   if (CI.hasFrontendTimer()) {
402     llvm::TimeRegion Timer(CI.getFrontendTimer());
403     ExecuteAction();
404   }
405   else ExecuteAction();
406 
407   // If we are supposed to rebuild the global module index, do so now unless
408   // there were any module-build failures.
409   if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
410       CI.hasPreprocessor()) {
411     GlobalModuleIndex::writeIndex(
412       CI.getFileManager(),
413       CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
414   }
415 
416   return true;
417 }
418 
419 void FrontendAction::EndSourceFile() {
420   CompilerInstance &CI = getCompilerInstance();
421 
422   // Inform the diagnostic client we are done with this source file.
423   CI.getDiagnosticClient().EndSourceFile();
424 
425   // Finalize the action.
426   EndSourceFileAction();
427 
428   // Release the consumer and the AST, in that order since the consumer may
429   // perform actions in its destructor which require the context.
430   //
431   // FIXME: There is more per-file stuff we could just drop here?
432   if (CI.getFrontendOpts().DisableFree) {
433     BuryPointer(CI.takeASTConsumer());
434     if (!isCurrentFileAST()) {
435       BuryPointer(CI.takeSema());
436       CI.resetAndLeakASTContext();
437     }
438   } else {
439     if (!isCurrentFileAST()) {
440       CI.setSema(0);
441       CI.setASTContext(0);
442     }
443     CI.setASTConsumer(0);
444   }
445 
446   // Inform the preprocessor we are done.
447   if (CI.hasPreprocessor())
448     CI.getPreprocessor().EndSourceFile();
449 
450   if (CI.getFrontendOpts().ShowStats) {
451     llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
452     CI.getPreprocessor().PrintStats();
453     CI.getPreprocessor().getIdentifierTable().PrintStats();
454     CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
455     CI.getSourceManager().PrintStats();
456     llvm::errs() << "\n";
457   }
458 
459   // Cleanup the output streams, and erase the output files if instructed by the
460   // FrontendAction.
461   CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
462 
463   if (isCurrentFileAST()) {
464     CI.takeSema();
465     CI.resetAndLeakASTContext();
466     CI.resetAndLeakPreprocessor();
467     CI.resetAndLeakSourceManager();
468     CI.resetAndLeakFileManager();
469   }
470 
471   setCompilerInstance(0);
472   setCurrentInput(FrontendInputFile());
473 }
474 
475 bool FrontendAction::shouldEraseOutputFiles() {
476   return getCompilerInstance().getDiagnostics().hasErrorOccurred();
477 }
478 
479 //===----------------------------------------------------------------------===//
480 // Utility Actions
481 //===----------------------------------------------------------------------===//
482 
483 void ASTFrontendAction::ExecuteAction() {
484   CompilerInstance &CI = getCompilerInstance();
485   if (!CI.hasPreprocessor())
486     return;
487 
488   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
489   // here so the source manager would be initialized.
490   if (hasCodeCompletionSupport() &&
491       !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
492     CI.createCodeCompletionConsumer();
493 
494   // Use a code completion consumer?
495   CodeCompleteConsumer *CompletionConsumer = 0;
496   if (CI.hasCodeCompletionConsumer())
497     CompletionConsumer = &CI.getCodeCompletionConsumer();
498 
499   if (!CI.hasSema())
500     CI.createSema(getTranslationUnitKind(), CompletionConsumer);
501 
502   ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
503            CI.getFrontendOpts().SkipFunctionBodies);
504 }
505 
506 void PluginASTAction::anchor() { }
507 
508 ASTConsumer *
509 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
510                                               StringRef InFile) {
511   llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
512 }
513 
514 ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
515                                                       StringRef InFile) {
516   return WrappedAction->CreateASTConsumer(CI, InFile);
517 }
518 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
519   return WrappedAction->BeginInvocation(CI);
520 }
521 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
522                                                   StringRef Filename) {
523   WrappedAction->setCurrentInput(getCurrentInput());
524   WrappedAction->setCompilerInstance(&CI);
525   return WrappedAction->BeginSourceFileAction(CI, Filename);
526 }
527 void WrapperFrontendAction::ExecuteAction() {
528   WrappedAction->ExecuteAction();
529 }
530 void WrapperFrontendAction::EndSourceFileAction() {
531   WrappedAction->EndSourceFileAction();
532 }
533 
534 bool WrapperFrontendAction::usesPreprocessorOnly() const {
535   return WrappedAction->usesPreprocessorOnly();
536 }
537 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
538   return WrappedAction->getTranslationUnitKind();
539 }
540 bool WrapperFrontendAction::hasPCHSupport() const {
541   return WrappedAction->hasPCHSupport();
542 }
543 bool WrapperFrontendAction::hasASTFileSupport() const {
544   return WrappedAction->hasASTFileSupport();
545 }
546 bool WrapperFrontendAction::hasIRSupport() const {
547   return WrappedAction->hasIRSupport();
548 }
549 bool WrapperFrontendAction::hasCodeCompletionSupport() const {
550   return WrappedAction->hasCodeCompletionSupport();
551 }
552 
553 WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction)
554   : WrappedAction(WrappedAction) {}
555 
556