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