39#include <system_error>
43#define CGOPT(TY, NAME) \
44 static cl::opt<TY> *NAME##View; \
45 TY codegen::get##NAME() { \
46 assert(NAME##View && "Flag not registered."); \
50#define CGLIST(TY, NAME) \
51 static cl::list<TY> *NAME##View; \
52 std::vector<TY> codegen::get##NAME() { \
53 assert(NAME##View && "Flag not registered."); \
58#define CGOPT_EXP(TY, NAME) \
60 std::optional<TY> codegen::getExplicit##NAME() { \
61 if (NAME##View->getNumOccurrences()) { \
62 TY res = *NAME##View; \
65 return std::nullopt; \
68CGOPT(std::string, MArch)
69CGOPT(std::string, MCPU)
70CGOPT(std::string, MTune)
82CGOPT(
bool, DontPlaceZerosInBSS)
83CGOPT(
bool, EnableGuaranteedTailCallOpt)
84CGOPT(
bool, DisableTailCalls)
85CGOPT(
bool, StackSymbolOrdering)
86CGOPT(
bool, StackRealign)
87CGOPT(std::string, TrapFuncName)
91CGOPT(
bool, IgnoreXCOFFVisibility)
92CGOPT(
bool, XCOFFTracebackTable)
93CGOPT(
bool, EnableBBAddrMap)
94CGOPT(std::string, BBSections)
95CGOPT(
unsigned, TLSSize)
98CGOPT(
bool, UniqueSectionNames)
99CGOPT(
bool, UniqueBasicBlockSectionNames)
100CGOPT(
bool, SeparateNamedSections)
103CGOPT(
bool, EnableStackSizeSection)
104CGOPT(
bool, EnableAddrsig)
105CGOPT(
bool, EnableCallGraphSection)
106CGOPT(
bool, EmitCallSiteInfo)
108CGOPT(
bool, EnableStaticDataPartitioning)
109CGOPT(
bool, EnableDebugEntryValues)
110CGOPT(
bool, ForceDwarfFrameSection)
111CGOPT(
bool, XRayFunctionIndex)
112CGOPT(
bool, DebugStrictDwarf)
113CGOPT(
unsigned, AlignLoops)
114CGOPT(
bool, JMCInstrument)
115CGOPT(
bool, XCOFFReadOnlyPointers)
118#define CGBINDOPT(NAME) \
120 NAME##View = std::addressof(NAME); \
125 "march",
cl::desc(
"Architecture to generate code for (see --version)"));
129 "mcpu",
cl::desc(
"Target a specific cpu type (-mcpu=help for details)"),
135 cl::desc(
"Target specific attributes (-mattr=help for details)"),
140 "relocation-model",
cl::desc(
"Choose relocation model"),
144 "Fully relocatable, position independent code"),
146 "Relocatable external references, non-relocatable code"),
149 "Code and read-only data relocatable, accessed PC-relative"),
152 "Read-write data relocatable, accessed relative to static base"),
154 "Combination of ropi and rwpi")));
158 "code-model",
cl::desc(
"Choose code model"),
167 "large-data-threshold",
168 cl::desc(
"Choose large data threshold for x86_64 medium code model"),
173 "exception-model",
cl::desc(
"exception model"),
177 "default exception handling model"),
180 "DWARF-like CFI based exception handling"),
182 "SjLj exception handling"),
185 "Windows exception model"),
187 "WebAssembly exception handling"),
189 "Emscripten JavaScript-based exception handling")));
195 "Choose a file type (not all types are supported by all targets):"),
197 "Emit an assembly ('.s') file"),
199 "Emit a native object ('.o') file"),
201 "Emit nothing, for performance testing")));
206 cl::desc(
"Specify frame pointer elimination optimization"),
210 "Disable frame pointer elimination"),
212 "Disable frame pointer elimination for non-leaf frame but "
213 "reserve the register in leaf functions"),
215 "Disable frame pointer elimination for non-leaf frame"),
217 "Enable frame pointer elimination, but reserve the frame "
220 "Enable frame pointer elimination")));
223 static const auto DenormFlagEnumOptions =
cl::values(
226 "the sign of a flushed-to-zero number is preserved "
229 "denormals are flushed to positive zero"),
231 "denormals have unknown treatment"));
236 cl::desc(
"Select which denormal numbers the code is permitted to require"),
238 DenormFlagEnumOptions);
242 "denormal-fp-math-f32",
243 cl::desc(
"Select which denormal numbers the code is permitted to require for float"),
245 DenormFlagEnumOptions);
249 "float-abi",
cl::desc(
"Choose float ABI type"),
252 "Target default float ABI type"),
254 "Soft float ABI (implied by -soft-float)"),
256 "Hard float ABI (uses FP registers)")));
261 cl::desc(
"Determine when the Swift async frame pointer should be set"),
264 "Determine based on deployment target"),
266 "Always set the bit"),
268 "Never set the bit")));
272 "nozero-initialized-in-bss",
273 cl::desc(
"Don't place zero-initialized symbols into bss section"),
280 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
289 "stack-symbol-ordering",
cl::desc(
"Order local stack symbols."),
295 cl::desc(
"Force align the stack to the minimum alignment"),
301 cl::desc(
"Emit a call to trap function rather than a trap instruction"),
306 cl::desc(
"Use .ctors instead of .init_array."),
311 "data-sections",
cl::desc(
"Emit data into separate sections"),
316 "function-sections",
cl::desc(
"Emit functions into separate sections"),
321 "ignore-xcoff-visibility",
322 cl::desc(
"Not emit the visibility attribute for asm in AIX OS or give "
323 "all symbols 'unspecified' visibility in XCOFF object file"),
328 "xcoff-traceback-table",
cl::desc(
"Emit the XCOFF traceback table"),
333 "basic-block-address-map",
338 "basic-block-sections",
339 cl::desc(
"Emit basic blocks into separate sections"),
353 "enable-tlsdesc",
cl::desc(
"Enable the use of TLS Descriptors"),
358 "unique-section-names",
cl::desc(
"Give unique names to every section"),
363 "unique-basic-block-section-names",
364 cl::desc(
"Give unique names to every basic block section"),
369 "separate-named-sections",
370 cl::desc(
"Use separate unique sections for named sections"),
375 "debugger-tune",
cl::desc(
"Tune debug info for a particular debugger"),
389 "No vector functions library"),
391 "Accelerate framework"),
393 "Darwin libsystem_m"),
395 "GLIBC Vector Math library"),
399 "SIMD Library for Evaluating Elementary Functions"),
401 "Arm Performance Libraries"),
403 "AMD vector math library")));
407 "stack-size-section",
408 cl::desc(
"Emit a section containing stack size metadata"),
413 "addrsig",
cl::desc(
"Emit an address-significance table"),
418 "call-graph-section",
cl::desc(
"Emit a call graph section"),
423 "emit-call-site-info",
425 "Emit call site debug information, if debug information is enabled."),
430 "debug-entry-values",
431 cl::desc(
"Enable debug info for the debug entry values."),
436 "split-machine-functions",
437 cl::desc(
"Split out cold basic blocks from machine functions based on "
438 "profile information"),
443 "partition-static-data-sections",
444 cl::desc(
"Partition data sections using profile information."),
449 "force-dwarf-frame-section",
453 static cl::opt<bool> XRayFunctionIndex(
"xray-function-index",
454 cl::desc(
"Emit xray_fn_idx section"),
463 cl::desc(
"Default alignment for loops"));
467 "enable-jmc-instrument",
468 cl::desc(
"Instrument functions with a call to __CheckForDebuggerJustMyCode"),
474 cl::desc(
"When set to true, const objects with relocatable address "
475 "values are put into the RO data section."),
485 cl::desc(
"Tune for a specific CPU microarchitecture (-mtune=help for "
495 "Save LLVM statistics to a file in the current directory"
496 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
497 "file (`-save-stats=obj`). (default: cwd)"),
499 "Save to the current working directory"),
502 "Save to the output file directory")),
517 errs() <<
"Error loading basic block sections function list file: "
518 << MBOrErr.
getError().message() <<
"\n";
520 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
579 if (MCPU ==
"native")
591 if (TuneCPU ==
"native")
632 B.addAttribute(Name, Val ?
"true" :
"false");
635#define HANDLE_BOOL_ATTR(CL, AttrName) \
637 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
638 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
643 auto &Ctx =
F.getContext();
645 AttrBuilder NewAttrs(Ctx);
647 if (!CPU.empty() && !
F.hasFnAttribute(
"target-cpu"))
648 NewAttrs.addAttribute(
"target-cpu", CPU);
649 if (!TuneCPU.
empty() && !
F.hasFnAttribute(
"tune-cpu"))
650 NewAttrs.addAttribute(
"tune-cpu", TuneCPU);
651 if (!Features.
empty()) {
654 F.getFnAttribute(
"target-features").getValueAsString();
655 if (OldFeatures.
empty())
656 NewAttrs.addAttribute(
"target-features", Features);
660 Appended.
append(Features);
661 NewAttrs.addAttribute(
"target-features", Appended);
664 if (FramePointerUsageView->getNumOccurrences() > 0 &&
665 !
F.hasFnAttribute(
"frame-pointer")) {
667 NewAttrs.addAttribute(
"frame-pointer",
"all");
669 NewAttrs.addAttribute(
"frame-pointer",
"non-leaf");
671 NewAttrs.addAttribute(
"frame-pointer",
"non-leaf-no-reserve");
673 NewAttrs.addAttribute(
"frame-pointer",
"reserved");
675 NewAttrs.addAttribute(
"frame-pointer",
"none");
677 if (DisableTailCallsView->getNumOccurrences() > 0)
678 NewAttrs.addAttribute(
"disable-tail-calls",
681 NewAttrs.addAttribute(
"stackrealign");
683 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
684 DenormalFP32MathView->getNumOccurrences() > 0) &&
685 !
F.hasFnAttribute(Attribute::DenormalFPEnv)) {
692 NewAttrs.addDenormalFPEnvAttr(FPEnv);
695 if (TrapFuncNameView->getNumOccurrences() > 0)
699 if (
const auto *
F =
Call->getCalledFunction())
700 if (
F->getIntrinsicID() == Intrinsic::debugtrap ||
701 F->getIntrinsicID() == Intrinsic::trap)
706 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
721 " conflicts with the \"float-abi\" module flag \"" +
722 Existing->getString() +
"\"");
741 " conflicts with the \"exception-model\" module flag \"" +
742 Existing->getString() +
"\"");
758 Triple TheTriple(TargetTriple);
760 const auto *TheTarget =
771 Twine(
"could not allocate target machine for ") +
773 return std::unique_ptr<TargetMachine>(
Target);
794 "Should have been a valid --save-stats value");
804 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
807 <<
"Unable to open statistics file: " << EC.message() <<
"\n";
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define CGOPT_EXP(TY, NAME)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Module.h This file contains the declarations for the Module class.
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
This file defines the SmallString class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
static cl::opt< bool > EnableMachineFunctionSplitter("enable-split-machine-functions", cl::Hidden, cl::desc("Split out cold blocks from machine functions based on profile " "information."))
Enable the machine function splitter pass.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
A Module instance is used to store all the information related to an LLVM module.
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
void append(StringRef RHS)
Append from a StringRef.
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
Manages the enabling and disabling of subtarget specific features.
const std::vector< std::string > & getFeatures() const
Returns the vector of individual subtarget features.
LLVM_ABI std::string getString() const
Returns features as a string.
LLVM_ABI void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
Triple - Helper class for working with autoconf configuration names.
bool hasDefaultTLSDESC() const
True if the target uses TLSDESC by default.
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
const std::string & str() const
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static LLVM_ABI raw_ostream & error()
Convenience method for printing "error: " to stderr.
StringRef getABITypeName(ABIType ABI)
Returns the string spelling used by the "float-abi" IR module flag for a Soft or Hard ABIType.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LLVM_ABI bool getEnableMachineFunctionSplitter()
LLVM_ABI std::string getTrapFuncName()
LLVM_ABI bool getEnableDebugEntryValues()
LLVM_ABI unsigned getTLSSize()
LLVM_ABI bool getEnableGuaranteedTailCallOpt()
LLVM_ABI std::optional< CodeModel::Model > getExplicitCodeModel()
LLVM_ABI bool getFunctionSections()
LLVM_ABI bool getDisableTailCalls()
LLVM_ABI std::string getCPUStr()
LLVM_ABI llvm::VectorLibrary getVectorLibrary()
LLVM_ABI bool getXCOFFReadOnlyPointers()
LLVM_ABI std::string getFeaturesStr()
LLVM_ABI bool getUniqueSectionNames()
LLVM_ABI DenormalMode::DenormalModeKind getDenormalFPMath()
LLVM_ABI llvm::FloatABI::ABIType getFloatABIForCalls()
LLVM_ABI void renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val)
LLVM_ABI bool getDebugStrictDwarf()
LLVM_ABI bool getForceDwarfFrameSection()
LLVM_ABI bool getStackRealign()
LLVM_ABI std::string getMCPU()
LLVM_ABI bool getJMCInstrument()
LLVM_ABI bool getEnableAddrsig()
LLVM_ABI void setFunctionAttributes(Function &F, StringRef CPU, StringRef Features, StringRef TuneCPU="")
Set function attributes of function F based on CPU, TuneCPU, Features, and command line flags.
LLVM_ABI std::string getTuneCPUStr()
LLVM_ABI std::string getMTune()
LLVM_ABI bool getStackSymbolOrdering()
LLVM_ABI void MaybeEnableStatistics()
Conditionally enables the collection of LLVM statistics during the tool run, based on the value of th...
LLVM_ABI SwiftAsyncFramePointerMode getSwiftAsyncFramePointer()
LLVM_ABI bool getEnableBBAddrMap()
LLVM_ABI std::vector< std::string > getFeatureList()
LLVM_ABI bool getEnableStaticDataPartitioning()
LLVM_ABI std::string getMArch()
LLVM_ABI DenormalMode::DenormalModeKind getDenormalFP32Math()
LLVM_ABI bool getEnableStackSizeSection()
LLVM_ABI bool getEnableCallGraphSection()
LLVM_ABI SaveStatsMode getSaveStats()
LLVM_ABI bool getUniqueBasicBlockSectionNames()
LLVM_ABI FramePointerKind getFramePointerUsage()
LLVM_ABI bool getDontPlaceZerosInBSS()
LLVM_ABI bool getSeparateNamedSections()
LLVM_ABI std::optional< bool > getExplicitDataSections()
LLVM_ABI bool getXCOFFTracebackTable()
LLVM_ABI bool getIgnoreXCOFFVisibility()
LLVM_ABI bool getUseCtors()
LLVM_ABI llvm::DebuggerKind getDebuggerTuningOpt()
LLVM_ABI std::vector< std::string > getMAttrs()
LLVM_ABI llvm::BasicBlockSection getBBSectionsMode(llvm::TargetOptions &Options)
LLVM_ABI TargetOptions InitTargetOptionsFromCodeGenFlags(const llvm::Triple &TheTriple)
Common utility function tightly tied to the options listed here.
LLVM_ABI std::string getBBSections()
LLVM_ABI std::optional< bool > getExplicitEnableTLSDESC()
LLVM_ABI unsigned getAlignLoops()
LLVM_ABI std::optional< Reloc::Model > getExplicitRelocModel()
LLVM_ABI int MaybeSaveStatistics(StringRef OutputFilename, StringRef ToolName)
Conditionally saves the collected LLVM statistics to the received output file, based on the value of ...
LLVM_ABI bool getXRayFunctionIndex()
LLVM_ABI llvm::ExceptionHandling getExceptionModel()
LLVM_ABI bool getEmitCallSiteInfo()
LLVM_ABI Expected< std::unique_ptr< TargetMachine > > createTargetMachineForTriple(const Triple &TargetTriple, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default)
Creates a TargetMachine instance with the options defined on the command line.
LLVM_ABI std::optional< bool > getExplicitEmulatedTLS()
LLVM_ABI MCTargetOptions InitMCTargetOptionsFromFlags()
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
LLVM_ABI void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
LLVM_ABI void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
StringRef getExceptionModelName(ExceptionHandling EH)
Returns the "exception-model" module flag spelling for an ExceptionHandling value.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
SwiftAsyncFramePointerMode
Indicates when and how the Swift async frame pointer bit should be set.
@ Always
Always set the bit.
@ Never
Never set the bit.
@ DeploymentBased
Determine whether to set the bit statically or dynamically based on the deployment target.
CodeGenOptLevel
Code generation optimization level.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ SjLj
setjmp/longjmp based exceptions
@ Emscripten
Emscripten JavaScript-based exception handling.
@ None
No exception support.
@ Default
Not specified; resolve to the target's default model.
@ DwarfCFI
DWARF-like instruction based exceptions.
@ WinEH
Windows Exception Handling.
@ Wasm
WebAssembly Exception Handling.
VectorLibrary
List of known vector-functions libraries.
DebuggerKind
Identify a debugger for "tuning" the debug info.
@ SCE
Tune debug info for SCE targets (e.g. PS4).
@ DBX
Tune debug info for dbx.
@ Default
No specific tuning requested.
@ GDB
Tune debug info for gdb.
@ LLDB
Tune debug info for lldb.
LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Represents the full denormal controls for a function, including the default mode and the f32 specific...
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind
Represent handled modes for denormal (aka subnormal) modes in the floating point environment.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
LLVM_ABI RegisterCodeGenFlags()
LLVM_ABI RegisterMTuneFlag()
LLVM_ABI RegisterSaveStatsFlag()
Create this object with static storage to register mc-related command line options.