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/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclGroup.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/CodeGen/BackendUtil.h"
19 #include "clang/CodeGen/CodeGenAction.h"
20 #include "clang/CodeGen/ModuleBuilder.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "llvm/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_pwrite_stream *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 HeaderSearchOptions &HeaderSearchOpts,
61 const PreprocessorOptions &PPOpts,
62 const CodeGenOptions &CodeGenOpts,
63 const TargetOptions &TargetOpts,
64 const LangOptions &LangOpts, bool TimePasses,
65 const std::string &InFile, llvm::Module *LinkModule,
66 raw_pwrite_stream *OS, LLVMContext &C,
67 CoverageSourceInfo *CoverageInfo = nullptr)
68 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
69 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
70 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
71 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
72 CodeGenOpts, C, CoverageInfo)),
73 LinkModule(LinkModule) {
74 llvm::TimePassesIsEnabled = TimePasses;
77 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
78 llvm::Module *takeLinkModule() { return LinkModule.release(); }
80 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
81 Gen->HandleCXXStaticMemberVarInstantiation(VD);
84 void Initialize(ASTContext &Ctx) override {
86 assert(Context == &Ctx);
92 if (llvm::TimePassesIsEnabled)
93 LLVMIRGeneration.startTimer();
97 TheModule.reset(Gen->GetModule());
99 if (llvm::TimePassesIsEnabled)
100 LLVMIRGeneration.stopTimer();
103 bool HandleTopLevelDecl(DeclGroupRef D) override {
104 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
105 Context->getSourceManager(),
106 "LLVM IR generation of declaration");
108 if (llvm::TimePassesIsEnabled)
109 LLVMIRGeneration.startTimer();
111 Gen->HandleTopLevelDecl(D);
113 if (llvm::TimePassesIsEnabled)
114 LLVMIRGeneration.stopTimer();
119 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
120 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
121 Context->getSourceManager(),
122 "LLVM IR generation of inline method");
123 if (llvm::TimePassesIsEnabled)
124 LLVMIRGeneration.startTimer();
126 Gen->HandleInlineMethodDefinition(D);
128 if (llvm::TimePassesIsEnabled)
129 LLVMIRGeneration.stopTimer();
132 void HandleTranslationUnit(ASTContext &C) override {
134 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
135 if (llvm::TimePassesIsEnabled)
136 LLVMIRGeneration.startTimer();
138 Gen->HandleTranslationUnit(C);
140 if (llvm::TimePassesIsEnabled)
141 LLVMIRGeneration.stopTimer();
144 // Silently ignore if we weren't initialized for some reason.
148 // Make sure IR generation is happy with the module. This is released by
149 // the module provider.
150 llvm::Module *M = Gen->ReleaseModule();
152 // The module has been released by IR gen on failures, do not double
158 assert(TheModule.get() == M &&
159 "Unexpected module change during IR generation");
161 // Link LinkModule into this module if present, preserving its validity.
163 if (Linker::LinkModules(
165 [=](const DiagnosticInfo &DI) { linkerDiagnosticHandler(DI); }))
169 // Install an inline asm handler so that diagnostics get printed through
170 // our diagnostics hooks.
171 LLVMContext &Ctx = TheModule->getContext();
172 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
173 Ctx.getInlineAsmDiagnosticHandler();
174 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
175 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
177 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
178 Ctx.getDiagnosticHandler();
179 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
180 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
182 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
183 C.getTargetInfo().getTargetDescription(),
184 TheModule.get(), Action, AsmOutStream);
186 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
188 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
191 void HandleTagDeclDefinition(TagDecl *D) override {
192 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
193 Context->getSourceManager(),
194 "LLVM IR generation of declaration");
195 Gen->HandleTagDeclDefinition(D);
198 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
199 Gen->HandleTagDeclRequiredDefinition(D);
202 void CompleteTentativeDefinition(VarDecl *D) override {
203 Gen->CompleteTentativeDefinition(D);
206 void HandleVTable(CXXRecordDecl *RD) override {
207 Gen->HandleVTable(RD);
210 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
211 Gen->HandleLinkerOptionPragma(Opts);
214 void HandleDetectMismatch(llvm::StringRef Name,
215 llvm::StringRef Value) override {
216 Gen->HandleDetectMismatch(Name, Value);
219 void HandleDependentLibrary(llvm::StringRef Opts) override {
220 Gen->HandleDependentLibrary(Opts);
223 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
224 unsigned LocCookie) {
225 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
226 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
229 void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI);
231 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
233 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
236 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
237 SourceLocation LocCookie);
239 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
240 /// \brief Specialized handler for InlineAsm diagnostic.
241 /// \return True if the diagnostic has been successfully reported, false
243 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
244 /// \brief Specialized handler for StackSize diagnostic.
245 /// \return True if the diagnostic has been successfully reported, false
247 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
248 /// \brief Specialized handlers for optimization remarks.
249 /// Note that these handlers only accept remarks and they always handle
251 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
254 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
255 void OptimizationRemarkHandler(
256 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
257 void OptimizationRemarkHandler(
258 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
259 void OptimizationFailureHandler(
260 const llvm::DiagnosticInfoOptimizationFailure &D);
263 void BackendConsumer::anchor() {}
266 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
267 /// buffer to be a valid FullSourceLoc.
268 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
269 SourceManager &CSM) {
270 // Get both the clang and llvm source managers. The location is relative to
271 // a memory buffer that the LLVM Source Manager is handling, we need to add
272 // a copy to the Clang source manager.
273 const llvm::SourceMgr &LSM = *D.getSourceMgr();
275 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
276 // already owns its one and clang::SourceManager wants to own its one.
277 const MemoryBuffer *LBuf =
278 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
280 // Create the copy and transfer ownership to clang::SourceManager.
281 // TODO: Avoid copying files into memory.
282 std::unique_ptr<llvm::MemoryBuffer> CBuf =
283 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
284 LBuf->getBufferIdentifier());
285 // FIXME: Keep a file ID map instead of creating new IDs for each location.
286 FileID FID = CSM.createFileID(std::move(CBuf));
288 // Translate the offset into the file.
289 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
290 SourceLocation NewLoc =
291 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
292 return FullSourceLoc(NewLoc, CSM);
296 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
297 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
298 /// the temporary memory buffer that the inline asm parser has set up.
299 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
300 SourceLocation LocCookie) {
301 // There are a couple of different kinds of errors we could get here. First,
302 // we re-format the SMDiagnostic in terms of a clang diagnostic.
304 // Strip "error: " off the start of the message string.
305 StringRef Message = D.getMessage();
306 if (Message.startswith("error: "))
307 Message = Message.substr(7);
309 // If the SMDiagnostic has an inline asm source location, translate it.
311 if (D.getLoc() != SMLoc())
312 Loc = ConvertBackendLocation(D, Context->getSourceManager());
315 switch (D.getKind()) {
316 case llvm::SourceMgr::DK_Error:
317 DiagID = diag::err_fe_inline_asm;
319 case llvm::SourceMgr::DK_Warning:
320 DiagID = diag::warn_fe_inline_asm;
322 case llvm::SourceMgr::DK_Note:
323 DiagID = diag::note_fe_inline_asm;
326 // If this problem has clang-level source location information, report the
327 // issue in the source with a note showing the instantiated
329 if (LocCookie.isValid()) {
330 Diags.Report(LocCookie, DiagID).AddString(Message);
332 if (D.getLoc().isValid()) {
333 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
334 // Convert the SMDiagnostic ranges into SourceRange and attach them
335 // to the diagnostic.
336 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
337 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
338 unsigned Column = D.getColumnNo();
339 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
340 Loc.getLocWithOffset(Range.second - Column));
346 // Otherwise, report the backend issue as occurring in the generated .s file.
347 // If Loc is invalid, we still need to report the issue, it just gets no
349 Diags.Report(Loc, DiagID).AddString(Message);
352 #define ComputeDiagID(Severity, GroupName, DiagID) \
354 switch (Severity) { \
355 case llvm::DS_Error: \
356 DiagID = diag::err_fe_##GroupName; \
358 case llvm::DS_Warning: \
359 DiagID = diag::warn_fe_##GroupName; \
361 case llvm::DS_Remark: \
362 llvm_unreachable("'remark' severity not expected"); \
364 case llvm::DS_Note: \
365 DiagID = diag::note_fe_##GroupName; \
370 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
372 switch (Severity) { \
373 case llvm::DS_Error: \
374 DiagID = diag::err_fe_##GroupName; \
376 case llvm::DS_Warning: \
377 DiagID = diag::warn_fe_##GroupName; \
379 case llvm::DS_Remark: \
380 DiagID = diag::remark_fe_##GroupName; \
382 case llvm::DS_Note: \
383 DiagID = diag::note_fe_##GroupName; \
389 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
391 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
392 std::string Message = D.getMsgStr().str();
394 // If this problem has clang-level source location information, report the
395 // issue as being a problem in the source with a note showing the instantiated
397 SourceLocation LocCookie =
398 SourceLocation::getFromRawEncoding(D.getLocCookie());
399 if (LocCookie.isValid())
400 Diags.Report(LocCookie, DiagID).AddString(Message);
402 // Otherwise, report the backend diagnostic as occurring in the generated
404 // If Loc is invalid, we still need to report the diagnostic, it just gets
407 Diags.Report(Loc, DiagID).AddString(Message);
409 // We handled all the possible severities.
414 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
415 if (D.getSeverity() != llvm::DS_Warning)
416 // For now, the only support we have for StackSize diagnostic is warning.
417 // We do not know how to format other severities.
420 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
421 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
422 diag::warn_fe_frame_larger_than)
423 << D.getStackSize() << Decl::castToDeclContext(ND);
430 void BackendConsumer::EmitOptimizationMessage(
431 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
432 // We only support warnings and remarks.
433 assert(D.getSeverity() == llvm::DS_Remark ||
434 D.getSeverity() == llvm::DS_Warning);
436 SourceManager &SourceMgr = Context->getSourceManager();
437 FileManager &FileMgr = SourceMgr.getFileManager();
439 unsigned Line, Column;
440 SourceLocation DILoc;
442 if (D.isLocationAvailable()) {
443 D.getLocation(&Filename, &Line, &Column);
444 const FileEntry *FE = FileMgr.getFile(Filename);
445 if (FE && Line > 0) {
446 // If -gcolumn-info was not used, Column will be 0. This upsets the
447 // source manager, so pass 1 if Column is not set.
448 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
452 // If a location isn't available, try to approximate it using the associated
453 // function definition. We use the definition's right brace to differentiate
454 // from diagnostics that genuinely relate to the function itself.
455 FullSourceLoc Loc(DILoc, SourceMgr);
457 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
458 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
460 Diags.Report(Loc, DiagID)
461 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
464 if (DILoc.isInvalid() && D.isLocationAvailable())
465 // If we were not able to translate the file:line:col information
466 // back to a SourceLocation, at least emit a note stating that
467 // we could not translate this location. This can happen in the
468 // case of #line directives.
469 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
470 << Filename << Line << Column;
473 void BackendConsumer::OptimizationRemarkHandler(
474 const llvm::DiagnosticInfoOptimizationRemark &D) {
475 // Optimization remarks are active only if the -Rpass flag has a regular
476 // expression that matches the name of the pass name in \p D.
477 if (CodeGenOpts.OptimizationRemarkPattern &&
478 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
479 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
482 void BackendConsumer::OptimizationRemarkHandler(
483 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
484 // Missed optimization remarks are active only if the -Rpass-missed
485 // flag has a regular expression that matches the name of the pass
487 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
488 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
489 EmitOptimizationMessage(D,
490 diag::remark_fe_backend_optimization_remark_missed);
493 void BackendConsumer::OptimizationRemarkHandler(
494 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
495 // Optimization analysis remarks are active only if the -Rpass-analysis
496 // flag has a regular expression that matches the name of the pass
498 if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
499 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
500 EmitOptimizationMessage(
501 D, diag::remark_fe_backend_optimization_remark_analysis);
504 void BackendConsumer::OptimizationFailureHandler(
505 const llvm::DiagnosticInfoOptimizationFailure &D) {
506 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
509 void BackendConsumer::linkerDiagnosticHandler(const DiagnosticInfo &DI) {
510 if (DI.getSeverity() != DS_Error)
513 std::string MsgStorage;
515 raw_string_ostream Stream(MsgStorage);
516 DiagnosticPrinterRawOStream DP(Stream);
520 Diags.Report(diag::err_fe_cannot_link_module)
521 << LinkModule->getModuleIdentifier() << MsgStorage;
524 /// \brief This function is invoked when the backend needs
525 /// to report something to the user.
526 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
527 unsigned DiagID = diag::err_fe_inline_asm;
528 llvm::DiagnosticSeverity Severity = DI.getSeverity();
529 // Get the diagnostic ID based.
530 switch (DI.getKind()) {
531 case llvm::DK_InlineAsm:
532 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
534 ComputeDiagID(Severity, inline_asm, DiagID);
536 case llvm::DK_StackSize:
537 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
539 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
541 case llvm::DK_OptimizationRemark:
542 // Optimization remarks are always handled completely by this
543 // handler. There is no generic way of emitting them.
544 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
546 case llvm::DK_OptimizationRemarkMissed:
547 // Optimization remarks are always handled completely by this
548 // handler. There is no generic way of emitting them.
549 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
551 case llvm::DK_OptimizationRemarkAnalysis:
552 // Optimization remarks are always handled completely by this
553 // handler. There is no generic way of emitting them.
554 OptimizationRemarkHandler(
555 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
557 case llvm::DK_OptimizationFailure:
558 // Optimization failures are always handled completely by this
560 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
563 // Plugin IDs are not bound to any value as they are set dynamically.
564 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
567 std::string MsgStorage;
569 raw_string_ostream Stream(MsgStorage);
570 DiagnosticPrinterRawOStream DP(Stream);
574 // Report the backend message using the usual diagnostic mechanism.
576 Diags.Report(Loc, DiagID).AddString(MsgStorage);
580 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
581 : Act(_Act), LinkModule(nullptr),
582 VMContext(_VMContext ? _VMContext : new LLVMContext),
583 OwnsVMContext(!_VMContext) {}
585 CodeGenAction::~CodeGenAction() {
591 bool CodeGenAction::hasIRSupport() const { return true; }
593 void CodeGenAction::EndSourceFileAction() {
594 // If the consumer creation failed, do nothing.
595 if (!getCompilerInstance().hasASTConsumer())
598 // If we were given a link module, release consumer's ownership of it.
600 BEConsumer->takeLinkModule();
602 // Steal the module from the consumer.
603 TheModule = BEConsumer->takeModule();
606 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
607 return std::move(TheModule);
610 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
611 OwnsVMContext = false;
615 static raw_pwrite_stream *
616 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
618 case Backend_EmitAssembly:
619 return CI.createDefaultOutputFile(false, InFile, "s");
621 return CI.createDefaultOutputFile(false, InFile, "ll");
623 return CI.createDefaultOutputFile(true, InFile, "bc");
624 case Backend_EmitNothing:
626 case Backend_EmitMCNull:
627 return CI.createNullOutputFile();
628 case Backend_EmitObj:
629 return CI.createDefaultOutputFile(true, InFile, "o");
632 llvm_unreachable("Invalid action!");
635 std::unique_ptr<ASTConsumer>
636 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
637 BackendAction BA = static_cast<BackendAction>(Act);
638 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
639 if (BA != Backend_EmitNothing && !OS)
642 llvm::Module *LinkModuleToUse = LinkModule;
644 // If we were not given a link module, and the user requested that one be
645 // loaded from bitcode, do so now.
646 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
647 if (!LinkModuleToUse && !LinkBCFile.empty()) {
648 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
650 CI.getDiagnostics().Report(diag::err_cannot_open_file)
651 << LinkBCFile << BCBuf.getError().message();
655 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
656 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
657 if (std::error_code EC = ModuleOrErr.getError()) {
658 CI.getDiagnostics().Report(diag::err_cannot_open_file)
659 << LinkBCFile << EC.message();
662 LinkModuleToUse = ModuleOrErr.get().release();
665 CoverageSourceInfo *CoverageInfo = nullptr;
666 // Add the preprocessor callback only when the coverage mapping is generated.
667 if (CI.getCodeGenOpts().CoverageMapping) {
668 CoverageInfo = new CoverageSourceInfo;
669 CI.getPreprocessor().addPPCallbacks(
670 std::unique_ptr<PPCallbacks>(CoverageInfo));
672 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
673 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
674 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
675 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
676 LinkModuleToUse, OS, *VMContext, CoverageInfo));
677 BEConsumer = Result.get();
678 return std::move(Result);
681 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
683 unsigned LocCookie) {
684 SM.print(nullptr, llvm::errs());
687 void CodeGenAction::ExecuteAction() {
688 // If this is an IR file, we have to treat it specially.
689 if (getCurrentFileKind() == IK_LLVM_IR) {
690 BackendAction BA = static_cast<BackendAction>(Act);
691 CompilerInstance &CI = getCompilerInstance();
692 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
693 if (BA != Backend_EmitNothing && !OS)
697 SourceManager &SM = CI.getSourceManager();
698 FileID FID = SM.getMainFileID();
699 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
703 llvm::SMDiagnostic Err;
704 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
706 // Translate from the diagnostic info to the SourceManager location if
708 // TODO: Unify this with ConvertBackendLocation()
710 if (Err.getLineNo() > 0) {
711 assert(Err.getColumnNo() >= 0);
712 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
713 Err.getLineNo(), Err.getColumnNo() + 1);
716 // Strip off a leading diagnostic code if there is one.
717 StringRef Msg = Err.getMessage();
718 if (Msg.startswith("error: "))
722 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
724 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
727 const TargetOptions &TargetOpts = CI.getTargetOpts();
728 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
729 CI.getDiagnostics().Report(SourceLocation(),
730 diag::warn_fe_override_module)
731 << TargetOpts.Triple;
732 TheModule->setTargetTriple(TargetOpts.Triple);
735 LLVMContext &Ctx = TheModule->getContext();
736 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
737 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
738 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
739 TheModule.get(), BA, OS);
743 // Otherwise follow the normal AST path.
744 this->ASTFrontendAction::ExecuteAction();
749 void EmitAssemblyAction::anchor() { }
750 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
751 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
753 void EmitBCAction::anchor() { }
754 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
755 : CodeGenAction(Backend_EmitBC, _VMContext) {}
757 void EmitLLVMAction::anchor() { }
758 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
759 : CodeGenAction(Backend_EmitLL, _VMContext) {}
761 void EmitLLVMOnlyAction::anchor() { }
762 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
763 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
765 void EmitCodeGenOnlyAction::anchor() { }
766 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
767 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
769 void EmitObjAction::anchor() { }
770 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
771 : CodeGenAction(Backend_EmitObj, _VMContext) {}