30#include "llvm/ADT/Hashing.h"
31#include "llvm/Bitcode/BitcodeReader.h"
32#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
33#include "llvm/Demangle/Demangle.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/DiagnosticInfo.h"
36#include "llvm/IR/DiagnosticPrinter.h"
37#include "llvm/IR/GlobalValue.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/LLVMRemarkStreamer.h"
40#include "llvm/IR/Module.h"
41#include "llvm/IRReader/IRReader.h"
42#include "llvm/LTO/LTOBackend.h"
43#include "llvm/Linker/Linker.h"
45#include "llvm/Support/MemoryBuffer.h"
46#include "llvm/Support/SourceMgr.h"
47#include "llvm/Support/TimeProfiler.h"
48#include "llvm/Support/Timer.h"
49#include "llvm/Support/ToolOutputFile.h"
50#include "llvm/Support/YAMLTraits.h"
51#include "llvm/Transforms/IPO/Internalize.h"
52#include "llvm/Transforms/Utils/Cloning.h"
58#define DEBUG_TYPE "codegenaction"
69 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
98 [&](
const LLVMRemarkSetupFileError &E) {
99 Diags.
Report(diag::err_cannot_open_file)
102 [&](
const LLVMRemarkSetupPatternError &E) {
103 Diags.
Report(diag::err_drv_optimization_remark_pattern)
106 [&](
const LLVMRemarkSetupFormatError &E) {
107 Diags.
Report(diag::err_drv_optimization_remark_format)
119 const std::string &InFile,
121 std::unique_ptr<raw_pwrite_stream> OS,
124 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
125 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
126 AsmOutStream(
std::move(OS)), Context(nullptr), FS(VFS),
127 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
128 LLVMIRGenerationRefCount(0),
130 PPOpts, CodeGenOpts,
C, CoverageInfo)),
131 LinkModules(
std::move(LinkModules)) {
132 TimerIsEnabled = CodeGenOpts.TimePasses;
133 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
134 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
151 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
152 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
153 Context(nullptr), FS(VFS),
154 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
155 LLVMIRGenerationRefCount(0),
157 PPOpts, CodeGenOpts,
C, CoverageInfo)),
158 LinkModules(
std::move(LinkModules)), CurLinkModule(
Module) {
159 TimerIsEnabled = CodeGenOpts.TimePasses;
160 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
161 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
165 return Gen->GetModule();
169 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
177 Gen->HandleCXXStaticMemberVarInstantiation(VD);
181 assert(!Context &&
"initialized multiple times");
186 LLVMIRGeneration.startTimer();
188 Gen->Initialize(Ctx);
191 LLVMIRGeneration.stopTimer();
197 "LLVM IR generation of declaration");
200 if (TimerIsEnabled) {
201 LLVMIRGenerationRefCount += 1;
202 if (LLVMIRGenerationRefCount == 1)
203 LLVMIRGeneration.startTimer();
206 Gen->HandleTopLevelDecl(D);
208 if (TimerIsEnabled) {
209 LLVMIRGenerationRefCount -= 1;
210 if (LLVMIRGenerationRefCount == 0)
211 LLVMIRGeneration.stopTimer();
220 "LLVM IR generation of inline function");
222 LLVMIRGeneration.startTimer();
224 Gen->HandleInlineFunctionDefinition(D);
227 LLVMIRGeneration.stopTimer();
239 for (
auto &LM : LinkModules) {
240 assert(LM.Module &&
"LinkModule does not actually have a module");
244 if (!LM.Internalize && !ShouldLinkFiles)
247 if (LM.PropagateAttrs)
254 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
257 CurLinkModule = LM.Module.get();
260 auto DoLink = [&](
auto &Mod) {
261 if (LM.Internalize) {
262 Err = Linker::linkModules(
263 *M, std::move(Mod), LM.LinkFlags,
264 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
265 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
266 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
270 Err = Linker::linkModules(*M, std::move(Mod), LM.LinkFlags);
278 if (Error E = CurLinkModule->materializeAll())
281 std::unique_ptr<llvm::Module> Clone = llvm::CloneModule(*LM.Module);
296 llvm::TimeTraceScope TimeScope(
"Frontend");
297 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
298 if (TimerIsEnabled) {
299 LLVMIRGenerationRefCount += 1;
300 if (LLVMIRGenerationRefCount == 1)
301 LLVMIRGeneration.startTimer();
304 Gen->HandleTranslationUnit(
C);
306 if (TimerIsEnabled) {
307 LLVMIRGenerationRefCount -= 1;
308 if (LLVMIRGenerationRefCount == 0)
309 LLVMIRGeneration.stopTimer();
312 IRGenFinished =
true;
319 LLVMContext &Ctx =
getModule()->getContext();
320 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
321 Ctx.getDiagnosticHandler();
322 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
326 setupLLVMOptimizationRemarks(
331 if (Error E = OptRecordFileOrErr.takeError()) {
336 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
337 std::move(*OptRecordFileOrErr);
341 Ctx.setDiagnosticsHotnessRequested(
true);
343 if (CodeGenOpts.MisExpect) {
344 Ctx.setMisExpectWarningRequested(
true);
348 Ctx.setDiagnosticsMisExpectTolerance(
356 for (
auto &F :
getModule()->functions()) {
357 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
358 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
361 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
365 if (CodeGenOpts.ClearASTBeforeBackend) {
366 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
374 C.getAllocator().Reset();
380 C.getTargetInfo().getDataLayoutString(),
getModule(),
381 Action, FS, std::move(AsmOutStream),
this);
383 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
386 OptRecordFile->keep();
392 "LLVM IR generation of declaration");
393 Gen->HandleTagDeclDefinition(D);
397 Gen->HandleTagDeclRequiredDefinition(D);
401 Gen->CompleteTentativeDefinition(D);
405 Gen->CompleteExternalDeclaration(D);
409 Gen->AssignInheritanceModel(RD);
413 Gen->HandleVTable(RD);
416void BackendConsumer::anchor() { }
432 const llvm::SourceMgr &LSM = *D.getSourceMgr();
436 const MemoryBuffer *LBuf =
437 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
441 std::unique_ptr<llvm::MemoryBuffer> CBuf =
442 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
443 LBuf->getBufferIdentifier());
448 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
454#define ComputeDiagID(Severity, GroupName, DiagID) \
456 switch (Severity) { \
457 case llvm::DS_Error: \
458 DiagID = diag::err_fe_##GroupName; \
460 case llvm::DS_Warning: \
461 DiagID = diag::warn_fe_##GroupName; \
463 case llvm::DS_Remark: \
464 llvm_unreachable("'remark' severity not expected"); \
466 case llvm::DS_Note: \
467 DiagID = diag::note_fe_##GroupName; \
472#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
474 switch (Severity) { \
475 case llvm::DS_Error: \
476 DiagID = diag::err_fe_##GroupName; \
478 case llvm::DS_Warning: \
479 DiagID = diag::warn_fe_##GroupName; \
481 case llvm::DS_Remark: \
482 DiagID = diag::remark_fe_##GroupName; \
484 case llvm::DS_Note: \
485 DiagID = diag::note_fe_##GroupName; \
491 const llvm::SMDiagnostic &D = DI.getSMDiag();
494 if (DI.isInlineAsmDiag())
502 D.print(
nullptr, llvm::errs());
511 StringRef Message = D.getMessage();
512 (void)Message.consume_front(
"error: ");
516 if (D.getLoc() != SMLoc())
522 if (DI.isInlineAsmDiag()) {
528 if (D.getLoc().isValid()) {
532 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
533 unsigned Column = D.getColumnNo();
552 std::string Message = D.getMsgStr().str();
575 if (D.getSeverity() != llvm::DS_Warning)
584 Diags.
Report(*Loc, diag::warn_fe_frame_larger_than)
585 << D.getStackSize() << D.getStackLimit()
586 << llvm::demangle(D.getFunction().getName());
591 const llvm::DiagnosticInfoResourceLimit &D) {
595 unsigned DiagID = diag::err_fe_backend_resource_limit;
596 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
598 Diags.
Report(*Loc, DiagID)
599 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
600 << llvm::demangle(D.getFunction().getName());
605 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
611 if (D.isLocationAvailable()) {
616 FE = FileMgr.
getFile(D.getAbsolutePath());
635 if (DILoc.
isInvalid() && D.isLocationAvailable())
640 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
646std::optional<FullSourceLoc>
649 for (
const auto &Pair : ManglingFullSourceLocs) {
650 if (Pair.first == Hash)
657 const llvm::DiagnosticInfoUnsupported &D) {
659 assert(D.getSeverity() == llvm::DS_Error ||
660 D.getSeverity() == llvm::DS_Warning);
664 bool BadDebugInfo =
false;
667 raw_string_ostream MsgStream(Msg);
671 if (Context !=
nullptr) {
673 MsgStream << D.getMessage();
675 DiagnosticPrinterRawOStream DP(MsgStream);
679 auto DiagType = D.getSeverity() == llvm::DS_Error
680 ? diag::err_fe_backend_unsupported
681 : diag::warn_fe_backend_unsupported;
682 Diags.
Report(Loc, DiagType) << MsgStream.str();
689 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
694 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
696 assert(D.getSeverity() == llvm::DS_Remark ||
697 D.getSeverity() == llvm::DS_Warning);
701 bool BadDebugInfo =
false;
704 raw_string_ostream MsgStream(Msg);
708 if (Context !=
nullptr) {
710 MsgStream << D.getMsg();
712 DiagnosticPrinterRawOStream DP(MsgStream);
717 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
728 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
733 const llvm::DiagnosticInfoOptimizationBase &D) {
735 if (D.isVerbose() && !D.getHotness())
743 }
else if (D.isMissed()) {
749 D, diag::remark_fe_backend_optimization_remark_missed);
751 assert(D.isAnalysis() &&
"Unknown remark type");
753 bool ShouldAlwaysPrint =
false;
754 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
755 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
757 if (ShouldAlwaysPrint ||
760 D, diag::remark_fe_backend_optimization_remark_analysis);
765 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
770 if (D.shouldAlwaysPrint() ||
773 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
777 const llvm::OptimizationRemarkAnalysisAliasing &D) {
782 if (D.shouldAlwaysPrint() ||
785 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
789 const llvm::DiagnosticInfoOptimizationFailure &D) {
802 Diags.
Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
803 ? diag::err_fe_backend_error_attr
804 : diag::warn_fe_backend_warning_attr)
805 << llvm::demangle(D.getFunctionName()) << D.getNote();
809 const llvm::DiagnosticInfoMisExpect &D) {
812 bool BadDebugInfo =
false;
816 Diags.
Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
823 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
830 unsigned DiagID = diag::err_fe_inline_asm;
831 llvm::DiagnosticSeverity Severity = DI.getSeverity();
833 switch (DI.getKind()) {
834 case llvm::DK_InlineAsm:
839 case llvm::DK_SrcMgr:
842 case llvm::DK_StackSize:
847 case llvm::DK_ResourceLimit:
855 case llvm::DK_OptimizationRemark:
860 case llvm::DK_OptimizationRemarkMissed:
865 case llvm::DK_OptimizationRemarkAnalysis:
870 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
875 case llvm::DK_OptimizationRemarkAnalysisAliasing:
880 case llvm::DK_MachineOptimizationRemark:
885 case llvm::DK_MachineOptimizationRemarkMissed:
890 case llvm::DK_MachineOptimizationRemarkAnalysis:
895 case llvm::DK_OptimizationFailure:
900 case llvm::DK_Unsupported:
903 case llvm::DK_DontCall:
906 case llvm::DK_MisExpect:
914 std::string MsgStorage;
916 raw_string_ostream Stream(MsgStorage);
917 DiagnosticPrinterRawOStream DP(Stream);
921 if (DI.getKind() == DK_Linker) {
922 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
923 Diags.
Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
934 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
935 OwnsVMContext(!_VMContext) {}
944 if (!LinkModules.empty())
952 << F.Filename << BCBuf.getError().message();
958 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
960 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
961 CI.getDiagnostics().Report(diag::err_cannot_open_file)
962 << F.Filename << EIB.message();
967 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
968 F.Internalize, F.LinkFlags});
985 return std::move(TheModule);
989 OwnsVMContext =
false;
997static std::unique_ptr<raw_pwrite_stream>
1014 llvm_unreachable(
"Invalid action!");
1017std::unique_ptr<ASTConsumer>
1028 if (loadLinkModules(CI))
1041 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
1046 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1048 std::unique_ptr<PPCallbacks> Callbacks =
1054 return std::move(
Result);
1057std::unique_ptr<llvm::Module>
1058CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1062 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1065 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1075 VMContext->enableDebugTypeODRUniquing();
1079 return DiagErrors(BMsOrErr.takeError());
1080 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1086 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1091 Bm->parseModule(*VMContext);
1093 return DiagErrors(MOrErr.takeError());
1094 return std::move(*MOrErr);
1098 if (loadLinkModules(CI))
1102 llvm::SMDiagnostic Err;
1103 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1110 if (BMsOrErr && BMsOrErr->size()) {
1111 std::unique_ptr<llvm::Module> FirstM;
1112 for (
auto &BM : *BMsOrErr) {
1114 BM.parseModule(*VMContext);
1116 return DiagErrors(MOrErr.takeError());
1118 LinkModules.push_back({std::move(*MOrErr),
false,
1121 FirstM = std::move(*MOrErr);
1128 consumeError(BMsOrErr.takeError());
1134 if (Err.getLineNo() > 0) {
1135 assert(Err.getColumnNo() >= 0);
1136 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1137 Err.getLineNo(), Err.getColumnNo() + 1);
1141 StringRef Msg = Err.getMessage();
1142 if (Msg.startswith(
"error: "))
1143 Msg = Msg.substr(7);
1163 std::unique_ptr<raw_pwrite_stream> OS =
1170 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1174 TheModule = loadModule(*MainFile);
1179 if (TheModule->getTargetTriple() != TargetOpts.
Triple) {
1180 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1182 TheModule->setTargetTriple(TargetOpts.
Triple);
1185 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1188 LLVMContext &Ctx = TheModule->getContext();
1194 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1195 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1204 std::move(LinkModules), *VMContext,
nullptr);
1207 if (
Result.LinkInModules(&*TheModule))
1212 Ctx.setDiscardValueNames(
false);
1213 Ctx.setDiagnosticHandler(
1214 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1217 setupLLVMOptimizationRemarks(
1218 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1219 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1220 CodeGenOpts.DiagnosticsHotnessThreshold);
1222 if (Error E = OptRecordFileOrErr.takeError()) {
1226 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1227 std::move(*OptRecordFileOrErr);
1234 OptRecordFile->keep();
1239void EmitAssemblyAction::anchor() { }
1243void EmitBCAction::anchor() { }
1247void EmitLLVMAction::anchor() { }
1251void EmitLLVMOnlyAction::anchor() { }
1255void EmitCodeGenOnlyAction::anchor() { }
1259void 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)
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 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.
~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.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
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
A SourceLocation and its associated SourceManager.
Represents a function declaration or definition.
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...
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)
@ LLVM_IR
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
@ 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)
YAML serialization mapping.
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
cl::opt< bool > ClRelinkBuiltinBitcodePostop