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