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/LiteralSupport.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Lex/PreprocessorOptions.h"
25 #include "clang/Parse/ParseAST.h"
26 #include "clang/Serialization/ASTDeserializationListener.h"
27 #include "clang/Serialization/ASTReader.h"
28 #include "clang/Serialization/GlobalModuleIndex.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Timer.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <system_error>
35 using namespace clang;
36 
37 LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
38 
39 namespace {
40 
41 class DelegatingDeserializationListener : public ASTDeserializationListener {
42   ASTDeserializationListener *Previous;
43   bool DeletePrevious;
44 
45 public:
46   explicit DelegatingDeserializationListener(
47       ASTDeserializationListener *Previous, bool DeletePrevious)
48       : Previous(Previous), DeletePrevious(DeletePrevious) {}
49   ~DelegatingDeserializationListener() override {
50     if (DeletePrevious)
51       delete Previous;
52   }
53 
54   void ReaderInitialized(ASTReader *Reader) override {
55     if (Previous)
56       Previous->ReaderInitialized(Reader);
57   }
58   void IdentifierRead(serialization::IdentID ID,
59                       IdentifierInfo *II) override {
60     if (Previous)
61       Previous->IdentifierRead(ID, II);
62   }
63   void TypeRead(serialization::TypeIdx Idx, QualType T) override {
64     if (Previous)
65       Previous->TypeRead(Idx, T);
66   }
67   void DeclRead(serialization::DeclID ID, const Decl *D) override {
68     if (Previous)
69       Previous->DeclRead(ID, D);
70   }
71   void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
72     if (Previous)
73       Previous->SelectorRead(ID, Sel);
74   }
75   void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
76                            MacroDefinitionRecord *MD) override {
77     if (Previous)
78       Previous->MacroDefinitionRead(PPID, MD);
79   }
80 };
81 
82 /// \brief Dumps deserialized declarations.
83 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
84 public:
85   explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
86                                    bool DeletePrevious)
87       : DelegatingDeserializationListener(Previous, DeletePrevious) {}
88 
89   void DeclRead(serialization::DeclID ID, const Decl *D) override {
90     llvm::outs() << "PCH DECL: " << D->getDeclKindName();
91     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
92       llvm::outs() << " - " << *ND;
93     llvm::outs() << "\n";
94 
95     DelegatingDeserializationListener::DeclRead(ID, D);
96   }
97 };
98 
99 /// \brief Checks deserialized declarations and emits error if a name
100 /// matches one given in command-line using -error-on-deserialized-decl.
101 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
102   ASTContext &Ctx;
103   std::set<std::string> NamesToCheck;
104 
105 public:
106   DeserializedDeclsChecker(ASTContext &Ctx,
107                            const std::set<std::string> &NamesToCheck,
108                            ASTDeserializationListener *Previous,
109                            bool DeletePrevious)
110       : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
111         NamesToCheck(NamesToCheck) {}
112 
113   void DeclRead(serialization::DeclID ID, const Decl *D) override {
114     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
115       if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
116         unsigned DiagID
117           = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
118                                                  "%0 was deserialized");
119         Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
120             << ND->getNameAsString();
121       }
122 
123     DelegatingDeserializationListener::DeclRead(ID, D);
124   }
125 };
126 
127 } // end anonymous namespace
128 
129 FrontendAction::FrontendAction() : Instance(nullptr) {}
130 
131 FrontendAction::~FrontendAction() {}
132 
133 void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
134                                      std::unique_ptr<ASTUnit> AST) {
135   this->CurrentInput = CurrentInput;
136   CurrentASTUnit = std::move(AST);
137 }
138 
139 Module *FrontendAction::getCurrentModule() const {
140   CompilerInstance &CI = getCompilerInstance();
141   return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
142       CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
143 }
144 
145 std::unique_ptr<ASTConsumer>
146 FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
147                                          StringRef InFile) {
148   std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
149   if (!Consumer)
150     return nullptr;
151 
152   // If there are no registered plugins we don't need to wrap the consumer
153   if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
154     return Consumer;
155 
156   // Collect the list of plugins that go before the main action (in Consumers)
157   // or after it (in AfterConsumers)
158   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
159   std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
160   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
161                                         ie = FrontendPluginRegistry::end();
162        it != ie; ++it) {
163     std::unique_ptr<PluginASTAction> P = it->instantiate();
164     PluginASTAction::ActionType ActionType = P->getActionType();
165     if (ActionType == PluginASTAction::Cmdline) {
166       // This is O(|plugins| * |add_plugins|), but since both numbers are
167       // way below 50 in practice, that's ok.
168       for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
169            i != e; ++i) {
170         if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
171           ActionType = PluginASTAction::AddAfterMainAction;
172           break;
173         }
174       }
175     }
176     if ((ActionType == PluginASTAction::AddBeforeMainAction ||
177          ActionType == PluginASTAction::AddAfterMainAction) &&
178         P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
179       std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
180       if (ActionType == PluginASTAction::AddBeforeMainAction) {
181         Consumers.push_back(std::move(PluginConsumer));
182       } else {
183         AfterConsumers.push_back(std::move(PluginConsumer));
184       }
185     }
186   }
187 
188   // Add to Consumers the main consumer, then all the plugins that go after it
189   Consumers.push_back(std::move(Consumer));
190   for (auto &C : AfterConsumers) {
191     Consumers.push_back(std::move(C));
192   }
193 
194   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
195 }
196 
197 /// For preprocessed files, if the first line is the linemarker and specifies
198 /// the original source file name, use that name as the input file name.
199 /// Returns the location of the first token after the line marker directive.
200 ///
201 /// \param CI The compiler instance.
202 /// \param InputFile Populated with the filename from the line marker.
203 /// \param AddLineNote If \c true, add a line note corresponding to this line
204 ///        directive. Only use this if the directive will not actually be
205 ///        visited by the preprocessor.
206 static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
207                                            std::string &InputFile,
208                                            bool AddLineNote = false) {
209   auto &SourceMgr = CI.getSourceManager();
210   auto MainFileID = SourceMgr.getMainFileID();
211 
212   bool Invalid = false;
213   const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
214   if (Invalid)
215     return SourceLocation();
216 
217   std::unique_ptr<Lexer> RawLexer(
218       new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
219 
220   // If the first line has the syntax of
221   //
222   // # NUM "FILENAME"
223   //
224   // we use FILENAME as the input file name.
225   Token T;
226   if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
227     return SourceLocation();
228   if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
229       T.getKind() != tok::numeric_constant)
230     return SourceLocation();
231 
232   unsigned LineNo;
233   SourceLocation LineNoLoc = T.getLocation();
234   if (AddLineNote) {
235     llvm::SmallString<16> Buffer;
236     if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
237             .getAsInteger(10, LineNo))
238       return SourceLocation();
239   }
240 
241   RawLexer->LexFromRawLexer(T);
242   if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
243     return SourceLocation();
244 
245   StringLiteralParser Literal(T, CI.getPreprocessor());
246   if (Literal.hadError)
247     return SourceLocation();
248   RawLexer->LexFromRawLexer(T);
249   if (T.isNot(tok::eof) && !T.isAtStartOfLine())
250     return SourceLocation();
251   InputFile = Literal.GetString().str();
252 
253   if (AddLineNote)
254     CI.getSourceManager().AddLineNote(
255         LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
256         false, SrcMgr::C_User);
257 
258   return T.getLocation();
259 }
260 
261 static SmallVectorImpl<char> &
262 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
263   Includes.append(RHS.begin(), RHS.end());
264   return Includes;
265 }
266 
267 static void addHeaderInclude(StringRef HeaderName,
268                              SmallVectorImpl<char> &Includes,
269                              const LangOptions &LangOpts,
270                              bool IsExternC) {
271   if (IsExternC && LangOpts.CPlusPlus)
272     Includes += "extern \"C\" {\n";
273   if (LangOpts.ObjC1)
274     Includes += "#import \"";
275   else
276     Includes += "#include \"";
277 
278   Includes += HeaderName;
279 
280   Includes += "\"\n";
281   if (IsExternC && LangOpts.CPlusPlus)
282     Includes += "}\n";
283 }
284 
285 /// \brief Collect the set of header includes needed to construct the given
286 /// module and update the TopHeaders file set of the module.
287 ///
288 /// \param Module The module we're collecting includes from.
289 ///
290 /// \param Includes Will be augmented with the set of \#includes or \#imports
291 /// needed to load all of the named headers.
292 static std::error_code collectModuleHeaderIncludes(
293     const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
294     ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
295   // Don't collect any headers for unavailable modules.
296   if (!Module->isAvailable())
297     return std::error_code();
298 
299   // Resolve all lazy header directives to header files.
300   ModMap.resolveHeaderDirectives(Module);
301 
302   // If any headers are missing, we can't build this module. In most cases,
303   // diagnostics for this should have already been produced; we only get here
304   // if explicit stat information was provided.
305   // FIXME: If the name resolves to a file with different stat information,
306   // produce a better diagnostic.
307   if (!Module->MissingHeaders.empty()) {
308     auto &MissingHeader = Module->MissingHeaders.front();
309     Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
310       << MissingHeader.IsUmbrella << MissingHeader.FileName;
311     return std::error_code();
312   }
313 
314   // Add includes for each of these headers.
315   for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
316     for (Module::Header &H : Module->Headers[HK]) {
317       Module->addTopHeader(H.Entry);
318       // Use the path as specified in the module map file. We'll look for this
319       // file relative to the module build directory (the directory containing
320       // the module map file) so this will find the same file that we found
321       // while parsing the module map.
322       addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
323     }
324   }
325   // Note that Module->PrivateHeaders will not be a TopHeader.
326 
327   if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
328     Module->addTopHeader(UmbrellaHeader.Entry);
329     if (Module->Parent)
330       // Include the umbrella header for submodules.
331       addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
332                        Module->IsExternC);
333   } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
334     // Add all of the headers we find in this subdirectory.
335     std::error_code EC;
336     SmallString<128> DirNative;
337     llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
338 
339     vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
340     for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
341          Dir != End && !EC; Dir.increment(EC)) {
342       // Check whether this entry has an extension typically associated with
343       // headers.
344       if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
345           .Cases(".h", ".H", ".hh", ".hpp", true)
346           .Default(false))
347         continue;
348 
349       const FileEntry *Header = FileMgr.getFile(Dir->getName());
350       // FIXME: This shouldn't happen unless there is a file system race. Is
351       // that worth diagnosing?
352       if (!Header)
353         continue;
354 
355       // If this header is marked 'unavailable' in this module, don't include
356       // it.
357       if (ModMap.isHeaderUnavailableInModule(Header, Module))
358         continue;
359 
360       // Compute the relative path from the directory to this file.
361       SmallVector<StringRef, 16> Components;
362       auto PathIt = llvm::sys::path::rbegin(Dir->getName());
363       for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
364         Components.push_back(*PathIt);
365       SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
366       for (auto It = Components.rbegin(), End = Components.rend(); It != End;
367            ++It)
368         llvm::sys::path::append(RelativeHeader, *It);
369 
370       // Include this header as part of the umbrella directory.
371       Module->addTopHeader(Header);
372       addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
373     }
374 
375     if (EC)
376       return EC;
377   }
378 
379   // Recurse into submodules.
380   for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
381                                       SubEnd = Module->submodule_end();
382        Sub != SubEnd; ++Sub)
383     if (std::error_code Err = collectModuleHeaderIncludes(
384             LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
385       return Err;
386 
387   return std::error_code();
388 }
389 
390 static bool loadModuleMapForModuleBuild(CompilerInstance &CI,
391                                         StringRef Filename, bool IsSystem,
392                                         bool IsPreprocessed,
393                                         std::string &PresumedModuleMapFile,
394                                         unsigned &Offset) {
395   auto &SrcMgr = CI.getSourceManager();
396   HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
397 
398   // Map the current input to a file.
399   FileID ModuleMapID = SrcMgr.getMainFileID();
400   const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
401 
402   // If the module map is preprocessed, handle the initial line marker;
403   // line directives are not part of the module map syntax in general.
404   Offset = 0;
405   if (IsPreprocessed) {
406     SourceLocation EndOfLineMarker =
407         ReadOriginalFileName(CI, PresumedModuleMapFile, /*AddLineNote*/true);
408     if (EndOfLineMarker.isValid())
409       Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
410   }
411 
412   // Load the module map file.
413   if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
414                            PresumedModuleMapFile))
415     return true;
416 
417   if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
418     Offset = 0;
419 
420   return false;
421 }
422 
423 static Module *prepareToBuildModule(CompilerInstance &CI,
424                                     StringRef ModuleMapFilename) {
425   if (CI.getLangOpts().CurrentModule.empty()) {
426     CI.getDiagnostics().Report(diag::err_missing_module_name);
427 
428     // FIXME: Eventually, we could consider asking whether there was just
429     // a single module described in the module map, and use that as a
430     // default. Then it would be fairly trivial to just "compile" a module
431     // map with a single module (the common case).
432     return nullptr;
433   }
434 
435   // Dig out the module definition.
436   HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
437   Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
438                               /*AllowSearch=*/false);
439   if (!M) {
440     CI.getDiagnostics().Report(diag::err_missing_module)
441       << CI.getLangOpts().CurrentModule << ModuleMapFilename;
442 
443     return nullptr;
444   }
445 
446   // Check whether we can build this module at all.
447   clang::Module::Requirement Requirement;
448   clang::Module::UnresolvedHeaderDirective MissingHeader;
449   if (!M->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
450                       MissingHeader)) {
451     if (MissingHeader.FileNameLoc.isValid()) {
452       CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
453                                  diag::err_module_header_missing)
454         << MissingHeader.IsUmbrella << MissingHeader.FileName;
455     } else {
456       CI.getDiagnostics().Report(diag::err_module_unavailable)
457         << M->getFullModuleName() << Requirement.second << Requirement.first;
458     }
459 
460     return nullptr;
461   }
462 
463   // Inform the preprocessor that includes from within the input buffer should
464   // be resolved relative to the build directory of the module map file.
465   CI.getPreprocessor().setMainFileDir(M->Directory);
466 
467   // If the module was inferred from a different module map (via an expanded
468   // umbrella module definition), track that fact.
469   // FIXME: It would be preferable to fill this in as part of processing
470   // the module map, rather than adding it after the fact.
471   StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
472   if (!OriginalModuleMapName.empty()) {
473     auto *OriginalModuleMap =
474         CI.getFileManager().getFile(OriginalModuleMapName,
475                                     /*openFile*/ true);
476     if (!OriginalModuleMap) {
477       CI.getDiagnostics().Report(diag::err_module_map_not_found)
478         << OriginalModuleMapName;
479       return nullptr;
480     }
481     if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
482                                  CI.getSourceManager().getMainFileID())) {
483       M->IsInferred = true;
484       CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
485         .setInferredModuleAllowedBy(M, OriginalModuleMap);
486     }
487   }
488 
489   // If we're being run from the command-line, the module build stack will not
490   // have been filled in yet, so complete it now in order to allow us to detect
491   // module cycles.
492   SourceManager &SourceMgr = CI.getSourceManager();
493   if (SourceMgr.getModuleBuildStack().empty())
494     SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
495                                    FullSourceLoc(SourceLocation(), SourceMgr));
496   return M;
497 }
498 
499 /// Compute the input buffer that should be used to build the specified module.
500 static std::unique_ptr<llvm::MemoryBuffer>
501 getInputBufferForModule(CompilerInstance &CI, Module *M) {
502   FileManager &FileMgr = CI.getFileManager();
503 
504   // Collect the set of #includes we need to build the module.
505   SmallString<256> HeaderContents;
506   std::error_code Err = std::error_code();
507   if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
508     addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
509                      CI.getLangOpts(), M->IsExternC);
510   Err = collectModuleHeaderIncludes(
511       CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
512       CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
513       HeaderContents);
514 
515   if (Err) {
516     CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
517       << M->getFullModuleName() << Err.message();
518     return nullptr;
519   }
520 
521   return llvm::MemoryBuffer::getMemBufferCopy(
522       HeaderContents, Module::getModuleInputBufferName());
523 }
524 
525 bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
526                                      const FrontendInputFile &Input) {
527   assert(!Instance && "Already processing a source file!");
528   assert(!Input.isEmpty() && "Unexpected empty filename!");
529   setCurrentInput(Input);
530   setCompilerInstance(&CI);
531 
532   StringRef InputFile = Input.getFile();
533   bool HasBegunSourceFile = false;
534   if (!BeginInvocation(CI))
535     goto failure;
536 
537   // AST files follow a very different path, since they share objects via the
538   // AST unit.
539   if (Input.getKind().getFormat() == InputKind::Precompiled) {
540     // FIXME: We should not be asserting on bad command-line arguments.
541     assert(!usesPreprocessorOnly() &&
542            "Attempt to pass AST file to preprocessor only action!");
543     assert(hasASTFileSupport() &&
544            "This action does not have AST file support!");
545 
546     IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
547 
548     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
549         InputFile, CI.getPCHContainerReader(), Diags, CI.getFileSystemOpts(),
550         CI.getCodeGenOpts().DebugTypeExtRefs);
551 
552     if (!AST)
553       goto failure;
554 
555     // Inform the diagnostic client we are processing a source file.
556     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
557     HasBegunSourceFile = true;
558 
559     // Set the shared objects, these are reset when we finish processing the
560     // file, otherwise the CompilerInstance will happily destroy them.
561     CI.setFileManager(&AST->getFileManager());
562     CI.setSourceManager(&AST->getSourceManager());
563     CI.setPreprocessor(AST->getPreprocessorPtr());
564     Preprocessor &PP = CI.getPreprocessor();
565     PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
566                                            PP.getLangOpts());
567     CI.setASTContext(&AST->getASTContext());
568 
569     setCurrentInput(Input, std::move(AST));
570 
571     // Initialize the action.
572     if (!BeginSourceFileAction(CI, InputFile))
573       goto failure;
574 
575     // Create the AST consumer.
576     CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
577     if (!CI.hasASTConsumer())
578       goto failure;
579 
580     return true;
581   }
582 
583   if (!CI.hasVirtualFileSystem()) {
584     if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
585           createVFSFromCompilerInvocation(CI.getInvocation(),
586                                           CI.getDiagnostics()))
587       CI.setVirtualFileSystem(VFS);
588     else
589       goto failure;
590   }
591 
592   // Set up the file and source managers, if needed.
593   if (!CI.hasFileManager())
594     CI.createFileManager();
595   if (!CI.hasSourceManager())
596     CI.createSourceManager(CI.getFileManager());
597 
598   // Set up embedding for any specified files. Do this before we load any
599   // source files, including the primary module map for the compilation.
600   for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
601     if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
602       CI.getSourceManager().setFileIsTransient(FE);
603     else
604       CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
605   }
606   if (CI.getFrontendOpts().ModulesEmbedAllFiles)
607     CI.getSourceManager().setAllFilesAreTransient(true);
608 
609   // IR files bypass the rest of initialization.
610   if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
611     assert(hasIRSupport() &&
612            "This action does not have IR file support!");
613 
614     // Inform the diagnostic client we are processing a source file.
615     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
616     HasBegunSourceFile = true;
617 
618     // Initialize the action.
619     if (!BeginSourceFileAction(CI, InputFile))
620       goto failure;
621 
622     // Initialize the main file entry.
623     if (!CI.InitializeSourceManager(CurrentInput))
624       goto failure;
625 
626     return true;
627   }
628 
629   // If the implicit PCH include is actually a directory, rather than
630   // a single file, search for a suitable PCH file in that directory.
631   if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
632     FileManager &FileMgr = CI.getFileManager();
633     PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
634     StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
635     std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
636     if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
637       std::error_code EC;
638       SmallString<128> DirNative;
639       llvm::sys::path::native(PCHDir->getName(), DirNative);
640       bool Found = false;
641       vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
642       for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
643            Dir != DirEnd && !EC; Dir.increment(EC)) {
644         // Check whether this is an acceptable AST file.
645         if (ASTReader::isAcceptableASTFile(
646                 Dir->getName(), FileMgr, CI.getPCHContainerReader(),
647                 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
648                 SpecificModuleCachePath)) {
649           PPOpts.ImplicitPCHInclude = Dir->getName();
650           Found = true;
651           break;
652         }
653       }
654 
655       if (!Found) {
656         CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
657         goto failure;
658       }
659     }
660   }
661 
662   // Set up the preprocessor if needed. When parsing model files the
663   // preprocessor of the original source is reused.
664   if (!isModelParsingAction())
665     CI.createPreprocessor(getTranslationUnitKind());
666 
667   // Inform the diagnostic client we are processing a source file.
668   CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
669                                            &CI.getPreprocessor());
670   HasBegunSourceFile = true;
671 
672   // Initialize the main file entry.
673   if (!CI.InitializeSourceManager(Input))
674     goto failure;
675 
676   // For module map files, we first parse the module map and synthesize a
677   // "<module-includes>" buffer before more conventional processing.
678   if (Input.getKind().getFormat() == InputKind::ModuleMap) {
679     CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
680 
681     std::string PresumedModuleMapFile;
682     unsigned OffsetToContents;
683     if (loadModuleMapForModuleBuild(CI, Input.getFile(), Input.isSystem(),
684                                     Input.isPreprocessed(),
685                                     PresumedModuleMapFile, OffsetToContents))
686       goto failure;
687 
688     auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
689     if (!CurrentModule)
690       goto failure;
691 
692     CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
693 
694     if (OffsetToContents)
695       // If the module contents are in the same file, skip to them.
696       CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
697     else {
698       // Otherwise, convert the module description to a suitable input buffer.
699       auto Buffer = getInputBufferForModule(CI, CurrentModule);
700       if (!Buffer)
701         goto failure;
702 
703       // Reinitialize the main file entry to refer to the new input.
704       if (!CI.InitializeSourceManager(FrontendInputFile(
705               Buffer.release(), Input.getKind().withFormat(InputKind::Source),
706               CurrentModule->IsSystem)))
707         goto failure;
708     }
709   }
710 
711   // Initialize the action.
712   if (!BeginSourceFileAction(CI, InputFile))
713     goto failure;
714 
715   // Create the AST context and consumer unless this is a preprocessor only
716   // action.
717   if (!usesPreprocessorOnly()) {
718     // Parsing a model file should reuse the existing ASTContext.
719     if (!isModelParsingAction())
720       CI.createASTContext();
721 
722     // For preprocessed files, check if the first line specifies the original
723     // source file name with a linemarker.
724     std::string PresumedInputFile = InputFile;
725     if (Input.isPreprocessed())
726       ReadOriginalFileName(CI, PresumedInputFile);
727 
728     std::unique_ptr<ASTConsumer> Consumer =
729         CreateWrappedASTConsumer(CI, PresumedInputFile);
730     if (!Consumer)
731       goto failure;
732 
733     // FIXME: should not overwrite ASTMutationListener when parsing model files?
734     if (!isModelParsingAction())
735       CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
736 
737     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
738       // Convert headers to PCH and chain them.
739       IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
740       source = createChainedIncludesSource(CI, FinalReader);
741       if (!source)
742         goto failure;
743       CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
744       CI.getASTContext().setExternalSource(source);
745     } else if (CI.getLangOpts().Modules ||
746                !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
747       // Use PCM or PCH.
748       assert(hasPCHSupport() && "This action does not have PCH support!");
749       ASTDeserializationListener *DeserialListener =
750           Consumer->GetASTDeserializationListener();
751       bool DeleteDeserialListener = false;
752       if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
753         DeserialListener = new DeserializedDeclsDumper(DeserialListener,
754                                                        DeleteDeserialListener);
755         DeleteDeserialListener = true;
756       }
757       if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
758         DeserialListener = new DeserializedDeclsChecker(
759             CI.getASTContext(),
760             CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
761             DeserialListener, DeleteDeserialListener);
762         DeleteDeserialListener = true;
763       }
764       if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
765         CI.createPCHExternalASTSource(
766             CI.getPreprocessorOpts().ImplicitPCHInclude,
767             CI.getPreprocessorOpts().DisablePCHValidation,
768           CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
769             DeleteDeserialListener);
770         if (!CI.getASTContext().getExternalSource())
771           goto failure;
772       }
773       // If modules are enabled, create the module manager before creating
774       // any builtins, so that all declarations know that they might be
775       // extended by an external source.
776       if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
777           !CI.getASTContext().getExternalSource()) {
778         CI.createModuleManager();
779         CI.getModuleManager()->setDeserializationListener(DeserialListener,
780                                                         DeleteDeserialListener);
781       }
782     }
783 
784     CI.setASTConsumer(std::move(Consumer));
785     if (!CI.hasASTConsumer())
786       goto failure;
787   }
788 
789   // Initialize built-in info as long as we aren't using an external AST
790   // source.
791   if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
792       !CI.getASTContext().getExternalSource()) {
793     Preprocessor &PP = CI.getPreprocessor();
794     PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
795                                            PP.getLangOpts());
796   } else {
797     // FIXME: If this is a problem, recover from it by creating a multiplex
798     // source.
799     assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
800            "modules enabled but created an external source that "
801            "doesn't support modules");
802   }
803 
804   // If we were asked to load any module map files, do so now.
805   for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
806     if (auto *File = CI.getFileManager().getFile(Filename))
807       CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
808           File, /*IsSystem*/false);
809     else
810       CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
811   }
812 
813   // If we were asked to load any module files, do so now.
814   for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
815     if (!CI.loadModuleFile(ModuleFile))
816       goto failure;
817 
818   // If there is a layout overrides file, attach an external AST source that
819   // provides the layouts from that file.
820   if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
821       CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
822     IntrusiveRefCntPtr<ExternalASTSource>
823       Override(new LayoutOverrideSource(
824                      CI.getFrontendOpts().OverrideRecordLayoutsFile));
825     CI.getASTContext().setExternalSource(Override);
826   }
827 
828   return true;
829 
830   // If we failed, reset state since the client will not end up calling the
831   // matching EndSourceFile().
832   failure:
833   if (isCurrentFileAST()) {
834     CI.setASTContext(nullptr);
835     CI.setPreprocessor(nullptr);
836     CI.setSourceManager(nullptr);
837     CI.setFileManager(nullptr);
838   }
839 
840   if (HasBegunSourceFile)
841     CI.getDiagnosticClient().EndSourceFile();
842   CI.clearOutputFiles(/*EraseFiles=*/true);
843   CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
844   setCurrentInput(FrontendInputFile());
845   setCompilerInstance(nullptr);
846   return false;
847 }
848 
849 bool FrontendAction::Execute() {
850   CompilerInstance &CI = getCompilerInstance();
851 
852   if (CI.hasFrontendTimer()) {
853     llvm::TimeRegion Timer(CI.getFrontendTimer());
854     ExecuteAction();
855   }
856   else ExecuteAction();
857 
858   // If we are supposed to rebuild the global module index, do so now unless
859   // there were any module-build failures.
860   if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
861       CI.hasPreprocessor()) {
862     StringRef Cache =
863         CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
864     if (!Cache.empty())
865       GlobalModuleIndex::writeIndex(CI.getFileManager(),
866                                     CI.getPCHContainerReader(), Cache);
867   }
868 
869   return true;
870 }
871 
872 void FrontendAction::EndSourceFile() {
873   CompilerInstance &CI = getCompilerInstance();
874 
875   // Inform the diagnostic client we are done with this source file.
876   CI.getDiagnosticClient().EndSourceFile();
877 
878   // Inform the preprocessor we are done.
879   if (CI.hasPreprocessor())
880     CI.getPreprocessor().EndSourceFile();
881 
882   // Finalize the action.
883   EndSourceFileAction();
884 
885   // Sema references the ast consumer, so reset sema first.
886   //
887   // FIXME: There is more per-file stuff we could just drop here?
888   bool DisableFree = CI.getFrontendOpts().DisableFree;
889   if (DisableFree) {
890     CI.resetAndLeakSema();
891     CI.resetAndLeakASTContext();
892     BuryPointer(CI.takeASTConsumer().get());
893   } else {
894     CI.setSema(nullptr);
895     CI.setASTContext(nullptr);
896     CI.setASTConsumer(nullptr);
897   }
898 
899   if (CI.getFrontendOpts().ShowStats) {
900     llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
901     CI.getPreprocessor().PrintStats();
902     CI.getPreprocessor().getIdentifierTable().PrintStats();
903     CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
904     CI.getSourceManager().PrintStats();
905     llvm::errs() << "\n";
906   }
907 
908   // Cleanup the output streams, and erase the output files if instructed by the
909   // FrontendAction.
910   CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
911 
912   if (isCurrentFileAST()) {
913     if (DisableFree) {
914       CI.resetAndLeakPreprocessor();
915       CI.resetAndLeakSourceManager();
916       CI.resetAndLeakFileManager();
917     } else {
918       CI.setPreprocessor(nullptr);
919       CI.setSourceManager(nullptr);
920       CI.setFileManager(nullptr);
921     }
922   }
923 
924   setCompilerInstance(nullptr);
925   setCurrentInput(FrontendInputFile());
926   CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
927 }
928 
929 bool FrontendAction::shouldEraseOutputFiles() {
930   return getCompilerInstance().getDiagnostics().hasErrorOccurred();
931 }
932 
933 //===----------------------------------------------------------------------===//
934 // Utility Actions
935 //===----------------------------------------------------------------------===//
936 
937 void ASTFrontendAction::ExecuteAction() {
938   CompilerInstance &CI = getCompilerInstance();
939   if (!CI.hasPreprocessor())
940     return;
941 
942   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
943   // here so the source manager would be initialized.
944   if (hasCodeCompletionSupport() &&
945       !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
946     CI.createCodeCompletionConsumer();
947 
948   // Use a code completion consumer?
949   CodeCompleteConsumer *CompletionConsumer = nullptr;
950   if (CI.hasCodeCompletionConsumer())
951     CompletionConsumer = &CI.getCodeCompletionConsumer();
952 
953   if (!CI.hasSema())
954     CI.createSema(getTranslationUnitKind(), CompletionConsumer);
955 
956   ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
957            CI.getFrontendOpts().SkipFunctionBodies);
958 }
959 
960 void PluginASTAction::anchor() { }
961 
962 std::unique_ptr<ASTConsumer>
963 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
964                                               StringRef InFile) {
965   llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
966 }
967 
968 std::unique_ptr<ASTConsumer>
969 WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
970                                          StringRef InFile) {
971   return WrappedAction->CreateASTConsumer(CI, InFile);
972 }
973 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
974   return WrappedAction->BeginInvocation(CI);
975 }
976 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
977                                                   StringRef Filename) {
978   WrappedAction->setCurrentInput(getCurrentInput());
979   WrappedAction->setCompilerInstance(&CI);
980   auto Ret = WrappedAction->BeginSourceFileAction(CI, Filename);
981   // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
982   setCurrentInput(WrappedAction->getCurrentInput());
983   return Ret;
984 }
985 void WrapperFrontendAction::ExecuteAction() {
986   WrappedAction->ExecuteAction();
987 }
988 void WrapperFrontendAction::EndSourceFileAction() {
989   WrappedAction->EndSourceFileAction();
990 }
991 
992 bool WrapperFrontendAction::usesPreprocessorOnly() const {
993   return WrappedAction->usesPreprocessorOnly();
994 }
995 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
996   return WrappedAction->getTranslationUnitKind();
997 }
998 bool WrapperFrontendAction::hasPCHSupport() const {
999   return WrappedAction->hasPCHSupport();
1000 }
1001 bool WrapperFrontendAction::hasASTFileSupport() const {
1002   return WrappedAction->hasASTFileSupport();
1003 }
1004 bool WrapperFrontendAction::hasIRSupport() const {
1005   return WrappedAction->hasIRSupport();
1006 }
1007 bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1008   return WrappedAction->hasCodeCompletionSupport();
1009 }
1010 
1011 WrapperFrontendAction::WrapperFrontendAction(
1012     std::unique_ptr<FrontendAction> WrappedAction)
1013   : WrappedAction(std::move(WrappedAction)) {}
1014 
1015