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