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