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 "clang/CodeGen/CodeGenAction.h"
11 #include "CodeGenModule.h"
12 #include "CoverageMappingGen.h"
13 #include "MacroPPCallbacks.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclGroup.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/CodeGen/BackendUtil.h"
22 #include "clang/CodeGen/ModuleBuilder.h"
23 #include "clang/Frontend/CompilerInstance.h"
24 #include "clang/Frontend/FrontendDiagnostic.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/Bitcode/BitcodeReader.h"
27 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/Timer.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/YAMLTraits.h"
42 #include "llvm/Transforms/IPO/Internalize.h"
45 using namespace clang;
49 class BackendConsumer : public ASTConsumer {
50 using LinkModule = CodeGenAction::LinkModule;
52 virtual void anchor();
53 DiagnosticsEngine &Diags;
55 const HeaderSearchOptions &HeaderSearchOpts;
56 const CodeGenOptions &CodeGenOpts;
57 const TargetOptions &TargetOpts;
58 const LangOptions &LangOpts;
59 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
62 Timer LLVMIRGeneration;
63 unsigned LLVMIRGenerationRefCount;
65 /// True if we've finished generating IR. This prevents us from generating
66 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
67 /// can happen when Clang plugins trigger additional AST deserialization.
68 bool IRGenFinished = false;
70 std::unique_ptr<CodeGenerator> Gen;
72 SmallVector<LinkModule, 4> LinkModules;
74 // This is here so that the diagnostic printer knows the module a diagnostic
76 llvm::Module *CurLinkModule = nullptr;
79 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
80 const HeaderSearchOptions &HeaderSearchOpts,
81 const PreprocessorOptions &PPOpts,
82 const CodeGenOptions &CodeGenOpts,
83 const TargetOptions &TargetOpts,
84 const LangOptions &LangOpts, bool TimePasses,
85 const std::string &InFile,
86 SmallVector<LinkModule, 4> LinkModules,
87 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
88 CoverageSourceInfo *CoverageInfo = nullptr)
89 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
90 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
91 AsmOutStream(std::move(OS)), Context(nullptr),
92 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
93 LLVMIRGenerationRefCount(0),
94 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
95 CodeGenOpts, C, CoverageInfo)),
96 LinkModules(std::move(LinkModules)) {
97 llvm::TimePassesIsEnabled = TimePasses;
99 llvm::Module *getModule() const { return Gen->GetModule(); }
100 std::unique_ptr<llvm::Module> takeModule() {
101 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
104 CodeGenerator *getCodeGenerator() { return Gen.get(); }
106 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
107 Gen->HandleCXXStaticMemberVarInstantiation(VD);
110 void Initialize(ASTContext &Ctx) override {
111 assert(!Context && "initialized multiple times");
115 if (llvm::TimePassesIsEnabled)
116 LLVMIRGeneration.startTimer();
118 Gen->Initialize(Ctx);
120 if (llvm::TimePassesIsEnabled)
121 LLVMIRGeneration.stopTimer();
124 bool HandleTopLevelDecl(DeclGroupRef D) override {
125 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
126 Context->getSourceManager(),
127 "LLVM IR generation of declaration");
130 if (llvm::TimePassesIsEnabled) {
131 LLVMIRGenerationRefCount += 1;
132 if (LLVMIRGenerationRefCount == 1)
133 LLVMIRGeneration.startTimer();
136 Gen->HandleTopLevelDecl(D);
138 if (llvm::TimePassesIsEnabled) {
139 LLVMIRGenerationRefCount -= 1;
140 if (LLVMIRGenerationRefCount == 0)
141 LLVMIRGeneration.stopTimer();
147 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
148 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
149 Context->getSourceManager(),
150 "LLVM IR generation of inline function");
151 if (llvm::TimePassesIsEnabled)
152 LLVMIRGeneration.startTimer();
154 Gen->HandleInlineFunctionDefinition(D);
156 if (llvm::TimePassesIsEnabled)
157 LLVMIRGeneration.stopTimer();
160 void HandleInterestingDecl(DeclGroupRef D) override {
161 // Ignore interesting decls from the AST reader after IRGen is finished.
163 HandleTopLevelDecl(D);
166 // Links each entry in LinkModules into our module. Returns true on error.
167 bool LinkInModules() {
168 for (auto &LM : LinkModules) {
169 if (LM.PropagateAttrs)
170 for (Function &F : *LM.Module)
171 Gen->CGM().AddDefaultFnAttrs(F);
173 CurLinkModule = LM.Module.get();
176 if (LM.Internalize) {
177 Err = Linker::linkModules(
178 *getModule(), std::move(LM.Module), LM.LinkFlags,
179 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
180 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
181 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
185 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
192 return false; // success
195 void HandleTranslationUnit(ASTContext &C) override {
197 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
198 if (llvm::TimePassesIsEnabled) {
199 LLVMIRGenerationRefCount += 1;
200 if (LLVMIRGenerationRefCount == 1)
201 LLVMIRGeneration.startTimer();
204 Gen->HandleTranslationUnit(C);
206 if (llvm::TimePassesIsEnabled) {
207 LLVMIRGenerationRefCount -= 1;
208 if (LLVMIRGenerationRefCount == 0)
209 LLVMIRGeneration.stopTimer();
212 IRGenFinished = true;
215 // Silently ignore if we weren't initialized for some reason.
219 // Install an inline asm handler so that diagnostics get printed through
220 // our diagnostics hooks.
221 LLVMContext &Ctx = getModule()->getContext();
222 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
223 Ctx.getInlineAsmDiagnosticHandler();
224 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
225 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
227 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
228 Ctx.getDiagnosticHandler();
229 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
230 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
231 Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
232 if (CodeGenOpts.DiagnosticsHotnessThreshold != 0)
233 Ctx.setDiagnosticsHotnessThreshold(
234 CodeGenOpts.DiagnosticsHotnessThreshold);
236 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
237 if (!CodeGenOpts.OptRecordFile.empty()) {
240 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
241 EC, sys::fs::F_None);
243 Diags.Report(diag::err_cannot_open_file) <<
244 CodeGenOpts.OptRecordFile << EC.message();
248 Ctx.setDiagnosticsOutputFile(
249 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
251 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
252 Ctx.setDiagnosticsHotnessRequested(true);
255 // Link each LinkModule into our module.
259 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
261 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
262 LangOpts, C.getTargetInfo().getDataLayout(),
263 getModule(), Action, std::move(AsmOutStream));
265 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
267 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
270 OptRecordFile->keep();
273 void HandleTagDeclDefinition(TagDecl *D) override {
274 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
275 Context->getSourceManager(),
276 "LLVM IR generation of declaration");
277 Gen->HandleTagDeclDefinition(D);
280 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
281 Gen->HandleTagDeclRequiredDefinition(D);
284 void CompleteTentativeDefinition(VarDecl *D) override {
285 Gen->CompleteTentativeDefinition(D);
288 void AssignInheritanceModel(CXXRecordDecl *RD) override {
289 Gen->AssignInheritanceModel(RD);
292 void HandleVTable(CXXRecordDecl *RD) override {
293 Gen->HandleVTable(RD);
296 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
297 unsigned LocCookie) {
298 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
299 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
302 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
304 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
307 /// Get the best possible source location to represent a diagnostic that
308 /// may have associated debug info.
310 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
311 bool &BadDebugInfo, StringRef &Filename,
312 unsigned &Line, unsigned &Column) const;
314 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
315 SourceLocation LocCookie);
317 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
318 /// \brief Specialized handler for InlineAsm diagnostic.
319 /// \return True if the diagnostic has been successfully reported, false
321 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
322 /// \brief Specialized handler for StackSize diagnostic.
323 /// \return True if the diagnostic has been successfully reported, false
325 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
326 /// \brief Specialized handler for unsupported backend feature diagnostic.
327 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
328 /// \brief Specialized handlers for optimization remarks.
329 /// Note that these handlers only accept remarks and they always handle
331 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
334 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
335 void OptimizationRemarkHandler(
336 const llvm::OptimizationRemarkAnalysisFPCommute &D);
337 void OptimizationRemarkHandler(
338 const llvm::OptimizationRemarkAnalysisAliasing &D);
339 void OptimizationFailureHandler(
340 const llvm::DiagnosticInfoOptimizationFailure &D);
343 void BackendConsumer::anchor() {}
346 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
347 /// buffer to be a valid FullSourceLoc.
348 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
349 SourceManager &CSM) {
350 // Get both the clang and llvm source managers. The location is relative to
351 // a memory buffer that the LLVM Source Manager is handling, we need to add
352 // a copy to the Clang source manager.
353 const llvm::SourceMgr &LSM = *D.getSourceMgr();
355 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
356 // already owns its one and clang::SourceManager wants to own its one.
357 const MemoryBuffer *LBuf =
358 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
360 // Create the copy and transfer ownership to clang::SourceManager.
361 // TODO: Avoid copying files into memory.
362 std::unique_ptr<llvm::MemoryBuffer> CBuf =
363 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
364 LBuf->getBufferIdentifier());
365 // FIXME: Keep a file ID map instead of creating new IDs for each location.
366 FileID FID = CSM.createFileID(std::move(CBuf));
368 // Translate the offset into the file.
369 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
370 SourceLocation NewLoc =
371 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
372 return FullSourceLoc(NewLoc, CSM);
376 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
377 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
378 /// the temporary memory buffer that the inline asm parser has set up.
379 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
380 SourceLocation LocCookie) {
381 // There are a couple of different kinds of errors we could get here. First,
382 // we re-format the SMDiagnostic in terms of a clang diagnostic.
384 // Strip "error: " off the start of the message string.
385 StringRef Message = D.getMessage();
386 if (Message.startswith("error: "))
387 Message = Message.substr(7);
389 // If the SMDiagnostic has an inline asm source location, translate it.
391 if (D.getLoc() != SMLoc())
392 Loc = ConvertBackendLocation(D, Context->getSourceManager());
395 switch (D.getKind()) {
396 case llvm::SourceMgr::DK_Error:
397 DiagID = diag::err_fe_inline_asm;
399 case llvm::SourceMgr::DK_Warning:
400 DiagID = diag::warn_fe_inline_asm;
402 case llvm::SourceMgr::DK_Note:
403 DiagID = diag::note_fe_inline_asm;
406 // If this problem has clang-level source location information, report the
407 // issue in the source with a note showing the instantiated
409 if (LocCookie.isValid()) {
410 Diags.Report(LocCookie, DiagID).AddString(Message);
412 if (D.getLoc().isValid()) {
413 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
414 // Convert the SMDiagnostic ranges into SourceRange and attach them
415 // to the diagnostic.
416 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
417 unsigned Column = D.getColumnNo();
418 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
419 Loc.getLocWithOffset(Range.second - Column));
425 // Otherwise, report the backend issue as occurring in the generated .s file.
426 // If Loc is invalid, we still need to report the issue, it just gets no
428 Diags.Report(Loc, DiagID).AddString(Message);
431 #define ComputeDiagID(Severity, GroupName, DiagID) \
433 switch (Severity) { \
434 case llvm::DS_Error: \
435 DiagID = diag::err_fe_##GroupName; \
437 case llvm::DS_Warning: \
438 DiagID = diag::warn_fe_##GroupName; \
440 case llvm::DS_Remark: \
441 llvm_unreachable("'remark' severity not expected"); \
443 case llvm::DS_Note: \
444 DiagID = diag::note_fe_##GroupName; \
449 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
451 switch (Severity) { \
452 case llvm::DS_Error: \
453 DiagID = diag::err_fe_##GroupName; \
455 case llvm::DS_Warning: \
456 DiagID = diag::warn_fe_##GroupName; \
458 case llvm::DS_Remark: \
459 DiagID = diag::remark_fe_##GroupName; \
461 case llvm::DS_Note: \
462 DiagID = diag::note_fe_##GroupName; \
468 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
470 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
471 std::string Message = D.getMsgStr().str();
473 // If this problem has clang-level source location information, report the
474 // issue as being a problem in the source with a note showing the instantiated
476 SourceLocation LocCookie =
477 SourceLocation::getFromRawEncoding(D.getLocCookie());
478 if (LocCookie.isValid())
479 Diags.Report(LocCookie, DiagID).AddString(Message);
481 // Otherwise, report the backend diagnostic as occurring in the generated
483 // If Loc is invalid, we still need to report the diagnostic, it just gets
486 Diags.Report(Loc, DiagID).AddString(Message);
488 // We handled all the possible severities.
493 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
494 if (D.getSeverity() != llvm::DS_Warning)
495 // For now, the only support we have for StackSize diagnostic is warning.
496 // We do not know how to format other severities.
499 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
500 // FIXME: Shouldn't need to truncate to uint32_t
501 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
502 diag::warn_fe_frame_larger_than)
503 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
510 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
511 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
512 StringRef &Filename, unsigned &Line, unsigned &Column) const {
513 SourceManager &SourceMgr = Context->getSourceManager();
514 FileManager &FileMgr = SourceMgr.getFileManager();
515 SourceLocation DILoc;
517 if (D.isLocationAvailable()) {
518 D.getLocation(&Filename, &Line, &Column);
519 const FileEntry *FE = FileMgr.getFile(Filename);
520 if (FE && Line > 0) {
521 // If -gcolumn-info was not used, Column will be 0. This upsets the
522 // source manager, so pass 1 if Column is not set.
523 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
525 BadDebugInfo = DILoc.isInvalid();
528 // If a location isn't available, try to approximate it using the associated
529 // function definition. We use the definition's right brace to differentiate
530 // from diagnostics that genuinely relate to the function itself.
531 FullSourceLoc Loc(DILoc, SourceMgr);
533 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
534 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
536 if (DILoc.isInvalid() && D.isLocationAvailable())
537 // If we were not able to translate the file:line:col information
538 // back to a SourceLocation, at least emit a note stating that
539 // we could not translate this location. This can happen in the
540 // case of #line directives.
541 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
542 << Filename << Line << Column;
547 void BackendConsumer::UnsupportedDiagHandler(
548 const llvm::DiagnosticInfoUnsupported &D) {
549 // We only support errors.
550 assert(D.getSeverity() == llvm::DS_Error);
553 unsigned Line, Column;
554 bool BadDebugInfo = false;
556 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
558 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
561 // If we were not able to translate the file:line:col information
562 // back to a SourceLocation, at least emit a note stating that
563 // we could not translate this location. This can happen in the
564 // case of #line directives.
565 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
566 << Filename << Line << Column;
569 void BackendConsumer::EmitOptimizationMessage(
570 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
571 // We only support warnings and remarks.
572 assert(D.getSeverity() == llvm::DS_Remark ||
573 D.getSeverity() == llvm::DS_Warning);
576 unsigned Line, Column;
577 bool BadDebugInfo = false;
579 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
582 raw_string_ostream MsgStream(Msg);
583 MsgStream << D.getMsg();
586 MsgStream << " (hotness: " << *D.getHotness() << ")";
588 Diags.Report(Loc, DiagID)
589 << AddFlagValue(D.getPassName())
593 // If we were not able to translate the file:line:col information
594 // back to a SourceLocation, at least emit a note stating that
595 // we could not translate this location. This can happen in the
596 // case of #line directives.
597 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
598 << Filename << Line << Column;
601 void BackendConsumer::OptimizationRemarkHandler(
602 const llvm::DiagnosticInfoOptimizationBase &D) {
604 // Optimization remarks are active only if the -Rpass flag has a regular
605 // expression that matches the name of the pass name in \p D.
606 if (CodeGenOpts.OptimizationRemarkPattern &&
607 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
608 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
609 } else if (D.isMissed()) {
610 // Missed optimization remarks are active only if the -Rpass-missed
611 // flag has a regular expression that matches the name of the pass
613 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
614 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
615 EmitOptimizationMessage(
616 D, diag::remark_fe_backend_optimization_remark_missed);
618 assert(D.isAnalysis() && "Unknown remark type");
620 bool ShouldAlwaysPrint = false;
621 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
622 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
624 if (ShouldAlwaysPrint ||
625 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
626 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
627 EmitOptimizationMessage(
628 D, diag::remark_fe_backend_optimization_remark_analysis);
632 void BackendConsumer::OptimizationRemarkHandler(
633 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
634 // Optimization analysis remarks are active if the pass name is set to
635 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
636 // regular expression that matches the name of the pass name in \p D.
638 if (D.shouldAlwaysPrint() ||
639 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
640 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
641 EmitOptimizationMessage(
642 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
645 void BackendConsumer::OptimizationRemarkHandler(
646 const llvm::OptimizationRemarkAnalysisAliasing &D) {
647 // Optimization analysis remarks are active if the pass name is set to
648 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
649 // regular expression that matches the name of the pass name in \p D.
651 if (D.shouldAlwaysPrint() ||
652 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
653 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
654 EmitOptimizationMessage(
655 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
658 void BackendConsumer::OptimizationFailureHandler(
659 const llvm::DiagnosticInfoOptimizationFailure &D) {
660 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
663 /// \brief This function is invoked when the backend needs
664 /// to report something to the user.
665 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
666 unsigned DiagID = diag::err_fe_inline_asm;
667 llvm::DiagnosticSeverity Severity = DI.getSeverity();
668 // Get the diagnostic ID based.
669 switch (DI.getKind()) {
670 case llvm::DK_InlineAsm:
671 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
673 ComputeDiagID(Severity, inline_asm, DiagID);
675 case llvm::DK_StackSize:
676 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
678 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
681 assert(CurLinkModule);
682 // FIXME: stop eating the warnings and notes.
683 if (Severity != DS_Error)
685 DiagID = diag::err_fe_cannot_link_module;
687 case llvm::DK_OptimizationRemark:
688 // Optimization remarks are always handled completely by this
689 // handler. There is no generic way of emitting them.
690 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
692 case llvm::DK_OptimizationRemarkMissed:
693 // Optimization remarks are always handled completely by this
694 // handler. There is no generic way of emitting them.
695 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
697 case llvm::DK_OptimizationRemarkAnalysis:
698 // Optimization remarks are always handled completely by this
699 // handler. There is no generic way of emitting them.
700 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
702 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
703 // Optimization remarks are always handled completely by this
704 // handler. There is no generic way of emitting them.
705 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
707 case llvm::DK_OptimizationRemarkAnalysisAliasing:
708 // Optimization remarks are always handled completely by this
709 // handler. There is no generic way of emitting them.
710 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
712 case llvm::DK_MachineOptimizationRemark:
713 // Optimization remarks are always handled completely by this
714 // handler. There is no generic way of emitting them.
715 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
717 case llvm::DK_MachineOptimizationRemarkMissed:
718 // Optimization remarks are always handled completely by this
719 // handler. There is no generic way of emitting them.
720 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
722 case llvm::DK_MachineOptimizationRemarkAnalysis:
723 // Optimization remarks are always handled completely by this
724 // handler. There is no generic way of emitting them.
725 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
727 case llvm::DK_OptimizationFailure:
728 // Optimization failures are always handled completely by this
730 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
732 case llvm::DK_Unsupported:
733 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
736 // Plugin IDs are not bound to any value as they are set dynamically.
737 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
740 std::string MsgStorage;
742 raw_string_ostream Stream(MsgStorage);
743 DiagnosticPrinterRawOStream DP(Stream);
747 if (DiagID == diag::err_fe_cannot_link_module) {
748 Diags.Report(diag::err_fe_cannot_link_module)
749 << CurLinkModule->getModuleIdentifier() << MsgStorage;
753 // Report the backend message using the usual diagnostic mechanism.
755 Diags.Report(Loc, DiagID).AddString(MsgStorage);
759 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
760 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
761 OwnsVMContext(!_VMContext) {}
763 CodeGenAction::~CodeGenAction() {
769 bool CodeGenAction::hasIRSupport() const { return true; }
771 void CodeGenAction::EndSourceFileAction() {
772 // If the consumer creation failed, do nothing.
773 if (!getCompilerInstance().hasASTConsumer())
776 // Steal the module from the consumer.
777 TheModule = BEConsumer->takeModule();
780 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
781 return std::move(TheModule);
784 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
785 OwnsVMContext = false;
789 static std::unique_ptr<raw_pwrite_stream>
790 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
792 case Backend_EmitAssembly:
793 return CI.createDefaultOutputFile(false, InFile, "s");
795 return CI.createDefaultOutputFile(false, InFile, "ll");
797 return CI.createDefaultOutputFile(true, InFile, "bc");
798 case Backend_EmitNothing:
800 case Backend_EmitMCNull:
801 return CI.createNullOutputFile();
802 case Backend_EmitObj:
803 return CI.createDefaultOutputFile(true, InFile, "o");
806 llvm_unreachable("Invalid action!");
809 std::unique_ptr<ASTConsumer>
810 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
811 BackendAction BA = static_cast<BackendAction>(Act);
812 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
813 if (BA != Backend_EmitNothing && !OS)
816 // Load bitcode modules to link with, if we need to.
817 if (LinkModules.empty())
818 for (const CodeGenOptions::BitcodeFileToLink &F :
819 CI.getCodeGenOpts().LinkBitcodeFiles) {
820 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
822 CI.getDiagnostics().Report(diag::err_cannot_open_file)
823 << F.Filename << BCBuf.getError().message();
828 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
829 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
831 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
832 CI.getDiagnostics().Report(diag::err_cannot_open_file)
833 << F.Filename << EIB.message();
838 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
839 F.Internalize, F.LinkFlags});
842 CoverageSourceInfo *CoverageInfo = nullptr;
843 // Add the preprocessor callback only when the coverage mapping is generated.
844 if (CI.getCodeGenOpts().CoverageMapping) {
845 CoverageInfo = new CoverageSourceInfo;
846 CI.getPreprocessor().addPPCallbacks(
847 std::unique_ptr<PPCallbacks>(CoverageInfo));
850 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
851 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
852 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
853 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
854 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
855 BEConsumer = Result.get();
857 // Enable generating macro debug info only when debug info is not disabled and
858 // also macro debug info is enabled.
859 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
860 CI.getCodeGenOpts().MacroDebugInfo) {
861 std::unique_ptr<PPCallbacks> Callbacks =
862 llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
863 CI.getPreprocessor());
864 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
867 return std::move(Result);
870 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
872 unsigned LocCookie) {
873 SM.print(nullptr, llvm::errs());
875 auto Diags = static_cast<DiagnosticsEngine *>(Context);
877 switch (SM.getKind()) {
878 case llvm::SourceMgr::DK_Error:
879 DiagID = diag::err_fe_inline_asm;
881 case llvm::SourceMgr::DK_Warning:
882 DiagID = diag::warn_fe_inline_asm;
884 case llvm::SourceMgr::DK_Note:
885 DiagID = diag::note_fe_inline_asm;
889 Diags->Report(DiagID).AddString("cannot compile inline asm");
892 std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
893 CompilerInstance &CI = getCompilerInstance();
894 SourceManager &SM = CI.getSourceManager();
896 // For ThinLTO backend invocations, ensure that the context
897 // merges types based on ODR identifiers. We also need to read
898 // the correct module out of a multi-module bitcode file.
899 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
900 VMContext->enableDebugTypeODRUniquing();
902 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
904 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
905 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
906 CI.getDiagnostics().Report(DiagID) << EIB.message();
911 Expected<llvm::BitcodeModule> BMOrErr = FindThinLTOModule(MBRef);
913 return DiagErrors(BMOrErr.takeError());
915 Expected<std::unique_ptr<llvm::Module>> MOrErr =
916 BMOrErr->parseModule(*VMContext);
918 return DiagErrors(MOrErr.takeError());
919 return std::move(*MOrErr);
922 llvm::SMDiagnostic Err;
923 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
926 // Translate from the diagnostic info to the SourceManager location if
928 // TODO: Unify this with ConvertBackendLocation()
930 if (Err.getLineNo() > 0) {
931 assert(Err.getColumnNo() >= 0);
932 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
933 Err.getLineNo(), Err.getColumnNo() + 1);
936 // Strip off a leading diagnostic code if there is one.
937 StringRef Msg = Err.getMessage();
938 if (Msg.startswith("error: "))
942 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
944 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
948 void CodeGenAction::ExecuteAction() {
949 // If this is an IR file, we have to treat it specially.
950 if (getCurrentFileKind().getLanguage() == InputKind::LLVM_IR) {
951 BackendAction BA = static_cast<BackendAction>(Act);
952 CompilerInstance &CI = getCompilerInstance();
953 std::unique_ptr<raw_pwrite_stream> OS =
954 GetOutputStream(CI, getCurrentFile(), BA);
955 if (BA != Backend_EmitNothing && !OS)
959 SourceManager &SM = CI.getSourceManager();
960 FileID FID = SM.getMainFileID();
961 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
965 TheModule = loadModule(*MainFile);
969 const TargetOptions &TargetOpts = CI.getTargetOpts();
970 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
971 CI.getDiagnostics().Report(SourceLocation(),
972 diag::warn_fe_override_module)
973 << TargetOpts.Triple;
974 TheModule->setTargetTriple(TargetOpts.Triple);
977 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
978 MainFile->getMemBufferRef());
980 LLVMContext &Ctx = TheModule->getContext();
981 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
982 &CI.getDiagnostics());
984 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
985 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
986 CI.getTarget().getDataLayout(), TheModule.get(), BA,
991 // Otherwise follow the normal AST path.
992 this->ASTFrontendAction::ExecuteAction();
997 void EmitAssemblyAction::anchor() { }
998 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
999 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1001 void EmitBCAction::anchor() { }
1002 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1003 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1005 void EmitLLVMAction::anchor() { }
1006 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1007 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1009 void EmitLLVMOnlyAction::anchor() { }
1010 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1011 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1013 void EmitCodeGenOnlyAction::anchor() { }
1014 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1015 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1017 void EmitObjAction::anchor() { }
1018 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1019 : CodeGenAction(Backend_EmitObj, _VMContext) {}