1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===// 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/CodeGen/CodeGenAction.h" 10 #include "CodeGenModule.h" 11 #include "CoverageMappingGen.h" 12 #include "MacroPPCallbacks.h" 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/DeclCXX.h" 16 #include "clang/AST/DeclGroup.h" 17 #include "clang/Basic/DiagnosticFrontend.h" 18 #include "clang/Basic/FileManager.h" 19 #include "clang/Basic/LangStandard.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Basic/TargetInfo.h" 22 #include "clang/CodeGen/BackendUtil.h" 23 #include "clang/CodeGen/ModuleBuilder.h" 24 #include "clang/Driver/DriverDiagnostic.h" 25 #include "clang/Frontend/CompilerInstance.h" 26 #include "clang/Frontend/FrontendDiagnostic.h" 27 #include "clang/Lex/Preprocessor.h" 28 #include "llvm/Bitcode/BitcodeReader.h" 29 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 30 #include "llvm/IR/DebugInfo.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/GlobalValue.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/LLVMRemarkStreamer.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IRReader/IRReader.h" 38 #include "llvm/LTO/LTOBackend.h" 39 #include "llvm/Linker/Linker.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/MemoryBuffer.h" 42 #include "llvm/Support/SourceMgr.h" 43 #include "llvm/Support/TimeProfiler.h" 44 #include "llvm/Support/Timer.h" 45 #include "llvm/Support/ToolOutputFile.h" 46 #include "llvm/Support/YAMLTraits.h" 47 #include "llvm/Transforms/IPO/Internalize.h" 48 49 #include <memory> 50 using namespace clang; 51 using namespace llvm; 52 53 namespace clang { 54 class BackendConsumer; 55 class ClangDiagnosticHandler final : public DiagnosticHandler { 56 public: 57 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon) 58 : CodeGenOpts(CGOpts), BackendCon(BCon) {} 59 60 bool handleDiagnostics(const DiagnosticInfo &DI) override; 61 62 bool isAnalysisRemarkEnabled(StringRef PassName) const override { 63 return (CodeGenOpts.OptimizationRemarkAnalysisPattern && 64 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName)); 65 } 66 bool isMissedOptRemarkEnabled(StringRef PassName) const override { 67 return (CodeGenOpts.OptimizationRemarkMissedPattern && 68 CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName)); 69 } 70 bool isPassedOptRemarkEnabled(StringRef PassName) const override { 71 return (CodeGenOpts.OptimizationRemarkPattern && 72 CodeGenOpts.OptimizationRemarkPattern->match(PassName)); 73 } 74 75 bool isAnyRemarkEnabled() const override { 76 return (CodeGenOpts.OptimizationRemarkAnalysisPattern || 77 CodeGenOpts.OptimizationRemarkMissedPattern || 78 CodeGenOpts.OptimizationRemarkPattern); 79 } 80 81 private: 82 const CodeGenOptions &CodeGenOpts; 83 BackendConsumer *BackendCon; 84 }; 85 86 static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, 87 const CodeGenOptions CodeGenOpts) { 88 handleAllErrors( 89 std::move(E), 90 [&](const LLVMRemarkSetupFileError &E) { 91 Diags.Report(diag::err_cannot_open_file) 92 << CodeGenOpts.OptRecordFile << E.message(); 93 }, 94 [&](const LLVMRemarkSetupPatternError &E) { 95 Diags.Report(diag::err_drv_optimization_remark_pattern) 96 << E.message() << CodeGenOpts.OptRecordPasses; 97 }, 98 [&](const LLVMRemarkSetupFormatError &E) { 99 Diags.Report(diag::err_drv_optimization_remark_format) 100 << CodeGenOpts.OptRecordFormat; 101 }); 102 } 103 104 class BackendConsumer : public ASTConsumer { 105 using LinkModule = CodeGenAction::LinkModule; 106 107 virtual void anchor(); 108 DiagnosticsEngine &Diags; 109 BackendAction Action; 110 const HeaderSearchOptions &HeaderSearchOpts; 111 const CodeGenOptions &CodeGenOpts; 112 const TargetOptions &TargetOpts; 113 const LangOptions &LangOpts; 114 std::unique_ptr<raw_pwrite_stream> AsmOutStream; 115 ASTContext *Context; 116 117 Timer LLVMIRGeneration; 118 unsigned LLVMIRGenerationRefCount; 119 120 /// True if we've finished generating IR. This prevents us from generating 121 /// additional LLVM IR after emitting output in HandleTranslationUnit. This 122 /// can happen when Clang plugins trigger additional AST deserialization. 123 bool IRGenFinished = false; 124 125 std::unique_ptr<CodeGenerator> Gen; 126 127 SmallVector<LinkModule, 4> LinkModules; 128 129 // This is here so that the diagnostic printer knows the module a diagnostic 130 // refers to. 131 llvm::Module *CurLinkModule = nullptr; 132 133 public: 134 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, 135 const HeaderSearchOptions &HeaderSearchOpts, 136 const PreprocessorOptions &PPOpts, 137 const CodeGenOptions &CodeGenOpts, 138 const TargetOptions &TargetOpts, 139 const LangOptions &LangOpts, bool TimePasses, 140 const std::string &InFile, 141 SmallVector<LinkModule, 4> LinkModules, 142 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C, 143 CoverageSourceInfo *CoverageInfo = nullptr) 144 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts), 145 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts), 146 AsmOutStream(std::move(OS)), Context(nullptr), 147 LLVMIRGeneration("irgen", "LLVM IR Generation Time"), 148 LLVMIRGenerationRefCount(0), 149 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts, 150 CodeGenOpts, C, CoverageInfo)), 151 LinkModules(std::move(LinkModules)) { 152 FrontendTimesIsEnabled = TimePasses; 153 llvm::TimePassesIsEnabled = TimePasses; 154 } 155 156 // This constructor is used in installing an empty BackendConsumer 157 // to use the clang diagnostic handler for IR input files. It avoids 158 // initializing the OS field. 159 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, 160 const HeaderSearchOptions &HeaderSearchOpts, 161 const PreprocessorOptions &PPOpts, 162 const CodeGenOptions &CodeGenOpts, 163 const TargetOptions &TargetOpts, 164 const LangOptions &LangOpts, bool TimePasses, 165 SmallVector<LinkModule, 4> LinkModules, LLVMContext &C, 166 CoverageSourceInfo *CoverageInfo = nullptr) 167 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts), 168 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts), 169 Context(nullptr), 170 LLVMIRGeneration("irgen", "LLVM IR Generation Time"), 171 LLVMIRGenerationRefCount(0), 172 Gen(CreateLLVMCodeGen(Diags, "", HeaderSearchOpts, PPOpts, 173 CodeGenOpts, C, CoverageInfo)), 174 LinkModules(std::move(LinkModules)) { 175 FrontendTimesIsEnabled = TimePasses; 176 llvm::TimePassesIsEnabled = TimePasses; 177 } 178 llvm::Module *getModule() const { return Gen->GetModule(); } 179 std::unique_ptr<llvm::Module> takeModule() { 180 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule()); 181 } 182 183 CodeGenerator *getCodeGenerator() { return Gen.get(); } 184 185 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 186 Gen->HandleCXXStaticMemberVarInstantiation(VD); 187 } 188 189 void Initialize(ASTContext &Ctx) override { 190 assert(!Context && "initialized multiple times"); 191 192 Context = &Ctx; 193 194 if (FrontendTimesIsEnabled) 195 LLVMIRGeneration.startTimer(); 196 197 Gen->Initialize(Ctx); 198 199 if (FrontendTimesIsEnabled) 200 LLVMIRGeneration.stopTimer(); 201 } 202 203 bool HandleTopLevelDecl(DeclGroupRef D) override { 204 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), 205 Context->getSourceManager(), 206 "LLVM IR generation of declaration"); 207 208 // Recurse. 209 if (FrontendTimesIsEnabled) { 210 LLVMIRGenerationRefCount += 1; 211 if (LLVMIRGenerationRefCount == 1) 212 LLVMIRGeneration.startTimer(); 213 } 214 215 Gen->HandleTopLevelDecl(D); 216 217 if (FrontendTimesIsEnabled) { 218 LLVMIRGenerationRefCount -= 1; 219 if (LLVMIRGenerationRefCount == 0) 220 LLVMIRGeneration.stopTimer(); 221 } 222 223 return true; 224 } 225 226 void HandleInlineFunctionDefinition(FunctionDecl *D) override { 227 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 228 Context->getSourceManager(), 229 "LLVM IR generation of inline function"); 230 if (FrontendTimesIsEnabled) 231 LLVMIRGeneration.startTimer(); 232 233 Gen->HandleInlineFunctionDefinition(D); 234 235 if (FrontendTimesIsEnabled) 236 LLVMIRGeneration.stopTimer(); 237 } 238 239 void HandleInterestingDecl(DeclGroupRef D) override { 240 // Ignore interesting decls from the AST reader after IRGen is finished. 241 if (!IRGenFinished) 242 HandleTopLevelDecl(D); 243 } 244 245 // Links each entry in LinkModules into our module. Returns true on error. 246 bool LinkInModules() { 247 for (auto &LM : LinkModules) { 248 if (LM.PropagateAttrs) 249 for (Function &F : *LM.Module) { 250 // Skip intrinsics. Keep consistent with how intrinsics are created 251 // in LLVM IR. 252 if (F.isIntrinsic()) 253 continue; 254 Gen->CGM().addDefaultFunctionDefinitionAttributes(F); 255 } 256 257 CurLinkModule = LM.Module.get(); 258 259 bool Err; 260 if (LM.Internalize) { 261 Err = Linker::linkModules( 262 *getModule(), std::move(LM.Module), LM.LinkFlags, 263 [](llvm::Module &M, const llvm::StringSet<> &GVS) { 264 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) { 265 return !GV.hasName() || (GVS.count(GV.getName()) == 0); 266 }); 267 }); 268 } else { 269 Err = Linker::linkModules(*getModule(), std::move(LM.Module), 270 LM.LinkFlags); 271 } 272 273 if (Err) 274 return true; 275 } 276 return false; // success 277 } 278 279 void HandleTranslationUnit(ASTContext &C) override { 280 { 281 llvm::TimeTraceScope TimeScope("Frontend"); 282 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); 283 if (FrontendTimesIsEnabled) { 284 LLVMIRGenerationRefCount += 1; 285 if (LLVMIRGenerationRefCount == 1) 286 LLVMIRGeneration.startTimer(); 287 } 288 289 Gen->HandleTranslationUnit(C); 290 291 if (FrontendTimesIsEnabled) { 292 LLVMIRGenerationRefCount -= 1; 293 if (LLVMIRGenerationRefCount == 0) 294 LLVMIRGeneration.stopTimer(); 295 } 296 297 IRGenFinished = true; 298 } 299 300 // Silently ignore if we weren't initialized for some reason. 301 if (!getModule()) 302 return; 303 304 // Install an inline asm handler so that diagnostics get printed through 305 // our diagnostics hooks. 306 LLVMContext &Ctx = getModule()->getContext(); 307 LLVMContext::InlineAsmDiagHandlerTy OldHandler = 308 Ctx.getInlineAsmDiagnosticHandler(); 309 void *OldContext = Ctx.getInlineAsmDiagnosticContext(); 310 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this); 311 312 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler = 313 Ctx.getDiagnosticHandler(); 314 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>( 315 CodeGenOpts, this)); 316 317 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr = 318 setupLLVMOptimizationRemarks( 319 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses, 320 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness, 321 CodeGenOpts.DiagnosticsHotnessThreshold); 322 323 if (Error E = OptRecordFileOrErr.takeError()) { 324 reportOptRecordError(std::move(E), Diags, CodeGenOpts); 325 return; 326 } 327 328 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile = 329 std::move(*OptRecordFileOrErr); 330 331 if (OptRecordFile && 332 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone) 333 Ctx.setDiagnosticsHotnessRequested(true); 334 335 // Link each LinkModule into our module. 336 if (LinkInModules()) 337 return; 338 339 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef()); 340 341 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, 342 LangOpts, C.getTargetInfo().getDataLayout(), 343 getModule(), Action, std::move(AsmOutStream)); 344 345 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext); 346 347 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); 348 349 if (OptRecordFile) 350 OptRecordFile->keep(); 351 } 352 353 void HandleTagDeclDefinition(TagDecl *D) override { 354 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 355 Context->getSourceManager(), 356 "LLVM IR generation of declaration"); 357 Gen->HandleTagDeclDefinition(D); 358 } 359 360 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 361 Gen->HandleTagDeclRequiredDefinition(D); 362 } 363 364 void CompleteTentativeDefinition(VarDecl *D) override { 365 Gen->CompleteTentativeDefinition(D); 366 } 367 368 void CompleteExternalDeclaration(VarDecl *D) override { 369 Gen->CompleteExternalDeclaration(D); 370 } 371 372 void AssignInheritanceModel(CXXRecordDecl *RD) override { 373 Gen->AssignInheritanceModel(RD); 374 } 375 376 void HandleVTable(CXXRecordDecl *RD) override { 377 Gen->HandleVTable(RD); 378 } 379 380 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context, 381 unsigned LocCookie) { 382 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie); 383 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc); 384 } 385 386 /// Get the best possible source location to represent a diagnostic that 387 /// may have associated debug info. 388 const FullSourceLoc 389 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, 390 bool &BadDebugInfo, StringRef &Filename, 391 unsigned &Line, unsigned &Column) const; 392 393 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &, 394 SourceLocation LocCookie); 395 396 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI); 397 /// Specialized handler for InlineAsm diagnostic. 398 /// \return True if the diagnostic has been successfully reported, false 399 /// otherwise. 400 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D); 401 /// Specialized handler for StackSize diagnostic. 402 /// \return True if the diagnostic has been successfully reported, false 403 /// otherwise. 404 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D); 405 /// Specialized handler for unsupported backend feature diagnostic. 406 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D); 407 /// Specialized handlers for optimization remarks. 408 /// Note that these handlers only accept remarks and they always handle 409 /// them. 410 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, 411 unsigned DiagID); 412 void 413 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D); 414 void OptimizationRemarkHandler( 415 const llvm::OptimizationRemarkAnalysisFPCommute &D); 416 void OptimizationRemarkHandler( 417 const llvm::OptimizationRemarkAnalysisAliasing &D); 418 void OptimizationFailureHandler( 419 const llvm::DiagnosticInfoOptimizationFailure &D); 420 }; 421 422 void BackendConsumer::anchor() {} 423 } 424 425 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) { 426 BackendCon->DiagnosticHandlerImpl(DI); 427 return true; 428 } 429 430 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr 431 /// buffer to be a valid FullSourceLoc. 432 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, 433 SourceManager &CSM) { 434 // Get both the clang and llvm source managers. The location is relative to 435 // a memory buffer that the LLVM Source Manager is handling, we need to add 436 // a copy to the Clang source manager. 437 const llvm::SourceMgr &LSM = *D.getSourceMgr(); 438 439 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr 440 // already owns its one and clang::SourceManager wants to own its one. 441 const MemoryBuffer *LBuf = 442 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); 443 444 // Create the copy and transfer ownership to clang::SourceManager. 445 // TODO: Avoid copying files into memory. 446 std::unique_ptr<llvm::MemoryBuffer> CBuf = 447 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), 448 LBuf->getBufferIdentifier()); 449 // FIXME: Keep a file ID map instead of creating new IDs for each location. 450 FileID FID = CSM.createFileID(std::move(CBuf)); 451 452 // Translate the offset into the file. 453 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); 454 SourceLocation NewLoc = 455 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); 456 return FullSourceLoc(NewLoc, CSM); 457 } 458 459 460 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an 461 /// error parsing inline asm. The SMDiagnostic indicates the error relative to 462 /// the temporary memory buffer that the inline asm parser has set up. 463 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D, 464 SourceLocation LocCookie) { 465 // There are a couple of different kinds of errors we could get here. First, 466 // we re-format the SMDiagnostic in terms of a clang diagnostic. 467 468 // Strip "error: " off the start of the message string. 469 StringRef Message = D.getMessage(); 470 if (Message.startswith("error: ")) 471 Message = Message.substr(7); 472 473 // If the SMDiagnostic has an inline asm source location, translate it. 474 FullSourceLoc Loc; 475 if (D.getLoc() != SMLoc()) 476 Loc = ConvertBackendLocation(D, Context->getSourceManager()); 477 478 unsigned DiagID; 479 switch (D.getKind()) { 480 case llvm::SourceMgr::DK_Error: 481 DiagID = diag::err_fe_inline_asm; 482 break; 483 case llvm::SourceMgr::DK_Warning: 484 DiagID = diag::warn_fe_inline_asm; 485 break; 486 case llvm::SourceMgr::DK_Note: 487 DiagID = diag::note_fe_inline_asm; 488 break; 489 case llvm::SourceMgr::DK_Remark: 490 llvm_unreachable("remarks unexpected"); 491 } 492 // If this problem has clang-level source location information, report the 493 // issue in the source with a note showing the instantiated 494 // code. 495 if (LocCookie.isValid()) { 496 Diags.Report(LocCookie, DiagID).AddString(Message); 497 498 if (D.getLoc().isValid()) { 499 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here); 500 // Convert the SMDiagnostic ranges into SourceRange and attach them 501 // to the diagnostic. 502 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) { 503 unsigned Column = D.getColumnNo(); 504 B << SourceRange(Loc.getLocWithOffset(Range.first - Column), 505 Loc.getLocWithOffset(Range.second - Column)); 506 } 507 } 508 return; 509 } 510 511 // Otherwise, report the backend issue as occurring in the generated .s file. 512 // If Loc is invalid, we still need to report the issue, it just gets no 513 // location info. 514 Diags.Report(Loc, DiagID).AddString(Message); 515 } 516 517 #define ComputeDiagID(Severity, GroupName, DiagID) \ 518 do { \ 519 switch (Severity) { \ 520 case llvm::DS_Error: \ 521 DiagID = diag::err_fe_##GroupName; \ 522 break; \ 523 case llvm::DS_Warning: \ 524 DiagID = diag::warn_fe_##GroupName; \ 525 break; \ 526 case llvm::DS_Remark: \ 527 llvm_unreachable("'remark' severity not expected"); \ 528 break; \ 529 case llvm::DS_Note: \ 530 DiagID = diag::note_fe_##GroupName; \ 531 break; \ 532 } \ 533 } while (false) 534 535 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \ 536 do { \ 537 switch (Severity) { \ 538 case llvm::DS_Error: \ 539 DiagID = diag::err_fe_##GroupName; \ 540 break; \ 541 case llvm::DS_Warning: \ 542 DiagID = diag::warn_fe_##GroupName; \ 543 break; \ 544 case llvm::DS_Remark: \ 545 DiagID = diag::remark_fe_##GroupName; \ 546 break; \ 547 case llvm::DS_Note: \ 548 DiagID = diag::note_fe_##GroupName; \ 549 break; \ 550 } \ 551 } while (false) 552 553 bool 554 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) { 555 unsigned DiagID; 556 ComputeDiagID(D.getSeverity(), inline_asm, DiagID); 557 std::string Message = D.getMsgStr().str(); 558 559 // If this problem has clang-level source location information, report the 560 // issue as being a problem in the source with a note showing the instantiated 561 // code. 562 SourceLocation LocCookie = 563 SourceLocation::getFromRawEncoding(D.getLocCookie()); 564 if (LocCookie.isValid()) 565 Diags.Report(LocCookie, DiagID).AddString(Message); 566 else { 567 // Otherwise, report the backend diagnostic as occurring in the generated 568 // .s file. 569 // If Loc is invalid, we still need to report the diagnostic, it just gets 570 // no location info. 571 FullSourceLoc Loc; 572 Diags.Report(Loc, DiagID).AddString(Message); 573 } 574 // We handled all the possible severities. 575 return true; 576 } 577 578 bool 579 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) { 580 if (D.getSeverity() != llvm::DS_Warning) 581 // For now, the only support we have for StackSize diagnostic is warning. 582 // We do not know how to format other severities. 583 return false; 584 585 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) { 586 // FIXME: Shouldn't need to truncate to uint32_t 587 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()), 588 diag::warn_fe_frame_larger_than) 589 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND); 590 return true; 591 } 592 593 return false; 594 } 595 596 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc( 597 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, 598 StringRef &Filename, unsigned &Line, unsigned &Column) const { 599 SourceManager &SourceMgr = Context->getSourceManager(); 600 FileManager &FileMgr = SourceMgr.getFileManager(); 601 SourceLocation DILoc; 602 603 if (D.isLocationAvailable()) { 604 D.getLocation(Filename, Line, Column); 605 if (Line > 0) { 606 auto FE = FileMgr.getFile(Filename); 607 if (!FE) 608 FE = FileMgr.getFile(D.getAbsolutePath()); 609 if (FE) { 610 // If -gcolumn-info was not used, Column will be 0. This upsets the 611 // source manager, so pass 1 if Column is not set. 612 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1); 613 } 614 } 615 BadDebugInfo = DILoc.isInvalid(); 616 } 617 618 // If a location isn't available, try to approximate it using the associated 619 // function definition. We use the definition's right brace to differentiate 620 // from diagnostics that genuinely relate to the function itself. 621 FullSourceLoc Loc(DILoc, SourceMgr); 622 if (Loc.isInvalid()) 623 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName())) 624 Loc = FD->getASTContext().getFullLoc(FD->getLocation()); 625 626 if (DILoc.isInvalid() && D.isLocationAvailable()) 627 // If we were not able to translate the file:line:col information 628 // back to a SourceLocation, at least emit a note stating that 629 // we could not translate this location. This can happen in the 630 // case of #line directives. 631 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 632 << Filename << Line << Column; 633 634 return Loc; 635 } 636 637 void BackendConsumer::UnsupportedDiagHandler( 638 const llvm::DiagnosticInfoUnsupported &D) { 639 // We only support warnings or errors. 640 assert(D.getSeverity() == llvm::DS_Error || 641 D.getSeverity() == llvm::DS_Warning); 642 643 StringRef Filename; 644 unsigned Line, Column; 645 bool BadDebugInfo = false; 646 FullSourceLoc Loc; 647 std::string Msg; 648 raw_string_ostream MsgStream(Msg); 649 650 // Context will be nullptr for IR input files, we will construct the diag 651 // message from llvm::DiagnosticInfoUnsupported. 652 if (Context != nullptr) { 653 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); 654 MsgStream << D.getMessage(); 655 } else { 656 DiagnosticPrinterRawOStream DP(MsgStream); 657 D.print(DP); 658 } 659 660 auto DiagType = D.getSeverity() == llvm::DS_Error 661 ? diag::err_fe_backend_unsupported 662 : diag::warn_fe_backend_unsupported; 663 Diags.Report(Loc, DiagType) << MsgStream.str(); 664 665 if (BadDebugInfo) 666 // If we were not able to translate the file:line:col information 667 // back to a SourceLocation, at least emit a note stating that 668 // we could not translate this location. This can happen in the 669 // case of #line directives. 670 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 671 << Filename << Line << Column; 672 } 673 674 void BackendConsumer::EmitOptimizationMessage( 675 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) { 676 // We only support warnings and remarks. 677 assert(D.getSeverity() == llvm::DS_Remark || 678 D.getSeverity() == llvm::DS_Warning); 679 680 StringRef Filename; 681 unsigned Line, Column; 682 bool BadDebugInfo = false; 683 FullSourceLoc Loc; 684 std::string Msg; 685 raw_string_ostream MsgStream(Msg); 686 687 // Context will be nullptr for IR input files, we will construct the remark 688 // message from llvm::DiagnosticInfoOptimizationBase. 689 if (Context != nullptr) { 690 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); 691 MsgStream << D.getMsg(); 692 } else { 693 DiagnosticPrinterRawOStream DP(MsgStream); 694 D.print(DP); 695 } 696 697 if (D.getHotness()) 698 MsgStream << " (hotness: " << *D.getHotness() << ")"; 699 700 Diags.Report(Loc, DiagID) 701 << AddFlagValue(D.getPassName()) 702 << MsgStream.str(); 703 704 if (BadDebugInfo) 705 // If we were not able to translate the file:line:col information 706 // back to a SourceLocation, at least emit a note stating that 707 // we could not translate this location. This can happen in the 708 // case of #line directives. 709 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 710 << Filename << Line << Column; 711 } 712 713 void BackendConsumer::OptimizationRemarkHandler( 714 const llvm::DiagnosticInfoOptimizationBase &D) { 715 // Without hotness information, don't show noisy remarks. 716 if (D.isVerbose() && !D.getHotness()) 717 return; 718 719 if (D.isPassed()) { 720 // Optimization remarks are active only if the -Rpass flag has a regular 721 // expression that matches the name of the pass name in \p D. 722 if (CodeGenOpts.OptimizationRemarkPattern && 723 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) 724 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark); 725 } else if (D.isMissed()) { 726 // Missed optimization remarks are active only if the -Rpass-missed 727 // flag has a regular expression that matches the name of the pass 728 // name in \p D. 729 if (CodeGenOpts.OptimizationRemarkMissedPattern && 730 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName())) 731 EmitOptimizationMessage( 732 D, diag::remark_fe_backend_optimization_remark_missed); 733 } else { 734 assert(D.isAnalysis() && "Unknown remark type"); 735 736 bool ShouldAlwaysPrint = false; 737 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D)) 738 ShouldAlwaysPrint = ORA->shouldAlwaysPrint(); 739 740 if (ShouldAlwaysPrint || 741 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 742 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 743 EmitOptimizationMessage( 744 D, diag::remark_fe_backend_optimization_remark_analysis); 745 } 746 } 747 748 void BackendConsumer::OptimizationRemarkHandler( 749 const llvm::OptimizationRemarkAnalysisFPCommute &D) { 750 // Optimization analysis remarks are active if the pass name is set to 751 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 752 // regular expression that matches the name of the pass name in \p D. 753 754 if (D.shouldAlwaysPrint() || 755 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 756 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 757 EmitOptimizationMessage( 758 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute); 759 } 760 761 void BackendConsumer::OptimizationRemarkHandler( 762 const llvm::OptimizationRemarkAnalysisAliasing &D) { 763 // Optimization analysis remarks are active if the pass name is set to 764 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 765 // regular expression that matches the name of the pass name in \p D. 766 767 if (D.shouldAlwaysPrint() || 768 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 769 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 770 EmitOptimizationMessage( 771 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing); 772 } 773 774 void BackendConsumer::OptimizationFailureHandler( 775 const llvm::DiagnosticInfoOptimizationFailure &D) { 776 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure); 777 } 778 779 /// This function is invoked when the backend needs 780 /// to report something to the user. 781 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) { 782 unsigned DiagID = diag::err_fe_inline_asm; 783 llvm::DiagnosticSeverity Severity = DI.getSeverity(); 784 // Get the diagnostic ID based. 785 switch (DI.getKind()) { 786 case llvm::DK_InlineAsm: 787 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI))) 788 return; 789 ComputeDiagID(Severity, inline_asm, DiagID); 790 break; 791 case llvm::DK_StackSize: 792 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI))) 793 return; 794 ComputeDiagID(Severity, backend_frame_larger_than, DiagID); 795 break; 796 case DK_Linker: 797 assert(CurLinkModule); 798 // FIXME: stop eating the warnings and notes. 799 if (Severity != DS_Error) 800 return; 801 DiagID = diag::err_fe_cannot_link_module; 802 break; 803 case llvm::DK_OptimizationRemark: 804 // Optimization remarks are always handled completely by this 805 // handler. There is no generic way of emitting them. 806 OptimizationRemarkHandler(cast<OptimizationRemark>(DI)); 807 return; 808 case llvm::DK_OptimizationRemarkMissed: 809 // Optimization remarks are always handled completely by this 810 // handler. There is no generic way of emitting them. 811 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI)); 812 return; 813 case llvm::DK_OptimizationRemarkAnalysis: 814 // Optimization remarks are always handled completely by this 815 // handler. There is no generic way of emitting them. 816 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI)); 817 return; 818 case llvm::DK_OptimizationRemarkAnalysisFPCommute: 819 // Optimization remarks are always handled completely by this 820 // handler. There is no generic way of emitting them. 821 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI)); 822 return; 823 case llvm::DK_OptimizationRemarkAnalysisAliasing: 824 // Optimization remarks are always handled completely by this 825 // handler. There is no generic way of emitting them. 826 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI)); 827 return; 828 case llvm::DK_MachineOptimizationRemark: 829 // Optimization remarks are always handled completely by this 830 // handler. There is no generic way of emitting them. 831 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI)); 832 return; 833 case llvm::DK_MachineOptimizationRemarkMissed: 834 // Optimization remarks are always handled completely by this 835 // handler. There is no generic way of emitting them. 836 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI)); 837 return; 838 case llvm::DK_MachineOptimizationRemarkAnalysis: 839 // Optimization remarks are always handled completely by this 840 // handler. There is no generic way of emitting them. 841 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI)); 842 return; 843 case llvm::DK_OptimizationFailure: 844 // Optimization failures are always handled completely by this 845 // handler. 846 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI)); 847 return; 848 case llvm::DK_Unsupported: 849 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI)); 850 return; 851 default: 852 // Plugin IDs are not bound to any value as they are set dynamically. 853 ComputeDiagRemarkID(Severity, backend_plugin, DiagID); 854 break; 855 } 856 std::string MsgStorage; 857 { 858 raw_string_ostream Stream(MsgStorage); 859 DiagnosticPrinterRawOStream DP(Stream); 860 DI.print(DP); 861 } 862 863 if (DiagID == diag::err_fe_cannot_link_module) { 864 Diags.Report(diag::err_fe_cannot_link_module) 865 << CurLinkModule->getModuleIdentifier() << MsgStorage; 866 return; 867 } 868 869 // Report the backend message using the usual diagnostic mechanism. 870 FullSourceLoc Loc; 871 Diags.Report(Loc, DiagID).AddString(MsgStorage); 872 } 873 #undef ComputeDiagID 874 875 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 876 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), 877 OwnsVMContext(!_VMContext) {} 878 879 CodeGenAction::~CodeGenAction() { 880 TheModule.reset(); 881 if (OwnsVMContext) 882 delete VMContext; 883 } 884 885 bool CodeGenAction::hasIRSupport() const { return true; } 886 887 void CodeGenAction::EndSourceFileAction() { 888 // If the consumer creation failed, do nothing. 889 if (!getCompilerInstance().hasASTConsumer()) 890 return; 891 892 // Steal the module from the consumer. 893 TheModule = BEConsumer->takeModule(); 894 } 895 896 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() { 897 return std::move(TheModule); 898 } 899 900 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 901 OwnsVMContext = false; 902 return VMContext; 903 } 904 905 static std::unique_ptr<raw_pwrite_stream> 906 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { 907 switch (Action) { 908 case Backend_EmitAssembly: 909 return CI.createDefaultOutputFile(false, InFile, "s"); 910 case Backend_EmitLL: 911 return CI.createDefaultOutputFile(false, InFile, "ll"); 912 case Backend_EmitBC: 913 return CI.createDefaultOutputFile(true, InFile, "bc"); 914 case Backend_EmitNothing: 915 return nullptr; 916 case Backend_EmitMCNull: 917 return CI.createNullOutputFile(); 918 case Backend_EmitObj: 919 return CI.createDefaultOutputFile(true, InFile, "o"); 920 } 921 922 llvm_unreachable("Invalid action!"); 923 } 924 925 std::unique_ptr<ASTConsumer> 926 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 927 BackendAction BA = static_cast<BackendAction>(Act); 928 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream(); 929 if (!OS) 930 OS = GetOutputStream(CI, InFile, BA); 931 932 if (BA != Backend_EmitNothing && !OS) 933 return nullptr; 934 935 // Load bitcode modules to link with, if we need to. 936 if (LinkModules.empty()) 937 for (const CodeGenOptions::BitcodeFileToLink &F : 938 CI.getCodeGenOpts().LinkBitcodeFiles) { 939 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename); 940 if (!BCBuf) { 941 CI.getDiagnostics().Report(diag::err_cannot_open_file) 942 << F.Filename << BCBuf.getError().message(); 943 LinkModules.clear(); 944 return nullptr; 945 } 946 947 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr = 948 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext); 949 if (!ModuleOrErr) { 950 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { 951 CI.getDiagnostics().Report(diag::err_cannot_open_file) 952 << F.Filename << EIB.message(); 953 }); 954 LinkModules.clear(); 955 return nullptr; 956 } 957 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs, 958 F.Internalize, F.LinkFlags}); 959 } 960 961 CoverageSourceInfo *CoverageInfo = nullptr; 962 // Add the preprocessor callback only when the coverage mapping is generated. 963 if (CI.getCodeGenOpts().CoverageMapping) 964 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks( 965 CI.getPreprocessor()); 966 967 std::unique_ptr<BackendConsumer> Result(new BackendConsumer( 968 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 969 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(), 970 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, std::string(InFile), 971 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo)); 972 BEConsumer = Result.get(); 973 974 // Enable generating macro debug info only when debug info is not disabled and 975 // also macro debug info is enabled. 976 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo && 977 CI.getCodeGenOpts().MacroDebugInfo) { 978 std::unique_ptr<PPCallbacks> Callbacks = 979 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(), 980 CI.getPreprocessor()); 981 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks)); 982 } 983 984 return std::move(Result); 985 } 986 987 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM, 988 void *Context, 989 unsigned LocCookie) { 990 SM.print(nullptr, llvm::errs()); 991 992 auto Diags = static_cast<DiagnosticsEngine *>(Context); 993 unsigned DiagID; 994 switch (SM.getKind()) { 995 case llvm::SourceMgr::DK_Error: 996 DiagID = diag::err_fe_inline_asm; 997 break; 998 case llvm::SourceMgr::DK_Warning: 999 DiagID = diag::warn_fe_inline_asm; 1000 break; 1001 case llvm::SourceMgr::DK_Note: 1002 DiagID = diag::note_fe_inline_asm; 1003 break; 1004 case llvm::SourceMgr::DK_Remark: 1005 llvm_unreachable("remarks unexpected"); 1006 } 1007 1008 Diags->Report(DiagID).AddString("cannot compile inline asm"); 1009 } 1010 1011 std::unique_ptr<llvm::Module> 1012 CodeGenAction::loadModule(MemoryBufferRef MBRef) { 1013 CompilerInstance &CI = getCompilerInstance(); 1014 SourceManager &SM = CI.getSourceManager(); 1015 1016 // For ThinLTO backend invocations, ensure that the context 1017 // merges types based on ODR identifiers. We also need to read 1018 // the correct module out of a multi-module bitcode file. 1019 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) { 1020 VMContext->enableDebugTypeODRUniquing(); 1021 1022 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> { 1023 unsigned DiagID = 1024 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1025 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1026 CI.getDiagnostics().Report(DiagID) << EIB.message(); 1027 }); 1028 return {}; 1029 }; 1030 1031 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 1032 if (!BMsOrErr) 1033 return DiagErrors(BMsOrErr.takeError()); 1034 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr); 1035 // We have nothing to do if the file contains no ThinLTO module. This is 1036 // possible if ThinLTO compilation was not able to split module. Content of 1037 // the file was already processed by indexing and will be passed to the 1038 // linker using merged object file. 1039 if (!Bm) { 1040 auto M = std::make_unique<llvm::Module>("empty", *VMContext); 1041 M->setTargetTriple(CI.getTargetOpts().Triple); 1042 return M; 1043 } 1044 Expected<std::unique_ptr<llvm::Module>> MOrErr = 1045 Bm->parseModule(*VMContext); 1046 if (!MOrErr) 1047 return DiagErrors(MOrErr.takeError()); 1048 return std::move(*MOrErr); 1049 } 1050 1051 llvm::SMDiagnostic Err; 1052 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) 1053 return M; 1054 1055 // Translate from the diagnostic info to the SourceManager location if 1056 // available. 1057 // TODO: Unify this with ConvertBackendLocation() 1058 SourceLocation Loc; 1059 if (Err.getLineNo() > 0) { 1060 assert(Err.getColumnNo() >= 0); 1061 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()), 1062 Err.getLineNo(), Err.getColumnNo() + 1); 1063 } 1064 1065 // Strip off a leading diagnostic code if there is one. 1066 StringRef Msg = Err.getMessage(); 1067 if (Msg.startswith("error: ")) 1068 Msg = Msg.substr(7); 1069 1070 unsigned DiagID = 1071 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1072 1073 CI.getDiagnostics().Report(Loc, DiagID) << Msg; 1074 return {}; 1075 } 1076 1077 void CodeGenAction::ExecuteAction() { 1078 // If this is an IR file, we have to treat it specially. 1079 if (getCurrentFileKind().getLanguage() == Language::LLVM_IR) { 1080 BackendAction BA = static_cast<BackendAction>(Act); 1081 CompilerInstance &CI = getCompilerInstance(); 1082 auto &CodeGenOpts = CI.getCodeGenOpts(); 1083 auto &Diagnostics = CI.getDiagnostics(); 1084 std::unique_ptr<raw_pwrite_stream> OS = 1085 GetOutputStream(CI, getCurrentFile(), BA); 1086 if (BA != Backend_EmitNothing && !OS) 1087 return; 1088 1089 SourceManager &SM = CI.getSourceManager(); 1090 FileID FID = SM.getMainFileID(); 1091 Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID); 1092 if (!MainFile) 1093 return; 1094 1095 TheModule = loadModule(*MainFile); 1096 if (!TheModule) 1097 return; 1098 1099 const TargetOptions &TargetOpts = CI.getTargetOpts(); 1100 if (TheModule->getTargetTriple() != TargetOpts.Triple) { 1101 Diagnostics.Report(SourceLocation(), 1102 diag::warn_fe_override_module) 1103 << TargetOpts.Triple; 1104 TheModule->setTargetTriple(TargetOpts.Triple); 1105 } 1106 1107 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile); 1108 1109 LLVMContext &Ctx = TheModule->getContext(); 1110 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler, 1111 &Diagnostics); 1112 1113 // Set clang diagnostic handler. To do this we need to create a fake 1114 // BackendConsumer. 1115 BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 1116 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), 1117 CI.getTargetOpts(), CI.getLangOpts(), 1118 CI.getFrontendOpts().ShowTimers, 1119 std::move(LinkModules), *VMContext, nullptr); 1120 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be 1121 // true here because the valued names are needed for reading textual IR. 1122 Ctx.setDiscardValueNames(false); 1123 Ctx.setDiagnosticHandler( 1124 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result)); 1125 1126 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr = 1127 setupLLVMOptimizationRemarks( 1128 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses, 1129 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness, 1130 CodeGenOpts.DiagnosticsHotnessThreshold); 1131 1132 if (Error E = OptRecordFileOrErr.takeError()) { 1133 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts); 1134 return; 1135 } 1136 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile = 1137 std::move(*OptRecordFileOrErr); 1138 1139 EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, 1140 TargetOpts, CI.getLangOpts(), 1141 CI.getTarget().getDataLayout(), TheModule.get(), BA, 1142 std::move(OS)); 1143 1144 if (OptRecordFile) 1145 OptRecordFile->keep(); 1146 return; 1147 } 1148 1149 // Otherwise follow the normal AST path. 1150 this->ASTFrontendAction::ExecuteAction(); 1151 } 1152 1153 // 1154 1155 void EmitAssemblyAction::anchor() { } 1156 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 1157 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 1158 1159 void EmitBCAction::anchor() { } 1160 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 1161 : CodeGenAction(Backend_EmitBC, _VMContext) {} 1162 1163 void EmitLLVMAction::anchor() { } 1164 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 1165 : CodeGenAction(Backend_EmitLL, _VMContext) {} 1166 1167 void EmitLLVMOnlyAction::anchor() { } 1168 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 1169 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 1170 1171 void EmitCodeGenOnlyAction::anchor() { } 1172 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 1173 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 1174 1175 void EmitObjAction::anchor() { } 1176 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 1177 : CodeGenAction(Backend_EmitObj, _VMContext) {} 1178