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/ReaderWriter.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"
37 using namespace clang;
41 class BackendConsumer : public ASTConsumer {
42 virtual void anchor();
43 DiagnosticsEngine &Diags;
45 const CodeGenOptions &CodeGenOpts;
46 const TargetOptions &TargetOpts;
47 const LangOptions &LangOpts;
48 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
51 Timer LLVMIRGeneration;
53 std::unique_ptr<CodeGenerator> Gen;
55 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
58 // This is here so that the diagnostic printer knows the module a diagnostic
60 llvm::Module *CurLinkModule = nullptr;
64 BackendAction Action, DiagnosticsEngine &Diags,
65 const HeaderSearchOptions &HeaderSearchOpts,
66 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
67 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
68 bool TimePasses, const std::string &InFile,
69 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
70 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
71 CoverageSourceInfo *CoverageInfo = nullptr)
72 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
73 TargetOpts(TargetOpts), LangOpts(LangOpts),
74 AsmOutStream(std::move(OS)), Context(nullptr),
75 LLVMIRGeneration("LLVM IR Generation Time"),
76 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
77 CodeGenOpts, C, CoverageInfo)) {
78 llvm::TimePassesIsEnabled = TimePasses;
79 for (auto &I : LinkModules)
80 this->LinkModules.push_back(
81 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
83 llvm::Module *getModule() const { return Gen->GetModule(); }
84 std::unique_ptr<llvm::Module> takeModule() {
85 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
87 void releaseLinkModules() {
88 for (auto &I : LinkModules)
92 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
93 Gen->HandleCXXStaticMemberVarInstantiation(VD);
96 void Initialize(ASTContext &Ctx) override {
97 assert(!Context && "initialized multiple times");
101 if (llvm::TimePassesIsEnabled)
102 LLVMIRGeneration.startTimer();
104 Gen->Initialize(Ctx);
106 if (llvm::TimePassesIsEnabled)
107 LLVMIRGeneration.stopTimer();
110 bool HandleTopLevelDecl(DeclGroupRef D) override {
111 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
112 Context->getSourceManager(),
113 "LLVM IR generation of declaration");
115 if (llvm::TimePassesIsEnabled)
116 LLVMIRGeneration.startTimer();
118 Gen->HandleTopLevelDecl(D);
120 if (llvm::TimePassesIsEnabled)
121 LLVMIRGeneration.stopTimer();
126 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
127 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128 Context->getSourceManager(),
129 "LLVM IR generation of inline function");
130 if (llvm::TimePassesIsEnabled)
131 LLVMIRGeneration.startTimer();
133 Gen->HandleInlineFunctionDefinition(D);
135 if (llvm::TimePassesIsEnabled)
136 LLVMIRGeneration.stopTimer();
139 void HandleTranslationUnit(ASTContext &C) override {
141 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
142 if (llvm::TimePassesIsEnabled)
143 LLVMIRGeneration.startTimer();
145 Gen->HandleTranslationUnit(C);
147 if (llvm::TimePassesIsEnabled)
148 LLVMIRGeneration.stopTimer();
151 // Silently ignore if we weren't initialized for some reason.
155 // Install an inline asm handler so that diagnostics get printed through
156 // our diagnostics hooks.
157 LLVMContext &Ctx = getModule()->getContext();
158 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
159 Ctx.getInlineAsmDiagnosticHandler();
160 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
161 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
163 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
164 Ctx.getDiagnosticHandler();
165 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
166 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
168 // Link LinkModule into this module if present, preserving its validity.
169 for (auto &I : LinkModules) {
170 unsigned LinkFlags = I.first;
171 CurLinkModule = I.second.get();
172 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
176 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
178 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
179 C.getTargetInfo().getDataLayout(),
180 getModule(), Action, std::move(AsmOutStream));
182 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
184 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
187 void HandleTagDeclDefinition(TagDecl *D) override {
188 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
189 Context->getSourceManager(),
190 "LLVM IR generation of declaration");
191 Gen->HandleTagDeclDefinition(D);
194 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
195 Gen->HandleTagDeclRequiredDefinition(D);
198 void CompleteTentativeDefinition(VarDecl *D) override {
199 Gen->CompleteTentativeDefinition(D);
202 void AssignInheritanceModel(CXXRecordDecl *RD) override {
203 Gen->AssignInheritanceModel(RD);
206 void HandleVTable(CXXRecordDecl *RD) override {
207 Gen->HandleVTable(RD);
210 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
211 unsigned LocCookie) {
212 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
213 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
216 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
218 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
221 /// Get the best possible source location to represent a diagnostic that
222 /// may have associated debug info.
224 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
225 bool &BadDebugInfo, StringRef &Filename,
226 unsigned &Line, unsigned &Column) const;
228 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
229 SourceLocation LocCookie);
231 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
232 /// \brief Specialized handler for InlineAsm diagnostic.
233 /// \return True if the diagnostic has been successfully reported, false
235 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
236 /// \brief Specialized handler for StackSize diagnostic.
237 /// \return True if the diagnostic has been successfully reported, false
239 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
240 /// \brief Specialized handler for unsupported backend feature diagnostic.
241 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
242 /// \brief Specialized handlers for optimization remarks.
243 /// Note that these handlers only accept remarks and they always handle
245 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
248 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
249 void OptimizationRemarkHandler(
250 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
251 void OptimizationRemarkHandler(
252 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
253 void OptimizationRemarkHandler(
254 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
255 void OptimizationRemarkHandler(
256 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
257 void OptimizationFailureHandler(
258 const llvm::DiagnosticInfoOptimizationFailure &D);
261 void BackendConsumer::anchor() {}
264 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
265 /// buffer to be a valid FullSourceLoc.
266 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
267 SourceManager &CSM) {
268 // Get both the clang and llvm source managers. The location is relative to
269 // a memory buffer that the LLVM Source Manager is handling, we need to add
270 // a copy to the Clang source manager.
271 const llvm::SourceMgr &LSM = *D.getSourceMgr();
273 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
274 // already owns its one and clang::SourceManager wants to own its one.
275 const MemoryBuffer *LBuf =
276 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
278 // Create the copy and transfer ownership to clang::SourceManager.
279 // TODO: Avoid copying files into memory.
280 std::unique_ptr<llvm::MemoryBuffer> CBuf =
281 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
282 LBuf->getBufferIdentifier());
283 // FIXME: Keep a file ID map instead of creating new IDs for each location.
284 FileID FID = CSM.createFileID(std::move(CBuf));
286 // Translate the offset into the file.
287 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
288 SourceLocation NewLoc =
289 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
290 return FullSourceLoc(NewLoc, CSM);
294 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
295 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
296 /// the temporary memory buffer that the inline asm parser has set up.
297 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
298 SourceLocation LocCookie) {
299 // There are a couple of different kinds of errors we could get here. First,
300 // we re-format the SMDiagnostic in terms of a clang diagnostic.
302 // Strip "error: " off the start of the message string.
303 StringRef Message = D.getMessage();
304 if (Message.startswith("error: "))
305 Message = Message.substr(7);
307 // If the SMDiagnostic has an inline asm source location, translate it.
309 if (D.getLoc() != SMLoc())
310 Loc = ConvertBackendLocation(D, Context->getSourceManager());
313 switch (D.getKind()) {
314 case llvm::SourceMgr::DK_Error:
315 DiagID = diag::err_fe_inline_asm;
317 case llvm::SourceMgr::DK_Warning:
318 DiagID = diag::warn_fe_inline_asm;
320 case llvm::SourceMgr::DK_Note:
321 DiagID = diag::note_fe_inline_asm;
324 // If this problem has clang-level source location information, report the
325 // issue in the source with a note showing the instantiated
327 if (LocCookie.isValid()) {
328 Diags.Report(LocCookie, DiagID).AddString(Message);
330 if (D.getLoc().isValid()) {
331 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
332 // Convert the SMDiagnostic ranges into SourceRange and attach them
333 // to the diagnostic.
334 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
335 unsigned Column = D.getColumnNo();
336 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
337 Loc.getLocWithOffset(Range.second - Column));
343 // Otherwise, report the backend issue as occurring in the generated .s file.
344 // If Loc is invalid, we still need to report the issue, it just gets no
346 Diags.Report(Loc, DiagID).AddString(Message);
349 #define ComputeDiagID(Severity, GroupName, DiagID) \
351 switch (Severity) { \
352 case llvm::DS_Error: \
353 DiagID = diag::err_fe_##GroupName; \
355 case llvm::DS_Warning: \
356 DiagID = diag::warn_fe_##GroupName; \
358 case llvm::DS_Remark: \
359 llvm_unreachable("'remark' severity not expected"); \
361 case llvm::DS_Note: \
362 DiagID = diag::note_fe_##GroupName; \
367 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
369 switch (Severity) { \
370 case llvm::DS_Error: \
371 DiagID = diag::err_fe_##GroupName; \
373 case llvm::DS_Warning: \
374 DiagID = diag::warn_fe_##GroupName; \
376 case llvm::DS_Remark: \
377 DiagID = diag::remark_fe_##GroupName; \
379 case llvm::DS_Note: \
380 DiagID = diag::note_fe_##GroupName; \
386 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
388 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
389 std::string Message = D.getMsgStr().str();
391 // If this problem has clang-level source location information, report the
392 // issue as being a problem in the source with a note showing the instantiated
394 SourceLocation LocCookie =
395 SourceLocation::getFromRawEncoding(D.getLocCookie());
396 if (LocCookie.isValid())
397 Diags.Report(LocCookie, DiagID).AddString(Message);
399 // Otherwise, report the backend diagnostic as occurring in the generated
401 // If Loc is invalid, we still need to report the diagnostic, it just gets
404 Diags.Report(Loc, DiagID).AddString(Message);
406 // We handled all the possible severities.
411 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
412 if (D.getSeverity() != llvm::DS_Warning)
413 // For now, the only support we have for StackSize diagnostic is warning.
414 // We do not know how to format other severities.
417 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
418 // FIXME: Shouldn't need to truncate to uint32_t
419 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
420 diag::warn_fe_frame_larger_than)
421 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
428 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
429 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
430 unsigned &Line, unsigned &Column) const {
431 SourceManager &SourceMgr = Context->getSourceManager();
432 FileManager &FileMgr = SourceMgr.getFileManager();
433 SourceLocation DILoc;
435 if (D.isLocationAvailable()) {
436 D.getLocation(&Filename, &Line, &Column);
437 const FileEntry *FE = FileMgr.getFile(Filename);
438 if (FE && Line > 0) {
439 // If -gcolumn-info was not used, Column will be 0. This upsets the
440 // source manager, so pass 1 if Column is not set.
441 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
443 BadDebugInfo = DILoc.isInvalid();
446 // If a location isn't available, try to approximate it using the associated
447 // function definition. We use the definition's right brace to differentiate
448 // from diagnostics that genuinely relate to the function itself.
449 FullSourceLoc Loc(DILoc, SourceMgr);
451 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
452 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
454 if (DILoc.isInvalid() && D.isLocationAvailable())
455 // If we were not able to translate the file:line:col information
456 // back to a SourceLocation, at least emit a note stating that
457 // we could not translate this location. This can happen in the
458 // case of #line directives.
459 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
460 << Filename << Line << Column;
465 void BackendConsumer::UnsupportedDiagHandler(
466 const llvm::DiagnosticInfoUnsupported &D) {
467 // We only support errors.
468 assert(D.getSeverity() == llvm::DS_Error);
471 unsigned Line, Column;
473 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
476 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
479 // If we were not able to translate the file:line:col information
480 // back to a SourceLocation, at least emit a note stating that
481 // we could not translate this location. This can happen in the
482 // case of #line directives.
483 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
484 << Filename << Line << Column;
487 void BackendConsumer::EmitOptimizationMessage(
488 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
489 // We only support warnings and remarks.
490 assert(D.getSeverity() == llvm::DS_Remark ||
491 D.getSeverity() == llvm::DS_Warning);
494 unsigned Line, Column;
495 bool BadDebugInfo = false;
496 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
499 Diags.Report(Loc, DiagID)
500 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
504 // If we were not able to translate the file:line:col information
505 // back to a SourceLocation, at least emit a note stating that
506 // we could not translate this location. This can happen in the
507 // case of #line directives.
508 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
509 << Filename << Line << Column;
512 void BackendConsumer::OptimizationRemarkHandler(
513 const llvm::DiagnosticInfoOptimizationRemark &D) {
514 // Optimization remarks are active only if the -Rpass flag has a regular
515 // expression that matches the name of the pass name in \p D.
516 if (CodeGenOpts.OptimizationRemarkPattern &&
517 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
518 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
521 void BackendConsumer::OptimizationRemarkHandler(
522 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
523 // Missed optimization remarks are active only if the -Rpass-missed
524 // flag has a regular expression that matches the name of the pass
526 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
527 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
528 EmitOptimizationMessage(D,
529 diag::remark_fe_backend_optimization_remark_missed);
532 void BackendConsumer::OptimizationRemarkHandler(
533 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
534 // Optimization analysis remarks are active if the pass name is set to
535 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
536 // regular expression that matches the name of the pass name in \p D.
538 if (D.shouldAlwaysPrint() ||
539 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
540 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
541 EmitOptimizationMessage(
542 D, diag::remark_fe_backend_optimization_remark_analysis);
545 void BackendConsumer::OptimizationRemarkHandler(
546 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
547 // Optimization analysis remarks are active if the pass name is set to
548 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
549 // regular expression that matches the name of the pass name in \p D.
551 if (D.shouldAlwaysPrint() ||
552 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
553 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
554 EmitOptimizationMessage(
555 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
558 void BackendConsumer::OptimizationRemarkHandler(
559 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
560 // Optimization analysis remarks are active if the pass name is set to
561 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
562 // regular expression that matches the name of the pass name in \p D.
564 if (D.shouldAlwaysPrint() ||
565 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
566 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
567 EmitOptimizationMessage(
568 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
571 void BackendConsumer::OptimizationFailureHandler(
572 const llvm::DiagnosticInfoOptimizationFailure &D) {
573 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
576 /// \brief This function is invoked when the backend needs
577 /// to report something to the user.
578 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
579 unsigned DiagID = diag::err_fe_inline_asm;
580 llvm::DiagnosticSeverity Severity = DI.getSeverity();
581 // Get the diagnostic ID based.
582 switch (DI.getKind()) {
583 case llvm::DK_InlineAsm:
584 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
586 ComputeDiagID(Severity, inline_asm, DiagID);
588 case llvm::DK_StackSize:
589 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
591 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
594 assert(CurLinkModule);
595 // FIXME: stop eating the warnings and notes.
596 if (Severity != DS_Error)
598 DiagID = diag::err_fe_cannot_link_module;
600 case llvm::DK_OptimizationRemark:
601 // Optimization remarks are always handled completely by this
602 // handler. There is no generic way of emitting them.
603 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
605 case llvm::DK_OptimizationRemarkMissed:
606 // Optimization remarks are always handled completely by this
607 // handler. There is no generic way of emitting them.
608 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
610 case llvm::DK_OptimizationRemarkAnalysis:
611 // Optimization remarks are always handled completely by this
612 // handler. There is no generic way of emitting them.
613 OptimizationRemarkHandler(
614 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
616 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
617 // Optimization remarks are always handled completely by this
618 // handler. There is no generic way of emitting them.
619 OptimizationRemarkHandler(
620 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
622 case llvm::DK_OptimizationRemarkAnalysisAliasing:
623 // Optimization remarks are always handled completely by this
624 // handler. There is no generic way of emitting them.
625 OptimizationRemarkHandler(
626 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
628 case llvm::DK_OptimizationFailure:
629 // Optimization failures are always handled completely by this
631 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
633 case llvm::DK_Unsupported:
634 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
637 // Plugin IDs are not bound to any value as they are set dynamically.
638 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
641 std::string MsgStorage;
643 raw_string_ostream Stream(MsgStorage);
644 DiagnosticPrinterRawOStream DP(Stream);
648 if (DiagID == diag::err_fe_cannot_link_module) {
649 Diags.Report(diag::err_fe_cannot_link_module)
650 << CurLinkModule->getModuleIdentifier() << MsgStorage;
654 // Report the backend message using the usual diagnostic mechanism.
656 Diags.Report(Loc, DiagID).AddString(MsgStorage);
660 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
661 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
662 OwnsVMContext(!_VMContext) {}
664 CodeGenAction::~CodeGenAction() {
670 bool CodeGenAction::hasIRSupport() const { return true; }
672 void CodeGenAction::EndSourceFileAction() {
673 // If the consumer creation failed, do nothing.
674 if (!getCompilerInstance().hasASTConsumer())
677 // Take back ownership of link modules we passed to consumer.
678 if (!LinkModules.empty())
679 BEConsumer->releaseLinkModules();
681 // Steal the module from the consumer.
682 TheModule = BEConsumer->takeModule();
685 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
686 return std::move(TheModule);
689 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
690 OwnsVMContext = false;
694 static std::unique_ptr<raw_pwrite_stream>
695 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
697 case Backend_EmitAssembly:
698 return CI.createDefaultOutputFile(false, InFile, "s");
700 return CI.createDefaultOutputFile(false, InFile, "ll");
702 return CI.createDefaultOutputFile(true, InFile, "bc");
703 case Backend_EmitNothing:
705 case Backend_EmitMCNull:
706 return CI.createNullOutputFile();
707 case Backend_EmitObj:
708 return CI.createDefaultOutputFile(true, InFile, "o");
711 llvm_unreachable("Invalid action!");
714 std::unique_ptr<ASTConsumer>
715 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
716 BackendAction BA = static_cast<BackendAction>(Act);
717 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
718 if (BA != Backend_EmitNothing && !OS)
721 // Load bitcode modules to link with, if we need to.
722 if (LinkModules.empty())
723 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
724 const std::string &LinkBCFile = I.second;
726 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
728 CI.getDiagnostics().Report(diag::err_cannot_open_file)
729 << LinkBCFile << BCBuf.getError().message();
734 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
735 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
736 if (std::error_code EC = ModuleOrErr.getError()) {
737 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
742 addLinkModule(ModuleOrErr.get().release(), I.first);
745 CoverageSourceInfo *CoverageInfo = nullptr;
746 // Add the preprocessor callback only when the coverage mapping is generated.
747 if (CI.getCodeGenOpts().CoverageMapping) {
748 CoverageInfo = new CoverageSourceInfo;
749 CI.getPreprocessor().addPPCallbacks(
750 std::unique_ptr<PPCallbacks>(CoverageInfo));
753 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
754 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
755 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
756 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
757 std::move(OS), *VMContext, CoverageInfo));
758 BEConsumer = Result.get();
759 return std::move(Result);
762 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
764 unsigned LocCookie) {
765 SM.print(nullptr, llvm::errs());
767 auto Diags = static_cast<DiagnosticsEngine *>(Context);
769 switch (SM.getKind()) {
770 case llvm::SourceMgr::DK_Error:
771 DiagID = diag::err_fe_inline_asm;
773 case llvm::SourceMgr::DK_Warning:
774 DiagID = diag::warn_fe_inline_asm;
776 case llvm::SourceMgr::DK_Note:
777 DiagID = diag::note_fe_inline_asm;
781 Diags->Report(DiagID).AddString("cannot compile inline asm");
784 void CodeGenAction::ExecuteAction() {
785 // If this is an IR file, we have to treat it specially.
786 if (getCurrentFileKind() == IK_LLVM_IR) {
787 BackendAction BA = static_cast<BackendAction>(Act);
788 CompilerInstance &CI = getCompilerInstance();
789 std::unique_ptr<raw_pwrite_stream> OS =
790 GetOutputStream(CI, getCurrentFile(), BA);
791 if (BA != Backend_EmitNothing && !OS)
795 SourceManager &SM = CI.getSourceManager();
796 FileID FID = SM.getMainFileID();
797 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
801 // For ThinLTO backend invocations, ensure that the context
802 // merges types based on ODR identifiers.
803 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
804 VMContext->enableDebugTypeODRUniquing();
806 llvm::SMDiagnostic Err;
807 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
809 // Translate from the diagnostic info to the SourceManager location if
811 // TODO: Unify this with ConvertBackendLocation()
813 if (Err.getLineNo() > 0) {
814 assert(Err.getColumnNo() >= 0);
815 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
816 Err.getLineNo(), Err.getColumnNo() + 1);
819 // Strip off a leading diagnostic code if there is one.
820 StringRef Msg = Err.getMessage();
821 if (Msg.startswith("error: "))
825 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
827 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
830 const TargetOptions &TargetOpts = CI.getTargetOpts();
831 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
832 CI.getDiagnostics().Report(SourceLocation(),
833 diag::warn_fe_override_module)
834 << TargetOpts.Triple;
835 TheModule->setTargetTriple(TargetOpts.Triple);
838 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
839 MainFile->getMemBufferRef());
841 LLVMContext &Ctx = TheModule->getContext();
842 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
843 &CI.getDiagnostics());
845 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
846 CI.getLangOpts(), CI.getTarget().getDataLayout(),
847 TheModule.get(), BA, std::move(OS));
851 // Otherwise follow the normal AST path.
852 this->ASTFrontendAction::ExecuteAction();
857 void EmitAssemblyAction::anchor() { }
858 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
859 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
861 void EmitBCAction::anchor() { }
862 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
863 : CodeGenAction(Backend_EmitBC, _VMContext) {}
865 void EmitLLVMAction::anchor() { }
866 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
867 : CodeGenAction(Backend_EmitLL, _VMContext) {}
869 void EmitLLVMOnlyAction::anchor() { }
870 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
871 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
873 void EmitCodeGenOnlyAction::anchor() { }
874 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
875 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
877 void EmitObjAction::anchor() { }
878 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
879 : CodeGenAction(Backend_EmitObj, _VMContext) {}