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.OptimizationRemarkAnalysis.patternMatches(PassName); 64 } 65 bool isMissedOptRemarkEnabled(StringRef PassName) const override { 66 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName); 67 } 68 bool isPassedOptRemarkEnabled(StringRef PassName) const override { 69 return CodeGenOpts.OptimizationRemark.patternMatches(PassName); 70 } 71 72 bool isAnyRemarkEnabled() const override { 73 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() || 74 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() || 75 CodeGenOpts.OptimizationRemark.hasValidPattern(); 76 } 77 78 private: 79 const CodeGenOptions &CodeGenOpts; 80 BackendConsumer *BackendCon; 81 }; 82 83 static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, 84 const CodeGenOptions CodeGenOpts) { 85 handleAllErrors( 86 std::move(E), 87 [&](const LLVMRemarkSetupFileError &E) { 88 Diags.Report(diag::err_cannot_open_file) 89 << CodeGenOpts.OptRecordFile << E.message(); 90 }, 91 [&](const LLVMRemarkSetupPatternError &E) { 92 Diags.Report(diag::err_drv_optimization_remark_pattern) 93 << E.message() << CodeGenOpts.OptRecordPasses; 94 }, 95 [&](const LLVMRemarkSetupFormatError &E) { 96 Diags.Report(diag::err_drv_optimization_remark_format) 97 << CodeGenOpts.OptRecordFormat; 98 }); 99 } 100 101 class BackendConsumer : public ASTConsumer { 102 using LinkModule = CodeGenAction::LinkModule; 103 104 virtual void anchor(); 105 DiagnosticsEngine &Diags; 106 BackendAction Action; 107 const HeaderSearchOptions &HeaderSearchOpts; 108 const CodeGenOptions &CodeGenOpts; 109 const TargetOptions &TargetOpts; 110 const LangOptions &LangOpts; 111 std::unique_ptr<raw_pwrite_stream> AsmOutStream; 112 ASTContext *Context; 113 114 Timer LLVMIRGeneration; 115 unsigned LLVMIRGenerationRefCount; 116 117 /// True if we've finished generating IR. This prevents us from generating 118 /// additional LLVM IR after emitting output in HandleTranslationUnit. This 119 /// can happen when Clang plugins trigger additional AST deserialization. 120 bool IRGenFinished = false; 121 122 bool TimerIsEnabled = false; 123 124 std::unique_ptr<CodeGenerator> Gen; 125 126 SmallVector<LinkModule, 4> LinkModules; 127 128 // This is here so that the diagnostic printer knows the module a diagnostic 129 // refers to. 130 llvm::Module *CurLinkModule = nullptr; 131 132 public: 133 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, 134 const HeaderSearchOptions &HeaderSearchOpts, 135 const PreprocessorOptions &PPOpts, 136 const CodeGenOptions &CodeGenOpts, 137 const TargetOptions &TargetOpts, 138 const LangOptions &LangOpts, const std::string &InFile, 139 SmallVector<LinkModule, 4> LinkModules, 140 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C, 141 CoverageSourceInfo *CoverageInfo = nullptr) 142 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts), 143 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts), 144 AsmOutStream(std::move(OS)), Context(nullptr), 145 LLVMIRGeneration("irgen", "LLVM IR Generation Time"), 146 LLVMIRGenerationRefCount(0), 147 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts, 148 CodeGenOpts, C, CoverageInfo)), 149 LinkModules(std::move(LinkModules)) { 150 TimerIsEnabled = CodeGenOpts.TimePasses; 151 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses; 152 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun; 153 } 154 155 // This constructor is used in installing an empty BackendConsumer 156 // to use the clang diagnostic handler for IR input files. It avoids 157 // initializing the OS field. 158 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, 159 const HeaderSearchOptions &HeaderSearchOpts, 160 const PreprocessorOptions &PPOpts, 161 const CodeGenOptions &CodeGenOpts, 162 const TargetOptions &TargetOpts, 163 const LangOptions &LangOpts, 164 SmallVector<LinkModule, 4> LinkModules, LLVMContext &C, 165 CoverageSourceInfo *CoverageInfo = nullptr) 166 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts), 167 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts), 168 Context(nullptr), 169 LLVMIRGeneration("irgen", "LLVM IR Generation Time"), 170 LLVMIRGenerationRefCount(0), 171 Gen(CreateLLVMCodeGen(Diags, "", HeaderSearchOpts, PPOpts, 172 CodeGenOpts, C, CoverageInfo)), 173 LinkModules(std::move(LinkModules)) { 174 TimerIsEnabled = CodeGenOpts.TimePasses; 175 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses; 176 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun; 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 (TimerIsEnabled) 195 LLVMIRGeneration.startTimer(); 196 197 Gen->Initialize(Ctx); 198 199 if (TimerIsEnabled) 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 (TimerIsEnabled) { 210 LLVMIRGenerationRefCount += 1; 211 if (LLVMIRGenerationRefCount == 1) 212 LLVMIRGeneration.startTimer(); 213 } 214 215 Gen->HandleTopLevelDecl(D); 216 217 if (TimerIsEnabled) { 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 (TimerIsEnabled) 231 LLVMIRGeneration.startTimer(); 232 233 Gen->HandleInlineFunctionDefinition(D); 234 235 if (TimerIsEnabled) 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 (TimerIsEnabled) { 284 LLVMIRGenerationRefCount += 1; 285 if (LLVMIRGenerationRefCount == 1) 286 LLVMIRGeneration.startTimer(); 287 } 288 289 Gen->HandleTranslationUnit(C); 290 291 if (TimerIsEnabled) { 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.OptimizationRemark.patternMatches(D.getPassName())) 723 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark); 724 } else if (D.isMissed()) { 725 // Missed optimization remarks are active only if the -Rpass-missed 726 // flag has a regular expression that matches the name of the pass 727 // name in \p D. 728 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName())) 729 EmitOptimizationMessage( 730 D, diag::remark_fe_backend_optimization_remark_missed); 731 } else { 732 assert(D.isAnalysis() && "Unknown remark type"); 733 734 bool ShouldAlwaysPrint = false; 735 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D)) 736 ShouldAlwaysPrint = ORA->shouldAlwaysPrint(); 737 738 if (ShouldAlwaysPrint || 739 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 740 EmitOptimizationMessage( 741 D, diag::remark_fe_backend_optimization_remark_analysis); 742 } 743 } 744 745 void BackendConsumer::OptimizationRemarkHandler( 746 const llvm::OptimizationRemarkAnalysisFPCommute &D) { 747 // Optimization analysis remarks are active if the pass name is set to 748 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 749 // regular expression that matches the name of the pass name in \p D. 750 751 if (D.shouldAlwaysPrint() || 752 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 753 EmitOptimizationMessage( 754 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute); 755 } 756 757 void BackendConsumer::OptimizationRemarkHandler( 758 const llvm::OptimizationRemarkAnalysisAliasing &D) { 759 // Optimization analysis remarks are active if the pass name is set to 760 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 761 // regular expression that matches the name of the pass name in \p D. 762 763 if (D.shouldAlwaysPrint() || 764 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 765 EmitOptimizationMessage( 766 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing); 767 } 768 769 void BackendConsumer::OptimizationFailureHandler( 770 const llvm::DiagnosticInfoOptimizationFailure &D) { 771 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure); 772 } 773 774 /// This function is invoked when the backend needs 775 /// to report something to the user. 776 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) { 777 unsigned DiagID = diag::err_fe_inline_asm; 778 llvm::DiagnosticSeverity Severity = DI.getSeverity(); 779 // Get the diagnostic ID based. 780 switch (DI.getKind()) { 781 case llvm::DK_InlineAsm: 782 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI))) 783 return; 784 ComputeDiagID(Severity, inline_asm, DiagID); 785 break; 786 case llvm::DK_StackSize: 787 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI))) 788 return; 789 ComputeDiagID(Severity, backend_frame_larger_than, DiagID); 790 break; 791 case DK_Linker: 792 assert(CurLinkModule); 793 // FIXME: stop eating the warnings and notes. 794 if (Severity != DS_Error) 795 return; 796 DiagID = diag::err_fe_cannot_link_module; 797 break; 798 case llvm::DK_OptimizationRemark: 799 // Optimization remarks are always handled completely by this 800 // handler. There is no generic way of emitting them. 801 OptimizationRemarkHandler(cast<OptimizationRemark>(DI)); 802 return; 803 case llvm::DK_OptimizationRemarkMissed: 804 // Optimization remarks are always handled completely by this 805 // handler. There is no generic way of emitting them. 806 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI)); 807 return; 808 case llvm::DK_OptimizationRemarkAnalysis: 809 // Optimization remarks are always handled completely by this 810 // handler. There is no generic way of emitting them. 811 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI)); 812 return; 813 case llvm::DK_OptimizationRemarkAnalysisFPCommute: 814 // Optimization remarks are always handled completely by this 815 // handler. There is no generic way of emitting them. 816 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI)); 817 return; 818 case llvm::DK_OptimizationRemarkAnalysisAliasing: 819 // Optimization remarks are always handled completely by this 820 // handler. There is no generic way of emitting them. 821 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI)); 822 return; 823 case llvm::DK_MachineOptimizationRemark: 824 // Optimization remarks are always handled completely by this 825 // handler. There is no generic way of emitting them. 826 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI)); 827 return; 828 case llvm::DK_MachineOptimizationRemarkMissed: 829 // Optimization remarks are always handled completely by this 830 // handler. There is no generic way of emitting them. 831 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI)); 832 return; 833 case llvm::DK_MachineOptimizationRemarkAnalysis: 834 // Optimization remarks are always handled completely by this 835 // handler. There is no generic way of emitting them. 836 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI)); 837 return; 838 case llvm::DK_OptimizationFailure: 839 // Optimization failures are always handled completely by this 840 // handler. 841 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI)); 842 return; 843 case llvm::DK_Unsupported: 844 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI)); 845 return; 846 default: 847 // Plugin IDs are not bound to any value as they are set dynamically. 848 ComputeDiagRemarkID(Severity, backend_plugin, DiagID); 849 break; 850 } 851 std::string MsgStorage; 852 { 853 raw_string_ostream Stream(MsgStorage); 854 DiagnosticPrinterRawOStream DP(Stream); 855 DI.print(DP); 856 } 857 858 if (DiagID == diag::err_fe_cannot_link_module) { 859 Diags.Report(diag::err_fe_cannot_link_module) 860 << CurLinkModule->getModuleIdentifier() << MsgStorage; 861 return; 862 } 863 864 // Report the backend message using the usual diagnostic mechanism. 865 FullSourceLoc Loc; 866 Diags.Report(Loc, DiagID).AddString(MsgStorage); 867 } 868 #undef ComputeDiagID 869 870 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 871 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), 872 OwnsVMContext(!_VMContext) {} 873 874 CodeGenAction::~CodeGenAction() { 875 TheModule.reset(); 876 if (OwnsVMContext) 877 delete VMContext; 878 } 879 880 bool CodeGenAction::hasIRSupport() const { return true; } 881 882 void CodeGenAction::EndSourceFileAction() { 883 // If the consumer creation failed, do nothing. 884 if (!getCompilerInstance().hasASTConsumer()) 885 return; 886 887 // Steal the module from the consumer. 888 TheModule = BEConsumer->takeModule(); 889 } 890 891 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() { 892 return std::move(TheModule); 893 } 894 895 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 896 OwnsVMContext = false; 897 return VMContext; 898 } 899 900 static std::unique_ptr<raw_pwrite_stream> 901 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { 902 switch (Action) { 903 case Backend_EmitAssembly: 904 return CI.createDefaultOutputFile(false, InFile, "s"); 905 case Backend_EmitLL: 906 return CI.createDefaultOutputFile(false, InFile, "ll"); 907 case Backend_EmitBC: 908 return CI.createDefaultOutputFile(true, InFile, "bc"); 909 case Backend_EmitNothing: 910 return nullptr; 911 case Backend_EmitMCNull: 912 return CI.createNullOutputFile(); 913 case Backend_EmitObj: 914 return CI.createDefaultOutputFile(true, InFile, "o"); 915 } 916 917 llvm_unreachable("Invalid action!"); 918 } 919 920 std::unique_ptr<ASTConsumer> 921 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 922 BackendAction BA = static_cast<BackendAction>(Act); 923 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream(); 924 if (!OS) 925 OS = GetOutputStream(CI, InFile, BA); 926 927 if (BA != Backend_EmitNothing && !OS) 928 return nullptr; 929 930 // Load bitcode modules to link with, if we need to. 931 if (LinkModules.empty()) 932 for (const CodeGenOptions::BitcodeFileToLink &F : 933 CI.getCodeGenOpts().LinkBitcodeFiles) { 934 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename); 935 if (!BCBuf) { 936 CI.getDiagnostics().Report(diag::err_cannot_open_file) 937 << F.Filename << BCBuf.getError().message(); 938 LinkModules.clear(); 939 return nullptr; 940 } 941 942 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr = 943 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext); 944 if (!ModuleOrErr) { 945 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { 946 CI.getDiagnostics().Report(diag::err_cannot_open_file) 947 << F.Filename << EIB.message(); 948 }); 949 LinkModules.clear(); 950 return nullptr; 951 } 952 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs, 953 F.Internalize, F.LinkFlags}); 954 } 955 956 CoverageSourceInfo *CoverageInfo = nullptr; 957 // Add the preprocessor callback only when the coverage mapping is generated. 958 if (CI.getCodeGenOpts().CoverageMapping) 959 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks( 960 CI.getPreprocessor()); 961 962 std::unique_ptr<BackendConsumer> Result(new BackendConsumer( 963 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 964 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(), 965 CI.getLangOpts(), std::string(InFile), std::move(LinkModules), 966 std::move(OS), *VMContext, CoverageInfo)); 967 BEConsumer = Result.get(); 968 969 // Enable generating macro debug info only when debug info is not disabled and 970 // also macro debug info is enabled. 971 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo && 972 CI.getCodeGenOpts().MacroDebugInfo) { 973 std::unique_ptr<PPCallbacks> Callbacks = 974 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(), 975 CI.getPreprocessor()); 976 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks)); 977 } 978 979 return std::move(Result); 980 } 981 982 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM, 983 void *Context, 984 unsigned LocCookie) { 985 SM.print(nullptr, llvm::errs()); 986 987 auto Diags = static_cast<DiagnosticsEngine *>(Context); 988 unsigned DiagID; 989 switch (SM.getKind()) { 990 case llvm::SourceMgr::DK_Error: 991 DiagID = diag::err_fe_inline_asm; 992 break; 993 case llvm::SourceMgr::DK_Warning: 994 DiagID = diag::warn_fe_inline_asm; 995 break; 996 case llvm::SourceMgr::DK_Note: 997 DiagID = diag::note_fe_inline_asm; 998 break; 999 case llvm::SourceMgr::DK_Remark: 1000 llvm_unreachable("remarks unexpected"); 1001 } 1002 1003 Diags->Report(DiagID).AddString("cannot compile inline asm"); 1004 } 1005 1006 std::unique_ptr<llvm::Module> 1007 CodeGenAction::loadModule(MemoryBufferRef MBRef) { 1008 CompilerInstance &CI = getCompilerInstance(); 1009 SourceManager &SM = CI.getSourceManager(); 1010 1011 // For ThinLTO backend invocations, ensure that the context 1012 // merges types based on ODR identifiers. We also need to read 1013 // the correct module out of a multi-module bitcode file. 1014 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) { 1015 VMContext->enableDebugTypeODRUniquing(); 1016 1017 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> { 1018 unsigned DiagID = 1019 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1020 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1021 CI.getDiagnostics().Report(DiagID) << EIB.message(); 1022 }); 1023 return {}; 1024 }; 1025 1026 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 1027 if (!BMsOrErr) 1028 return DiagErrors(BMsOrErr.takeError()); 1029 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr); 1030 // We have nothing to do if the file contains no ThinLTO module. This is 1031 // possible if ThinLTO compilation was not able to split module. Content of 1032 // the file was already processed by indexing and will be passed to the 1033 // linker using merged object file. 1034 if (!Bm) { 1035 auto M = std::make_unique<llvm::Module>("empty", *VMContext); 1036 M->setTargetTriple(CI.getTargetOpts().Triple); 1037 return M; 1038 } 1039 Expected<std::unique_ptr<llvm::Module>> MOrErr = 1040 Bm->parseModule(*VMContext); 1041 if (!MOrErr) 1042 return DiagErrors(MOrErr.takeError()); 1043 return std::move(*MOrErr); 1044 } 1045 1046 llvm::SMDiagnostic Err; 1047 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) 1048 return M; 1049 1050 // Translate from the diagnostic info to the SourceManager location if 1051 // available. 1052 // TODO: Unify this with ConvertBackendLocation() 1053 SourceLocation Loc; 1054 if (Err.getLineNo() > 0) { 1055 assert(Err.getColumnNo() >= 0); 1056 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()), 1057 Err.getLineNo(), Err.getColumnNo() + 1); 1058 } 1059 1060 // Strip off a leading diagnostic code if there is one. 1061 StringRef Msg = Err.getMessage(); 1062 if (Msg.startswith("error: ")) 1063 Msg = Msg.substr(7); 1064 1065 unsigned DiagID = 1066 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1067 1068 CI.getDiagnostics().Report(Loc, DiagID) << Msg; 1069 return {}; 1070 } 1071 1072 void CodeGenAction::ExecuteAction() { 1073 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) { 1074 this->ASTFrontendAction::ExecuteAction(); 1075 return; 1076 } 1077 1078 // If this is an IR file, we have to treat it specially. 1079 BackendAction BA = static_cast<BackendAction>(Act); 1080 CompilerInstance &CI = getCompilerInstance(); 1081 auto &CodeGenOpts = CI.getCodeGenOpts(); 1082 auto &Diagnostics = CI.getDiagnostics(); 1083 std::unique_ptr<raw_pwrite_stream> OS = 1084 GetOutputStream(CI, getCurrentFile(), BA); 1085 if (BA != Backend_EmitNothing && !OS) 1086 return; 1087 1088 SourceManager &SM = CI.getSourceManager(); 1089 FileID FID = SM.getMainFileID(); 1090 Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID); 1091 if (!MainFile) 1092 return; 1093 1094 TheModule = loadModule(*MainFile); 1095 if (!TheModule) 1096 return; 1097 1098 const TargetOptions &TargetOpts = CI.getTargetOpts(); 1099 if (TheModule->getTargetTriple() != TargetOpts.Triple) { 1100 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module) 1101 << TargetOpts.Triple; 1102 TheModule->setTargetTriple(TargetOpts.Triple); 1103 } 1104 1105 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile); 1106 1107 LLVMContext &Ctx = TheModule->getContext(); 1108 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler, &Diagnostics); 1109 1110 // Restore any diagnostic handler previously set before returning from this 1111 // function. 1112 struct RAII { 1113 LLVMContext &Ctx; 1114 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler(); 1115 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); } 1116 } _{Ctx}; 1117 1118 // Set clang diagnostic handler. To do this we need to create a fake 1119 // BackendConsumer. 1120 BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 1121 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), 1122 CI.getTargetOpts(), CI.getLangOpts(), 1123 std::move(LinkModules), *VMContext, nullptr); 1124 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be 1125 // true here because the valued names are needed for reading textual IR. 1126 Ctx.setDiscardValueNames(false); 1127 Ctx.setDiagnosticHandler( 1128 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result)); 1129 1130 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr = 1131 setupLLVMOptimizationRemarks( 1132 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses, 1133 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness, 1134 CodeGenOpts.DiagnosticsHotnessThreshold); 1135 1136 if (Error E = OptRecordFileOrErr.takeError()) { 1137 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts); 1138 return; 1139 } 1140 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile = 1141 std::move(*OptRecordFileOrErr); 1142 1143 EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, 1144 TargetOpts, CI.getLangOpts(), 1145 CI.getTarget().getDataLayout(), TheModule.get(), BA, 1146 std::move(OS)); 1147 if (OptRecordFile) 1148 OptRecordFile->keep(); 1149 } 1150 1151 // 1152 1153 void EmitAssemblyAction::anchor() { } 1154 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 1155 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 1156 1157 void EmitBCAction::anchor() { } 1158 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 1159 : CodeGenAction(Backend_EmitBC, _VMContext) {} 1160 1161 void EmitLLVMAction::anchor() { } 1162 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 1163 : CodeGenAction(Backend_EmitLL, _VMContext) {} 1164 1165 void EmitLLVMOnlyAction::anchor() { } 1166 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 1167 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 1168 1169 void EmitCodeGenOnlyAction::anchor() { } 1170 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 1171 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 1172 1173 void EmitObjAction::anchor() { } 1174 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 1175 : CodeGenAction(Backend_EmitObj, _VMContext) {} 1176