31#include "llvm/ADT/Hashing.h"
32#include "llvm/ADT/ScopeExit.h"
33#include "llvm/Bitcode/BitcodeReader.h"
34#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
35#include "llvm/Demangle/Demangle.h"
36#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/DiagnosticInfo.h"
38#include "llvm/IR/DiagnosticPrinter.h"
39#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/LLVMRemarkStreamer.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Verifier.h"
44#include "llvm/IRReader/IRReader.h"
45#include "llvm/LTO/LTOBackend.h"
46#include "llvm/Linker/Linker.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/SourceMgr.h"
50#include "llvm/Support/TimeProfiler.h"
51#include "llvm/Support/Timer.h"
52#include "llvm/Support/ToolOutputFile.h"
53#include "llvm/Transforms/IPO/Internalize.h"
54#include "llvm/Transforms/Utils/Cloning.h"
60#define DEBUG_TYPE "codegenaction"
67 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
72 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
75 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
78 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
82 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
83 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
84 CodeGenOpts.OptimizationRemark.hasValidPattern();
96 [&](
const LLVMRemarkSetupFileError &E) {
97 Diags.
Report(diag::err_cannot_open_file)
100 [&](
const LLVMRemarkSetupPatternError &E) {
101 Diags.
Report(diag::err_drv_optimization_remark_pattern)
104 [&](
const LLVMRemarkSetupFormatError &E) {
105 Diags.
Report(diag::err_drv_optimization_remark_format)
115 std::unique_ptr<raw_pwrite_stream> OS,
117 llvm::Module *CurLinkModule)
118 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
119 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
120 AsmOutStream(
std::move(OS)), FS(VFS), Action(Action),
122 LinkModules(
std::move(LinkModules)), CurLinkModule(CurLinkModule) {
123 TimerIsEnabled = CodeGenOpts.TimePasses;
124 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
125 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
126 if (CodeGenOpts.TimePasses)
127 LLVMIRGeneration.init(
"irgen",
"LLVM IR generation", CI.getTimerGroup());
131 return Gen->GetModule();
135 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
147 assert(!Context &&
"initialized multiple times");
152 LLVMIRGeneration.startTimer();
154 Gen->Initialize(Ctx);
157 LLVMIRGeneration.stopTimer();
162 Context->getSourceManager(),
163 "LLVM IR generation of declaration");
166 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
167 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
169 Gen->HandleTopLevelDecl(D);
171 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
172 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
179 Context->getSourceManager(),
180 "LLVM IR generation of inline function");
182 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
184 Gen->HandleInlineFunctionDefinition(D);
187 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
196 for (
auto &LM : LinkModules) {
197 assert(LM.Module &&
"LinkModule does not actually have a module");
199 if (LM.PropagateAttrs)
206 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
209 CurLinkModule = LM.Module.get();
212 if (LM.Internalize) {
213 Err = Linker::linkModules(
214 *M, std::move(LM.Module), LM.LinkFlags,
215 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
216 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
217 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
221 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
233 llvm::TimeTraceScope TimeScope(
"Frontend");
234 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
235 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
236 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
238 Gen->HandleTranslationUnit(
C);
240 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
241 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
248 LLVMContext &Ctx =
getModule()->getContext();
249 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
250 Ctx.getDiagnosticHandler();
251 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
254 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
255 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features,
","));
258 setupLLVMOptimizationRemarks(
259 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
260 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
261 CodeGenOpts.DiagnosticsHotnessThreshold);
263 if (
Error E = OptRecordFileOrErr.takeError()) {
268 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
270 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
271 llvm::driver::ProfileInstrKind::ProfileNone)
272 Ctx.setDiagnosticsHotnessRequested(
true);
274 if (CodeGenOpts.MisExpect) {
275 Ctx.setMisExpectWarningRequested(
true);
278 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
279 Ctx.setDiagnosticsMisExpectTolerance(
280 CodeGenOpts.DiagnosticsMisExpectTolerance);
287 for (
auto &F :
getModule()->functions()) {
288 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
289 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
292 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
296 if (CodeGenOpts.ClearASTBeforeBackend) {
297 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
305 C.getAllocator().Reset();
311 C.getTargetInfo().getDataLayoutString(),
getModule(),
312 Action, FS, std::move(AsmOutStream),
this);
314 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
317 OptRecordFile->keep();
322 Context->getSourceManager(),
323 "LLVM IR generation of declaration");
324 Gen->HandleTagDeclDefinition(D);
328 Gen->HandleTagDeclRequiredDefinition(D);
332 Gen->CompleteTentativeDefinition(D);
336 Gen->CompleteExternalDeclaration(D);
340 Gen->AssignInheritanceModel(RD);
344 Gen->HandleVTable(RD);
347void BackendConsumer::anchor() { }
352 BackendCon->DiagnosticHandlerImpl(DI);
363 const llvm::SourceMgr &LSM = *D.getSourceMgr();
367 const MemoryBuffer *LBuf =
368 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
372 std::unique_ptr<llvm::MemoryBuffer> CBuf =
373 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
374 LBuf->getBufferIdentifier());
379 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
385#define ComputeDiagID(Severity, GroupName, DiagID) \
387 switch (Severity) { \
388 case llvm::DS_Error: \
389 DiagID = diag::err_fe_##GroupName; \
391 case llvm::DS_Warning: \
392 DiagID = diag::warn_fe_##GroupName; \
394 case llvm::DS_Remark: \
395 llvm_unreachable("'remark' severity not expected"); \
397 case llvm::DS_Note: \
398 DiagID = diag::note_fe_##GroupName; \
403#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
405 switch (Severity) { \
406 case llvm::DS_Error: \
407 DiagID = diag::err_fe_##GroupName; \
409 case llvm::DS_Warning: \
410 DiagID = diag::warn_fe_##GroupName; \
412 case llvm::DS_Remark: \
413 DiagID = diag::remark_fe_##GroupName; \
415 case llvm::DS_Note: \
416 DiagID = diag::note_fe_##GroupName; \
422 const llvm::SMDiagnostic &D = DI.getSMDiag();
425 if (DI.isInlineAsmDiag())
433 D.print(
nullptr, llvm::errs());
434 Diags.Report(DiagID).AddString(
"cannot compile inline asm");
442 StringRef Message = D.getMessage();
443 (void)Message.consume_front(
"error: ");
447 if (D.getLoc() != SMLoc())
453 if (DI.isInlineAsmDiag()) {
457 Diags.Report(LocCookie, DiagID).AddString(Message);
459 if (D.getLoc().isValid()) {
463 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
464 unsigned Column = D.getColumnNo();
476 Diags.Report(Loc, DiagID).AddString(Message);
483 std::string Message = D.getMsgStr().str();
491 Diags.Report(LocCookie, DiagID).AddString(Message);
498 Diags.Report(Loc, DiagID).AddString(Message);
506 if (D.getSeverity() != llvm::DS_Warning)
515 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
516 << D.getStackSize() << D.getStackLimit()
517 << llvm::demangle(D.getFunction().getName());
522 const llvm::DiagnosticInfoResourceLimit &D) {
526 unsigned DiagID = diag::err_fe_backend_resource_limit;
527 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
529 Diags.Report(*Loc, DiagID)
530 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
531 << llvm::demangle(D.getFunction().getName());
536 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
537 StringRef &Filename,
unsigned &
Line,
unsigned &
Column)
const {
542 if (D.isLocationAvailable()) {
545 auto FE =
FileMgr.getOptionalFileRef(Filename);
547 FE =
FileMgr.getOptionalFileRef(D.getAbsolutePath());
566 if (DILoc.
isInvalid() && D.isLocationAvailable())
571 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
577std::optional<FullSourceLoc>
580 for (
const auto &Pair : ManglingFullSourceLocs) {
581 if (Pair.first == Hash)
588 const llvm::DiagnosticInfoUnsupported &D) {
590 assert(D.getSeverity() == llvm::DS_Error ||
591 D.getSeverity() == llvm::DS_Warning);
595 bool BadDebugInfo =
false;
598 raw_string_ostream MsgStream(Msg);
602 if (Context !=
nullptr) {
604 MsgStream << D.getMessage();
606 DiagnosticPrinterRawOStream DP(MsgStream);
610 auto DiagType = D.getSeverity() == llvm::DS_Error
611 ? diag::err_fe_backend_unsupported
612 : diag::warn_fe_backend_unsupported;
613 Diags.Report(Loc, DiagType) << Msg;
620 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
625 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
627 assert(D.getSeverity() == llvm::DS_Remark ||
628 D.getSeverity() == llvm::DS_Warning);
632 bool BadDebugInfo =
false;
635 raw_string_ostream MsgStream(Msg);
639 if (Context !=
nullptr) {
641 MsgStream << D.getMsg();
643 DiagnosticPrinterRawOStream DP(MsgStream);
648 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
650 Diags.Report(Loc, DiagID) <<
AddFlagValue(D.getPassName()) << Msg;
657 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
662 const llvm::DiagnosticInfoOptimizationBase &D) {
664 if (D.isVerbose() && !D.getHotness())
670 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
672 }
else if (D.isMissed()) {
676 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
678 D, diag::remark_fe_backend_optimization_remark_missed);
680 assert(D.isAnalysis() &&
"Unknown remark type");
682 bool ShouldAlwaysPrint =
false;
683 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
684 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
686 if (ShouldAlwaysPrint ||
687 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
689 D, diag::remark_fe_backend_optimization_remark_analysis);
694 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
699 if (D.shouldAlwaysPrint() ||
700 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
702 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
706 const llvm::OptimizationRemarkAnalysisAliasing &D) {
711 if (D.shouldAlwaysPrint() ||
712 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
714 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
718 const llvm::DiagnosticInfoOptimizationFailure &D) {
731 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
732 ? diag::err_fe_backend_error_attr
733 : diag::warn_fe_backend_warning_attr)
734 << llvm::demangle(D.getFunctionName()) << D.getNote();
738 const llvm::DiagnosticInfoMisExpect &D) {
741 bool BadDebugInfo =
false;
745 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
752 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
759 unsigned DiagID = diag::err_fe_inline_asm;
760 llvm::DiagnosticSeverity Severity = DI.getSeverity();
762 switch (DI.getKind()) {
763 case llvm::DK_InlineAsm:
768 case llvm::DK_SrcMgr:
771 case llvm::DK_StackSize:
776 case llvm::DK_ResourceLimit:
784 case llvm::DK_OptimizationRemark:
789 case llvm::DK_OptimizationRemarkMissed:
794 case llvm::DK_OptimizationRemarkAnalysis:
799 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
804 case llvm::DK_OptimizationRemarkAnalysisAliasing:
809 case llvm::DK_MachineOptimizationRemark:
814 case llvm::DK_MachineOptimizationRemarkMissed:
819 case llvm::DK_MachineOptimizationRemarkAnalysis:
824 case llvm::DK_OptimizationFailure:
829 case llvm::DK_Unsupported:
832 case llvm::DK_DontCall:
835 case llvm::DK_MisExpect:
843 std::string MsgStorage;
845 raw_string_ostream Stream(MsgStorage);
846 DiagnosticPrinterRawOStream DP(Stream);
850 if (DI.getKind() == DK_Linker) {
851 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
852 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
858 Diags.Report(Loc, DiagID).AddString(MsgStorage);
863 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
864 OwnsVMContext(!_VMContext) {}
873 if (!LinkModules.empty())
881 << F.Filename << BCBuf.getError().message();
887 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
889 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
890 CI.getDiagnostics().Report(diag::err_cannot_open_file)
891 << F.Filename << EIB.message();
896 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
897 F.Internalize, F.LinkFlags});
916 return std::move(TheModule);
920 OwnsVMContext =
false;
934static std::unique_ptr<raw_pwrite_stream>
951 llvm_unreachable(
"Invalid action!");
954std::unique_ptr<ASTConsumer>
965 if (loadLinkModules(CI))
976 InFile, std::move(OS), CoverageInfo));
981 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
983 std::unique_ptr<PPCallbacks> Callbacks =
984 std::make_unique<MacroPPCallbacks>(
BEConsumer->getCodeGenerator(),
991 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
992 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
995 Consumers[1] = std::move(
Result);
996 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1002std::unique_ptr<llvm::Module>
1003CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1007 auto DiagErrors = [&](
Error E) -> std::unique_ptr<llvm::Module> {
1010 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1020 VMContext->enableDebugTypeODRUniquing();
1022 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1024 return DiagErrors(BMsOrErr.takeError());
1025 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1031 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1035 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1036 Bm->parseModule(*VMContext);
1038 return DiagErrors(MOrErr.takeError());
1039 return std::move(*MOrErr);
1043 if (loadLinkModules(CI))
1047 llvm::SMDiagnostic Err;
1048 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
1051 std::string VerifierErr;
1052 raw_string_ostream VerifierErrStream(VerifierErr);
1053 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1063 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1064 if (BMsOrErr && BMsOrErr->size()) {
1065 std::unique_ptr<llvm::Module> FirstM;
1066 for (
auto &BM : *BMsOrErr) {
1067 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1068 BM.parseModule(*VMContext);
1070 return DiagErrors(MOrErr.takeError());
1072 LinkModules.push_back({std::move(*MOrErr),
false,
1075 FirstM = std::move(*MOrErr);
1082 consumeError(BMsOrErr.takeError());
1088 if (Err.getLineNo() > 0) {
1089 assert(Err.getColumnNo() >= 0);
1090 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1091 Err.getLineNo(), Err.getColumnNo() + 1);
1095 StringRef Msg = Err.getMessage();
1096 Msg.consume_front(
"error: ");
1116 std::unique_ptr<raw_pwrite_stream> OS =
1123 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1127 TheModule = loadModule(*MainFile);
1132 if (TheModule->getTargetTriple().str() != TargetOpts.
Triple) {
1133 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1135 TheModule->setTargetTriple(Triple(TargetOpts.
Triple));
1142 LLVMContext &Ctx = TheModule->getContext();
1148 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1149 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1155 std::move(LinkModules),
"",
nullptr,
nullptr,
1159 if (!CodeGenOpts.LinkBitcodePostopt &&
Result.LinkInModules(&*TheModule))
1164 Ctx.setDiscardValueNames(
false);
1165 Ctx.setDiagnosticHandler(
1166 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1168 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
1169 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
1172 setupLLVMOptimizationRemarks(
1173 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1174 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1175 CodeGenOpts.DiagnosticsHotnessThreshold);
1177 if (
Error E = OptRecordFileOrErr.takeError()) {
1181 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1188 OptRecordFile->keep();
1193void EmitAssemblyAction::anchor() { }
1197void EmitBCAction::anchor() { }
1201void EmitLLVMAction::anchor() { }
1205void EmitLLVMOnlyAction::anchor() { }
1209void EmitCodeGenOnlyAction::anchor() { }
1213void EmitObjAction::anchor() { }
Defines the clang::ASTContext interface.
#define ComputeDiagID(Severity, GroupName, DiagID)
static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM)
ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr buffer to be a valid FullS...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::FileManager interface and associated types.
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
llvm::Module * getModule() const
void CompleteExternalDeclaration(DeclaratorDecl *D) override
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
void OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D)
bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D)
Specialized handler for StackSize diagnostic.
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
void HandleTagDeclDefinition(TagDecl *D) override
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
bool HandleTopLevelDecl(DeclGroupRef D) override
HandleTopLevelDecl - Handle the specified top-level declaration.
void Initialize(ASTContext &Ctx) override
Initialize - This is called to initialize the consumer, providing the ASTContext.
void HandleInlineFunctionDefinition(FunctionDecl *D) override
This callback is invoked each time an inline (method or friend) function definition in a class is com...
void OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure &D)
void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI)
This function is invoked when the backend needs to report something to the user.
void HandleTagDeclRequiredDefinition(const TagDecl *D) override
This callback is invoked the first time each TagDecl is required to be complete.
void HandleInterestingDecl(DeclGroupRef D) override
HandleInterestingDecl - Handle the specified interesting declaration.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
std::optional< FullSourceLoc > getFunctionSourceLocation(const llvm::Function &F) const
bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D)
Specialized handler for ResourceLimit diagnostic.
std::unique_ptr< llvm::Module > takeModule()
void AssignInheritanceModel(CXXRecordDecl *RD) override
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)
Specialized handler for unsupported backend feature diagnostic.
bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D)
Specialized handler for InlineAsm diagnostic.
bool LinkInModules(llvm::Module *M)
const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const
Get the best possible source location to represent a diagnostic that may have associated debug info.
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)
Specialized handlers for optimization remarks.
void DontCallDiagHandler(const llvm::DiagnosticInfoDontCall &D)
void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)
Specialized handler for misexpect warnings.
CodeGenerator * getCodeGenerator()
void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D)
Specialized handler for diagnostics reported using SMDiagnostic.
BackendConsumer(CompilerInstance &CI, BackendAction Action, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, llvm::LLVMContext &C, SmallVector< LinkModule, 4 > LinkModules, StringRef InFile, std::unique_ptr< raw_pwrite_stream > OS, CoverageSourceInfo *CoverageInfo, llvm::Module *CurLinkModule=nullptr)
Represents a C++ struct/union/class.
bool isMissedOptRemarkEnabled(StringRef PassName) const override
bool handleDiagnostics(const DiagnosticInfo &DI) override
ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
bool isPassedOptRemarkEnabled(StringRef PassName) const override
bool isAnyRemarkEnabled() const override
bool isAnalysisRemarkEnabled(StringRef PassName) const override
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
CodeGenerator * getCodeGenerator() const
friend class BackendConsumer
void EndSourceFileAction() override
Callback at the end of processing a single input.
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
~CodeGenAction() override
CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext=nullptr)
Create a new code generation action.
llvm::LLVMContext * takeLLVMContext()
Take the LLVM context used by this action.
BackendConsumer * BEConsumer
bool hasIRSupport() const override
Does this action support use with IR files?
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
std::unique_ptr< llvm::Module > takeModule()
Take the generated LLVM module, for use after the action has been run.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
The primary public interface to the Clang code generator.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
FileManager & getFileManager() const
Return the current file manager to the caller.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Decl - This represents one declaration (or definition), e.g.
Represents a ValueDecl that came out of a declarator.
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
EmitAssemblyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitBCAction(llvm::LLVMContext *_VMContext=nullptr)
EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitObjAction(llvm::LLVMContext *_VMContext=nullptr)
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
InputKind getCurrentFileKind() const
virtual void EndSourceFileAction()
Callback at the end of processing a single input.
CompilerInstance & getCompilerInstance() const
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
StringRef getCurrentFileOrBufferName() const
unsigned GenReducedBMI
Whether to generate reduced BMI for C++20 named modules.
std::string ModuleOutputPath
Output Path for module output file.
A SourceLocation and its associated SourceManager.
Represents a function declaration or definition.
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
A trivial tuple used to represent a source range.
Represents the declaration of a struct/union/class/enum.
const char * getDataLayoutString() const
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string CPU
If given, the name of the target CPU to generate code for.
Represents a variable declaration or definition.
Defines the clang::TargetInfo interface.
void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)
Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...
The JSON file list parser is used to communicate input to InstallAPI.
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
@ Result
The result type of a method or function.
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
std::unique_ptr< CodeGenerator > CreateLLVMCodeGen(const CompilerInstance &CI, llvm::StringRef ModuleName, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
U cast(CodeGen::Address addr)
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::dependencies::ModuleID &ID)