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