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 "CoverageMappingGen.h" 11 #include "clang/AST/ASTConsumer.h" 12 #include "clang/AST/ASTContext.h" 13 #include "clang/AST/DeclCXX.h" 14 #include "clang/AST/DeclGroup.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/SourceManager.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/CodeGen/BackendUtil.h" 19 #include "clang/CodeGen/CodeGenAction.h" 20 #include "clang/CodeGen/ModuleBuilder.h" 21 #include "clang/Frontend/CompilerInstance.h" 22 #include "clang/Frontend/FrontendDiagnostic.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "llvm/ADT/SmallString.h" 25 #include "llvm/Bitcode/ReaderWriter.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/DiagnosticPrinter.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/IRReader/IRReader.h" 32 #include "llvm/Linker/Linker.h" 33 #include "llvm/Pass.h" 34 #include "llvm/Support/MemoryBuffer.h" 35 #include "llvm/Support/SourceMgr.h" 36 #include "llvm/Support/Timer.h" 37 #include <memory> 38 using namespace clang; 39 using namespace llvm; 40 41 namespace clang { 42 class BackendConsumer : public ASTConsumer { 43 virtual void anchor(); 44 DiagnosticsEngine &Diags; 45 BackendAction Action; 46 const CodeGenOptions &CodeGenOpts; 47 const TargetOptions &TargetOpts; 48 const LangOptions &LangOpts; 49 raw_pwrite_stream *AsmOutStream; 50 ASTContext *Context; 51 52 Timer LLVMIRGeneration; 53 54 std::unique_ptr<CodeGenerator> Gen; 55 56 std::unique_ptr<llvm::Module> TheModule, LinkModule; 57 58 public: 59 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, 60 const HeaderSearchOptions &HeaderSearchOpts, 61 const PreprocessorOptions &PPOpts, 62 const CodeGenOptions &CodeGenOpts, 63 const TargetOptions &TargetOpts, 64 const LangOptions &LangOpts, bool TimePasses, 65 const std::string &InFile, llvm::Module *LinkModule, 66 raw_pwrite_stream *OS, LLVMContext &C, 67 CoverageSourceInfo *CoverageInfo = nullptr) 68 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts), 69 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS), 70 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"), 71 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts, 72 CodeGenOpts, C, CoverageInfo)), 73 LinkModule(LinkModule) { 74 llvm::TimePassesIsEnabled = TimePasses; 75 } 76 77 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); } 78 llvm::Module *takeLinkModule() { return LinkModule.release(); } 79 80 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 81 Gen->HandleCXXStaticMemberVarInstantiation(VD); 82 } 83 84 void Initialize(ASTContext &Ctx) override { 85 assert(!Context && "initialized multiple times"); 86 87 Context = &Ctx; 88 89 if (llvm::TimePassesIsEnabled) 90 LLVMIRGeneration.startTimer(); 91 92 Gen->Initialize(Ctx); 93 94 TheModule.reset(Gen->GetModule()); 95 96 if (llvm::TimePassesIsEnabled) 97 LLVMIRGeneration.stopTimer(); 98 } 99 100 bool HandleTopLevelDecl(DeclGroupRef D) override { 101 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), 102 Context->getSourceManager(), 103 "LLVM IR generation of declaration"); 104 105 if (llvm::TimePassesIsEnabled) 106 LLVMIRGeneration.startTimer(); 107 108 Gen->HandleTopLevelDecl(D); 109 110 if (llvm::TimePassesIsEnabled) 111 LLVMIRGeneration.stopTimer(); 112 113 return true; 114 } 115 116 void HandleInlineMethodDefinition(CXXMethodDecl *D) override { 117 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 118 Context->getSourceManager(), 119 "LLVM IR generation of inline method"); 120 if (llvm::TimePassesIsEnabled) 121 LLVMIRGeneration.startTimer(); 122 123 Gen->HandleInlineMethodDefinition(D); 124 125 if (llvm::TimePassesIsEnabled) 126 LLVMIRGeneration.stopTimer(); 127 } 128 129 void HandleTranslationUnit(ASTContext &C) override { 130 { 131 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); 132 if (llvm::TimePassesIsEnabled) 133 LLVMIRGeneration.startTimer(); 134 135 Gen->HandleTranslationUnit(C); 136 137 if (llvm::TimePassesIsEnabled) 138 LLVMIRGeneration.stopTimer(); 139 } 140 141 // Silently ignore if we weren't initialized for some reason. 142 if (!TheModule) 143 return; 144 145 // Make sure IR generation is happy with the module. This is released by 146 // the module provider. 147 llvm::Module *M = Gen->ReleaseModule(); 148 if (!M) { 149 // The module has been released by IR gen on failures, do not double 150 // free. 151 TheModule.release(); 152 return; 153 } 154 155 assert(TheModule.get() == M && 156 "Unexpected module change during IR generation"); 157 158 // Link LinkModule into this module if present, preserving its validity. 159 if (LinkModule) { 160 if (Linker::LinkModules( 161 M, LinkModule.get(), 162 [=](const DiagnosticInfo &DI) { linkerDiagnosticHandler(DI); }, 163 (LangOpts.CUDA && LangOpts.CUDAIsDevice && 164 LangOpts.CUDAUsesLibDevice) 165 ? (Linker::Flags::LinkOnlyNeeded | 166 Linker::Flags::InternalizeLinkedSymbols) 167 : Linker::Flags::None)) 168 return; 169 } 170 171 // Install an inline asm handler so that diagnostics get printed through 172 // our diagnostics hooks. 173 LLVMContext &Ctx = TheModule->getContext(); 174 LLVMContext::InlineAsmDiagHandlerTy OldHandler = 175 Ctx.getInlineAsmDiagnosticHandler(); 176 void *OldContext = Ctx.getInlineAsmDiagnosticContext(); 177 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this); 178 179 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler = 180 Ctx.getDiagnosticHandler(); 181 void *OldDiagnosticContext = Ctx.getDiagnosticContext(); 182 Ctx.setDiagnosticHandler(DiagnosticHandler, this); 183 184 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts, 185 C.getTargetInfo().getDataLayoutString(), 186 TheModule.get(), Action, AsmOutStream); 187 188 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext); 189 190 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext); 191 } 192 193 void HandleTagDeclDefinition(TagDecl *D) override { 194 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 195 Context->getSourceManager(), 196 "LLVM IR generation of declaration"); 197 Gen->HandleTagDeclDefinition(D); 198 } 199 200 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 201 Gen->HandleTagDeclRequiredDefinition(D); 202 } 203 204 void CompleteTentativeDefinition(VarDecl *D) override { 205 Gen->CompleteTentativeDefinition(D); 206 } 207 208 void HandleVTable(CXXRecordDecl *RD) override { 209 Gen->HandleVTable(RD); 210 } 211 212 void HandleLinkerOptionPragma(llvm::StringRef Opts) override { 213 Gen->HandleLinkerOptionPragma(Opts); 214 } 215 216 void HandleDetectMismatch(llvm::StringRef Name, 217 llvm::StringRef Value) override { 218 Gen->HandleDetectMismatch(Name, Value); 219 } 220 221 void HandleDependentLibrary(llvm::StringRef Opts) override { 222 Gen->HandleDependentLibrary(Opts); 223 } 224 225 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context, 226 unsigned LocCookie) { 227 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie); 228 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc); 229 } 230 231 void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI); 232 233 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI, 234 void *Context) { 235 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI); 236 } 237 238 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &, 239 SourceLocation LocCookie); 240 241 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI); 242 /// \brief Specialized handler for InlineAsm diagnostic. 243 /// \return True if the diagnostic has been successfully reported, false 244 /// otherwise. 245 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D); 246 /// \brief Specialized handler for StackSize diagnostic. 247 /// \return True if the diagnostic has been successfully reported, false 248 /// otherwise. 249 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D); 250 /// \brief Specialized handlers for optimization remarks. 251 /// Note that these handlers only accept remarks and they always handle 252 /// them. 253 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, 254 unsigned DiagID); 255 void 256 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D); 257 void OptimizationRemarkHandler( 258 const llvm::DiagnosticInfoOptimizationRemarkMissed &D); 259 void OptimizationRemarkHandler( 260 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D); 261 void OptimizationRemarkHandler( 262 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D); 263 void OptimizationRemarkHandler( 264 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D); 265 void OptimizationFailureHandler( 266 const llvm::DiagnosticInfoOptimizationFailure &D); 267 }; 268 269 void BackendConsumer::anchor() {} 270 } 271 272 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr 273 /// buffer to be a valid FullSourceLoc. 274 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, 275 SourceManager &CSM) { 276 // Get both the clang and llvm source managers. The location is relative to 277 // a memory buffer that the LLVM Source Manager is handling, we need to add 278 // a copy to the Clang source manager. 279 const llvm::SourceMgr &LSM = *D.getSourceMgr(); 280 281 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr 282 // already owns its one and clang::SourceManager wants to own its one. 283 const MemoryBuffer *LBuf = 284 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); 285 286 // Create the copy and transfer ownership to clang::SourceManager. 287 // TODO: Avoid copying files into memory. 288 std::unique_ptr<llvm::MemoryBuffer> CBuf = 289 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), 290 LBuf->getBufferIdentifier()); 291 // FIXME: Keep a file ID map instead of creating new IDs for each location. 292 FileID FID = CSM.createFileID(std::move(CBuf)); 293 294 // Translate the offset into the file. 295 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); 296 SourceLocation NewLoc = 297 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); 298 return FullSourceLoc(NewLoc, CSM); 299 } 300 301 302 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an 303 /// error parsing inline asm. The SMDiagnostic indicates the error relative to 304 /// the temporary memory buffer that the inline asm parser has set up. 305 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D, 306 SourceLocation LocCookie) { 307 // There are a couple of different kinds of errors we could get here. First, 308 // we re-format the SMDiagnostic in terms of a clang diagnostic. 309 310 // Strip "error: " off the start of the message string. 311 StringRef Message = D.getMessage(); 312 if (Message.startswith("error: ")) 313 Message = Message.substr(7); 314 315 // If the SMDiagnostic has an inline asm source location, translate it. 316 FullSourceLoc Loc; 317 if (D.getLoc() != SMLoc()) 318 Loc = ConvertBackendLocation(D, Context->getSourceManager()); 319 320 unsigned DiagID; 321 switch (D.getKind()) { 322 case llvm::SourceMgr::DK_Error: 323 DiagID = diag::err_fe_inline_asm; 324 break; 325 case llvm::SourceMgr::DK_Warning: 326 DiagID = diag::warn_fe_inline_asm; 327 break; 328 case llvm::SourceMgr::DK_Note: 329 DiagID = diag::note_fe_inline_asm; 330 break; 331 } 332 // If this problem has clang-level source location information, report the 333 // issue in the source with a note showing the instantiated 334 // code. 335 if (LocCookie.isValid()) { 336 Diags.Report(LocCookie, DiagID).AddString(Message); 337 338 if (D.getLoc().isValid()) { 339 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here); 340 // Convert the SMDiagnostic ranges into SourceRange and attach them 341 // to the diagnostic. 342 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) { 343 unsigned Column = D.getColumnNo(); 344 B << SourceRange(Loc.getLocWithOffset(Range.first - Column), 345 Loc.getLocWithOffset(Range.second - Column)); 346 } 347 } 348 return; 349 } 350 351 // Otherwise, report the backend issue as occurring in the generated .s file. 352 // If Loc is invalid, we still need to report the issue, it just gets no 353 // location info. 354 Diags.Report(Loc, DiagID).AddString(Message); 355 } 356 357 #define ComputeDiagID(Severity, GroupName, DiagID) \ 358 do { \ 359 switch (Severity) { \ 360 case llvm::DS_Error: \ 361 DiagID = diag::err_fe_##GroupName; \ 362 break; \ 363 case llvm::DS_Warning: \ 364 DiagID = diag::warn_fe_##GroupName; \ 365 break; \ 366 case llvm::DS_Remark: \ 367 llvm_unreachable("'remark' severity not expected"); \ 368 break; \ 369 case llvm::DS_Note: \ 370 DiagID = diag::note_fe_##GroupName; \ 371 break; \ 372 } \ 373 } while (false) 374 375 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \ 376 do { \ 377 switch (Severity) { \ 378 case llvm::DS_Error: \ 379 DiagID = diag::err_fe_##GroupName; \ 380 break; \ 381 case llvm::DS_Warning: \ 382 DiagID = diag::warn_fe_##GroupName; \ 383 break; \ 384 case llvm::DS_Remark: \ 385 DiagID = diag::remark_fe_##GroupName; \ 386 break; \ 387 case llvm::DS_Note: \ 388 DiagID = diag::note_fe_##GroupName; \ 389 break; \ 390 } \ 391 } while (false) 392 393 bool 394 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) { 395 unsigned DiagID; 396 ComputeDiagID(D.getSeverity(), inline_asm, DiagID); 397 std::string Message = D.getMsgStr().str(); 398 399 // If this problem has clang-level source location information, report the 400 // issue as being a problem in the source with a note showing the instantiated 401 // code. 402 SourceLocation LocCookie = 403 SourceLocation::getFromRawEncoding(D.getLocCookie()); 404 if (LocCookie.isValid()) 405 Diags.Report(LocCookie, DiagID).AddString(Message); 406 else { 407 // Otherwise, report the backend diagnostic as occurring in the generated 408 // .s file. 409 // If Loc is invalid, we still need to report the diagnostic, it just gets 410 // no location info. 411 FullSourceLoc Loc; 412 Diags.Report(Loc, DiagID).AddString(Message); 413 } 414 // We handled all the possible severities. 415 return true; 416 } 417 418 bool 419 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) { 420 if (D.getSeverity() != llvm::DS_Warning) 421 // For now, the only support we have for StackSize diagnostic is warning. 422 // We do not know how to format other severities. 423 return false; 424 425 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) { 426 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()), 427 diag::warn_fe_frame_larger_than) 428 << D.getStackSize() << Decl::castToDeclContext(ND); 429 return true; 430 } 431 432 return false; 433 } 434 435 void BackendConsumer::EmitOptimizationMessage( 436 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) { 437 // We only support warnings and remarks. 438 assert(D.getSeverity() == llvm::DS_Remark || 439 D.getSeverity() == llvm::DS_Warning); 440 441 SourceManager &SourceMgr = Context->getSourceManager(); 442 FileManager &FileMgr = SourceMgr.getFileManager(); 443 StringRef Filename; 444 unsigned Line, Column; 445 SourceLocation DILoc; 446 447 if (D.isLocationAvailable()) { 448 D.getLocation(&Filename, &Line, &Column); 449 const FileEntry *FE = FileMgr.getFile(Filename); 450 if (FE && Line > 0) { 451 // If -gcolumn-info was not used, Column will be 0. This upsets the 452 // source manager, so pass 1 if Column is not set. 453 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1); 454 } 455 } 456 457 // If a location isn't available, try to approximate it using the associated 458 // function definition. We use the definition's right brace to differentiate 459 // from diagnostics that genuinely relate to the function itself. 460 FullSourceLoc Loc(DILoc, SourceMgr); 461 if (Loc.isInvalid()) 462 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName())) 463 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace()); 464 465 Diags.Report(Loc, DiagID) 466 << AddFlagValue(D.getPassName() ? D.getPassName() : "") 467 << D.getMsg().str(); 468 469 if (DILoc.isInvalid() && D.isLocationAvailable()) 470 // If we were not able to translate the file:line:col information 471 // back to a SourceLocation, at least emit a note stating that 472 // we could not translate this location. This can happen in the 473 // case of #line directives. 474 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc) 475 << Filename << Line << Column; 476 } 477 478 void BackendConsumer::OptimizationRemarkHandler( 479 const llvm::DiagnosticInfoOptimizationRemark &D) { 480 // Optimization remarks are active only if the -Rpass flag has a regular 481 // expression that matches the name of the pass name in \p D. 482 if (CodeGenOpts.OptimizationRemarkPattern && 483 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) 484 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark); 485 } 486 487 void BackendConsumer::OptimizationRemarkHandler( 488 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) { 489 // Missed optimization remarks are active only if the -Rpass-missed 490 // flag has a regular expression that matches the name of the pass 491 // name in \p D. 492 if (CodeGenOpts.OptimizationRemarkMissedPattern && 493 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName())) 494 EmitOptimizationMessage(D, 495 diag::remark_fe_backend_optimization_remark_missed); 496 } 497 498 void BackendConsumer::OptimizationRemarkHandler( 499 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) { 500 // Optimization analysis remarks are active if the pass name is set to 501 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 502 // regular expression that matches the name of the pass name in \p D. 503 504 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint || 505 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 506 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 507 EmitOptimizationMessage( 508 D, diag::remark_fe_backend_optimization_remark_analysis); 509 } 510 511 void BackendConsumer::OptimizationRemarkHandler( 512 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) { 513 // Optimization analysis remarks are active if the pass name is set to 514 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 515 // regular expression that matches the name of the pass name in \p D. 516 517 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint || 518 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 519 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 520 EmitOptimizationMessage( 521 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute); 522 } 523 524 void BackendConsumer::OptimizationRemarkHandler( 525 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) { 526 // Optimization analysis remarks are active if the pass name is set to 527 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 528 // regular expression that matches the name of the pass name in \p D. 529 530 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint || 531 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 532 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 533 EmitOptimizationMessage( 534 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing); 535 } 536 537 void BackendConsumer::OptimizationFailureHandler( 538 const llvm::DiagnosticInfoOptimizationFailure &D) { 539 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure); 540 } 541 542 void BackendConsumer::linkerDiagnosticHandler(const DiagnosticInfo &DI) { 543 if (DI.getSeverity() != DS_Error) 544 return; 545 546 std::string MsgStorage; 547 { 548 raw_string_ostream Stream(MsgStorage); 549 DiagnosticPrinterRawOStream DP(Stream); 550 DI.print(DP); 551 } 552 553 Diags.Report(diag::err_fe_cannot_link_module) 554 << LinkModule->getModuleIdentifier() << MsgStorage; 555 } 556 557 /// \brief This function is invoked when the backend needs 558 /// to report something to the user. 559 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) { 560 unsigned DiagID = diag::err_fe_inline_asm; 561 llvm::DiagnosticSeverity Severity = DI.getSeverity(); 562 // Get the diagnostic ID based. 563 switch (DI.getKind()) { 564 case llvm::DK_InlineAsm: 565 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI))) 566 return; 567 ComputeDiagID(Severity, inline_asm, DiagID); 568 break; 569 case llvm::DK_StackSize: 570 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI))) 571 return; 572 ComputeDiagID(Severity, backend_frame_larger_than, DiagID); 573 break; 574 case llvm::DK_OptimizationRemark: 575 // Optimization remarks are always handled completely by this 576 // handler. There is no generic way of emitting them. 577 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI)); 578 return; 579 case llvm::DK_OptimizationRemarkMissed: 580 // Optimization remarks are always handled completely by this 581 // handler. There is no generic way of emitting them. 582 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI)); 583 return; 584 case llvm::DK_OptimizationRemarkAnalysis: 585 // Optimization remarks are always handled completely by this 586 // handler. There is no generic way of emitting them. 587 OptimizationRemarkHandler( 588 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI)); 589 return; 590 case llvm::DK_OptimizationRemarkAnalysisFPCommute: 591 // Optimization remarks are always handled completely by this 592 // handler. There is no generic way of emitting them. 593 OptimizationRemarkHandler( 594 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI)); 595 return; 596 case llvm::DK_OptimizationRemarkAnalysisAliasing: 597 // Optimization remarks are always handled completely by this 598 // handler. There is no generic way of emitting them. 599 OptimizationRemarkHandler( 600 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI)); 601 return; 602 case llvm::DK_OptimizationFailure: 603 // Optimization failures are always handled completely by this 604 // handler. 605 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI)); 606 return; 607 default: 608 // Plugin IDs are not bound to any value as they are set dynamically. 609 ComputeDiagRemarkID(Severity, backend_plugin, DiagID); 610 break; 611 } 612 std::string MsgStorage; 613 { 614 raw_string_ostream Stream(MsgStorage); 615 DiagnosticPrinterRawOStream DP(Stream); 616 DI.print(DP); 617 } 618 619 // Report the backend message using the usual diagnostic mechanism. 620 FullSourceLoc Loc; 621 Diags.Report(Loc, DiagID).AddString(MsgStorage); 622 } 623 #undef ComputeDiagID 624 625 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 626 : Act(_Act), LinkModule(nullptr), 627 VMContext(_VMContext ? _VMContext : new LLVMContext), 628 OwnsVMContext(!_VMContext) {} 629 630 CodeGenAction::~CodeGenAction() { 631 TheModule.reset(); 632 if (OwnsVMContext) 633 delete VMContext; 634 } 635 636 bool CodeGenAction::hasIRSupport() const { return true; } 637 638 void CodeGenAction::EndSourceFileAction() { 639 // If the consumer creation failed, do nothing. 640 if (!getCompilerInstance().hasASTConsumer()) 641 return; 642 643 // If we were given a link module, release consumer's ownership of it. 644 if (LinkModule) 645 BEConsumer->takeLinkModule(); 646 647 // Steal the module from the consumer. 648 TheModule = BEConsumer->takeModule(); 649 } 650 651 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() { 652 return std::move(TheModule); 653 } 654 655 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 656 OwnsVMContext = false; 657 return VMContext; 658 } 659 660 static raw_pwrite_stream * 661 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { 662 switch (Action) { 663 case Backend_EmitAssembly: 664 return CI.createDefaultOutputFile(false, InFile, "s"); 665 case Backend_EmitLL: 666 return CI.createDefaultOutputFile(false, InFile, "ll"); 667 case Backend_EmitBC: 668 return CI.createDefaultOutputFile(true, InFile, "bc"); 669 case Backend_EmitNothing: 670 return nullptr; 671 case Backend_EmitMCNull: 672 return CI.createNullOutputFile(); 673 case Backend_EmitObj: 674 return CI.createDefaultOutputFile(true, InFile, "o"); 675 } 676 677 llvm_unreachable("Invalid action!"); 678 } 679 680 std::unique_ptr<ASTConsumer> 681 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 682 BackendAction BA = static_cast<BackendAction>(Act); 683 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA); 684 if (BA != Backend_EmitNothing && !OS) 685 return nullptr; 686 687 llvm::Module *LinkModuleToUse = LinkModule; 688 689 // If we were not given a link module, and the user requested that one be 690 // loaded from bitcode, do so now. 691 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile; 692 if (!LinkModuleToUse && !LinkBCFile.empty()) { 693 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile); 694 if (!BCBuf) { 695 CI.getDiagnostics().Report(diag::err_cannot_open_file) 696 << LinkBCFile << BCBuf.getError().message(); 697 return nullptr; 698 } 699 700 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr = 701 getLazyBitcodeModule(std::move(*BCBuf), *VMContext); 702 if (std::error_code EC = ModuleOrErr.getError()) { 703 CI.getDiagnostics().Report(diag::err_cannot_open_file) 704 << LinkBCFile << EC.message(); 705 return nullptr; 706 } 707 LinkModuleToUse = ModuleOrErr.get().release(); 708 } 709 710 CoverageSourceInfo *CoverageInfo = nullptr; 711 // Add the preprocessor callback only when the coverage mapping is generated. 712 if (CI.getCodeGenOpts().CoverageMapping) { 713 CoverageInfo = new CoverageSourceInfo; 714 CI.getPreprocessor().addPPCallbacks( 715 std::unique_ptr<PPCallbacks>(CoverageInfo)); 716 } 717 std::unique_ptr<BackendConsumer> Result(new BackendConsumer( 718 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 719 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(), 720 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, 721 LinkModuleToUse, OS, *VMContext, CoverageInfo)); 722 BEConsumer = Result.get(); 723 return std::move(Result); 724 } 725 726 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM, 727 void *Context, 728 unsigned LocCookie) { 729 SM.print(nullptr, llvm::errs()); 730 } 731 732 void CodeGenAction::ExecuteAction() { 733 // If this is an IR file, we have to treat it specially. 734 if (getCurrentFileKind() == IK_LLVM_IR) { 735 BackendAction BA = static_cast<BackendAction>(Act); 736 CompilerInstance &CI = getCompilerInstance(); 737 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA); 738 if (BA != Backend_EmitNothing && !OS) 739 return; 740 741 bool Invalid; 742 SourceManager &SM = CI.getSourceManager(); 743 FileID FID = SM.getMainFileID(); 744 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid); 745 if (Invalid) 746 return; 747 748 llvm::SMDiagnostic Err; 749 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext); 750 if (!TheModule) { 751 // Translate from the diagnostic info to the SourceManager location if 752 // available. 753 // TODO: Unify this with ConvertBackendLocation() 754 SourceLocation Loc; 755 if (Err.getLineNo() > 0) { 756 assert(Err.getColumnNo() >= 0); 757 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID), 758 Err.getLineNo(), Err.getColumnNo() + 1); 759 } 760 761 // Strip off a leading diagnostic code if there is one. 762 StringRef Msg = Err.getMessage(); 763 if (Msg.startswith("error: ")) 764 Msg = Msg.substr(7); 765 766 unsigned DiagID = 767 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 768 769 CI.getDiagnostics().Report(Loc, DiagID) << Msg; 770 return; 771 } 772 const TargetOptions &TargetOpts = CI.getTargetOpts(); 773 if (TheModule->getTargetTriple() != TargetOpts.Triple) { 774 CI.getDiagnostics().Report(SourceLocation(), 775 diag::warn_fe_override_module) 776 << TargetOpts.Triple; 777 TheModule->setTargetTriple(TargetOpts.Triple); 778 } 779 780 LLVMContext &Ctx = TheModule->getContext(); 781 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler); 782 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts, 783 CI.getLangOpts(), CI.getTarget().getDataLayoutString(), 784 TheModule.get(), BA, OS); 785 return; 786 } 787 788 // Otherwise follow the normal AST path. 789 this->ASTFrontendAction::ExecuteAction(); 790 } 791 792 // 793 794 void EmitAssemblyAction::anchor() { } 795 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 796 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 797 798 void EmitBCAction::anchor() { } 799 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 800 : CodeGenAction(Backend_EmitBC, _VMContext) {} 801 802 void EmitLLVMAction::anchor() { } 803 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 804 : CodeGenAction(Backend_EmitLL, _VMContext) {} 805 806 void EmitLLVMOnlyAction::anchor() { } 807 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 808 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 809 810 void EmitCodeGenOnlyAction::anchor() { } 811 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 812 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 813 814 void EmitObjAction::anchor() { } 815 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 816 : CodeGenAction(Backend_EmitObj, _VMContext) {} 817