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/PassTimingInfo.h"
44#include "llvm/IR/Verifier.h"
45#include "llvm/IRReader/IRReader.h"
46#include "llvm/LTO/LTOBackend.h"
47#include "llvm/Linker/Linker.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Mutex.h"
52#include "llvm/Support/SourceMgr.h"
53#include "llvm/Support/TimeProfiler.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/ToolOutputFile.h"
56#include "llvm/Transforms/IPO/Internalize.h"
57#include "llvm/Transforms/Utils/Cloning.h"
63#define DEBUG_TYPE "codegenaction"
66llvm::ManagedStatic<llvm::sys::SmartMutex<true>> TimePassesMutex;
74 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
79 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
82 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
85 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
89 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
90 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
91 CodeGenOpts.OptimizationRemark.hasValidPattern();
103 [&](
const LLVMRemarkSetupFileError &E) {
104 Diags.
Report(diag::err_cannot_open_file)
107 [&](
const LLVMRemarkSetupPatternError &E) {
108 Diags.
Report(diag::err_drv_optimization_remark_pattern)
111 [&](
const LLVMRemarkSetupFormatError &E) {
112 Diags.
Report(diag::err_drv_optimization_remark_format)
122 std::unique_ptr<raw_pwrite_stream> OS,
124 llvm::Module *CurLinkModule)
125 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
126 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
127 AsmOutStream(
std::move(OS)), FS(VFS), Action(Action),
129 LinkModules(
std::move(LinkModules)), CurLinkModule(CurLinkModule) {
130 TimerIsEnabled = CodeGenOpts.TimePasses;
132 llvm::sys::SmartScopedLock<true> Lock(*TimePassesMutex);
133 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
134 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
136 if (CodeGenOpts.TimePasses)
137 LLVMIRGeneration.init(
"irgen",
"LLVM IR generation", CI.getTimerGroup());
141 return Gen->GetModule();
145 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
157 assert(!Context &&
"initialized multiple times");
162 LLVMIRGeneration.startTimer();
164 Gen->Initialize(Ctx);
167 LLVMIRGeneration.stopTimer();
172 Context->getSourceManager(),
173 "LLVM IR generation of declaration");
176 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
177 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
179 Gen->HandleTopLevelDecl(D);
181 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
182 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
189 Context->getSourceManager(),
190 "LLVM IR generation of inline function");
192 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
194 Gen->HandleInlineFunctionDefinition(D);
197 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
206 for (
auto &LM : LinkModules) {
207 assert(LM.Module &&
"LinkModule does not actually have a module");
209 if (LM.PropagateAttrs)
216 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
219 CurLinkModule = LM.Module.get();
222 if (LM.Internalize) {
223 Err = Linker::linkModules(
224 *M, std::move(LM.Module), LM.LinkFlags,
225 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
226 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
227 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
231 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
243 llvm::TimeTraceScope TimeScope(
"Frontend");
244 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
245 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
246 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
248 Gen->HandleTranslationUnit(
C);
250 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
251 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
258 LLVMContext &Ctx =
getModule()->getContext();
259 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
260 Ctx.getDiagnosticHandler();
261 llvm::scope_exit RestoreDiagnosticHandler(
262 [&]() { Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); });
263 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
266 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
267 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features,
","));
270 setupLLVMOptimizationRemarks(
271 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
272 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
273 CodeGenOpts.DiagnosticsHotnessThreshold);
275 if (
Error E = OptRecordFileOrErr.takeError()) {
280 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
282 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
283 llvm::driver::ProfileInstrKind::ProfileNone)
284 Ctx.setDiagnosticsHotnessRequested(
true);
286 if (CodeGenOpts.MisExpect) {
287 Ctx.setMisExpectWarningRequested(
true);
290 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
291 Ctx.setDiagnosticsMisExpectTolerance(
292 CodeGenOpts.DiagnosticsMisExpectTolerance);
299 for (
auto &F :
getModule()->functions()) {
300 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
301 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
304 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
308 if (CodeGenOpts.ClearASTBeforeBackend) {
309 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
317 C.getAllocator().Reset();
323 std::move(AsmOutStream),
this);
326 OptRecordFile->keep();
331 Context->getSourceManager(),
332 "LLVM IR generation of declaration");
333 Gen->HandleTagDeclDefinition(D);
337 Gen->HandleTagDeclRequiredDefinition(D);
341 Gen->CompleteTentativeDefinition(D);
345 Gen->CompleteExternalDeclaration(D);
349 Gen->AssignInheritanceModel(RD);
353 Gen->HandleVTable(RD);
356void BackendConsumer::anchor() { }
361 BackendCon->DiagnosticHandlerImpl(DI);
372 const llvm::SourceMgr &LSM = *D.getSourceMgr();
376 const MemoryBuffer *LBuf =
377 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
381 std::unique_ptr<llvm::MemoryBuffer> CBuf =
382 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
383 LBuf->getBufferIdentifier());
388 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
394#define ComputeDiagID(Severity, GroupName, DiagID) \
396 switch (Severity) { \
397 case llvm::DS_Error: \
398 DiagID = diag::err_fe_##GroupName; \
400 case llvm::DS_Warning: \
401 DiagID = diag::warn_fe_##GroupName; \
403 case llvm::DS_Remark: \
404 llvm_unreachable("'remark' severity not expected"); \
406 case llvm::DS_Note: \
407 DiagID = diag::note_fe_##GroupName; \
412#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
414 switch (Severity) { \
415 case llvm::DS_Error: \
416 DiagID = diag::err_fe_##GroupName; \
418 case llvm::DS_Warning: \
419 DiagID = diag::warn_fe_##GroupName; \
421 case llvm::DS_Remark: \
422 DiagID = diag::remark_fe_##GroupName; \
424 case llvm::DS_Note: \
425 DiagID = diag::note_fe_##GroupName; \
431 const llvm::SMDiagnostic &D = DI.getSMDiag();
434 if (DI.isInlineAsmDiag())
442 D.print(
nullptr, llvm::errs());
443 Diags.Report(DiagID).AddString(
"cannot compile inline asm");
451 StringRef Message = D.getMessage();
452 (void)Message.consume_front(
"error: ");
456 if (D.getLoc() != SMLoc())
462 if (DI.isInlineAsmDiag()) {
466 Diags.Report(LocCookie, DiagID).AddString(Message);
468 if (D.getLoc().isValid()) {
472 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
473 unsigned Column = D.getColumnNo();
485 Diags.Report(Loc, DiagID).AddString(Message);
492 std::string Message = D.getMsgStr().str();
500 Diags.Report(LocCookie, DiagID).AddString(Message);
507 Diags.Report(Loc, DiagID).AddString(Message);
515 if (D.getSeverity() != llvm::DS_Warning)
524 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
525 << D.getStackSize() << D.getStackLimit()
526 << llvm::demangle(D.getFunction().getName());
531 const llvm::DiagnosticInfoResourceLimit &D) {
535 unsigned DiagID = diag::err_fe_backend_resource_limit;
536 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
538 Diags.Report(*Loc, DiagID)
539 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
540 << llvm::demangle(D.getFunction().getName());
545 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
546 StringRef &Filename,
unsigned &
Line,
unsigned &
Column)
const {
551 if (D.isLocationAvailable()) {
554 auto FE =
FileMgr.getOptionalFileRef(Filename);
556 FE =
FileMgr.getOptionalFileRef(D.getAbsolutePath());
575 if (DILoc.
isInvalid() && D.isLocationAvailable())
580 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
586std::optional<FullSourceLoc>
589 for (
const auto &Pair : ManglingFullSourceLocs) {
590 if (Pair.first == Hash)
597 const llvm::DiagnosticInfoUnsupported &D) {
599 assert(D.getSeverity() == llvm::DS_Error ||
600 D.getSeverity() == llvm::DS_Warning);
604 bool BadDebugInfo =
false;
607 raw_string_ostream MsgStream(Msg);
611 if (Context !=
nullptr) {
613 MsgStream << D.getMessage();
615 DiagnosticPrinterRawOStream DP(MsgStream);
619 auto DiagType = D.getSeverity() == llvm::DS_Error
620 ? diag::err_fe_backend_unsupported
621 : diag::warn_fe_backend_unsupported;
622 Diags.Report(Loc, DiagType) << Msg;
629 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
634 const llvm::DiagnosticInfoUnsupportedTargetIntrinsic &D) {
635 assert(D.getSeverity() == llvm::DS_Error &&
636 "unsupported target intrinsic diagnostic should be an error");
640 bool BadDebugInfo =
false;
643 raw_string_ostream MsgStream(Msg);
647 if (Context !=
nullptr) {
649 MsgStream << D.getMessage();
651 DiagnosticPrinterRawOStream DP(MsgStream);
655 Diags.Report(Loc, diag::err_fe_backend_unsupported) << Msg;
662 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
668 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
670 assert(D.getSeverity() == llvm::DS_Remark ||
671 D.getSeverity() == llvm::DS_Warning);
675 bool BadDebugInfo =
false;
678 raw_string_ostream MsgStream(Msg);
682 if (Context !=
nullptr) {
684 MsgStream << D.getMsg();
686 DiagnosticPrinterRawOStream DP(MsgStream);
691 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
693 Diags.Report(Loc, DiagID) <<
AddFlagValue(D.getPassName()) << Msg;
700 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
705 const llvm::DiagnosticInfoOptimizationBase &D) {
707 if (D.isVerbose() && !D.getHotness())
713 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
715 }
else if (D.isMissed()) {
719 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
721 D, diag::remark_fe_backend_optimization_remark_missed);
723 assert(D.isAnalysis() &&
"Unknown remark type");
725 bool ShouldAlwaysPrint =
false;
726 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
727 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
729 if (ShouldAlwaysPrint ||
730 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
732 D, diag::remark_fe_backend_optimization_remark_analysis);
737 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
742 if (D.shouldAlwaysPrint() ||
743 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
745 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
749 const llvm::OptimizationRemarkAnalysisAliasing &D) {
754 if (D.shouldAlwaysPrint() ||
755 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
757 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
761 const llvm::DiagnosticInfoOptimizationFailure &D) {
774 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
775 ? diag::err_fe_backend_error_attr
776 : diag::warn_fe_backend_warning_attr)
777 << llvm::demangle(D.getFunctionName()) << D.getNote();
779 if (!CodeGenOpts.ShowInliningChain)
786 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
787 Diags.Report(Loc, DiagID) << llvm::demangle(FuncName.str());
791 if (!D.getDebugInlineChain().empty()) {
794 for (
const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
799 Info.Column ? Info.Column : 1);
800 EmitNote(Loc, Info.FuncName, I == 0);
806 auto InliningDecisions = D.getInliningDecisions();
807 if (InliningDecisions.empty())
810 for (
const auto &[I, Entry] : llvm::enumerate(InliningDecisions)) {
813 EmitNote(Loc, Entry.first, I == 0);
818 Diags.Report(LocCookie, diag::note_fe_backend_inlining_debug_info);
822 const llvm::DiagnosticInfoMisExpect &D) {
825 bool BadDebugInfo =
false;
829 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
836 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
843 unsigned DiagID = diag::err_fe_inline_asm;
844 llvm::DiagnosticSeverity Severity = DI.getSeverity();
846 switch (DI.getKind()) {
847 case llvm::DK_InlineAsm:
852 case llvm::DK_SrcMgr:
855 case llvm::DK_StackSize:
860 case llvm::DK_ResourceLimit:
868 case llvm::DK_OptimizationRemark:
873 case llvm::DK_OptimizationRemarkMissed:
878 case llvm::DK_OptimizationRemarkAnalysis:
883 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
888 case llvm::DK_OptimizationRemarkAnalysisAliasing:
893 case llvm::DK_MachineOptimizationRemark:
898 case llvm::DK_MachineOptimizationRemarkMissed:
903 case llvm::DK_MachineOptimizationRemarkAnalysis:
908 case llvm::DK_OptimizationFailure:
913 case llvm::DK_Unsupported:
916 case llvm::DK_UnsupportedTargetIntrinsic:
920 case llvm::DK_DontCall:
923 case llvm::DK_MisExpect:
931 std::string MsgStorage;
933 raw_string_ostream Stream(MsgStorage);
934 DiagnosticPrinterRawOStream DP(Stream);
938 if (DI.getKind() == DK_Linker) {
939 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
940 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
946 Diags.Report(Loc, DiagID).AddString(MsgStorage);
951 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
952 OwnsVMContext(!_VMContext) {}
974 return std::move(TheModule);
978 OwnsVMContext =
false;
992static std::unique_ptr<raw_pwrite_stream>
1009 llvm_unreachable(
"Invalid action!");
1012std::unique_ptr<ASTConsumer>
1034 InFile, std::move(OS), CoverageInfo));
1039 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1041 std::unique_ptr<PPCallbacks> Callbacks =
1042 std::make_unique<MacroPPCallbacks>(
BEConsumer->getCodeGenerator(),
1049 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1050 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1053 Consumers[1] = std::move(
Result);
1054 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1057 return std::move(
Result);
1060std::unique_ptr<llvm::Module>
1061CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1065 auto DiagErrors = [&](
Error E) -> std::unique_ptr<llvm::Module> {
1068 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1078 VMContext->enableDebugTypeODRUniquing();
1080 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1082 return DiagErrors(BMsOrErr.takeError());
1083 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1089 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1093 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1094 Bm->parseModule(*VMContext);
1096 return DiagErrors(MOrErr.takeError());
1097 return std::move(*MOrErr);
1105 llvm::SMDiagnostic Err;
1106 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
1109 std::string VerifierErr;
1110 raw_string_ostream VerifierErrStream(VerifierErr);
1111 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1121 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1122 if (BMsOrErr && BMsOrErr->size()) {
1123 std::unique_ptr<llvm::Module> FirstM;
1124 for (
auto &BM : *BMsOrErr) {
1125 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1126 BM.parseModule(*VMContext);
1128 return DiagErrors(MOrErr.takeError());
1130 LinkModules.push_back({std::move(*MOrErr),
false,
1133 FirstM = std::move(*MOrErr);
1140 consumeError(BMsOrErr.takeError());
1146 if (Err.getLineNo() > 0) {
1147 assert(Err.getColumnNo() >= 0);
1149 Err.getLineNo(), Err.getColumnNo() + 1);
1153 StringRef Msg = Err.getMessage();
1154 Msg.consume_front(
"error: ");
1174 std::unique_ptr<raw_pwrite_stream> OS =
1185 TheModule = loadModule(*MainFile);
1190 if (TheModule->getTargetTriple().str() != TargetOpts.
Triple) {
1191 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1193 TheModule->setTargetTriple(Triple(TargetOpts.
Triple));
1200 LLVMContext &Ctx = TheModule->getContext();
1206 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1207 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1213 std::move(LinkModules),
"",
nullptr,
nullptr,
1217 if (!CodeGenOpts.LinkBitcodePostopt &&
Result.LinkInModules(&*TheModule))
1222 Ctx.setDiscardValueNames(
false);
1223 Ctx.setDiagnosticHandler(
1224 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1226 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
1227 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
1230 setupLLVMOptimizationRemarks(
1231 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1232 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1233 CodeGenOpts.DiagnosticsHotnessThreshold);
1235 if (
Error E = OptRecordFileOrErr.takeError()) {
1239 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1245 OptRecordFile->keep();
1250void EmitAssemblyAction::anchor() { }
1254void EmitBCAction::anchor() { }
1258void EmitLLVMAction::anchor() { }
1262void EmitLLVMOnlyAction::anchor() { }
1266void EmitCodeGenOnlyAction::anchor() { }
1270void 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 UnsupportedTargetIntrinsicDiagHandler(const llvm::DiagnosticInfoUnsupportedTargetIntrinsic &D)
Specialized handler for unsupported target intrinsic diagnostic.
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
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::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.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
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()
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::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
InputKind getCurrentFileKind() const
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
CompilerInstance & getCompilerInstance() const
virtual void EndSourceFileAction()
Callback at the end 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...
FileManager & getFileManager() const
FileID getMainFileID() const
Returns the FileID of the main source file.
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
A trivial tuple used to represent a source range.
Represents the declaration of a struct/union/class/enum.
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...
Top level wrappers for InstallAPI frontend operations.
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
@ Result
The result type of a method or function.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
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)
bool loadLinkModules(CompilerInstance &CI, llvm::LLVMContext &Ctx, llvm::SmallVectorImpl< LinkModule > &LinkModules)
Load every bitcode file listed in CodeGenOpts.LinkBitcodeFiles into LinkModules.
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::dependencies::ModuleID &ID)