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