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 llvm::Module *takeModule() { return TheModule.release(); }
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 std::string ErrorMsg;
157 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
159 Diags.Report(diag::err_fe_cannot_link_module)
160 << LinkModule->getModuleIdentifier() << ErrorMsg;
165 // Install an inline asm handler so that diagnostics get printed through
166 // our diagnostics hooks.
167 LLVMContext &Ctx = TheModule->getContext();
168 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
169 Ctx.getInlineAsmDiagnosticHandler();
170 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
171 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
173 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
174 Ctx.getDiagnosticHandler();
175 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
176 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
178 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
179 C.getTargetInfo().getTargetDescription(),
180 TheModule.get(), Action, AsmOutStream);
182 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
184 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
187 void HandleTagDeclDefinition(TagDecl *D) override {
188 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
189 Context->getSourceManager(),
190 "LLVM IR generation of declaration");
191 Gen->HandleTagDeclDefinition(D);
194 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
195 Gen->HandleTagDeclRequiredDefinition(D);
198 void CompleteTentativeDefinition(VarDecl *D) override {
199 Gen->CompleteTentativeDefinition(D);
202 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
203 Gen->HandleVTable(RD, DefinitionRequired);
206 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
207 Gen->HandleLinkerOptionPragma(Opts);
210 void HandleDetectMismatch(llvm::StringRef Name,
211 llvm::StringRef Value) override {
212 Gen->HandleDetectMismatch(Name, Value);
215 void HandleDependentLibrary(llvm::StringRef Opts) override {
216 Gen->HandleDependentLibrary(Opts);
219 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
220 unsigned LocCookie) {
221 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
222 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
225 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
227 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
230 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
231 SourceLocation LocCookie);
233 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
234 /// \brief Specialized handler for InlineAsm diagnostic.
235 /// \return True if the diagnostic has been successfully reported, false
237 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
238 /// \brief Specialized handler for StackSize diagnostic.
239 /// \return True if the diagnostic has been successfully reported, false
241 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
242 /// \brief Specialized handlers for optimization remarks.
243 /// Note that these handlers only accept remarks and they always handle
245 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
248 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
249 void OptimizationRemarkHandler(
250 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
251 void OptimizationRemarkHandler(
252 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
253 void OptimizationFailureHandler(
254 const llvm::DiagnosticInfoOptimizationFailure &D);
257 void BackendConsumer::anchor() {}
260 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
261 /// buffer to be a valid FullSourceLoc.
262 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
263 SourceManager &CSM) {
264 // Get both the clang and llvm source managers. The location is relative to
265 // a memory buffer that the LLVM Source Manager is handling, we need to add
266 // a copy to the Clang source manager.
267 const llvm::SourceMgr &LSM = *D.getSourceMgr();
269 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
270 // already owns its one and clang::SourceManager wants to own its one.
271 const MemoryBuffer *LBuf =
272 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
274 // Create the copy and transfer ownership to clang::SourceManager.
275 // TODO: Avoid copying files into memory.
276 llvm::MemoryBuffer *CBuf =
277 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
278 LBuf->getBufferIdentifier());
279 // FIXME: Keep a file ID map instead of creating new IDs for each location.
280 FileID FID = CSM.createFileID(CBuf);
282 // Translate the offset into the file.
283 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
284 SourceLocation NewLoc =
285 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
286 return FullSourceLoc(NewLoc, CSM);
290 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
291 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
292 /// the temporary memory buffer that the inline asm parser has set up.
293 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
294 SourceLocation LocCookie) {
295 // There are a couple of different kinds of errors we could get here. First,
296 // we re-format the SMDiagnostic in terms of a clang diagnostic.
298 // Strip "error: " off the start of the message string.
299 StringRef Message = D.getMessage();
300 if (Message.startswith("error: "))
301 Message = Message.substr(7);
303 // If the SMDiagnostic has an inline asm source location, translate it.
305 if (D.getLoc() != SMLoc())
306 Loc = ConvertBackendLocation(D, Context->getSourceManager());
309 switch (D.getKind()) {
310 case llvm::SourceMgr::DK_Error:
311 DiagID = diag::err_fe_inline_asm;
313 case llvm::SourceMgr::DK_Warning:
314 DiagID = diag::warn_fe_inline_asm;
316 case llvm::SourceMgr::DK_Note:
317 DiagID = diag::note_fe_inline_asm;
320 // If this problem has clang-level source location information, report the
321 // issue in the source with a note showing the instantiated
323 if (LocCookie.isValid()) {
324 Diags.Report(LocCookie, DiagID).AddString(Message);
326 if (D.getLoc().isValid()) {
327 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
328 // Convert the SMDiagnostic ranges into SourceRange and attach them
329 // to the diagnostic.
330 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
331 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
332 unsigned Column = D.getColumnNo();
333 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
334 Loc.getLocWithOffset(Range.second - Column));
340 // Otherwise, report the backend issue as occurring in the generated .s file.
341 // If Loc is invalid, we still need to report the issue, it just gets no
343 Diags.Report(Loc, DiagID).AddString(Message);
346 #define ComputeDiagID(Severity, GroupName, DiagID) \
348 switch (Severity) { \
349 case llvm::DS_Error: \
350 DiagID = diag::err_fe_##GroupName; \
352 case llvm::DS_Warning: \
353 DiagID = diag::warn_fe_##GroupName; \
355 case llvm::DS_Remark: \
356 llvm_unreachable("'remark' severity not expected"); \
358 case llvm::DS_Note: \
359 DiagID = diag::note_fe_##GroupName; \
364 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
366 switch (Severity) { \
367 case llvm::DS_Error: \
368 DiagID = diag::err_fe_##GroupName; \
370 case llvm::DS_Warning: \
371 DiagID = diag::warn_fe_##GroupName; \
373 case llvm::DS_Remark: \
374 DiagID = diag::remark_fe_##GroupName; \
376 case llvm::DS_Note: \
377 DiagID = diag::note_fe_##GroupName; \
383 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
385 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
386 std::string Message = D.getMsgStr().str();
388 // If this problem has clang-level source location information, report the
389 // issue as being a problem in the source with a note showing the instantiated
391 SourceLocation LocCookie =
392 SourceLocation::getFromRawEncoding(D.getLocCookie());
393 if (LocCookie.isValid())
394 Diags.Report(LocCookie, DiagID).AddString(Message);
396 // Otherwise, report the backend diagnostic as occurring in the generated
398 // If Loc is invalid, we still need to report the diagnostic, it just gets
401 Diags.Report(Loc, DiagID).AddString(Message);
403 // We handled all the possible severities.
408 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
409 if (D.getSeverity() != llvm::DS_Warning)
410 // For now, the only support we have for StackSize diagnostic is warning.
411 // We do not know how to format other severities.
414 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
415 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
416 diag::warn_fe_frame_larger_than)
417 << D.getStackSize() << Decl::castToDeclContext(ND);
424 void BackendConsumer::EmitOptimizationMessage(
425 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
426 // We only support warnings and remarks.
427 assert(D.getSeverity() == llvm::DS_Remark ||
428 D.getSeverity() == llvm::DS_Warning);
430 SourceManager &SourceMgr = Context->getSourceManager();
431 FileManager &FileMgr = SourceMgr.getFileManager();
433 unsigned Line, Column;
434 D.getLocation(&Filename, &Line, &Column);
435 SourceLocation DILoc;
436 const FileEntry *FE = FileMgr.getFile(Filename);
437 if (FE && Line > 0) {
438 // If -gcolumn-info was not used, Column will be 0. This upsets the
439 // source manager, so pass 1 if Column is not set.
440 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
443 // If a location isn't available, try to approximate it using the associated
444 // function definition. We use the definition's right brace to differentiate
445 // from diagnostics that genuinely relate to the function itself.
446 FullSourceLoc Loc(DILoc, SourceMgr);
448 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
449 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
451 Diags.Report(Loc, DiagID)
452 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
455 if (DILoc.isInvalid())
456 // If we were not able to translate the file:line:col information
457 // back to a SourceLocation, at least emit a note stating that
458 // we could not translate this location. This can happen in the
459 // case of #line directives.
460 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
461 << Filename << Line << Column;
464 void BackendConsumer::OptimizationRemarkHandler(
465 const llvm::DiagnosticInfoOptimizationRemark &D) {
466 // Optimization remarks are active only if the -Rpass flag has a regular
467 // expression that matches the name of the pass name in \p D.
468 if (CodeGenOpts.OptimizationRemarkPattern &&
469 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
470 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
473 void BackendConsumer::OptimizationRemarkHandler(
474 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
475 // Missed optimization remarks are active only if the -Rpass-missed
476 // flag has a regular expression that matches the name of the pass
478 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
479 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
480 EmitOptimizationMessage(D,
481 diag::remark_fe_backend_optimization_remark_missed);
484 void BackendConsumer::OptimizationRemarkHandler(
485 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
486 // Optimization analysis remarks are active only if the -Rpass-analysis
487 // flag has a regular expression that matches the name of the pass
489 if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
490 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
491 EmitOptimizationMessage(
492 D, diag::remark_fe_backend_optimization_remark_analysis);
495 void BackendConsumer::OptimizationFailureHandler(
496 const llvm::DiagnosticInfoOptimizationFailure &D) {
497 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
500 /// \brief This function is invoked when the backend needs
501 /// to report something to the user.
502 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
503 unsigned DiagID = diag::err_fe_inline_asm;
504 llvm::DiagnosticSeverity Severity = DI.getSeverity();
505 // Get the diagnostic ID based.
506 switch (DI.getKind()) {
507 case llvm::DK_InlineAsm:
508 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
510 ComputeDiagID(Severity, inline_asm, DiagID);
512 case llvm::DK_StackSize:
513 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
515 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
517 case llvm::DK_OptimizationRemark:
518 // Optimization remarks are always handled completely by this
519 // handler. There is no generic way of emitting them.
520 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
522 case llvm::DK_OptimizationRemarkMissed:
523 // Optimization remarks are always handled completely by this
524 // handler. There is no generic way of emitting them.
525 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
527 case llvm::DK_OptimizationRemarkAnalysis:
528 // Optimization remarks are always handled completely by this
529 // handler. There is no generic way of emitting them.
530 OptimizationRemarkHandler(
531 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
533 case llvm::DK_OptimizationFailure:
534 // Optimization failures are always handled completely by this
536 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
539 // Plugin IDs are not bound to any value as they are set dynamically.
540 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
543 std::string MsgStorage;
545 raw_string_ostream Stream(MsgStorage);
546 DiagnosticPrinterRawOStream DP(Stream);
550 // Report the backend message using the usual diagnostic mechanism.
552 Diags.Report(Loc, DiagID).AddString(MsgStorage);
556 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
557 : Act(_Act), LinkModule(nullptr),
558 VMContext(_VMContext ? _VMContext : new LLVMContext),
559 OwnsVMContext(!_VMContext) {}
561 CodeGenAction::~CodeGenAction() {
567 bool CodeGenAction::hasIRSupport() const { return true; }
569 void CodeGenAction::EndSourceFileAction() {
570 // If the consumer creation failed, do nothing.
571 if (!getCompilerInstance().hasASTConsumer())
574 // If we were given a link module, release consumer's ownership of it.
576 BEConsumer->takeLinkModule();
578 // Steal the module from the consumer.
579 TheModule.reset(BEConsumer->takeModule());
582 llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
584 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
585 OwnsVMContext = false;
589 static raw_ostream *GetOutputStream(CompilerInstance &CI,
591 BackendAction Action) {
593 case Backend_EmitAssembly:
594 return CI.createDefaultOutputFile(false, InFile, "s");
596 return CI.createDefaultOutputFile(false, InFile, "ll");
598 return CI.createDefaultOutputFile(true, InFile, "bc");
599 case Backend_EmitNothing:
601 case Backend_EmitMCNull:
602 return CI.createNullOutputFile();
603 case Backend_EmitObj:
604 return CI.createDefaultOutputFile(true, InFile, "o");
607 llvm_unreachable("Invalid action!");
610 std::unique_ptr<ASTConsumer>
611 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
612 BackendAction BA = static_cast<BackendAction>(Act);
613 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
614 if (BA != Backend_EmitNothing && !OS)
617 llvm::Module *LinkModuleToUse = LinkModule;
619 // If we were not given a link module, and the user requested that one be
620 // loaded from bitcode, do so now.
621 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
622 if (!LinkModuleToUse && !LinkBCFile.empty()) {
623 std::string ErrorStr;
625 llvm::MemoryBuffer *BCBuf =
626 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
628 CI.getDiagnostics().Report(diag::err_cannot_open_file)
629 << LinkBCFile << ErrorStr;
633 ErrorOr<llvm::Module *> ModuleOrErr =
634 getLazyBitcodeModule(BCBuf, *VMContext);
635 if (std::error_code EC = ModuleOrErr.getError()) {
636 CI.getDiagnostics().Report(diag::err_cannot_open_file)
637 << LinkBCFile << EC.message();
640 LinkModuleToUse = ModuleOrErr.get();
643 CoverageSourceInfo *CoverageInfo = nullptr;
644 // Add the preprocessor callback only when the coverage mapping is generated.
645 if (CI.getCodeGenOpts().CoverageMapping) {
646 CoverageInfo = new CoverageSourceInfo;
647 CI.getPreprocessor().addPPCallbacks(CoverageInfo);
649 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
650 BA, CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(),
651 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
652 LinkModuleToUse, OS.release(), *VMContext, CoverageInfo));
653 BEConsumer = Result.get();
654 return std::move(Result);
657 void CodeGenAction::ExecuteAction() {
658 // If this is an IR file, we have to treat it specially.
659 if (getCurrentFileKind() == IK_LLVM_IR) {
660 BackendAction BA = static_cast<BackendAction>(Act);
661 CompilerInstance &CI = getCompilerInstance();
662 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
663 if (BA != Backend_EmitNothing && !OS)
667 SourceManager &SM = CI.getSourceManager();
668 FileID FID = SM.getMainFileID();
669 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
673 llvm::SMDiagnostic Err;
674 TheModule.reset(ParseIR(MainFile, Err, *VMContext));
676 // Translate from the diagnostic info to the SourceManager location if
678 // TODO: Unify this with ConvertBackendLocation()
680 if (Err.getLineNo() > 0) {
681 assert(Err.getColumnNo() >= 0);
682 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
683 Err.getLineNo(), Err.getColumnNo() + 1);
686 // Strip off a leading diagnostic code if there is one.
687 StringRef Msg = Err.getMessage();
688 if (Msg.startswith("error: "))
692 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
694 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
697 const TargetOptions &TargetOpts = CI.getTargetOpts();
698 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
699 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
700 DiagnosticsEngine::Warning,
701 "overriding the module target triple with %0");
703 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
704 TheModule->setTargetTriple(TargetOpts.Triple);
707 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
708 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
709 TheModule.get(), BA, OS);
713 // Otherwise follow the normal AST path.
714 this->ASTFrontendAction::ExecuteAction();
719 void EmitAssemblyAction::anchor() { }
720 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
721 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
723 void EmitBCAction::anchor() { }
724 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
725 : CodeGenAction(Backend_EmitBC, _VMContext) {}
727 void EmitLLVMAction::anchor() { }
728 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
729 : CodeGenAction(Backend_EmitLL, _VMContext) {}
731 void EmitLLVMOnlyAction::anchor() { }
732 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
733 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
735 void EmitCodeGenOnlyAction::anchor() { }
736 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
737 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
739 void EmitObjAction::anchor() { }
740 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
741 : CodeGenAction(Backend_EmitObj, _VMContext) {}