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