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;
50 class ClangDiagnosticHandler final : public DiagnosticHandler {
52 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
53 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
55 bool handleDiagnostics(const DiagnosticInfo &DI) override;
57 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
58 return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
59 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
61 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
62 return (CodeGenOpts.OptimizationRemarkMissedPattern &&
63 CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
65 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
66 return (CodeGenOpts.OptimizationRemarkPattern &&
67 CodeGenOpts.OptimizationRemarkPattern->match(PassName));
70 bool isAnyRemarkEnabled() const override {
71 return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
72 CodeGenOpts.OptimizationRemarkMissedPattern ||
73 CodeGenOpts.OptimizationRemarkPattern);
77 const CodeGenOptions &CodeGenOpts;
78 BackendConsumer *BackendCon;
81 class BackendConsumer : public ASTConsumer {
82 using LinkModule = CodeGenAction::LinkModule;
84 virtual void anchor();
85 DiagnosticsEngine &Diags;
87 const HeaderSearchOptions &HeaderSearchOpts;
88 const CodeGenOptions &CodeGenOpts;
89 const TargetOptions &TargetOpts;
90 const LangOptions &LangOpts;
91 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
94 Timer LLVMIRGeneration;
95 unsigned LLVMIRGenerationRefCount;
97 /// True if we've finished generating IR. This prevents us from generating
98 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
99 /// can happen when Clang plugins trigger additional AST deserialization.
100 bool IRGenFinished = false;
102 std::unique_ptr<CodeGenerator> Gen;
104 SmallVector<LinkModule, 4> LinkModules;
106 // This is here so that the diagnostic printer knows the module a diagnostic
108 llvm::Module *CurLinkModule = nullptr;
111 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
112 const HeaderSearchOptions &HeaderSearchOpts,
113 const PreprocessorOptions &PPOpts,
114 const CodeGenOptions &CodeGenOpts,
115 const TargetOptions &TargetOpts,
116 const LangOptions &LangOpts, bool TimePasses,
117 const std::string &InFile,
118 SmallVector<LinkModule, 4> LinkModules,
119 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
120 CoverageSourceInfo *CoverageInfo = nullptr)
121 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
122 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
123 AsmOutStream(std::move(OS)), Context(nullptr),
124 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
125 LLVMIRGenerationRefCount(0),
126 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
127 CodeGenOpts, C, CoverageInfo)),
128 LinkModules(std::move(LinkModules)) {
129 FrontendTimesIsEnabled = TimePasses;
130 llvm::TimePassesIsEnabled = TimePasses;
132 llvm::Module *getModule() const { return Gen->GetModule(); }
133 std::unique_ptr<llvm::Module> takeModule() {
134 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
137 CodeGenerator *getCodeGenerator() { return Gen.get(); }
139 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
140 Gen->HandleCXXStaticMemberVarInstantiation(VD);
143 void Initialize(ASTContext &Ctx) override {
144 assert(!Context && "initialized multiple times");
148 if (FrontendTimesIsEnabled)
149 LLVMIRGeneration.startTimer();
151 Gen->Initialize(Ctx);
153 if (FrontendTimesIsEnabled)
154 LLVMIRGeneration.stopTimer();
157 bool HandleTopLevelDecl(DeclGroupRef D) override {
158 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
159 Context->getSourceManager(),
160 "LLVM IR generation of declaration");
163 if (FrontendTimesIsEnabled) {
164 LLVMIRGenerationRefCount += 1;
165 if (LLVMIRGenerationRefCount == 1)
166 LLVMIRGeneration.startTimer();
169 Gen->HandleTopLevelDecl(D);
171 if (FrontendTimesIsEnabled) {
172 LLVMIRGenerationRefCount -= 1;
173 if (LLVMIRGenerationRefCount == 0)
174 LLVMIRGeneration.stopTimer();
180 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
181 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
182 Context->getSourceManager(),
183 "LLVM IR generation of inline function");
184 if (FrontendTimesIsEnabled)
185 LLVMIRGeneration.startTimer();
187 Gen->HandleInlineFunctionDefinition(D);
189 if (FrontendTimesIsEnabled)
190 LLVMIRGeneration.stopTimer();
193 void HandleInterestingDecl(DeclGroupRef D) override {
194 // Ignore interesting decls from the AST reader after IRGen is finished.
196 HandleTopLevelDecl(D);
199 // Links each entry in LinkModules into our module. Returns true on error.
200 bool LinkInModules() {
201 for (auto &LM : LinkModules) {
202 if (LM.PropagateAttrs)
203 for (Function &F : *LM.Module)
204 Gen->CGM().AddDefaultFnAttrs(F);
206 CurLinkModule = LM.Module.get();
209 if (LM.Internalize) {
210 Err = Linker::linkModules(
211 *getModule(), std::move(LM.Module), LM.LinkFlags,
212 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
213 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
214 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
218 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
225 return false; // success
228 void HandleTranslationUnit(ASTContext &C) override {
230 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
231 if (FrontendTimesIsEnabled) {
232 LLVMIRGenerationRefCount += 1;
233 if (LLVMIRGenerationRefCount == 1)
234 LLVMIRGeneration.startTimer();
237 Gen->HandleTranslationUnit(C);
239 if (FrontendTimesIsEnabled) {
240 LLVMIRGenerationRefCount -= 1;
241 if (LLVMIRGenerationRefCount == 0)
242 LLVMIRGeneration.stopTimer();
245 IRGenFinished = true;
248 // Silently ignore if we weren't initialized for some reason.
252 // Install an inline asm handler so that diagnostics get printed through
253 // our diagnostics hooks.
254 LLVMContext &Ctx = getModule()->getContext();
255 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
256 Ctx.getInlineAsmDiagnosticHandler();
257 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
258 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
260 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
261 Ctx.getDiagnosticHandler();
262 Ctx.setDiagnosticHandler(llvm::make_unique<ClangDiagnosticHandler>(
264 Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
265 if (CodeGenOpts.DiagnosticsHotnessThreshold != 0)
266 Ctx.setDiagnosticsHotnessThreshold(
267 CodeGenOpts.DiagnosticsHotnessThreshold);
269 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile;
270 if (!CodeGenOpts.OptRecordFile.empty()) {
272 OptRecordFile = llvm::make_unique<llvm::ToolOutputFile>(
273 CodeGenOpts.OptRecordFile, EC, sys::fs::F_None);
275 Diags.Report(diag::err_cannot_open_file) <<
276 CodeGenOpts.OptRecordFile << EC.message();
280 Ctx.setDiagnosticsOutputFile(
281 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
283 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
284 Ctx.setDiagnosticsHotnessRequested(true);
287 // Link each LinkModule into our module.
291 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
293 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
294 LangOpts, C.getTargetInfo().getDataLayout(),
295 getModule(), Action, std::move(AsmOutStream));
297 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
299 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
302 OptRecordFile->keep();
305 void HandleTagDeclDefinition(TagDecl *D) override {
306 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
307 Context->getSourceManager(),
308 "LLVM IR generation of declaration");
309 Gen->HandleTagDeclDefinition(D);
312 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
313 Gen->HandleTagDeclRequiredDefinition(D);
316 void CompleteTentativeDefinition(VarDecl *D) override {
317 Gen->CompleteTentativeDefinition(D);
320 void AssignInheritanceModel(CXXRecordDecl *RD) override {
321 Gen->AssignInheritanceModel(RD);
324 void HandleVTable(CXXRecordDecl *RD) override {
325 Gen->HandleVTable(RD);
328 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
329 unsigned LocCookie) {
330 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
331 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
334 /// Get the best possible source location to represent a diagnostic that
335 /// may have associated debug info.
337 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
338 bool &BadDebugInfo, StringRef &Filename,
339 unsigned &Line, unsigned &Column) const;
341 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
342 SourceLocation LocCookie);
344 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
345 /// Specialized handler for InlineAsm diagnostic.
346 /// \return True if the diagnostic has been successfully reported, false
348 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
349 /// Specialized handler for StackSize diagnostic.
350 /// \return True if the diagnostic has been successfully reported, false
352 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
353 /// Specialized handler for unsupported backend feature diagnostic.
354 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
355 /// Specialized handlers for optimization remarks.
356 /// Note that these handlers only accept remarks and they always handle
358 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
361 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
362 void OptimizationRemarkHandler(
363 const llvm::OptimizationRemarkAnalysisFPCommute &D);
364 void OptimizationRemarkHandler(
365 const llvm::OptimizationRemarkAnalysisAliasing &D);
366 void OptimizationFailureHandler(
367 const llvm::DiagnosticInfoOptimizationFailure &D);
370 void BackendConsumer::anchor() {}
373 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
374 BackendCon->DiagnosticHandlerImpl(DI);
378 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
379 /// buffer to be a valid FullSourceLoc.
380 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
381 SourceManager &CSM) {
382 // Get both the clang and llvm source managers. The location is relative to
383 // a memory buffer that the LLVM Source Manager is handling, we need to add
384 // a copy to the Clang source manager.
385 const llvm::SourceMgr &LSM = *D.getSourceMgr();
387 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
388 // already owns its one and clang::SourceManager wants to own its one.
389 const MemoryBuffer *LBuf =
390 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
392 // Create the copy and transfer ownership to clang::SourceManager.
393 // TODO: Avoid copying files into memory.
394 std::unique_ptr<llvm::MemoryBuffer> CBuf =
395 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
396 LBuf->getBufferIdentifier());
397 // FIXME: Keep a file ID map instead of creating new IDs for each location.
398 FileID FID = CSM.createFileID(std::move(CBuf));
400 // Translate the offset into the file.
401 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
402 SourceLocation NewLoc =
403 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
404 return FullSourceLoc(NewLoc, CSM);
408 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
409 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
410 /// the temporary memory buffer that the inline asm parser has set up.
411 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
412 SourceLocation LocCookie) {
413 // There are a couple of different kinds of errors we could get here. First,
414 // we re-format the SMDiagnostic in terms of a clang diagnostic.
416 // Strip "error: " off the start of the message string.
417 StringRef Message = D.getMessage();
418 if (Message.startswith("error: "))
419 Message = Message.substr(7);
421 // If the SMDiagnostic has an inline asm source location, translate it.
423 if (D.getLoc() != SMLoc())
424 Loc = ConvertBackendLocation(D, Context->getSourceManager());
427 switch (D.getKind()) {
428 case llvm::SourceMgr::DK_Error:
429 DiagID = diag::err_fe_inline_asm;
431 case llvm::SourceMgr::DK_Warning:
432 DiagID = diag::warn_fe_inline_asm;
434 case llvm::SourceMgr::DK_Note:
435 DiagID = diag::note_fe_inline_asm;
437 case llvm::SourceMgr::DK_Remark:
438 llvm_unreachable("remarks unexpected");
440 // If this problem has clang-level source location information, report the
441 // issue in the source with a note showing the instantiated
443 if (LocCookie.isValid()) {
444 Diags.Report(LocCookie, DiagID).AddString(Message);
446 if (D.getLoc().isValid()) {
447 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
448 // Convert the SMDiagnostic ranges into SourceRange and attach them
449 // to the diagnostic.
450 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
451 unsigned Column = D.getColumnNo();
452 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
453 Loc.getLocWithOffset(Range.second - Column));
459 // Otherwise, report the backend issue as occurring in the generated .s file.
460 // If Loc is invalid, we still need to report the issue, it just gets no
462 Diags.Report(Loc, DiagID).AddString(Message);
465 #define ComputeDiagID(Severity, GroupName, DiagID) \
467 switch (Severity) { \
468 case llvm::DS_Error: \
469 DiagID = diag::err_fe_##GroupName; \
471 case llvm::DS_Warning: \
472 DiagID = diag::warn_fe_##GroupName; \
474 case llvm::DS_Remark: \
475 llvm_unreachable("'remark' severity not expected"); \
477 case llvm::DS_Note: \
478 DiagID = diag::note_fe_##GroupName; \
483 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
485 switch (Severity) { \
486 case llvm::DS_Error: \
487 DiagID = diag::err_fe_##GroupName; \
489 case llvm::DS_Warning: \
490 DiagID = diag::warn_fe_##GroupName; \
492 case llvm::DS_Remark: \
493 DiagID = diag::remark_fe_##GroupName; \
495 case llvm::DS_Note: \
496 DiagID = diag::note_fe_##GroupName; \
502 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
504 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
505 std::string Message = D.getMsgStr().str();
507 // If this problem has clang-level source location information, report the
508 // issue as being a problem in the source with a note showing the instantiated
510 SourceLocation LocCookie =
511 SourceLocation::getFromRawEncoding(D.getLocCookie());
512 if (LocCookie.isValid())
513 Diags.Report(LocCookie, DiagID).AddString(Message);
515 // Otherwise, report the backend diagnostic as occurring in the generated
517 // If Loc is invalid, we still need to report the diagnostic, it just gets
520 Diags.Report(Loc, DiagID).AddString(Message);
522 // We handled all the possible severities.
527 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
528 if (D.getSeverity() != llvm::DS_Warning)
529 // For now, the only support we have for StackSize diagnostic is warning.
530 // We do not know how to format other severities.
533 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
534 // FIXME: Shouldn't need to truncate to uint32_t
535 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
536 diag::warn_fe_frame_larger_than)
537 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
544 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
545 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
546 StringRef &Filename, unsigned &Line, unsigned &Column) const {
547 SourceManager &SourceMgr = Context->getSourceManager();
548 FileManager &FileMgr = SourceMgr.getFileManager();
549 SourceLocation DILoc;
551 if (D.isLocationAvailable()) {
552 D.getLocation(Filename, Line, Column);
554 const FileEntry *FE = FileMgr.getFile(Filename);
556 FE = FileMgr.getFile(D.getAbsolutePath());
558 // If -gcolumn-info was not used, Column will be 0. This upsets the
559 // source manager, so pass 1 if Column is not set.
560 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
563 BadDebugInfo = DILoc.isInvalid();
566 // If a location isn't available, try to approximate it using the associated
567 // function definition. We use the definition's right brace to differentiate
568 // from diagnostics that genuinely relate to the function itself.
569 FullSourceLoc Loc(DILoc, SourceMgr);
571 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
572 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
574 if (DILoc.isInvalid() && D.isLocationAvailable())
575 // If we were not able to translate the file:line:col information
576 // back to a SourceLocation, at least emit a note stating that
577 // we could not translate this location. This can happen in the
578 // case of #line directives.
579 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
580 << Filename << Line << Column;
585 void BackendConsumer::UnsupportedDiagHandler(
586 const llvm::DiagnosticInfoUnsupported &D) {
587 // We only support errors.
588 assert(D.getSeverity() == llvm::DS_Error);
591 unsigned Line, Column;
592 bool BadDebugInfo = false;
594 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
596 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
599 // If we were not able to translate the file:line:col information
600 // back to a SourceLocation, at least emit a note stating that
601 // we could not translate this location. This can happen in the
602 // case of #line directives.
603 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
604 << Filename << Line << Column;
607 void BackendConsumer::EmitOptimizationMessage(
608 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
609 // We only support warnings and remarks.
610 assert(D.getSeverity() == llvm::DS_Remark ||
611 D.getSeverity() == llvm::DS_Warning);
614 unsigned Line, Column;
615 bool BadDebugInfo = false;
617 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
620 raw_string_ostream MsgStream(Msg);
621 MsgStream << D.getMsg();
624 MsgStream << " (hotness: " << *D.getHotness() << ")";
626 Diags.Report(Loc, DiagID)
627 << AddFlagValue(D.getPassName())
631 // If we were not able to translate the file:line:col information
632 // back to a SourceLocation, at least emit a note stating that
633 // we could not translate this location. This can happen in the
634 // case of #line directives.
635 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
636 << Filename << Line << Column;
639 void BackendConsumer::OptimizationRemarkHandler(
640 const llvm::DiagnosticInfoOptimizationBase &D) {
641 // Without hotness information, don't show noisy remarks.
642 if (D.isVerbose() && !D.getHotness())
646 // Optimization remarks are active only if the -Rpass flag has a regular
647 // expression that matches the name of the pass name in \p D.
648 if (CodeGenOpts.OptimizationRemarkPattern &&
649 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
650 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
651 } else if (D.isMissed()) {
652 // Missed optimization remarks are active only if the -Rpass-missed
653 // flag has a regular expression that matches the name of the pass
655 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
656 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
657 EmitOptimizationMessage(
658 D, diag::remark_fe_backend_optimization_remark_missed);
660 assert(D.isAnalysis() && "Unknown remark type");
662 bool ShouldAlwaysPrint = false;
663 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
664 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
666 if (ShouldAlwaysPrint ||
667 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
668 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
669 EmitOptimizationMessage(
670 D, diag::remark_fe_backend_optimization_remark_analysis);
674 void BackendConsumer::OptimizationRemarkHandler(
675 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
676 // Optimization analysis remarks are active if the pass name is set to
677 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
678 // regular expression that matches the name of the pass name in \p D.
680 if (D.shouldAlwaysPrint() ||
681 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
682 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
683 EmitOptimizationMessage(
684 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
687 void BackendConsumer::OptimizationRemarkHandler(
688 const llvm::OptimizationRemarkAnalysisAliasing &D) {
689 // Optimization analysis remarks are active if the pass name is set to
690 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
691 // regular expression that matches the name of the pass name in \p D.
693 if (D.shouldAlwaysPrint() ||
694 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
695 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
696 EmitOptimizationMessage(
697 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
700 void BackendConsumer::OptimizationFailureHandler(
701 const llvm::DiagnosticInfoOptimizationFailure &D) {
702 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
705 /// This function is invoked when the backend needs
706 /// to report something to the user.
707 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
708 unsigned DiagID = diag::err_fe_inline_asm;
709 llvm::DiagnosticSeverity Severity = DI.getSeverity();
710 // Get the diagnostic ID based.
711 switch (DI.getKind()) {
712 case llvm::DK_InlineAsm:
713 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
715 ComputeDiagID(Severity, inline_asm, DiagID);
717 case llvm::DK_StackSize:
718 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
720 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
723 assert(CurLinkModule);
724 // FIXME: stop eating the warnings and notes.
725 if (Severity != DS_Error)
727 DiagID = diag::err_fe_cannot_link_module;
729 case llvm::DK_OptimizationRemark:
730 // Optimization remarks are always handled completely by this
731 // handler. There is no generic way of emitting them.
732 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
734 case llvm::DK_OptimizationRemarkMissed:
735 // Optimization remarks are always handled completely by this
736 // handler. There is no generic way of emitting them.
737 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
739 case llvm::DK_OptimizationRemarkAnalysis:
740 // Optimization remarks are always handled completely by this
741 // handler. There is no generic way of emitting them.
742 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
744 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
745 // Optimization remarks are always handled completely by this
746 // handler. There is no generic way of emitting them.
747 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
749 case llvm::DK_OptimizationRemarkAnalysisAliasing:
750 // Optimization remarks are always handled completely by this
751 // handler. There is no generic way of emitting them.
752 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
754 case llvm::DK_MachineOptimizationRemark:
755 // Optimization remarks are always handled completely by this
756 // handler. There is no generic way of emitting them.
757 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
759 case llvm::DK_MachineOptimizationRemarkMissed:
760 // Optimization remarks are always handled completely by this
761 // handler. There is no generic way of emitting them.
762 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
764 case llvm::DK_MachineOptimizationRemarkAnalysis:
765 // Optimization remarks are always handled completely by this
766 // handler. There is no generic way of emitting them.
767 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
769 case llvm::DK_OptimizationFailure:
770 // Optimization failures are always handled completely by this
772 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
774 case llvm::DK_Unsupported:
775 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
778 // Plugin IDs are not bound to any value as they are set dynamically.
779 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
782 std::string MsgStorage;
784 raw_string_ostream Stream(MsgStorage);
785 DiagnosticPrinterRawOStream DP(Stream);
789 if (DiagID == diag::err_fe_cannot_link_module) {
790 Diags.Report(diag::err_fe_cannot_link_module)
791 << CurLinkModule->getModuleIdentifier() << MsgStorage;
795 // Report the backend message using the usual diagnostic mechanism.
797 Diags.Report(Loc, DiagID).AddString(MsgStorage);
801 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
802 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
803 OwnsVMContext(!_VMContext) {}
805 CodeGenAction::~CodeGenAction() {
811 bool CodeGenAction::hasIRSupport() const { return true; }
813 void CodeGenAction::EndSourceFileAction() {
814 // If the consumer creation failed, do nothing.
815 if (!getCompilerInstance().hasASTConsumer())
818 // Steal the module from the consumer.
819 TheModule = BEConsumer->takeModule();
822 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
823 return std::move(TheModule);
826 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
827 OwnsVMContext = false;
831 static std::unique_ptr<raw_pwrite_stream>
832 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
834 case Backend_EmitAssembly:
835 return CI.createDefaultOutputFile(false, InFile, "s");
837 return CI.createDefaultOutputFile(false, InFile, "ll");
839 return CI.createDefaultOutputFile(true, InFile, "bc");
840 case Backend_EmitNothing:
842 case Backend_EmitMCNull:
843 return CI.createNullOutputFile();
844 case Backend_EmitObj:
845 return CI.createDefaultOutputFile(true, InFile, "o");
848 llvm_unreachable("Invalid action!");
851 std::unique_ptr<ASTConsumer>
852 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
853 BackendAction BA = static_cast<BackendAction>(Act);
854 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
856 OS = GetOutputStream(CI, InFile, BA);
858 if (BA != Backend_EmitNothing && !OS)
861 // Load bitcode modules to link with, if we need to.
862 if (LinkModules.empty())
863 for (const CodeGenOptions::BitcodeFileToLink &F :
864 CI.getCodeGenOpts().LinkBitcodeFiles) {
865 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
867 CI.getDiagnostics().Report(diag::err_cannot_open_file)
868 << F.Filename << BCBuf.getError().message();
873 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
874 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
876 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
877 CI.getDiagnostics().Report(diag::err_cannot_open_file)
878 << F.Filename << EIB.message();
883 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
884 F.Internalize, F.LinkFlags});
887 CoverageSourceInfo *CoverageInfo = nullptr;
888 // Add the preprocessor callback only when the coverage mapping is generated.
889 if (CI.getCodeGenOpts().CoverageMapping) {
890 CoverageInfo = new CoverageSourceInfo;
891 CI.getPreprocessor().addPPCallbacks(
892 std::unique_ptr<PPCallbacks>(CoverageInfo));
895 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
896 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
897 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
898 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
899 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
900 BEConsumer = Result.get();
902 // Enable generating macro debug info only when debug info is not disabled and
903 // also macro debug info is enabled.
904 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
905 CI.getCodeGenOpts().MacroDebugInfo) {
906 std::unique_ptr<PPCallbacks> Callbacks =
907 llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
908 CI.getPreprocessor());
909 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
912 return std::move(Result);
915 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
917 unsigned LocCookie) {
918 SM.print(nullptr, llvm::errs());
920 auto Diags = static_cast<DiagnosticsEngine *>(Context);
922 switch (SM.getKind()) {
923 case llvm::SourceMgr::DK_Error:
924 DiagID = diag::err_fe_inline_asm;
926 case llvm::SourceMgr::DK_Warning:
927 DiagID = diag::warn_fe_inline_asm;
929 case llvm::SourceMgr::DK_Note:
930 DiagID = diag::note_fe_inline_asm;
932 case llvm::SourceMgr::DK_Remark:
933 llvm_unreachable("remarks unexpected");
936 Diags->Report(DiagID).AddString("cannot compile inline asm");
939 std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
940 CompilerInstance &CI = getCompilerInstance();
941 SourceManager &SM = CI.getSourceManager();
943 // For ThinLTO backend invocations, ensure that the context
944 // merges types based on ODR identifiers. We also need to read
945 // the correct module out of a multi-module bitcode file.
946 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
947 VMContext->enableDebugTypeODRUniquing();
949 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
951 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
952 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
953 CI.getDiagnostics().Report(DiagID) << EIB.message();
958 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
960 return DiagErrors(BMsOrErr.takeError());
961 BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
962 // We have nothing to do if the file contains no ThinLTO module. This is
963 // possible if ThinLTO compilation was not able to split module. Content of
964 // the file was already processed by indexing and will be passed to the
965 // linker using merged object file.
967 auto M = llvm::make_unique<llvm::Module>("empty", *VMContext);
968 M->setTargetTriple(CI.getTargetOpts().Triple);
971 Expected<std::unique_ptr<llvm::Module>> MOrErr =
972 Bm->parseModule(*VMContext);
974 return DiagErrors(MOrErr.takeError());
975 return std::move(*MOrErr);
978 llvm::SMDiagnostic Err;
979 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
982 // Translate from the diagnostic info to the SourceManager location if
984 // TODO: Unify this with ConvertBackendLocation()
986 if (Err.getLineNo() > 0) {
987 assert(Err.getColumnNo() >= 0);
988 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
989 Err.getLineNo(), Err.getColumnNo() + 1);
992 // Strip off a leading diagnostic code if there is one.
993 StringRef Msg = Err.getMessage();
994 if (Msg.startswith("error: "))
998 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1000 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1004 void CodeGenAction::ExecuteAction() {
1005 // If this is an IR file, we have to treat it specially.
1006 if (getCurrentFileKind().getLanguage() == InputKind::LLVM_IR) {
1007 BackendAction BA = static_cast<BackendAction>(Act);
1008 CompilerInstance &CI = getCompilerInstance();
1009 std::unique_ptr<raw_pwrite_stream> OS =
1010 GetOutputStream(CI, getCurrentFile(), BA);
1011 if (BA != Backend_EmitNothing && !OS)
1015 SourceManager &SM = CI.getSourceManager();
1016 FileID FID = SM.getMainFileID();
1017 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
1021 TheModule = loadModule(*MainFile);
1025 const TargetOptions &TargetOpts = CI.getTargetOpts();
1026 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1027 CI.getDiagnostics().Report(SourceLocation(),
1028 diag::warn_fe_override_module)
1029 << TargetOpts.Triple;
1030 TheModule->setTargetTriple(TargetOpts.Triple);
1033 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
1034 MainFile->getMemBufferRef());
1036 LLVMContext &Ctx = TheModule->getContext();
1037 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
1038 &CI.getDiagnostics());
1040 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1041 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
1042 CI.getTarget().getDataLayout(), TheModule.get(), BA,
1047 // Otherwise follow the normal AST path.
1048 this->ASTFrontendAction::ExecuteAction();
1053 void EmitAssemblyAction::anchor() { }
1054 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1055 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1057 void EmitBCAction::anchor() { }
1058 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1059 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1061 void EmitLLVMAction::anchor() { }
1062 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1063 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1065 void EmitLLVMOnlyAction::anchor() { }
1066 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1067 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1069 void EmitCodeGenOnlyAction::anchor() { }
1070 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1071 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1073 void EmitObjAction::anchor() { }
1074 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1075 : CodeGenAction(Backend_EmitObj, _VMContext) {}