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, llvm::Module *Module, 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)), CurLinkModule(Module) { 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 LLVMContext &Ctx = getModule()->getContext(); 305 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler = 306 Ctx.getDiagnosticHandler(); 307 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>( 308 CodeGenOpts, this)); 309 310 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr = 311 setupLLVMOptimizationRemarks( 312 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses, 313 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness, 314 CodeGenOpts.DiagnosticsHotnessThreshold); 315 316 if (Error E = OptRecordFileOrErr.takeError()) { 317 reportOptRecordError(std::move(E), Diags, CodeGenOpts); 318 return; 319 } 320 321 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile = 322 std::move(*OptRecordFileOrErr); 323 324 if (OptRecordFile && 325 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone) 326 Ctx.setDiagnosticsHotnessRequested(true); 327 328 // Link each LinkModule into our module. 329 if (LinkInModules()) 330 return; 331 332 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef()); 333 334 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, 335 LangOpts, C.getTargetInfo().getDataLayoutString(), 336 getModule(), Action, std::move(AsmOutStream)); 337 338 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); 339 340 if (OptRecordFile) 341 OptRecordFile->keep(); 342 } 343 344 void HandleTagDeclDefinition(TagDecl *D) override { 345 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 346 Context->getSourceManager(), 347 "LLVM IR generation of declaration"); 348 Gen->HandleTagDeclDefinition(D); 349 } 350 351 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 352 Gen->HandleTagDeclRequiredDefinition(D); 353 } 354 355 void CompleteTentativeDefinition(VarDecl *D) override { 356 Gen->CompleteTentativeDefinition(D); 357 } 358 359 void CompleteExternalDeclaration(VarDecl *D) override { 360 Gen->CompleteExternalDeclaration(D); 361 } 362 363 void AssignInheritanceModel(CXXRecordDecl *RD) override { 364 Gen->AssignInheritanceModel(RD); 365 } 366 367 void HandleVTable(CXXRecordDecl *RD) override { 368 Gen->HandleVTable(RD); 369 } 370 371 /// Get the best possible source location to represent a diagnostic that 372 /// may have associated debug info. 373 const FullSourceLoc 374 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, 375 bool &BadDebugInfo, StringRef &Filename, 376 unsigned &Line, unsigned &Column) const; 377 378 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI); 379 /// Specialized handler for InlineAsm diagnostic. 380 /// \return True if the diagnostic has been successfully reported, false 381 /// otherwise. 382 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D); 383 /// Specialized handler for diagnostics reported using SMDiagnostic. 384 void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D); 385 /// Specialized handler for StackSize diagnostic. 386 /// \return True if the diagnostic has been successfully reported, false 387 /// otherwise. 388 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D); 389 /// Specialized handler for unsupported backend feature diagnostic. 390 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D); 391 /// Specialized handlers for optimization remarks. 392 /// Note that these handlers only accept remarks and they always handle 393 /// them. 394 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, 395 unsigned DiagID); 396 void 397 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D); 398 void OptimizationRemarkHandler( 399 const llvm::OptimizationRemarkAnalysisFPCommute &D); 400 void OptimizationRemarkHandler( 401 const llvm::OptimizationRemarkAnalysisAliasing &D); 402 void OptimizationFailureHandler( 403 const llvm::DiagnosticInfoOptimizationFailure &D); 404 void DontCallDiagHandler(const DiagnosticInfoDontCall &D); 405 }; 406 407 void BackendConsumer::anchor() {} 408 } 409 410 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) { 411 BackendCon->DiagnosticHandlerImpl(DI); 412 return true; 413 } 414 415 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr 416 /// buffer to be a valid FullSourceLoc. 417 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, 418 SourceManager &CSM) { 419 // Get both the clang and llvm source managers. The location is relative to 420 // a memory buffer that the LLVM Source Manager is handling, we need to add 421 // a copy to the Clang source manager. 422 const llvm::SourceMgr &LSM = *D.getSourceMgr(); 423 424 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr 425 // already owns its one and clang::SourceManager wants to own its one. 426 const MemoryBuffer *LBuf = 427 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); 428 429 // Create the copy and transfer ownership to clang::SourceManager. 430 // TODO: Avoid copying files into memory. 431 std::unique_ptr<llvm::MemoryBuffer> CBuf = 432 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), 433 LBuf->getBufferIdentifier()); 434 // FIXME: Keep a file ID map instead of creating new IDs for each location. 435 FileID FID = CSM.createFileID(std::move(CBuf)); 436 437 // Translate the offset into the file. 438 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); 439 SourceLocation NewLoc = 440 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); 441 return FullSourceLoc(NewLoc, CSM); 442 } 443 444 #define ComputeDiagID(Severity, GroupName, DiagID) \ 445 do { \ 446 switch (Severity) { \ 447 case llvm::DS_Error: \ 448 DiagID = diag::err_fe_##GroupName; \ 449 break; \ 450 case llvm::DS_Warning: \ 451 DiagID = diag::warn_fe_##GroupName; \ 452 break; \ 453 case llvm::DS_Remark: \ 454 llvm_unreachable("'remark' severity not expected"); \ 455 break; \ 456 case llvm::DS_Note: \ 457 DiagID = diag::note_fe_##GroupName; \ 458 break; \ 459 } \ 460 } while (false) 461 462 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \ 463 do { \ 464 switch (Severity) { \ 465 case llvm::DS_Error: \ 466 DiagID = diag::err_fe_##GroupName; \ 467 break; \ 468 case llvm::DS_Warning: \ 469 DiagID = diag::warn_fe_##GroupName; \ 470 break; \ 471 case llvm::DS_Remark: \ 472 DiagID = diag::remark_fe_##GroupName; \ 473 break; \ 474 case llvm::DS_Note: \ 475 DiagID = diag::note_fe_##GroupName; \ 476 break; \ 477 } \ 478 } while (false) 479 480 void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) { 481 const llvm::SMDiagnostic &D = DI.getSMDiag(); 482 483 unsigned DiagID; 484 if (DI.isInlineAsmDiag()) 485 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID); 486 else 487 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID); 488 489 // This is for the empty BackendConsumer that uses the clang diagnostic 490 // handler for IR input files. 491 if (!Context) { 492 D.print(nullptr, llvm::errs()); 493 Diags.Report(DiagID).AddString("cannot compile inline asm"); 494 return; 495 } 496 497 // There are a couple of different kinds of errors we could get here. 498 // First, we re-format the SMDiagnostic in terms of a clang diagnostic. 499 500 // Strip "error: " off the start of the message string. 501 StringRef Message = D.getMessage(); 502 (void)Message.consume_front("error: "); 503 504 // If the SMDiagnostic has an inline asm source location, translate it. 505 FullSourceLoc Loc; 506 if (D.getLoc() != SMLoc()) 507 Loc = ConvertBackendLocation(D, Context->getSourceManager()); 508 509 // If this problem has clang-level source location information, report the 510 // issue in the source with a note showing the instantiated 511 // code. 512 if (DI.isInlineAsmDiag()) { 513 SourceLocation LocCookie = 514 SourceLocation::getFromRawEncoding(DI.getLocCookie()); 515 if (LocCookie.isValid()) { 516 Diags.Report(LocCookie, DiagID).AddString(Message); 517 518 if (D.getLoc().isValid()) { 519 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here); 520 // Convert the SMDiagnostic ranges into SourceRange and attach them 521 // to the diagnostic. 522 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) { 523 unsigned Column = D.getColumnNo(); 524 B << SourceRange(Loc.getLocWithOffset(Range.first - Column), 525 Loc.getLocWithOffset(Range.second - Column)); 526 } 527 } 528 return; 529 } 530 } 531 532 // Otherwise, report the backend issue as occurring in the generated .s file. 533 // If Loc is invalid, we still need to report the issue, it just gets no 534 // location info. 535 Diags.Report(Loc, DiagID).AddString(Message); 536 return; 537 } 538 539 bool 540 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) { 541 unsigned DiagID; 542 ComputeDiagID(D.getSeverity(), inline_asm, DiagID); 543 std::string Message = D.getMsgStr().str(); 544 545 // If this problem has clang-level source location information, report the 546 // issue as being a problem in the source with a note showing the instantiated 547 // code. 548 SourceLocation LocCookie = 549 SourceLocation::getFromRawEncoding(D.getLocCookie()); 550 if (LocCookie.isValid()) 551 Diags.Report(LocCookie, DiagID).AddString(Message); 552 else { 553 // Otherwise, report the backend diagnostic as occurring in the generated 554 // .s file. 555 // If Loc is invalid, we still need to report the diagnostic, it just gets 556 // no location info. 557 FullSourceLoc Loc; 558 Diags.Report(Loc, DiagID).AddString(Message); 559 } 560 // We handled all the possible severities. 561 return true; 562 } 563 564 bool 565 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) { 566 if (D.getSeverity() != llvm::DS_Warning) 567 // For now, the only support we have for StackSize diagnostic is warning. 568 // We do not know how to format other severities. 569 return false; 570 571 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) { 572 // FIXME: Shouldn't need to truncate to uint32_t 573 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()), 574 diag::warn_fe_frame_larger_than) 575 << static_cast<uint32_t>(D.getStackSize()) 576 << static_cast<uint32_t>(D.getStackLimit()) 577 << Decl::castToDeclContext(ND); 578 return true; 579 } 580 581 return false; 582 } 583 584 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc( 585 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, 586 StringRef &Filename, unsigned &Line, unsigned &Column) const { 587 SourceManager &SourceMgr = Context->getSourceManager(); 588 FileManager &FileMgr = SourceMgr.getFileManager(); 589 SourceLocation DILoc; 590 591 if (D.isLocationAvailable()) { 592 D.getLocation(Filename, Line, Column); 593 if (Line > 0) { 594 auto FE = FileMgr.getFile(Filename); 595 if (!FE) 596 FE = FileMgr.getFile(D.getAbsolutePath()); 597 if (FE) { 598 // If -gcolumn-info was not used, Column will be 0. This upsets the 599 // source manager, so pass 1 if Column is not set. 600 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1); 601 } 602 } 603 BadDebugInfo = DILoc.isInvalid(); 604 } 605 606 // If a location isn't available, try to approximate it using the associated 607 // function definition. We use the definition's right brace to differentiate 608 // from diagnostics that genuinely relate to the function itself. 609 FullSourceLoc Loc(DILoc, SourceMgr); 610 if (Loc.isInvalid()) 611 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName())) 612 Loc = FD->getASTContext().getFullLoc(FD->getLocation()); 613 614 if (DILoc.isInvalid() && D.isLocationAvailable()) 615 // If we were not able to translate the file:line:col information 616 // back to a SourceLocation, at least emit a note stating that 617 // we could not translate this location. This can happen in the 618 // case of #line directives. 619 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 620 << Filename << Line << Column; 621 622 return Loc; 623 } 624 625 void BackendConsumer::UnsupportedDiagHandler( 626 const llvm::DiagnosticInfoUnsupported &D) { 627 // We only support warnings or errors. 628 assert(D.getSeverity() == llvm::DS_Error || 629 D.getSeverity() == llvm::DS_Warning); 630 631 StringRef Filename; 632 unsigned Line, Column; 633 bool BadDebugInfo = false; 634 FullSourceLoc Loc; 635 std::string Msg; 636 raw_string_ostream MsgStream(Msg); 637 638 // Context will be nullptr for IR input files, we will construct the diag 639 // message from llvm::DiagnosticInfoUnsupported. 640 if (Context != nullptr) { 641 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); 642 MsgStream << D.getMessage(); 643 } else { 644 DiagnosticPrinterRawOStream DP(MsgStream); 645 D.print(DP); 646 } 647 648 auto DiagType = D.getSeverity() == llvm::DS_Error 649 ? diag::err_fe_backend_unsupported 650 : diag::warn_fe_backend_unsupported; 651 Diags.Report(Loc, DiagType) << MsgStream.str(); 652 653 if (BadDebugInfo) 654 // If we were not able to translate the file:line:col information 655 // back to a SourceLocation, at least emit a note stating that 656 // we could not translate this location. This can happen in the 657 // case of #line directives. 658 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 659 << Filename << Line << Column; 660 } 661 662 void BackendConsumer::EmitOptimizationMessage( 663 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) { 664 // We only support warnings and remarks. 665 assert(D.getSeverity() == llvm::DS_Remark || 666 D.getSeverity() == llvm::DS_Warning); 667 668 StringRef Filename; 669 unsigned Line, Column; 670 bool BadDebugInfo = false; 671 FullSourceLoc Loc; 672 std::string Msg; 673 raw_string_ostream MsgStream(Msg); 674 675 // Context will be nullptr for IR input files, we will construct the remark 676 // message from llvm::DiagnosticInfoOptimizationBase. 677 if (Context != nullptr) { 678 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); 679 MsgStream << D.getMsg(); 680 } else { 681 DiagnosticPrinterRawOStream DP(MsgStream); 682 D.print(DP); 683 } 684 685 if (D.getHotness()) 686 MsgStream << " (hotness: " << *D.getHotness() << ")"; 687 688 Diags.Report(Loc, DiagID) 689 << AddFlagValue(D.getPassName()) 690 << MsgStream.str(); 691 692 if (BadDebugInfo) 693 // If we were not able to translate the file:line:col information 694 // back to a SourceLocation, at least emit a note stating that 695 // we could not translate this location. This can happen in the 696 // case of #line directives. 697 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 698 << Filename << Line << Column; 699 } 700 701 void BackendConsumer::OptimizationRemarkHandler( 702 const llvm::DiagnosticInfoOptimizationBase &D) { 703 // Without hotness information, don't show noisy remarks. 704 if (D.isVerbose() && !D.getHotness()) 705 return; 706 707 if (D.isPassed()) { 708 // Optimization remarks are active only if the -Rpass flag has a regular 709 // expression that matches the name of the pass name in \p D. 710 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName())) 711 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark); 712 } else if (D.isMissed()) { 713 // Missed optimization remarks are active only if the -Rpass-missed 714 // flag has a regular expression that matches the name of the pass 715 // name in \p D. 716 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName())) 717 EmitOptimizationMessage( 718 D, diag::remark_fe_backend_optimization_remark_missed); 719 } else { 720 assert(D.isAnalysis() && "Unknown remark type"); 721 722 bool ShouldAlwaysPrint = false; 723 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D)) 724 ShouldAlwaysPrint = ORA->shouldAlwaysPrint(); 725 726 if (ShouldAlwaysPrint || 727 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 728 EmitOptimizationMessage( 729 D, diag::remark_fe_backend_optimization_remark_analysis); 730 } 731 } 732 733 void BackendConsumer::OptimizationRemarkHandler( 734 const llvm::OptimizationRemarkAnalysisFPCommute &D) { 735 // Optimization analysis remarks are active if the pass name is set to 736 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 737 // regular expression that matches the name of the pass name in \p D. 738 739 if (D.shouldAlwaysPrint() || 740 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 741 EmitOptimizationMessage( 742 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute); 743 } 744 745 void BackendConsumer::OptimizationRemarkHandler( 746 const llvm::OptimizationRemarkAnalysisAliasing &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_aliasing); 755 } 756 757 void BackendConsumer::OptimizationFailureHandler( 758 const llvm::DiagnosticInfoOptimizationFailure &D) { 759 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure); 760 } 761 762 void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) { 763 if (const Decl *DE = Gen->GetDeclForMangledName(D.getFunctionName())) 764 if (const auto *FD = dyn_cast<FunctionDecl>(DE)) { 765 assert(FD->hasAttr<ErrorAttr>() && 766 "expected error or warning function attribute"); 767 768 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 769 assert((EA->isError() || EA->isWarning()) && 770 "ErrorAttr neither error or warning"); 771 772 SourceLocation LocCookie = 773 SourceLocation::getFromRawEncoding(D.getLocCookie()); 774 775 // FIXME: we can't yet diagnose indirect calls. When/if we can, we 776 // should instead assert that LocCookie.isValid(). 777 if (!LocCookie.isValid()) 778 return; 779 780 Diags.Report(LocCookie, EA->isError() 781 ? diag::err_fe_backend_error_attr 782 : diag::warn_fe_backend_warning_attr) 783 << FD << EA->getUserDiagnostic(); 784 } 785 } 786 // TODO: assert if DE or FD were nullptr? 787 } 788 789 /// This function is invoked when the backend needs 790 /// to report something to the user. 791 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) { 792 unsigned DiagID = diag::err_fe_inline_asm; 793 llvm::DiagnosticSeverity Severity = DI.getSeverity(); 794 // Get the diagnostic ID based. 795 switch (DI.getKind()) { 796 case llvm::DK_InlineAsm: 797 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI))) 798 return; 799 ComputeDiagID(Severity, inline_asm, DiagID); 800 break; 801 case llvm::DK_SrcMgr: 802 SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI)); 803 return; 804 case llvm::DK_StackSize: 805 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI))) 806 return; 807 ComputeDiagID(Severity, backend_frame_larger_than, DiagID); 808 break; 809 case DK_Linker: 810 ComputeDiagID(Severity, linking_module, DiagID); 811 break; 812 case llvm::DK_OptimizationRemark: 813 // Optimization remarks are always handled completely by this 814 // handler. There is no generic way of emitting them. 815 OptimizationRemarkHandler(cast<OptimizationRemark>(DI)); 816 return; 817 case llvm::DK_OptimizationRemarkMissed: 818 // Optimization remarks are always handled completely by this 819 // handler. There is no generic way of emitting them. 820 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI)); 821 return; 822 case llvm::DK_OptimizationRemarkAnalysis: 823 // Optimization remarks are always handled completely by this 824 // handler. There is no generic way of emitting them. 825 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI)); 826 return; 827 case llvm::DK_OptimizationRemarkAnalysisFPCommute: 828 // Optimization remarks are always handled completely by this 829 // handler. There is no generic way of emitting them. 830 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI)); 831 return; 832 case llvm::DK_OptimizationRemarkAnalysisAliasing: 833 // Optimization remarks are always handled completely by this 834 // handler. There is no generic way of emitting them. 835 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI)); 836 return; 837 case llvm::DK_MachineOptimizationRemark: 838 // Optimization remarks are always handled completely by this 839 // handler. There is no generic way of emitting them. 840 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI)); 841 return; 842 case llvm::DK_MachineOptimizationRemarkMissed: 843 // Optimization remarks are always handled completely by this 844 // handler. There is no generic way of emitting them. 845 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI)); 846 return; 847 case llvm::DK_MachineOptimizationRemarkAnalysis: 848 // Optimization remarks are always handled completely by this 849 // handler. There is no generic way of emitting them. 850 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI)); 851 return; 852 case llvm::DK_OptimizationFailure: 853 // Optimization failures are always handled completely by this 854 // handler. 855 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI)); 856 return; 857 case llvm::DK_Unsupported: 858 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI)); 859 return; 860 case llvm::DK_DontCall: 861 DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI)); 862 return; 863 default: 864 // Plugin IDs are not bound to any value as they are set dynamically. 865 ComputeDiagRemarkID(Severity, backend_plugin, DiagID); 866 break; 867 } 868 std::string MsgStorage; 869 { 870 raw_string_ostream Stream(MsgStorage); 871 DiagnosticPrinterRawOStream DP(Stream); 872 DI.print(DP); 873 } 874 875 if (DI.getKind() == DK_Linker) { 876 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics"); 877 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage; 878 return; 879 } 880 881 // Report the backend message using the usual diagnostic mechanism. 882 FullSourceLoc Loc; 883 Diags.Report(Loc, DiagID).AddString(MsgStorage); 884 } 885 #undef ComputeDiagID 886 887 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 888 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), 889 OwnsVMContext(!_VMContext) {} 890 891 CodeGenAction::~CodeGenAction() { 892 TheModule.reset(); 893 if (OwnsVMContext) 894 delete VMContext; 895 } 896 897 bool CodeGenAction::hasIRSupport() const { return true; } 898 899 void CodeGenAction::EndSourceFileAction() { 900 // If the consumer creation failed, do nothing. 901 if (!getCompilerInstance().hasASTConsumer()) 902 return; 903 904 // Steal the module from the consumer. 905 TheModule = BEConsumer->takeModule(); 906 } 907 908 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() { 909 return std::move(TheModule); 910 } 911 912 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 913 OwnsVMContext = false; 914 return VMContext; 915 } 916 917 CodeGenerator *CodeGenAction::getCodeGenerator() const { 918 return BEConsumer->getCodeGenerator(); 919 } 920 921 static std::unique_ptr<raw_pwrite_stream> 922 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { 923 switch (Action) { 924 case Backend_EmitAssembly: 925 return CI.createDefaultOutputFile(false, InFile, "s"); 926 case Backend_EmitLL: 927 return CI.createDefaultOutputFile(false, InFile, "ll"); 928 case Backend_EmitBC: 929 return CI.createDefaultOutputFile(true, InFile, "bc"); 930 case Backend_EmitNothing: 931 return nullptr; 932 case Backend_EmitMCNull: 933 return CI.createNullOutputFile(); 934 case Backend_EmitObj: 935 return CI.createDefaultOutputFile(true, InFile, "o"); 936 } 937 938 llvm_unreachable("Invalid action!"); 939 } 940 941 std::unique_ptr<ASTConsumer> 942 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 943 BackendAction BA = static_cast<BackendAction>(Act); 944 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream(); 945 if (!OS) 946 OS = GetOutputStream(CI, InFile, BA); 947 948 if (BA != Backend_EmitNothing && !OS) 949 return nullptr; 950 951 // Load bitcode modules to link with, if we need to. 952 if (LinkModules.empty()) 953 for (const CodeGenOptions::BitcodeFileToLink &F : 954 CI.getCodeGenOpts().LinkBitcodeFiles) { 955 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename); 956 if (!BCBuf) { 957 CI.getDiagnostics().Report(diag::err_cannot_open_file) 958 << F.Filename << BCBuf.getError().message(); 959 LinkModules.clear(); 960 return nullptr; 961 } 962 963 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr = 964 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext); 965 if (!ModuleOrErr) { 966 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { 967 CI.getDiagnostics().Report(diag::err_cannot_open_file) 968 << F.Filename << EIB.message(); 969 }); 970 LinkModules.clear(); 971 return nullptr; 972 } 973 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs, 974 F.Internalize, F.LinkFlags}); 975 } 976 977 CoverageSourceInfo *CoverageInfo = nullptr; 978 // Add the preprocessor callback only when the coverage mapping is generated. 979 if (CI.getCodeGenOpts().CoverageMapping) 980 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks( 981 CI.getPreprocessor()); 982 983 std::unique_ptr<BackendConsumer> Result(new BackendConsumer( 984 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 985 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(), 986 CI.getLangOpts(), std::string(InFile), std::move(LinkModules), 987 std::move(OS), *VMContext, CoverageInfo)); 988 BEConsumer = Result.get(); 989 990 // Enable generating macro debug info only when debug info is not disabled and 991 // also macro debug info is enabled. 992 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo && 993 CI.getCodeGenOpts().MacroDebugInfo) { 994 std::unique_ptr<PPCallbacks> Callbacks = 995 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(), 996 CI.getPreprocessor()); 997 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks)); 998 } 999 1000 return std::move(Result); 1001 } 1002 1003 std::unique_ptr<llvm::Module> 1004 CodeGenAction::loadModule(MemoryBufferRef MBRef) { 1005 CompilerInstance &CI = getCompilerInstance(); 1006 SourceManager &SM = CI.getSourceManager(); 1007 1008 // For ThinLTO backend invocations, ensure that the context 1009 // merges types based on ODR identifiers. We also need to read 1010 // the correct module out of a multi-module bitcode file. 1011 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) { 1012 VMContext->enableDebugTypeODRUniquing(); 1013 1014 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> { 1015 unsigned DiagID = 1016 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1017 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1018 CI.getDiagnostics().Report(DiagID) << EIB.message(); 1019 }); 1020 return {}; 1021 }; 1022 1023 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 1024 if (!BMsOrErr) 1025 return DiagErrors(BMsOrErr.takeError()); 1026 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr); 1027 // We have nothing to do if the file contains no ThinLTO module. This is 1028 // possible if ThinLTO compilation was not able to split module. Content of 1029 // the file was already processed by indexing and will be passed to the 1030 // linker using merged object file. 1031 if (!Bm) { 1032 auto M = std::make_unique<llvm::Module>("empty", *VMContext); 1033 M->setTargetTriple(CI.getTargetOpts().Triple); 1034 return M; 1035 } 1036 Expected<std::unique_ptr<llvm::Module>> MOrErr = 1037 Bm->parseModule(*VMContext); 1038 if (!MOrErr) 1039 return DiagErrors(MOrErr.takeError()); 1040 return std::move(*MOrErr); 1041 } 1042 1043 llvm::SMDiagnostic Err; 1044 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) 1045 return M; 1046 1047 // Translate from the diagnostic info to the SourceManager location if 1048 // available. 1049 // TODO: Unify this with ConvertBackendLocation() 1050 SourceLocation Loc; 1051 if (Err.getLineNo() > 0) { 1052 assert(Err.getColumnNo() >= 0); 1053 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()), 1054 Err.getLineNo(), Err.getColumnNo() + 1); 1055 } 1056 1057 // Strip off a leading diagnostic code if there is one. 1058 StringRef Msg = Err.getMessage(); 1059 if (Msg.startswith("error: ")) 1060 Msg = Msg.substr(7); 1061 1062 unsigned DiagID = 1063 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1064 1065 CI.getDiagnostics().Report(Loc, DiagID) << Msg; 1066 return {}; 1067 } 1068 1069 void CodeGenAction::ExecuteAction() { 1070 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) { 1071 this->ASTFrontendAction::ExecuteAction(); 1072 return; 1073 } 1074 1075 // If this is an IR file, we have to treat it specially. 1076 BackendAction BA = static_cast<BackendAction>(Act); 1077 CompilerInstance &CI = getCompilerInstance(); 1078 auto &CodeGenOpts = CI.getCodeGenOpts(); 1079 auto &Diagnostics = CI.getDiagnostics(); 1080 std::unique_ptr<raw_pwrite_stream> OS = 1081 GetOutputStream(CI, getCurrentFile(), BA); 1082 if (BA != Backend_EmitNothing && !OS) 1083 return; 1084 1085 SourceManager &SM = CI.getSourceManager(); 1086 FileID FID = SM.getMainFileID(); 1087 Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID); 1088 if (!MainFile) 1089 return; 1090 1091 TheModule = loadModule(*MainFile); 1092 if (!TheModule) 1093 return; 1094 1095 const TargetOptions &TargetOpts = CI.getTargetOpts(); 1096 if (TheModule->getTargetTriple() != TargetOpts.Triple) { 1097 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module) 1098 << TargetOpts.Triple; 1099 TheModule->setTargetTriple(TargetOpts.Triple); 1100 } 1101 1102 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile); 1103 1104 LLVMContext &Ctx = TheModule->getContext(); 1105 1106 // Restore any diagnostic handler previously set before returning from this 1107 // function. 1108 struct RAII { 1109 LLVMContext &Ctx; 1110 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler(); 1111 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); } 1112 } _{Ctx}; 1113 1114 // Set clang diagnostic handler. To do this we need to create a fake 1115 // BackendConsumer. 1116 BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 1117 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), 1118 CI.getTargetOpts(), CI.getLangOpts(), TheModule.get(), 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().getDataLayoutString(), TheModule.get(), BA, 1142 std::move(OS)); 1143 if (OptRecordFile) 1144 OptRecordFile->keep(); 1145 } 1146 1147 // 1148 1149 void EmitAssemblyAction::anchor() { } 1150 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 1151 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 1152 1153 void EmitBCAction::anchor() { } 1154 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 1155 : CodeGenAction(Backend_EmitBC, _VMContext) {} 1156 1157 void EmitLLVMAction::anchor() { } 1158 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 1159 : CodeGenAction(Backend_EmitLL, _VMContext) {} 1160 1161 void EmitLLVMOnlyAction::anchor() { } 1162 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 1163 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 1164 1165 void EmitCodeGenOnlyAction::anchor() { } 1166 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 1167 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 1168 1169 void EmitObjAction::anchor() { } 1170 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 1171 : CodeGenAction(Backend_EmitObj, _VMContext) {} 1172