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