1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "CoverageMappingGen.h"
11 #include "clang/CodeGen/CodeGenAction.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclGroup.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/CodeGen/BackendUtil.h"
21 #include "clang/CodeGen/ModuleBuilder.h"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/Timer.h"
38 using namespace clang;
42 class BackendConsumer : public ASTConsumer {
43 virtual void anchor();
44 DiagnosticsEngine &Diags;
46 const CodeGenOptions &CodeGenOpts;
47 const TargetOptions &TargetOpts;
48 const LangOptions &LangOpts;
49 raw_ostream *AsmOutStream;
52 Timer LLVMIRGeneration;
54 std::unique_ptr<CodeGenerator> Gen;
56 std::unique_ptr<llvm::Module> TheModule, LinkModule;
59 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
60 const CodeGenOptions &compopts,
61 const TargetOptions &targetopts,
62 const LangOptions &langopts, bool TimePasses,
63 const std::string &infile, llvm::Module *LinkModule,
64 raw_ostream *OS, LLVMContext &C,
65 CoverageSourceInfo *CoverageInfo = nullptr)
66 : Diags(_Diags), Action(action), CodeGenOpts(compopts),
67 TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
68 Context(), LLVMIRGeneration("LLVM IR Generation Time"),
69 Gen(CreateLLVMCodeGen(Diags, infile, compopts,
70 targetopts, C, CoverageInfo)),
71 LinkModule(LinkModule) {
72 llvm::TimePassesIsEnabled = TimePasses;
75 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
76 llvm::Module *takeLinkModule() { return LinkModule.release(); }
78 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
79 Gen->HandleCXXStaticMemberVarInstantiation(VD);
82 void Initialize(ASTContext &Ctx) override {
85 if (llvm::TimePassesIsEnabled)
86 LLVMIRGeneration.startTimer();
90 TheModule.reset(Gen->GetModule());
92 if (llvm::TimePassesIsEnabled)
93 LLVMIRGeneration.stopTimer();
96 bool HandleTopLevelDecl(DeclGroupRef D) override {
97 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
98 Context->getSourceManager(),
99 "LLVM IR generation of declaration");
101 if (llvm::TimePassesIsEnabled)
102 LLVMIRGeneration.startTimer();
104 Gen->HandleTopLevelDecl(D);
106 if (llvm::TimePassesIsEnabled)
107 LLVMIRGeneration.stopTimer();
112 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
113 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
114 Context->getSourceManager(),
115 "LLVM IR generation of inline method");
116 if (llvm::TimePassesIsEnabled)
117 LLVMIRGeneration.startTimer();
119 Gen->HandleInlineMethodDefinition(D);
121 if (llvm::TimePassesIsEnabled)
122 LLVMIRGeneration.stopTimer();
125 void HandleTranslationUnit(ASTContext &C) override {
127 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
128 if (llvm::TimePassesIsEnabled)
129 LLVMIRGeneration.startTimer();
131 Gen->HandleTranslationUnit(C);
133 if (llvm::TimePassesIsEnabled)
134 LLVMIRGeneration.stopTimer();
137 // Silently ignore if we weren't initialized for some reason.
141 // Make sure IR generation is happy with the module. This is released by
142 // the module provider.
143 llvm::Module *M = Gen->ReleaseModule();
145 // The module has been released by IR gen on failures, do not double
151 assert(TheModule.get() == M &&
152 "Unexpected module change during IR generation");
154 // Link LinkModule into this module if present, preserving its validity.
156 LLVMContext &Ctx = LinkModule->getContext();
157 LLVMContext::DiagnosticHandlerTy OldHandler =
158 Ctx.getDiagnosticHandler();
159 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
160 Ctx.setDiagnosticHandler(linkerDiagnosticHandler, this);
162 Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource);
163 Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext);
168 // Install an inline asm handler so that diagnostics get printed through
169 // our diagnostics hooks.
170 LLVMContext &Ctx = TheModule->getContext();
171 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
172 Ctx.getInlineAsmDiagnosticHandler();
173 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
174 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
176 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
177 Ctx.getDiagnosticHandler();
178 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
179 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
181 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
182 C.getTargetInfo().getTargetDescription(),
183 TheModule.get(), Action, AsmOutStream);
185 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
187 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
190 void HandleTagDeclDefinition(TagDecl *D) override {
191 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
192 Context->getSourceManager(),
193 "LLVM IR generation of declaration");
194 Gen->HandleTagDeclDefinition(D);
197 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
198 Gen->HandleTagDeclRequiredDefinition(D);
201 void CompleteTentativeDefinition(VarDecl *D) override {
202 Gen->CompleteTentativeDefinition(D);
205 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
206 Gen->HandleVTable(RD, DefinitionRequired);
209 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
210 Gen->HandleLinkerOptionPragma(Opts);
213 void HandleDetectMismatch(llvm::StringRef Name,
214 llvm::StringRef Value) override {
215 Gen->HandleDetectMismatch(Name, Value);
218 void HandleDependentLibrary(llvm::StringRef Opts) override {
219 Gen->HandleDependentLibrary(Opts);
222 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
223 unsigned LocCookie) {
224 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
225 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
228 static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI,
230 ((BackendConsumer *)Context)->linkerDiagnosticHandlerImpl(DI);
233 void linkerDiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
235 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
237 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
240 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
241 SourceLocation LocCookie);
243 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
244 /// \brief Specialized handler for InlineAsm diagnostic.
245 /// \return True if the diagnostic has been successfully reported, false
247 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
248 /// \brief Specialized handler for StackSize diagnostic.
249 /// \return True if the diagnostic has been successfully reported, false
251 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
252 /// \brief Specialized handlers for optimization remarks.
253 /// Note that these handlers only accept remarks and they always handle
255 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
258 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
259 void OptimizationRemarkHandler(
260 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
261 void OptimizationRemarkHandler(
262 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
263 void OptimizationFailureHandler(
264 const llvm::DiagnosticInfoOptimizationFailure &D);
267 void BackendConsumer::anchor() {}
270 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
271 /// buffer to be a valid FullSourceLoc.
272 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
273 SourceManager &CSM) {
274 // Get both the clang and llvm source managers. The location is relative to
275 // a memory buffer that the LLVM Source Manager is handling, we need to add
276 // a copy to the Clang source manager.
277 const llvm::SourceMgr &LSM = *D.getSourceMgr();
279 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
280 // already owns its one and clang::SourceManager wants to own its one.
281 const MemoryBuffer *LBuf =
282 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
284 // Create the copy and transfer ownership to clang::SourceManager.
285 // TODO: Avoid copying files into memory.
286 std::unique_ptr<llvm::MemoryBuffer> CBuf =
287 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
288 LBuf->getBufferIdentifier());
289 // FIXME: Keep a file ID map instead of creating new IDs for each location.
290 FileID FID = CSM.createFileID(std::move(CBuf));
292 // Translate the offset into the file.
293 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
294 SourceLocation NewLoc =
295 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
296 return FullSourceLoc(NewLoc, CSM);
300 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
301 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
302 /// the temporary memory buffer that the inline asm parser has set up.
303 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
304 SourceLocation LocCookie) {
305 // There are a couple of different kinds of errors we could get here. First,
306 // we re-format the SMDiagnostic in terms of a clang diagnostic.
308 // Strip "error: " off the start of the message string.
309 StringRef Message = D.getMessage();
310 if (Message.startswith("error: "))
311 Message = Message.substr(7);
313 // If the SMDiagnostic has an inline asm source location, translate it.
315 if (D.getLoc() != SMLoc())
316 Loc = ConvertBackendLocation(D, Context->getSourceManager());
319 switch (D.getKind()) {
320 case llvm::SourceMgr::DK_Error:
321 DiagID = diag::err_fe_inline_asm;
323 case llvm::SourceMgr::DK_Warning:
324 DiagID = diag::warn_fe_inline_asm;
326 case llvm::SourceMgr::DK_Note:
327 DiagID = diag::note_fe_inline_asm;
330 // If this problem has clang-level source location information, report the
331 // issue in the source with a note showing the instantiated
333 if (LocCookie.isValid()) {
334 Diags.Report(LocCookie, DiagID).AddString(Message);
336 if (D.getLoc().isValid()) {
337 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
338 // Convert the SMDiagnostic ranges into SourceRange and attach them
339 // to the diagnostic.
340 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
341 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
342 unsigned Column = D.getColumnNo();
343 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
344 Loc.getLocWithOffset(Range.second - Column));
350 // Otherwise, report the backend issue as occurring in the generated .s file.
351 // If Loc is invalid, we still need to report the issue, it just gets no
353 Diags.Report(Loc, DiagID).AddString(Message);
356 #define ComputeDiagID(Severity, GroupName, DiagID) \
358 switch (Severity) { \
359 case llvm::DS_Error: \
360 DiagID = diag::err_fe_##GroupName; \
362 case llvm::DS_Warning: \
363 DiagID = diag::warn_fe_##GroupName; \
365 case llvm::DS_Remark: \
366 llvm_unreachable("'remark' severity not expected"); \
368 case llvm::DS_Note: \
369 DiagID = diag::note_fe_##GroupName; \
374 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
376 switch (Severity) { \
377 case llvm::DS_Error: \
378 DiagID = diag::err_fe_##GroupName; \
380 case llvm::DS_Warning: \
381 DiagID = diag::warn_fe_##GroupName; \
383 case llvm::DS_Remark: \
384 DiagID = diag::remark_fe_##GroupName; \
386 case llvm::DS_Note: \
387 DiagID = diag::note_fe_##GroupName; \
393 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
395 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
396 std::string Message = D.getMsgStr().str();
398 // If this problem has clang-level source location information, report the
399 // issue as being a problem in the source with a note showing the instantiated
401 SourceLocation LocCookie =
402 SourceLocation::getFromRawEncoding(D.getLocCookie());
403 if (LocCookie.isValid())
404 Diags.Report(LocCookie, DiagID).AddString(Message);
406 // Otherwise, report the backend diagnostic as occurring in the generated
408 // If Loc is invalid, we still need to report the diagnostic, it just gets
411 Diags.Report(Loc, DiagID).AddString(Message);
413 // We handled all the possible severities.
418 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
419 if (D.getSeverity() != llvm::DS_Warning)
420 // For now, the only support we have for StackSize diagnostic is warning.
421 // We do not know how to format other severities.
424 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
425 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
426 diag::warn_fe_frame_larger_than)
427 << D.getStackSize() << Decl::castToDeclContext(ND);
434 void BackendConsumer::EmitOptimizationMessage(
435 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
436 // We only support warnings and remarks.
437 assert(D.getSeverity() == llvm::DS_Remark ||
438 D.getSeverity() == llvm::DS_Warning);
440 SourceManager &SourceMgr = Context->getSourceManager();
441 FileManager &FileMgr = SourceMgr.getFileManager();
443 unsigned Line, Column;
444 D.getLocation(&Filename, &Line, &Column);
445 SourceLocation DILoc;
446 const FileEntry *FE = FileMgr.getFile(Filename);
447 if (FE && Line > 0) {
448 // If -gcolumn-info was not used, Column will be 0. This upsets the
449 // source manager, so pass 1 if Column is not set.
450 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
453 // If a location isn't available, try to approximate it using the associated
454 // function definition. We use the definition's right brace to differentiate
455 // from diagnostics that genuinely relate to the function itself.
456 FullSourceLoc Loc(DILoc, SourceMgr);
458 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
459 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
461 Diags.Report(Loc, DiagID)
462 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
465 if (DILoc.isInvalid())
466 // If we were not able to translate the file:line:col information
467 // back to a SourceLocation, at least emit a note stating that
468 // we could not translate this location. This can happen in the
469 // case of #line directives.
470 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
471 << Filename << Line << Column;
474 void BackendConsumer::OptimizationRemarkHandler(
475 const llvm::DiagnosticInfoOptimizationRemark &D) {
476 // Optimization remarks are active only if the -Rpass flag has a regular
477 // expression that matches the name of the pass name in \p D.
478 if (CodeGenOpts.OptimizationRemarkPattern &&
479 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
480 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
483 void BackendConsumer::OptimizationRemarkHandler(
484 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
485 // Missed optimization remarks are active only if the -Rpass-missed
486 // flag has a regular expression that matches the name of the pass
488 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
489 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
490 EmitOptimizationMessage(D,
491 diag::remark_fe_backend_optimization_remark_missed);
494 void BackendConsumer::OptimizationRemarkHandler(
495 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
496 // Optimization analysis remarks are active only if the -Rpass-analysis
497 // flag has a regular expression that matches the name of the pass
499 if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
500 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
501 EmitOptimizationMessage(
502 D, diag::remark_fe_backend_optimization_remark_analysis);
505 void BackendConsumer::OptimizationFailureHandler(
506 const llvm::DiagnosticInfoOptimizationFailure &D) {
507 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
510 void BackendConsumer::linkerDiagnosticHandlerImpl(const DiagnosticInfo &DI) {
511 if (DI.getSeverity() != DS_Error)
514 std::string MsgStorage;
516 raw_string_ostream Stream(MsgStorage);
517 DiagnosticPrinterRawOStream DP(Stream);
521 Diags.Report(diag::err_fe_cannot_link_module)
522 << LinkModule->getModuleIdentifier() << MsgStorage;
525 /// \brief This function is invoked when the backend needs
526 /// to report something to the user.
527 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
528 unsigned DiagID = diag::err_fe_inline_asm;
529 llvm::DiagnosticSeverity Severity = DI.getSeverity();
530 // Get the diagnostic ID based.
531 switch (DI.getKind()) {
532 case llvm::DK_InlineAsm:
533 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
535 ComputeDiagID(Severity, inline_asm, DiagID);
537 case llvm::DK_StackSize:
538 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
540 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
542 case llvm::DK_OptimizationRemark:
543 // Optimization remarks are always handled completely by this
544 // handler. There is no generic way of emitting them.
545 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
547 case llvm::DK_OptimizationRemarkMissed:
548 // Optimization remarks are always handled completely by this
549 // handler. There is no generic way of emitting them.
550 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
552 case llvm::DK_OptimizationRemarkAnalysis:
553 // Optimization remarks are always handled completely by this
554 // handler. There is no generic way of emitting them.
555 OptimizationRemarkHandler(
556 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
558 case llvm::DK_OptimizationFailure:
559 // Optimization failures are always handled completely by this
561 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
564 // Plugin IDs are not bound to any value as they are set dynamically.
565 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
568 std::string MsgStorage;
570 raw_string_ostream Stream(MsgStorage);
571 DiagnosticPrinterRawOStream DP(Stream);
575 // Report the backend message using the usual diagnostic mechanism.
577 Diags.Report(Loc, DiagID).AddString(MsgStorage);
581 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
582 : Act(_Act), LinkModule(nullptr),
583 VMContext(_VMContext ? _VMContext : new LLVMContext),
584 OwnsVMContext(!_VMContext) {}
586 CodeGenAction::~CodeGenAction() {
592 bool CodeGenAction::hasIRSupport() const { return true; }
594 void CodeGenAction::EndSourceFileAction() {
595 // If the consumer creation failed, do nothing.
596 if (!getCompilerInstance().hasASTConsumer())
599 // If we were given a link module, release consumer's ownership of it.
601 BEConsumer->takeLinkModule();
603 // Steal the module from the consumer.
604 TheModule = BEConsumer->takeModule();
607 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
608 return std::move(TheModule);
611 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
612 OwnsVMContext = false;
616 static raw_ostream *GetOutputStream(CompilerInstance &CI,
618 BackendAction Action) {
620 case Backend_EmitAssembly:
621 return CI.createDefaultOutputFile(false, InFile, "s");
623 return CI.createDefaultOutputFile(false, InFile, "ll");
625 return CI.createDefaultOutputFile(true, InFile, "bc");
626 case Backend_EmitNothing:
628 case Backend_EmitMCNull:
629 return CI.createNullOutputFile();
630 case Backend_EmitObj:
631 return CI.createDefaultOutputFile(true, InFile, "o");
634 llvm_unreachable("Invalid action!");
637 std::unique_ptr<ASTConsumer>
638 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
639 BackendAction BA = static_cast<BackendAction>(Act);
640 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
641 if (BA != Backend_EmitNothing && !OS)
644 llvm::Module *LinkModuleToUse = LinkModule;
646 // If we were not given a link module, and the user requested that one be
647 // loaded from bitcode, do so now.
648 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
649 if (!LinkModuleToUse && !LinkBCFile.empty()) {
650 std::string ErrorStr;
652 std::unique_ptr<llvm::MemoryBuffer> BCBuf =
653 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
655 CI.getDiagnostics().Report(diag::err_cannot_open_file)
656 << LinkBCFile << ErrorStr;
660 ErrorOr<llvm::Module *> ModuleOrErr =
661 getLazyBitcodeModule(std::move(BCBuf), *VMContext);
662 if (std::error_code EC = ModuleOrErr.getError()) {
663 CI.getDiagnostics().Report(diag::err_cannot_open_file)
664 << LinkBCFile << EC.message();
667 LinkModuleToUse = ModuleOrErr.get();
670 CoverageSourceInfo *CoverageInfo = nullptr;
671 // Add the preprocessor callback only when the coverage mapping is generated.
672 if (CI.getCodeGenOpts().CoverageMapping) {
673 CoverageInfo = new CoverageSourceInfo;
674 CI.getPreprocessor().addPPCallbacks(
675 std::unique_ptr<PPCallbacks>(CoverageInfo));
677 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
678 BA, CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(),
679 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
680 LinkModuleToUse, OS.release(), *VMContext, CoverageInfo));
681 BEConsumer = Result.get();
682 return std::move(Result);
685 void CodeGenAction::ExecuteAction() {
686 // If this is an IR file, we have to treat it specially.
687 if (getCurrentFileKind() == IK_LLVM_IR) {
688 BackendAction BA = static_cast<BackendAction>(Act);
689 CompilerInstance &CI = getCompilerInstance();
690 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
691 if (BA != Backend_EmitNothing && !OS)
695 SourceManager &SM = CI.getSourceManager();
696 FileID FID = SM.getMainFileID();
697 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
701 llvm::SMDiagnostic Err;
702 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
704 // Translate from the diagnostic info to the SourceManager location if
706 // TODO: Unify this with ConvertBackendLocation()
708 if (Err.getLineNo() > 0) {
709 assert(Err.getColumnNo() >= 0);
710 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
711 Err.getLineNo(), Err.getColumnNo() + 1);
714 // Strip off a leading diagnostic code if there is one.
715 StringRef Msg = Err.getMessage();
716 if (Msg.startswith("error: "))
720 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
722 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
725 const TargetOptions &TargetOpts = CI.getTargetOpts();
726 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
727 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
728 DiagnosticsEngine::Warning,
729 "overriding the module target triple with %0");
731 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
732 TheModule->setTargetTriple(TargetOpts.Triple);
735 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
736 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
737 TheModule.get(), BA, OS);
741 // Otherwise follow the normal AST path.
742 this->ASTFrontendAction::ExecuteAction();
747 void EmitAssemblyAction::anchor() { }
748 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
749 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
751 void EmitBCAction::anchor() { }
752 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
753 : CodeGenAction(Backend_EmitBC, _VMContext) {}
755 void EmitLLVMAction::anchor() { }
756 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
757 : CodeGenAction(Backend_EmitLL, _VMContext) {}
759 void EmitLLVMOnlyAction::anchor() { }
760 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
761 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
763 void EmitCodeGenOnlyAction::anchor() { }
764 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
765 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
767 void EmitObjAction::anchor() { }
768 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
769 : CodeGenAction(Backend_EmitObj, _VMContext) {}