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