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 OptimizationFailureHandler( 250 const llvm::DiagnosticInfoOptimizationFailure &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 Diags.Report(Loc, DiagID) 448 << AddFlagValue(D.getPassName() ? D.getPassName() : "") 449 << D.getMsg().str(); 450 451 if (DILoc.isInvalid()) 452 // If we were not able to translate the file:line:col information 453 // back to a SourceLocation, at least emit a note stating that 454 // we could not translate this location. This can happen in the 455 // case of #line directives. 456 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc) 457 << Filename << Line << Column; 458 } 459 460 void BackendConsumer::OptimizationRemarkHandler( 461 const llvm::DiagnosticInfoOptimizationRemark &D) { 462 // Optimization remarks are active only if the -Rpass flag has a regular 463 // expression that matches the name of the pass name in \p D. 464 if (CodeGenOpts.OptimizationRemarkPattern && 465 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) 466 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark); 467 } 468 469 void BackendConsumer::OptimizationRemarkHandler( 470 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) { 471 // Missed optimization remarks are active only if the -Rpass-missed 472 // flag has a regular expression that matches the name of the pass 473 // name in \p D. 474 if (CodeGenOpts.OptimizationRemarkMissedPattern && 475 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName())) 476 EmitOptimizationMessage(D, 477 diag::remark_fe_backend_optimization_remark_missed); 478 } 479 480 void BackendConsumer::OptimizationRemarkHandler( 481 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) { 482 // Optimization analysis remarks are active only if the -Rpass-analysis 483 // flag has a regular expression that matches the name of the pass 484 // name in \p D. 485 if (CodeGenOpts.OptimizationRemarkAnalysisPattern && 486 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())) 487 EmitOptimizationMessage( 488 D, diag::remark_fe_backend_optimization_remark_analysis); 489 } 490 491 void BackendConsumer::OptimizationFailureHandler( 492 const llvm::DiagnosticInfoOptimizationFailure &D) { 493 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure); 494 } 495 496 /// \brief This function is invoked when the backend needs 497 /// to report something to the user. 498 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) { 499 unsigned DiagID = diag::err_fe_inline_asm; 500 llvm::DiagnosticSeverity Severity = DI.getSeverity(); 501 // Get the diagnostic ID based. 502 switch (DI.getKind()) { 503 case llvm::DK_InlineAsm: 504 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI))) 505 return; 506 ComputeDiagID(Severity, inline_asm, DiagID); 507 break; 508 case llvm::DK_StackSize: 509 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI))) 510 return; 511 ComputeDiagID(Severity, backend_frame_larger_than, DiagID); 512 break; 513 case llvm::DK_OptimizationRemark: 514 // Optimization remarks are always handled completely by this 515 // handler. There is no generic way of emitting them. 516 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI)); 517 return; 518 case llvm::DK_OptimizationRemarkMissed: 519 // Optimization remarks are always handled completely by this 520 // handler. There is no generic way of emitting them. 521 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI)); 522 return; 523 case llvm::DK_OptimizationRemarkAnalysis: 524 // Optimization remarks are always handled completely by this 525 // handler. There is no generic way of emitting them. 526 OptimizationRemarkHandler( 527 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI)); 528 return; 529 case llvm::DK_OptimizationFailure: 530 // Optimization failures are always handled completely by this 531 // handler. 532 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI)); 533 return; 534 default: 535 // Plugin IDs are not bound to any value as they are set dynamically. 536 ComputeDiagRemarkID(Severity, backend_plugin, DiagID); 537 break; 538 } 539 std::string MsgStorage; 540 { 541 raw_string_ostream Stream(MsgStorage); 542 DiagnosticPrinterRawOStream DP(Stream); 543 DI.print(DP); 544 } 545 546 // Report the backend message using the usual diagnostic mechanism. 547 FullSourceLoc Loc; 548 Diags.Report(Loc, DiagID).AddString(MsgStorage); 549 } 550 #undef ComputeDiagID 551 552 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 553 : Act(_Act), LinkModule(nullptr), 554 VMContext(_VMContext ? _VMContext : new LLVMContext), 555 OwnsVMContext(!_VMContext) {} 556 557 CodeGenAction::~CodeGenAction() { 558 TheModule.reset(); 559 if (OwnsVMContext) 560 delete VMContext; 561 } 562 563 bool CodeGenAction::hasIRSupport() const { return true; } 564 565 void CodeGenAction::EndSourceFileAction() { 566 // If the consumer creation failed, do nothing. 567 if (!getCompilerInstance().hasASTConsumer()) 568 return; 569 570 // If we were given a link module, release consumer's ownership of it. 571 if (LinkModule) 572 BEConsumer->takeLinkModule(); 573 574 // Steal the module from the consumer. 575 TheModule.reset(BEConsumer->takeModule()); 576 } 577 578 llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); } 579 580 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 581 OwnsVMContext = false; 582 return VMContext; 583 } 584 585 static raw_ostream *GetOutputStream(CompilerInstance &CI, 586 StringRef InFile, 587 BackendAction Action) { 588 switch (Action) { 589 case Backend_EmitAssembly: 590 return CI.createDefaultOutputFile(false, InFile, "s"); 591 case Backend_EmitLL: 592 return CI.createDefaultOutputFile(false, InFile, "ll"); 593 case Backend_EmitBC: 594 return CI.createDefaultOutputFile(true, InFile, "bc"); 595 case Backend_EmitNothing: 596 return nullptr; 597 case Backend_EmitMCNull: 598 return CI.createNullOutputFile(); 599 case Backend_EmitObj: 600 return CI.createDefaultOutputFile(true, InFile, "o"); 601 } 602 603 llvm_unreachable("Invalid action!"); 604 } 605 606 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI, 607 StringRef InFile) { 608 BackendAction BA = static_cast<BackendAction>(Act); 609 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA)); 610 if (BA != Backend_EmitNothing && !OS) 611 return nullptr; 612 613 llvm::Module *LinkModuleToUse = LinkModule; 614 615 // If we were not given a link module, and the user requested that one be 616 // loaded from bitcode, do so now. 617 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile; 618 if (!LinkModuleToUse && !LinkBCFile.empty()) { 619 std::string ErrorStr; 620 621 llvm::MemoryBuffer *BCBuf = 622 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr); 623 if (!BCBuf) { 624 CI.getDiagnostics().Report(diag::err_cannot_open_file) 625 << LinkBCFile << ErrorStr; 626 return nullptr; 627 } 628 629 ErrorOr<llvm::Module *> ModuleOrErr = 630 getLazyBitcodeModule(BCBuf, *VMContext); 631 if (std::error_code EC = ModuleOrErr.getError()) { 632 CI.getDiagnostics().Report(diag::err_cannot_open_file) 633 << LinkBCFile << EC.message(); 634 return nullptr; 635 } 636 LinkModuleToUse = ModuleOrErr.get(); 637 } 638 639 BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(), 640 CI.getTargetOpts(), CI.getLangOpts(), 641 CI.getFrontendOpts().ShowTimers, InFile, 642 LinkModuleToUse, OS.release(), *VMContext); 643 return BEConsumer; 644 } 645 646 void CodeGenAction::ExecuteAction() { 647 // If this is an IR file, we have to treat it specially. 648 if (getCurrentFileKind() == IK_LLVM_IR) { 649 BackendAction BA = static_cast<BackendAction>(Act); 650 CompilerInstance &CI = getCompilerInstance(); 651 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA); 652 if (BA != Backend_EmitNothing && !OS) 653 return; 654 655 bool Invalid; 656 SourceManager &SM = CI.getSourceManager(); 657 FileID FID = SM.getMainFileID(); 658 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid); 659 if (Invalid) 660 return; 661 662 llvm::SMDiagnostic Err; 663 TheModule.reset(ParseIR(MainFile, Err, *VMContext)); 664 if (!TheModule) { 665 // Translate from the diagnostic info to the SourceManager location if 666 // available. 667 // TODO: Unify this with ConvertBackendLocation() 668 SourceLocation Loc; 669 if (Err.getLineNo() > 0) { 670 assert(Err.getColumnNo() >= 0); 671 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID), 672 Err.getLineNo(), Err.getColumnNo() + 1); 673 } 674 675 // Strip off a leading diagnostic code if there is one. 676 StringRef Msg = Err.getMessage(); 677 if (Msg.startswith("error: ")) 678 Msg = Msg.substr(7); 679 680 unsigned DiagID = 681 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 682 683 CI.getDiagnostics().Report(Loc, DiagID) << Msg; 684 return; 685 } 686 const TargetOptions &TargetOpts = CI.getTargetOpts(); 687 if (TheModule->getTargetTriple() != TargetOpts.Triple) { 688 unsigned DiagID = CI.getDiagnostics().getCustomDiagID( 689 DiagnosticsEngine::Warning, 690 "overriding the module target triple with %0"); 691 692 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple; 693 TheModule->setTargetTriple(TargetOpts.Triple); 694 } 695 696 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts, 697 CI.getLangOpts(), CI.getTarget().getTargetDescription(), 698 TheModule.get(), BA, OS); 699 return; 700 } 701 702 // Otherwise follow the normal AST path. 703 this->ASTFrontendAction::ExecuteAction(); 704 } 705 706 // 707 708 void EmitAssemblyAction::anchor() { } 709 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 710 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 711 712 void EmitBCAction::anchor() { } 713 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 714 : CodeGenAction(Backend_EmitBC, _VMContext) {} 715 716 void EmitLLVMAction::anchor() { } 717 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 718 : CodeGenAction(Backend_EmitLL, _VMContext) {} 719 720 void EmitLLVMOnlyAction::anchor() { } 721 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 722 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 723 724 void EmitCodeGenOnlyAction::anchor() { } 725 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 726 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 727 728 void EmitObjAction::anchor() { } 729 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 730 : CodeGenAction(Backend_EmitObj, _VMContext) {} 731