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