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