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/Bitcode/BitcodeReader.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IRReader/IRReader.h"
31 #include "llvm/Linker/Linker.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/Timer.h"
36 #include "llvm/Support/ToolOutputFile.h"
37 #include "llvm/Support/YAMLTraits.h"
39 using namespace clang;
43 class BackendConsumer : public ASTConsumer {
44 virtual void anchor();
45 DiagnosticsEngine &Diags;
47 const HeaderSearchOptions &HeaderSearchOpts;
48 const CodeGenOptions &CodeGenOpts;
49 const TargetOptions &TargetOpts;
50 const LangOptions &LangOpts;
51 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
54 Timer LLVMIRGeneration;
55 unsigned LLVMIRGenerationRefCount;
57 /// True if we've finished generating IR. This prevents us from generating
58 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
59 /// can happen when Clang plugins trigger additional AST deserialization.
60 bool IRGenFinished = false;
62 std::unique_ptr<CodeGenerator> Gen;
64 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
67 // This is here so that the diagnostic printer knows the module a diagnostic
69 llvm::Module *CurLinkModule = nullptr;
73 BackendAction Action, DiagnosticsEngine &Diags,
74 const HeaderSearchOptions &HeaderSearchOpts,
75 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
76 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
77 bool TimePasses, const std::string &InFile,
78 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
79 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
80 CoverageSourceInfo *CoverageInfo = nullptr)
81 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
82 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
83 AsmOutStream(std::move(OS)), Context(nullptr),
84 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
85 LLVMIRGenerationRefCount(0),
86 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
87 CodeGenOpts, C, CoverageInfo)) {
88 llvm::TimePassesIsEnabled = TimePasses;
89 for (auto &I : LinkModules)
90 this->LinkModules.push_back(
91 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
93 llvm::Module *getModule() const { return Gen->GetModule(); }
94 std::unique_ptr<llvm::Module> takeModule() {
95 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
97 void releaseLinkModules() {
98 for (auto &I : LinkModules)
102 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
103 Gen->HandleCXXStaticMemberVarInstantiation(VD);
106 void Initialize(ASTContext &Ctx) override {
107 assert(!Context && "initialized multiple times");
111 if (llvm::TimePassesIsEnabled)
112 LLVMIRGeneration.startTimer();
114 Gen->Initialize(Ctx);
116 if (llvm::TimePassesIsEnabled)
117 LLVMIRGeneration.stopTimer();
120 bool HandleTopLevelDecl(DeclGroupRef D) override {
121 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
122 Context->getSourceManager(),
123 "LLVM IR generation of declaration");
126 if (llvm::TimePassesIsEnabled) {
127 LLVMIRGenerationRefCount += 1;
128 if (LLVMIRGenerationRefCount == 1)
129 LLVMIRGeneration.startTimer();
132 Gen->HandleTopLevelDecl(D);
134 if (llvm::TimePassesIsEnabled) {
135 LLVMIRGenerationRefCount -= 1;
136 if (LLVMIRGenerationRefCount == 0)
137 LLVMIRGeneration.stopTimer();
143 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
144 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
145 Context->getSourceManager(),
146 "LLVM IR generation of inline function");
147 if (llvm::TimePassesIsEnabled)
148 LLVMIRGeneration.startTimer();
150 Gen->HandleInlineFunctionDefinition(D);
152 if (llvm::TimePassesIsEnabled)
153 LLVMIRGeneration.stopTimer();
156 void HandleInterestingDecl(DeclGroupRef D) override {
157 // Ignore interesting decls from the AST reader after IRGen is finished.
159 HandleTopLevelDecl(D);
162 void HandleTranslationUnit(ASTContext &C) override {
164 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
165 if (llvm::TimePassesIsEnabled) {
166 LLVMIRGenerationRefCount += 1;
167 if (LLVMIRGenerationRefCount == 1)
168 LLVMIRGeneration.startTimer();
171 Gen->HandleTranslationUnit(C);
173 if (llvm::TimePassesIsEnabled) {
174 LLVMIRGenerationRefCount -= 1;
175 if (LLVMIRGenerationRefCount == 0)
176 LLVMIRGeneration.stopTimer();
179 IRGenFinished = true;
182 // Silently ignore if we weren't initialized for some reason.
186 // Install an inline asm handler so that diagnostics get printed through
187 // our diagnostics hooks.
188 LLVMContext &Ctx = getModule()->getContext();
189 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
190 Ctx.getInlineAsmDiagnosticHandler();
191 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
192 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
194 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
195 Ctx.getDiagnosticHandler();
196 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
197 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
198 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
200 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
201 if (!CodeGenOpts.OptRecordFile.empty()) {
204 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
205 EC, sys::fs::F_None);
207 Diags.Report(diag::err_cannot_open_file) <<
208 CodeGenOpts.OptRecordFile << EC.message();
212 Ctx.setDiagnosticsOutputFile(
213 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
215 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
216 Ctx.setDiagnosticHotnessRequested(true);
219 // Link LinkModule into this module if present, preserving its validity.
220 for (auto &I : LinkModules) {
221 unsigned LinkFlags = I.first;
222 CurLinkModule = I.second.get();
223 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
227 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
229 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
230 LangOpts, C.getTargetInfo().getDataLayout(),
231 getModule(), Action, std::move(AsmOutStream));
233 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
235 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
238 OptRecordFile->keep();
241 void HandleTagDeclDefinition(TagDecl *D) override {
242 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
243 Context->getSourceManager(),
244 "LLVM IR generation of declaration");
245 Gen->HandleTagDeclDefinition(D);
248 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
249 Gen->HandleTagDeclRequiredDefinition(D);
252 void CompleteTentativeDefinition(VarDecl *D) override {
253 Gen->CompleteTentativeDefinition(D);
256 void AssignInheritanceModel(CXXRecordDecl *RD) override {
257 Gen->AssignInheritanceModel(RD);
260 void HandleVTable(CXXRecordDecl *RD) override {
261 Gen->HandleVTable(RD);
264 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
265 unsigned LocCookie) {
266 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
267 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
270 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
272 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
275 /// Get the best possible source location to represent a diagnostic that
276 /// may have associated debug info.
278 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
279 bool &BadDebugInfo, StringRef &Filename,
280 unsigned &Line, unsigned &Column) const;
282 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
283 SourceLocation LocCookie);
285 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
286 /// \brief Specialized handler for InlineAsm diagnostic.
287 /// \return True if the diagnostic has been successfully reported, false
289 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
290 /// \brief Specialized handler for StackSize diagnostic.
291 /// \return True if the diagnostic has been successfully reported, false
293 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
294 /// \brief Specialized handler for unsupported backend feature diagnostic.
295 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
296 /// \brief Specialized handlers for optimization remarks.
297 /// Note that these handlers only accept remarks and they always handle
299 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
301 void OptimizationRemarkHandler(const llvm::OptimizationRemark &D);
302 void OptimizationRemarkHandler(const llvm::OptimizationRemarkMissed &D);
303 void OptimizationRemarkHandler(const llvm::OptimizationRemarkAnalysis &D);
304 void OptimizationRemarkHandler(
305 const llvm::OptimizationRemarkAnalysisFPCommute &D);
306 void OptimizationRemarkHandler(
307 const llvm::OptimizationRemarkAnalysisAliasing &D);
308 void OptimizationFailureHandler(
309 const llvm::DiagnosticInfoOptimizationFailure &D);
312 void BackendConsumer::anchor() {}
315 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
316 /// buffer to be a valid FullSourceLoc.
317 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
318 SourceManager &CSM) {
319 // Get both the clang and llvm source managers. The location is relative to
320 // a memory buffer that the LLVM Source Manager is handling, we need to add
321 // a copy to the Clang source manager.
322 const llvm::SourceMgr &LSM = *D.getSourceMgr();
324 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
325 // already owns its one and clang::SourceManager wants to own its one.
326 const MemoryBuffer *LBuf =
327 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
329 // Create the copy and transfer ownership to clang::SourceManager.
330 // TODO: Avoid copying files into memory.
331 std::unique_ptr<llvm::MemoryBuffer> CBuf =
332 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
333 LBuf->getBufferIdentifier());
334 // FIXME: Keep a file ID map instead of creating new IDs for each location.
335 FileID FID = CSM.createFileID(std::move(CBuf));
337 // Translate the offset into the file.
338 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
339 SourceLocation NewLoc =
340 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
341 return FullSourceLoc(NewLoc, CSM);
345 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
346 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
347 /// the temporary memory buffer that the inline asm parser has set up.
348 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
349 SourceLocation LocCookie) {
350 // There are a couple of different kinds of errors we could get here. First,
351 // we re-format the SMDiagnostic in terms of a clang diagnostic.
353 // Strip "error: " off the start of the message string.
354 StringRef Message = D.getMessage();
355 if (Message.startswith("error: "))
356 Message = Message.substr(7);
358 // If the SMDiagnostic has an inline asm source location, translate it.
360 if (D.getLoc() != SMLoc())
361 Loc = ConvertBackendLocation(D, Context->getSourceManager());
364 switch (D.getKind()) {
365 case llvm::SourceMgr::DK_Error:
366 DiagID = diag::err_fe_inline_asm;
368 case llvm::SourceMgr::DK_Warning:
369 DiagID = diag::warn_fe_inline_asm;
371 case llvm::SourceMgr::DK_Note:
372 DiagID = diag::note_fe_inline_asm;
375 // If this problem has clang-level source location information, report the
376 // issue in the source with a note showing the instantiated
378 if (LocCookie.isValid()) {
379 Diags.Report(LocCookie, DiagID).AddString(Message);
381 if (D.getLoc().isValid()) {
382 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
383 // Convert the SMDiagnostic ranges into SourceRange and attach them
384 // to the diagnostic.
385 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
386 unsigned Column = D.getColumnNo();
387 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
388 Loc.getLocWithOffset(Range.second - Column));
394 // Otherwise, report the backend issue as occurring in the generated .s file.
395 // If Loc is invalid, we still need to report the issue, it just gets no
397 Diags.Report(Loc, DiagID).AddString(Message);
400 #define ComputeDiagID(Severity, GroupName, DiagID) \
402 switch (Severity) { \
403 case llvm::DS_Error: \
404 DiagID = diag::err_fe_##GroupName; \
406 case llvm::DS_Warning: \
407 DiagID = diag::warn_fe_##GroupName; \
409 case llvm::DS_Remark: \
410 llvm_unreachable("'remark' severity not expected"); \
412 case llvm::DS_Note: \
413 DiagID = diag::note_fe_##GroupName; \
418 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
420 switch (Severity) { \
421 case llvm::DS_Error: \
422 DiagID = diag::err_fe_##GroupName; \
424 case llvm::DS_Warning: \
425 DiagID = diag::warn_fe_##GroupName; \
427 case llvm::DS_Remark: \
428 DiagID = diag::remark_fe_##GroupName; \
430 case llvm::DS_Note: \
431 DiagID = diag::note_fe_##GroupName; \
437 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
439 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
440 std::string Message = D.getMsgStr().str();
442 // If this problem has clang-level source location information, report the
443 // issue as being a problem in the source with a note showing the instantiated
445 SourceLocation LocCookie =
446 SourceLocation::getFromRawEncoding(D.getLocCookie());
447 if (LocCookie.isValid())
448 Diags.Report(LocCookie, DiagID).AddString(Message);
450 // Otherwise, report the backend diagnostic as occurring in the generated
452 // If Loc is invalid, we still need to report the diagnostic, it just gets
455 Diags.Report(Loc, DiagID).AddString(Message);
457 // We handled all the possible severities.
462 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
463 if (D.getSeverity() != llvm::DS_Warning)
464 // For now, the only support we have for StackSize diagnostic is warning.
465 // We do not know how to format other severities.
468 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
469 // FIXME: Shouldn't need to truncate to uint32_t
470 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
471 diag::warn_fe_frame_larger_than)
472 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
479 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
480 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
481 unsigned &Line, unsigned &Column) const {
482 SourceManager &SourceMgr = Context->getSourceManager();
483 FileManager &FileMgr = SourceMgr.getFileManager();
484 SourceLocation DILoc;
486 if (D.isLocationAvailable()) {
487 D.getLocation(&Filename, &Line, &Column);
488 const FileEntry *FE = FileMgr.getFile(Filename);
489 if (FE && Line > 0) {
490 // If -gcolumn-info was not used, Column will be 0. This upsets the
491 // source manager, so pass 1 if Column is not set.
492 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
494 BadDebugInfo = DILoc.isInvalid();
497 // If a location isn't available, try to approximate it using the associated
498 // function definition. We use the definition's right brace to differentiate
499 // from diagnostics that genuinely relate to the function itself.
500 FullSourceLoc Loc(DILoc, SourceMgr);
502 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
503 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
505 if (DILoc.isInvalid() && D.isLocationAvailable())
506 // If we were not able to translate the file:line:col information
507 // back to a SourceLocation, at least emit a note stating that
508 // we could not translate this location. This can happen in the
509 // case of #line directives.
510 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
511 << Filename << Line << Column;
516 void BackendConsumer::UnsupportedDiagHandler(
517 const llvm::DiagnosticInfoUnsupported &D) {
518 // We only support errors.
519 assert(D.getSeverity() == llvm::DS_Error);
522 unsigned Line, Column;
524 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
527 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
530 // If we were not able to translate the file:line:col information
531 // back to a SourceLocation, at least emit a note stating that
532 // we could not translate this location. This can happen in the
533 // case of #line directives.
534 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
535 << Filename << Line << Column;
538 void BackendConsumer::EmitOptimizationMessage(
539 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
540 // We only support warnings and remarks.
541 assert(D.getSeverity() == llvm::DS_Remark ||
542 D.getSeverity() == llvm::DS_Warning);
545 unsigned Line, Column;
546 bool BadDebugInfo = false;
547 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
551 raw_string_ostream MsgStream(Msg);
552 MsgStream << D.getMsg();
555 MsgStream << " (hotness: " << *D.getHotness() << ")";
557 Diags.Report(Loc, DiagID)
558 << AddFlagValue(D.getPassName())
562 // If we were not able to translate the file:line:col information
563 // back to a SourceLocation, at least emit a note stating that
564 // we could not translate this location. This can happen in the
565 // case of #line directives.
566 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
567 << Filename << Line << Column;
570 void BackendConsumer::OptimizationRemarkHandler(
571 const llvm::OptimizationRemark &D) {
572 // Optimization remarks are active only if the -Rpass flag has a regular
573 // expression that matches the name of the pass name in \p D.
574 if (CodeGenOpts.OptimizationRemarkPattern &&
575 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
576 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
579 void BackendConsumer::OptimizationRemarkHandler(
580 const llvm::OptimizationRemarkMissed &D) {
581 // Missed optimization remarks are active only if the -Rpass-missed
582 // flag has a regular expression that matches the name of the pass
584 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
585 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
586 EmitOptimizationMessage(D,
587 diag::remark_fe_backend_optimization_remark_missed);
590 void BackendConsumer::OptimizationRemarkHandler(
591 const llvm::OptimizationRemarkAnalysis &D) {
592 // Optimization analysis remarks are active if the pass name is set to
593 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
594 // regular expression that matches the name of the pass name in \p D.
596 if (D.shouldAlwaysPrint() ||
597 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
598 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
599 EmitOptimizationMessage(
600 D, diag::remark_fe_backend_optimization_remark_analysis);
603 void BackendConsumer::OptimizationRemarkHandler(
604 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
605 // Optimization analysis remarks are active if the pass name is set to
606 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
607 // regular expression that matches the name of the pass name in \p D.
609 if (D.shouldAlwaysPrint() ||
610 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
611 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
612 EmitOptimizationMessage(
613 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
616 void BackendConsumer::OptimizationRemarkHandler(
617 const llvm::OptimizationRemarkAnalysisAliasing &D) {
618 // Optimization analysis remarks are active if the pass name is set to
619 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
620 // regular expression that matches the name of the pass name in \p D.
622 if (D.shouldAlwaysPrint() ||
623 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
624 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
625 EmitOptimizationMessage(
626 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
629 void BackendConsumer::OptimizationFailureHandler(
630 const llvm::DiagnosticInfoOptimizationFailure &D) {
631 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
634 /// \brief This function is invoked when the backend needs
635 /// to report something to the user.
636 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
637 unsigned DiagID = diag::err_fe_inline_asm;
638 llvm::DiagnosticSeverity Severity = DI.getSeverity();
639 // Get the diagnostic ID based.
640 switch (DI.getKind()) {
641 case llvm::DK_InlineAsm:
642 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
644 ComputeDiagID(Severity, inline_asm, DiagID);
646 case llvm::DK_StackSize:
647 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
649 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
652 assert(CurLinkModule);
653 // FIXME: stop eating the warnings and notes.
654 if (Severity != DS_Error)
656 DiagID = diag::err_fe_cannot_link_module;
658 case llvm::DK_OptimizationRemark:
659 // Optimization remarks are always handled completely by this
660 // handler. There is no generic way of emitting them.
661 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
663 case llvm::DK_OptimizationRemarkMissed:
664 // Optimization remarks are always handled completely by this
665 // handler. There is no generic way of emitting them.
666 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
668 case llvm::DK_OptimizationRemarkAnalysis:
669 // Optimization remarks are always handled completely by this
670 // handler. There is no generic way of emitting them.
671 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
673 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
674 // Optimization remarks are always handled completely by this
675 // handler. There is no generic way of emitting them.
676 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
678 case llvm::DK_OptimizationRemarkAnalysisAliasing:
679 // Optimization remarks are always handled completely by this
680 // handler. There is no generic way of emitting them.
681 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
683 case llvm::DK_OptimizationFailure:
684 // Optimization failures are always handled completely by this
686 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
688 case llvm::DK_Unsupported:
689 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
692 // Plugin IDs are not bound to any value as they are set dynamically.
693 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
696 std::string MsgStorage;
698 raw_string_ostream Stream(MsgStorage);
699 DiagnosticPrinterRawOStream DP(Stream);
703 if (DiagID == diag::err_fe_cannot_link_module) {
704 Diags.Report(diag::err_fe_cannot_link_module)
705 << CurLinkModule->getModuleIdentifier() << MsgStorage;
709 // Report the backend message using the usual diagnostic mechanism.
711 Diags.Report(Loc, DiagID).AddString(MsgStorage);
715 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
716 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
717 OwnsVMContext(!_VMContext) {}
719 CodeGenAction::~CodeGenAction() {
725 bool CodeGenAction::hasIRSupport() const { return true; }
727 void CodeGenAction::EndSourceFileAction() {
728 // If the consumer creation failed, do nothing.
729 if (!getCompilerInstance().hasASTConsumer())
732 // Take back ownership of link modules we passed to consumer.
733 if (!LinkModules.empty())
734 BEConsumer->releaseLinkModules();
736 // Steal the module from the consumer.
737 TheModule = BEConsumer->takeModule();
740 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
741 return std::move(TheModule);
744 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
745 OwnsVMContext = false;
749 static std::unique_ptr<raw_pwrite_stream>
750 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
752 case Backend_EmitAssembly:
753 return CI.createDefaultOutputFile(false, InFile, "s");
755 return CI.createDefaultOutputFile(false, InFile, "ll");
757 return CI.createDefaultOutputFile(true, InFile, "bc");
758 case Backend_EmitNothing:
760 case Backend_EmitMCNull:
761 return CI.createNullOutputFile();
762 case Backend_EmitObj:
763 return CI.createDefaultOutputFile(true, InFile, "o");
766 llvm_unreachable("Invalid action!");
769 std::unique_ptr<ASTConsumer>
770 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
771 BackendAction BA = static_cast<BackendAction>(Act);
772 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
773 if (BA != Backend_EmitNothing && !OS)
776 // Load bitcode modules to link with, if we need to.
777 if (LinkModules.empty())
778 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
779 const std::string &LinkBCFile = I.second;
781 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
783 CI.getDiagnostics().Report(diag::err_cannot_open_file)
784 << LinkBCFile << BCBuf.getError().message();
789 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
790 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
792 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
793 CI.getDiagnostics().Report(diag::err_cannot_open_file)
794 << LinkBCFile << EIB.message();
799 addLinkModule(ModuleOrErr.get().release(), I.first);
802 CoverageSourceInfo *CoverageInfo = nullptr;
803 // Add the preprocessor callback only when the coverage mapping is generated.
804 if (CI.getCodeGenOpts().CoverageMapping) {
805 CoverageInfo = new CoverageSourceInfo;
806 CI.getPreprocessor().addPPCallbacks(
807 std::unique_ptr<PPCallbacks>(CoverageInfo));
810 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
811 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
812 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
813 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
814 std::move(OS), *VMContext, CoverageInfo));
815 BEConsumer = Result.get();
816 return std::move(Result);
819 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
821 unsigned LocCookie) {
822 SM.print(nullptr, llvm::errs());
824 auto Diags = static_cast<DiagnosticsEngine *>(Context);
826 switch (SM.getKind()) {
827 case llvm::SourceMgr::DK_Error:
828 DiagID = diag::err_fe_inline_asm;
830 case llvm::SourceMgr::DK_Warning:
831 DiagID = diag::warn_fe_inline_asm;
833 case llvm::SourceMgr::DK_Note:
834 DiagID = diag::note_fe_inline_asm;
838 Diags->Report(DiagID).AddString("cannot compile inline asm");
841 void CodeGenAction::ExecuteAction() {
842 // If this is an IR file, we have to treat it specially.
843 if (getCurrentFileKind() == IK_LLVM_IR) {
844 BackendAction BA = static_cast<BackendAction>(Act);
845 CompilerInstance &CI = getCompilerInstance();
846 std::unique_ptr<raw_pwrite_stream> OS =
847 GetOutputStream(CI, getCurrentFile(), BA);
848 if (BA != Backend_EmitNothing && !OS)
852 SourceManager &SM = CI.getSourceManager();
853 FileID FID = SM.getMainFileID();
854 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
858 // For ThinLTO backend invocations, ensure that the context
859 // merges types based on ODR identifiers.
860 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
861 VMContext->enableDebugTypeODRUniquing();
863 llvm::SMDiagnostic Err;
864 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
866 // Translate from the diagnostic info to the SourceManager location if
868 // TODO: Unify this with ConvertBackendLocation()
870 if (Err.getLineNo() > 0) {
871 assert(Err.getColumnNo() >= 0);
872 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
873 Err.getLineNo(), Err.getColumnNo() + 1);
876 // Strip off a leading diagnostic code if there is one.
877 StringRef Msg = Err.getMessage();
878 if (Msg.startswith("error: "))
882 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
884 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
887 const TargetOptions &TargetOpts = CI.getTargetOpts();
888 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
889 CI.getDiagnostics().Report(SourceLocation(),
890 diag::warn_fe_override_module)
891 << TargetOpts.Triple;
892 TheModule->setTargetTriple(TargetOpts.Triple);
895 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
896 MainFile->getMemBufferRef());
898 LLVMContext &Ctx = TheModule->getContext();
899 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
900 &CI.getDiagnostics());
902 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
903 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
904 CI.getTarget().getDataLayout(), TheModule.get(), BA,
909 // Otherwise follow the normal AST path.
910 this->ASTFrontendAction::ExecuteAction();
915 void EmitAssemblyAction::anchor() { }
916 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
917 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
919 void EmitBCAction::anchor() { }
920 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
921 : CodeGenAction(Backend_EmitBC, _VMContext) {}
923 void EmitLLVMAction::anchor() { }
924 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
925 : CodeGenAction(Backend_EmitLL, _VMContext) {}
927 void EmitLLVMOnlyAction::anchor() { }
928 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
929 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
931 void EmitCodeGenOnlyAction::anchor() { }
932 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
933 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
935 void EmitObjAction::anchor() { }
936 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
937 : CodeGenAction(Backend_EmitObj, _VMContext) {}