33#include "llvm/ADT/Hashing.h"
34#include "llvm/Bitcode/BitcodeReader.h"
35#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
36#include "llvm/Demangle/Demangle.h"
37#include "llvm/IR/DebugInfo.h"
38#include "llvm/IR/DiagnosticInfo.h"
39#include "llvm/IR/DiagnosticPrinter.h"
40#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/LLVMRemarkStreamer.h"
43#include "llvm/IR/Module.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/Support/YAMLTraits.h"
54#include "llvm/Transforms/IPO/Internalize.h"
55#include "llvm/Transforms/Utils/Cloning.h"
61#define DEBUG_TYPE "codegenaction"
72 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
101 [&](
const LLVMRemarkSetupFileError &E) {
102 Diags.
Report(diag::err_cannot_open_file)
105 [&](
const LLVMRemarkSetupPatternError &E) {
106 Diags.
Report(diag::err_drv_optimization_remark_pattern)
109 [&](
const LLVMRemarkSetupFormatError &E) {
110 Diags.
Report(diag::err_drv_optimization_remark_format)
121 const FileManager &FileMgr,
const std::string &InFile,
123 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &
C,
125 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
126 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
127 FileMgr(FileMgr), AsmOutStream(
std::move(OS)), Context(nullptr), FS(VFS),
128 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
129 LLVMIRGenerationRefCount(0),
131 PPOpts, CodeGenOpts,
C, CoverageInfo)),
132 LinkModules(
std::move(LinkModules)) {
133 TimerIsEnabled = CodeGenOpts.TimePasses;
134 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
135 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
150 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
151 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
152 FileMgr(FileMgr), Context(nullptr), FS(
VFS),
153 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
154 LLVMIRGenerationRefCount(0),
156 CodeGenOpts,
C, CoverageInfo)),
157 LinkModules(
std::move(LinkModules)), CurLinkModule(
Module) {
158 TimerIsEnabled = CodeGenOpts.TimePasses;
159 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
160 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
164 return Gen->GetModule();
168 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
176 Gen->HandleCXXStaticMemberVarInstantiation(VD);
180 assert(!Context &&
"initialized multiple times");
185 LLVMIRGeneration.startTimer();
187 Gen->Initialize(Ctx);
190 LLVMIRGeneration.stopTimer();
196 "LLVM IR generation of declaration");
199 if (TimerIsEnabled) {
200 LLVMIRGenerationRefCount += 1;
201 if (LLVMIRGenerationRefCount == 1)
202 LLVMIRGeneration.startTimer();
205 Gen->HandleTopLevelDecl(D);
207 if (TimerIsEnabled) {
208 LLVMIRGenerationRefCount -= 1;
209 if (LLVMIRGenerationRefCount == 0)
210 LLVMIRGeneration.stopTimer();
219 "LLVM IR generation of inline function");
221 LLVMIRGeneration.startTimer();
223 Gen->HandleInlineFunctionDefinition(D);
226 LLVMIRGeneration.stopTimer();
240 Diags.
Report(diag::err_cannot_open_file)
241 << F.
Filename << BCBuf.getError().message();
246 LLVMContext &Ctx =
getModule()->getContext();
248 getOwningLazyBitcodeModule(std::move(*BCBuf), Ctx);
251 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
252 Diags.Report(diag::err_cannot_open_file) << F.Filename << EIB.message();
257 LinkModules.push_back({std::move(ModuleOrErr.get()), F.
PropagateAttrs,
266 for (
auto &LM : LinkModules) {
267 assert(LM.Module &&
"LinkModule does not actually have a module");
271 if (!LM.Internalize && !ShouldLinkFiles)
274 if (LM.PropagateAttrs)
281 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
284 CurLinkModule = LM.Module.get();
287 if (LM.Internalize) {
288 Err = Linker::linkModules(
289 *M, std::move(LM.Module), LM.LinkFlags,
290 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
291 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
292 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
296 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
308 llvm::TimeTraceScope TimeScope(
"Frontend");
309 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
310 if (TimerIsEnabled) {
311 LLVMIRGenerationRefCount += 1;
312 if (LLVMIRGenerationRefCount == 1)
313 LLVMIRGeneration.startTimer();
316 Gen->HandleTranslationUnit(
C);
318 if (TimerIsEnabled) {
319 LLVMIRGenerationRefCount -= 1;
320 if (LLVMIRGenerationRefCount == 0)
321 LLVMIRGeneration.stopTimer();
324 IRGenFinished =
true;
331 LLVMContext &Ctx =
getModule()->getContext();
332 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
333 Ctx.getDiagnosticHandler();
334 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
338 setupLLVMOptimizationRemarks(
343 if (Error E = OptRecordFileOrErr.takeError()) {
348 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
349 std::move(*OptRecordFileOrErr);
353 Ctx.setDiagnosticsHotnessRequested(
true);
355 if (CodeGenOpts.MisExpect) {
356 Ctx.setMisExpectWarningRequested(
true);
360 Ctx.setDiagnosticsMisExpectTolerance(
368 for (
auto &F :
getModule()->functions()) {
369 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
370 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
373 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
377 if (CodeGenOpts.ClearASTBeforeBackend) {
378 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
386 C.getAllocator().Reset();
392 C.getTargetInfo().getDataLayoutString(),
getModule(),
393 Action, FS, std::move(AsmOutStream),
this);
395 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
398 OptRecordFile->keep();
404 "LLVM IR generation of declaration");
405 Gen->HandleTagDeclDefinition(D);
409 Gen->HandleTagDeclRequiredDefinition(D);
413 Gen->CompleteTentativeDefinition(D);
417 Gen->CompleteExternalDeclaration(D);
421 Gen->AssignInheritanceModel(RD);
425 Gen->HandleVTable(RD);
428void BackendConsumer::anchor() { }
444 const llvm::SourceMgr &LSM = *D.getSourceMgr();
448 const MemoryBuffer *LBuf =
449 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
453 std::unique_ptr<llvm::MemoryBuffer> CBuf =
454 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
455 LBuf->getBufferIdentifier());
460 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
466#define ComputeDiagID(Severity, GroupName, DiagID) \
468 switch (Severity) { \
469 case llvm::DS_Error: \
470 DiagID = diag::err_fe_##GroupName; \
472 case llvm::DS_Warning: \
473 DiagID = diag::warn_fe_##GroupName; \
475 case llvm::DS_Remark: \
476 llvm_unreachable("'remark' severity not expected"); \
478 case llvm::DS_Note: \
479 DiagID = diag::note_fe_##GroupName; \
484#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
486 switch (Severity) { \
487 case llvm::DS_Error: \
488 DiagID = diag::err_fe_##GroupName; \
490 case llvm::DS_Warning: \
491 DiagID = diag::warn_fe_##GroupName; \
493 case llvm::DS_Remark: \
494 DiagID = diag::remark_fe_##GroupName; \
496 case llvm::DS_Note: \
497 DiagID = diag::note_fe_##GroupName; \
503 const llvm::SMDiagnostic &D = DI.getSMDiag();
506 if (DI.isInlineAsmDiag())
514 D.print(
nullptr, llvm::errs());
523 StringRef Message = D.getMessage();
524 (void)Message.consume_front(
"error: ");
528 if (D.getLoc() != SMLoc())
534 if (DI.isInlineAsmDiag()) {
540 if (D.getLoc().isValid()) {
544 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
545 unsigned Column = D.getColumnNo();
564 std::string Message = D.getMsgStr().str();
587 if (D.getSeverity() != llvm::DS_Warning)
596 Diags.
Report(*Loc, diag::warn_fe_frame_larger_than)
597 << D.getStackSize() << D.getStackLimit()
598 << llvm::demangle(D.getFunction().getName());
603 const llvm::DiagnosticInfoResourceLimit &D) {
607 unsigned DiagID = diag::err_fe_backend_resource_limit;
608 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
610 Diags.
Report(*Loc, DiagID)
611 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
612 << llvm::demangle(D.getFunction().getName());
617 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
623 if (D.isLocationAvailable()) {
628 FE = FileMgr.
getFile(D.getAbsolutePath());
647 if (DILoc.
isInvalid() && D.isLocationAvailable())
652 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
658std::optional<FullSourceLoc>
661 for (
const auto &Pair : ManglingFullSourceLocs) {
662 if (Pair.first == Hash)
669 const llvm::DiagnosticInfoUnsupported &D) {
671 assert(D.getSeverity() == llvm::DS_Error ||
672 D.getSeverity() == llvm::DS_Warning);
676 bool BadDebugInfo =
false;
679 raw_string_ostream MsgStream(Msg);
683 if (Context !=
nullptr) {
685 MsgStream << D.getMessage();
687 DiagnosticPrinterRawOStream DP(MsgStream);
691 auto DiagType = D.getSeverity() == llvm::DS_Error
692 ? diag::err_fe_backend_unsupported
693 : diag::warn_fe_backend_unsupported;
694 Diags.
Report(Loc, DiagType) << MsgStream.str();
701 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
706 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
708 assert(D.getSeverity() == llvm::DS_Remark ||
709 D.getSeverity() == llvm::DS_Warning);
713 bool BadDebugInfo =
false;
716 raw_string_ostream MsgStream(Msg);
720 if (Context !=
nullptr) {
722 MsgStream << D.getMsg();
724 DiagnosticPrinterRawOStream DP(MsgStream);
729 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
740 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
745 const llvm::DiagnosticInfoOptimizationBase &D) {
747 if (D.isVerbose() && !D.getHotness())
755 }
else if (D.isMissed()) {
761 D, diag::remark_fe_backend_optimization_remark_missed);
763 assert(D.isAnalysis() &&
"Unknown remark type");
765 bool ShouldAlwaysPrint =
false;
766 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
767 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
769 if (ShouldAlwaysPrint ||
772 D, diag::remark_fe_backend_optimization_remark_analysis);
777 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
782 if (D.shouldAlwaysPrint() ||
785 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
789 const llvm::OptimizationRemarkAnalysisAliasing &D) {
794 if (D.shouldAlwaysPrint() ||
797 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
801 const llvm::DiagnosticInfoOptimizationFailure &D) {
814 Diags.
Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
815 ? diag::err_fe_backend_error_attr
816 : diag::warn_fe_backend_warning_attr)
817 << llvm::demangle(D.getFunctionName()) << D.getNote();
821 const llvm::DiagnosticInfoMisExpect &D) {
824 bool BadDebugInfo =
false;
828 Diags.
Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
835 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
842 unsigned DiagID = diag::err_fe_inline_asm;
843 llvm::DiagnosticSeverity Severity = DI.getSeverity();
845 switch (DI.getKind()) {
846 case llvm::DK_InlineAsm:
851 case llvm::DK_SrcMgr:
854 case llvm::DK_StackSize:
859 case llvm::DK_ResourceLimit:
867 case llvm::DK_OptimizationRemark:
872 case llvm::DK_OptimizationRemarkMissed:
877 case llvm::DK_OptimizationRemarkAnalysis:
882 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
887 case llvm::DK_OptimizationRemarkAnalysisAliasing:
892 case llvm::DK_MachineOptimizationRemark:
897 case llvm::DK_MachineOptimizationRemarkMissed:
902 case llvm::DK_MachineOptimizationRemarkAnalysis:
907 case llvm::DK_OptimizationFailure:
912 case llvm::DK_Unsupported:
915 case llvm::DK_DontCall:
918 case llvm::DK_MisExpect:
926 std::string MsgStorage;
928 raw_string_ostream Stream(MsgStorage);
929 DiagnosticPrinterRawOStream DP(Stream);
933 if (DI.getKind() == DK_Linker) {
934 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
935 Diags.
Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
946 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
947 OwnsVMContext(!_VMContext) {}
956 if (!LinkModules.empty())
964 << F.Filename << BCBuf.getError().message();
970 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
972 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
973 CI.getDiagnostics().Report(diag::err_cannot_open_file)
974 << F.Filename << EIB.message();
979 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
980 F.Internalize, F.LinkFlags});
997 return std::move(TheModule);
1001 OwnsVMContext =
false;
1015static std::unique_ptr<raw_pwrite_stream>
1032 llvm_unreachable(
"Invalid action!");
1035std::unique_ptr<ASTConsumer>
1046 if (loadLinkModules(CI))
1059 std::string(InFile), std::move(LinkModules), std::move(OS), *VMContext,
1065 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1067 std::unique_ptr<PPCallbacks> Callbacks =
1075 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1076 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1079 Consumers[1] = std::move(
Result);
1080 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1083 return std::move(
Result);
1086std::unique_ptr<llvm::Module>
1087CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1091 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1094 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1104 VMContext->enableDebugTypeODRUniquing();
1108 return DiagErrors(BMsOrErr.takeError());
1109 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1115 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1120 Bm->parseModule(*VMContext);
1122 return DiagErrors(MOrErr.takeError());
1123 return std::move(*MOrErr);
1127 if (loadLinkModules(CI))
1131 llvm::SMDiagnostic Err;
1132 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1139 if (BMsOrErr && BMsOrErr->size()) {
1140 std::unique_ptr<llvm::Module> FirstM;
1141 for (
auto &BM : *BMsOrErr) {
1143 BM.parseModule(*VMContext);
1145 return DiagErrors(MOrErr.takeError());
1147 LinkModules.push_back({std::move(*MOrErr),
false,
1150 FirstM = std::move(*MOrErr);
1157 consumeError(BMsOrErr.takeError());
1163 if (Err.getLineNo() > 0) {
1164 assert(Err.getColumnNo() >= 0);
1165 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1166 Err.getLineNo(), Err.getColumnNo() + 1);
1170 StringRef Msg = Err.getMessage();
1171 Msg.consume_front(
"error: ");
1191 std::unique_ptr<raw_pwrite_stream> OS =
1198 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1202 TheModule = loadModule(*MainFile);
1207 if (TheModule->getTargetTriple() != TargetOpts.
Triple) {
1208 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1210 TheModule->setTargetTriple(TargetOpts.
Triple);
1213 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1216 LLVMContext &Ctx = TheModule->getContext();
1222 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1223 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1232 std::move(LinkModules), *VMContext,
nullptr);
1235 if (
Result.LinkInModules(&*TheModule))
1240 Ctx.setDiscardValueNames(
false);
1241 Ctx.setDiagnosticHandler(
1242 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1245 setupLLVMOptimizationRemarks(
1246 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1247 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1248 CodeGenOpts.DiagnosticsHotnessThreshold);
1250 if (Error E = OptRecordFileOrErr.takeError()) {
1254 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1255 std::move(*OptRecordFileOrErr);
1262 OptRecordFile->keep();
1267void EmitAssemblyAction::anchor() { }
1271void EmitBCAction::anchor() { }
1275void EmitLLVMAction::anchor() { }
1279void EmitLLVMOnlyAction::anchor() { }
1283void EmitCodeGenOnlyAction::anchor() { }
1287void 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.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
llvm::Module * getModule() const
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.
bool LinkInModules(llvm::Module *M, bool ShouldLinkFiles=true)
bool ReloadModules(llvm::Module *M)
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 CompleteExternalDeclaration(VarDecl *D) override
CompleteExternalDeclaration - 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.
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, const FileManager &FileMgr, const std::string &InFile, SmallVector< LinkModule, 4 > LinkModules, std::unique_ptr< raw_pwrite_stream > OS, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
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.
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
Callback to run the program action, using the initialized compiler instance.
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::optional< uint64_t > DiagnosticsHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
std::optional< uint32_t > DiagnosticsMisExpectTolerance
The maximum percentage profiling weights can deviate from the expected values in order to be included...
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
OptRemark OptimizationRemark
Selected optimizations for which we should enable optimization remarks.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
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.
InMemoryModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
PreprocessorOptions & getPreprocessorOpts()
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.
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)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
InputKind getCurrentFileKind() const
CompilerInstance & getCompilerInstance() const
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.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Describes a module or submodule.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
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
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
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.
void AddString(StringRef V) const
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.
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.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
@ Result
The result type of a method or function.
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)
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
cl::opt< bool > ClRelinkBuiltinBitcodePostop
bool Internalize
If true, we use LLVM module internalizer.
bool PropagateAttrs
If true, we set attributes functions in the bitcode library according to our CodeGenOptions,...
std::string Filename
The filename of the bitcode file to link in.
unsigned LinkFlags
Bitwise combination of llvm::Linker::Flags, passed to the LLVM linker.