Path: blob/main/contrib/llvm-project/llvm/lib/CodeGen/CommandFlags.cpp
35232 views
//===-- CommandFlags.cpp - Command Line Flags Interface ---------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains codegen-specific flags that are shared between different9// command line tools. The tools "llc" and "opt" both use this file to prevent10// flag duplication.11//12//===----------------------------------------------------------------------===//1314#include "llvm/CodeGen/CommandFlags.h"15#include "llvm/ADT/StringExtras.h"16#include "llvm/IR/Instructions.h"17#include "llvm/IR/Intrinsics.h"18#include "llvm/IR/Module.h"19#include "llvm/MC/MCTargetOptionsCommandFlags.h"20#include "llvm/MC/TargetRegistry.h"21#include "llvm/Support/CommandLine.h"22#include "llvm/Support/MemoryBuffer.h"23#include "llvm/Target/TargetMachine.h"24#include "llvm/TargetParser/Host.h"25#include "llvm/TargetParser/SubtargetFeature.h"26#include "llvm/TargetParser/Triple.h"27#include <optional>2829using namespace llvm;3031#define CGOPT(TY, NAME) \32static cl::opt<TY> *NAME##View; \33TY codegen::get##NAME() { \34assert(NAME##View && "RegisterCodeGenFlags not created."); \35return *NAME##View; \36}3738#define CGLIST(TY, NAME) \39static cl::list<TY> *NAME##View; \40std::vector<TY> codegen::get##NAME() { \41assert(NAME##View && "RegisterCodeGenFlags not created."); \42return *NAME##View; \43}4445// Temporary macro for incremental transition to std::optional.46#define CGOPT_EXP(TY, NAME) \47CGOPT(TY, NAME) \48std::optional<TY> codegen::getExplicit##NAME() { \49if (NAME##View->getNumOccurrences()) { \50TY res = *NAME##View; \51return res; \52} \53return std::nullopt; \54}5556CGOPT(std::string, MArch)57CGOPT(std::string, MCPU)58CGLIST(std::string, MAttrs)59CGOPT_EXP(Reloc::Model, RelocModel)60CGOPT(ThreadModel::Model, ThreadModel)61CGOPT_EXP(CodeModel::Model, CodeModel)62CGOPT_EXP(uint64_t, LargeDataThreshold)63CGOPT(ExceptionHandling, ExceptionModel)64CGOPT_EXP(CodeGenFileType, FileType)65CGOPT(FramePointerKind, FramePointerUsage)66CGOPT(bool, EnableUnsafeFPMath)67CGOPT(bool, EnableNoInfsFPMath)68CGOPT(bool, EnableNoNaNsFPMath)69CGOPT(bool, EnableNoSignedZerosFPMath)70CGOPT(bool, EnableApproxFuncFPMath)71CGOPT(bool, EnableNoTrappingFPMath)72CGOPT(bool, EnableAIXExtendedAltivecABI)73CGOPT(DenormalMode::DenormalModeKind, DenormalFPMath)74CGOPT(DenormalMode::DenormalModeKind, DenormalFP32Math)75CGOPT(bool, EnableHonorSignDependentRoundingFPMath)76CGOPT(FloatABI::ABIType, FloatABIForCalls)77CGOPT(FPOpFusion::FPOpFusionMode, FuseFPOps)78CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)79CGOPT(bool, DontPlaceZerosInBSS)80CGOPT(bool, EnableGuaranteedTailCallOpt)81CGOPT(bool, DisableTailCalls)82CGOPT(bool, StackSymbolOrdering)83CGOPT(bool, StackRealign)84CGOPT(std::string, TrapFuncName)85CGOPT(bool, UseCtors)86CGOPT(bool, DisableIntegratedAS)87CGOPT_EXP(bool, DataSections)88CGOPT_EXP(bool, FunctionSections)89CGOPT(bool, IgnoreXCOFFVisibility)90CGOPT(bool, XCOFFTracebackTable)91CGOPT(bool, EnableBBAddrMap)92CGOPT(std::string, BBSections)93CGOPT(unsigned, TLSSize)94CGOPT_EXP(bool, EmulatedTLS)95CGOPT_EXP(bool, EnableTLSDESC)96CGOPT(bool, UniqueSectionNames)97CGOPT(bool, UniqueBasicBlockSectionNames)98CGOPT(bool, SeparateNamedSections)99CGOPT(EABI, EABIVersion)100CGOPT(DebuggerKind, DebuggerTuningOpt)101CGOPT(bool, EnableStackSizeSection)102CGOPT(bool, EnableAddrsig)103CGOPT(bool, EmitCallSiteInfo)104CGOPT(bool, EnableMachineFunctionSplitter)105CGOPT(bool, EnableDebugEntryValues)106CGOPT(bool, ForceDwarfFrameSection)107CGOPT(bool, XRayFunctionIndex)108CGOPT(bool, DebugStrictDwarf)109CGOPT(unsigned, AlignLoops)110CGOPT(bool, JMCInstrument)111CGOPT(bool, XCOFFReadOnlyPointers)112113codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {114#define CGBINDOPT(NAME) \115do { \116NAME##View = std::addressof(NAME); \117} while (0)118119static cl::opt<std::string> MArch(120"march", cl::desc("Architecture to generate code for (see --version)"));121CGBINDOPT(MArch);122123static cl::opt<std::string> MCPU(124"mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),125cl::value_desc("cpu-name"), cl::init(""));126CGBINDOPT(MCPU);127128static cl::list<std::string> MAttrs(129"mattr", cl::CommaSeparated,130cl::desc("Target specific attributes (-mattr=help for details)"),131cl::value_desc("a1,+a2,-a3,..."));132CGBINDOPT(MAttrs);133134static cl::opt<Reloc::Model> RelocModel(135"relocation-model", cl::desc("Choose relocation model"),136cl::values(137clEnumValN(Reloc::Static, "static", "Non-relocatable code"),138clEnumValN(Reloc::PIC_, "pic",139"Fully relocatable, position independent code"),140clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",141"Relocatable external references, non-relocatable code"),142clEnumValN(143Reloc::ROPI, "ropi",144"Code and read-only data relocatable, accessed PC-relative"),145clEnumValN(146Reloc::RWPI, "rwpi",147"Read-write data relocatable, accessed relative to static base"),148clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",149"Combination of ropi and rwpi")));150CGBINDOPT(RelocModel);151152static cl::opt<ThreadModel::Model> ThreadModel(153"thread-model", cl::desc("Choose threading model"),154cl::init(ThreadModel::POSIX),155cl::values(156clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),157clEnumValN(ThreadModel::Single, "single", "Single thread model")));158CGBINDOPT(ThreadModel);159160static cl::opt<CodeModel::Model> CodeModel(161"code-model", cl::desc("Choose code model"),162cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),163clEnumValN(CodeModel::Small, "small", "Small code model"),164clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),165clEnumValN(CodeModel::Medium, "medium", "Medium code model"),166clEnumValN(CodeModel::Large, "large", "Large code model")));167CGBINDOPT(CodeModel);168169static cl::opt<uint64_t> LargeDataThreshold(170"large-data-threshold",171cl::desc("Choose large data threshold for x86_64 medium code model"),172cl::init(0));173CGBINDOPT(LargeDataThreshold);174175static cl::opt<ExceptionHandling> ExceptionModel(176"exception-model", cl::desc("exception model"),177cl::init(ExceptionHandling::None),178cl::values(179clEnumValN(ExceptionHandling::None, "default",180"default exception handling model"),181clEnumValN(ExceptionHandling::DwarfCFI, "dwarf",182"DWARF-like CFI based exception handling"),183clEnumValN(ExceptionHandling::SjLj, "sjlj",184"SjLj exception handling"),185clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),186clEnumValN(ExceptionHandling::WinEH, "wineh",187"Windows exception model"),188clEnumValN(ExceptionHandling::Wasm, "wasm",189"WebAssembly exception handling")));190CGBINDOPT(ExceptionModel);191192static cl::opt<CodeGenFileType> FileType(193"filetype", cl::init(CodeGenFileType::AssemblyFile),194cl::desc(195"Choose a file type (not all types are supported by all targets):"),196cl::values(clEnumValN(CodeGenFileType::AssemblyFile, "asm",197"Emit an assembly ('.s') file"),198clEnumValN(CodeGenFileType::ObjectFile, "obj",199"Emit a native object ('.o') file"),200clEnumValN(CodeGenFileType::Null, "null",201"Emit nothing, for performance testing")));202CGBINDOPT(FileType);203204static cl::opt<FramePointerKind> FramePointerUsage(205"frame-pointer",206cl::desc("Specify frame pointer elimination optimization"),207cl::init(FramePointerKind::None),208cl::values(209clEnumValN(FramePointerKind::All, "all",210"Disable frame pointer elimination"),211clEnumValN(FramePointerKind::NonLeaf, "non-leaf",212"Disable frame pointer elimination for non-leaf frame"),213clEnumValN(FramePointerKind::Reserved, "reserved",214"Enable frame pointer elimination, but reserve the frame "215"pointer register"),216clEnumValN(FramePointerKind::None, "none",217"Enable frame pointer elimination")));218CGBINDOPT(FramePointerUsage);219220static cl::opt<bool> EnableUnsafeFPMath(221"enable-unsafe-fp-math",222cl::desc("Enable optimizations that may decrease FP precision"),223cl::init(false));224CGBINDOPT(EnableUnsafeFPMath);225226static cl::opt<bool> EnableNoInfsFPMath(227"enable-no-infs-fp-math",228cl::desc("Enable FP math optimizations that assume no +-Infs"),229cl::init(false));230CGBINDOPT(EnableNoInfsFPMath);231232static cl::opt<bool> EnableNoNaNsFPMath(233"enable-no-nans-fp-math",234cl::desc("Enable FP math optimizations that assume no NaNs"),235cl::init(false));236CGBINDOPT(EnableNoNaNsFPMath);237238static cl::opt<bool> EnableNoSignedZerosFPMath(239"enable-no-signed-zeros-fp-math",240cl::desc("Enable FP math optimizations that assume "241"the sign of 0 is insignificant"),242cl::init(false));243CGBINDOPT(EnableNoSignedZerosFPMath);244245static cl::opt<bool> EnableApproxFuncFPMath(246"enable-approx-func-fp-math",247cl::desc("Enable FP math optimizations that assume approx func"),248cl::init(false));249CGBINDOPT(EnableApproxFuncFPMath);250251static cl::opt<bool> EnableNoTrappingFPMath(252"enable-no-trapping-fp-math",253cl::desc("Enable setting the FP exceptions build "254"attribute not to use exceptions"),255cl::init(false));256CGBINDOPT(EnableNoTrappingFPMath);257258static const auto DenormFlagEnumOptions = cl::values(259clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),260clEnumValN(DenormalMode::PreserveSign, "preserve-sign",261"the sign of a flushed-to-zero number is preserved "262"in the sign of 0"),263clEnumValN(DenormalMode::PositiveZero, "positive-zero",264"denormals are flushed to positive zero"),265clEnumValN(DenormalMode::Dynamic, "dynamic",266"denormals have unknown treatment"));267268// FIXME: Doesn't have way to specify separate input and output modes.269static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(270"denormal-fp-math",271cl::desc("Select which denormal numbers the code is permitted to require"),272cl::init(DenormalMode::IEEE),273DenormFlagEnumOptions);274CGBINDOPT(DenormalFPMath);275276static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(277"denormal-fp-math-f32",278cl::desc("Select which denormal numbers the code is permitted to require for float"),279cl::init(DenormalMode::Invalid),280DenormFlagEnumOptions);281CGBINDOPT(DenormalFP32Math);282283static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(284"enable-sign-dependent-rounding-fp-math", cl::Hidden,285cl::desc("Force codegen to assume rounding mode can change dynamically"),286cl::init(false));287CGBINDOPT(EnableHonorSignDependentRoundingFPMath);288289static cl::opt<FloatABI::ABIType> FloatABIForCalls(290"float-abi", cl::desc("Choose float ABI type"),291cl::init(FloatABI::Default),292cl::values(clEnumValN(FloatABI::Default, "default",293"Target default float ABI type"),294clEnumValN(FloatABI::Soft, "soft",295"Soft float ABI (implied by -soft-float)"),296clEnumValN(FloatABI::Hard, "hard",297"Hard float ABI (uses FP registers)")));298CGBINDOPT(FloatABIForCalls);299300static cl::opt<FPOpFusion::FPOpFusionMode> FuseFPOps(301"fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),302cl::init(FPOpFusion::Standard),303cl::values(304clEnumValN(FPOpFusion::Fast, "fast",305"Fuse FP ops whenever profitable"),306clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),307clEnumValN(FPOpFusion::Strict, "off",308"Only fuse FP ops when the result won't be affected.")));309CGBINDOPT(FuseFPOps);310311static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(312"swift-async-fp",313cl::desc("Determine when the Swift async frame pointer should be set"),314cl::init(SwiftAsyncFramePointerMode::Always),315cl::values(clEnumValN(SwiftAsyncFramePointerMode::DeploymentBased, "auto",316"Determine based on deployment target"),317clEnumValN(SwiftAsyncFramePointerMode::Always, "always",318"Always set the bit"),319clEnumValN(SwiftAsyncFramePointerMode::Never, "never",320"Never set the bit")));321CGBINDOPT(SwiftAsyncFramePointer);322323static cl::opt<bool> DontPlaceZerosInBSS(324"nozero-initialized-in-bss",325cl::desc("Don't place zero-initialized symbols into bss section"),326cl::init(false));327CGBINDOPT(DontPlaceZerosInBSS);328329static cl::opt<bool> EnableAIXExtendedAltivecABI(330"vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),331cl::init(false));332CGBINDOPT(EnableAIXExtendedAltivecABI);333334static cl::opt<bool> EnableGuaranteedTailCallOpt(335"tailcallopt",336cl::desc(337"Turn fastcc calls into tail calls by (potentially) changing ABI."),338cl::init(false));339CGBINDOPT(EnableGuaranteedTailCallOpt);340341static cl::opt<bool> DisableTailCalls(342"disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));343CGBINDOPT(DisableTailCalls);344345static cl::opt<bool> StackSymbolOrdering(346"stack-symbol-ordering", cl::desc("Order local stack symbols."),347cl::init(true));348CGBINDOPT(StackSymbolOrdering);349350static cl::opt<bool> StackRealign(351"stackrealign",352cl::desc("Force align the stack to the minimum alignment"),353cl::init(false));354CGBINDOPT(StackRealign);355356static cl::opt<std::string> TrapFuncName(357"trap-func", cl::Hidden,358cl::desc("Emit a call to trap function rather than a trap instruction"),359cl::init(""));360CGBINDOPT(TrapFuncName);361362static cl::opt<bool> UseCtors("use-ctors",363cl::desc("Use .ctors instead of .init_array."),364cl::init(false));365CGBINDOPT(UseCtors);366367static cl::opt<bool> DataSections(368"data-sections", cl::desc("Emit data into separate sections"),369cl::init(false));370CGBINDOPT(DataSections);371372static cl::opt<bool> FunctionSections(373"function-sections", cl::desc("Emit functions into separate sections"),374cl::init(false));375CGBINDOPT(FunctionSections);376377static cl::opt<bool> IgnoreXCOFFVisibility(378"ignore-xcoff-visibility",379cl::desc("Not emit the visibility attribute for asm in AIX OS or give "380"all symbols 'unspecified' visibility in XCOFF object file"),381cl::init(false));382CGBINDOPT(IgnoreXCOFFVisibility);383384static cl::opt<bool> XCOFFTracebackTable(385"xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),386cl::init(true));387CGBINDOPT(XCOFFTracebackTable);388389static cl::opt<bool> EnableBBAddrMap(390"basic-block-address-map",391cl::desc("Emit the basic block address map section"), cl::init(false));392CGBINDOPT(EnableBBAddrMap);393394static cl::opt<std::string> BBSections(395"basic-block-sections",396cl::desc("Emit basic blocks into separate sections"),397cl::value_desc("all | <function list (file)> | labels | none"),398cl::init("none"));399CGBINDOPT(BBSections);400401static cl::opt<unsigned> TLSSize(402"tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));403CGBINDOPT(TLSSize);404405static cl::opt<bool> EmulatedTLS(406"emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));407CGBINDOPT(EmulatedTLS);408409static cl::opt<bool> EnableTLSDESC(410"enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),411cl::init(false));412CGBINDOPT(EnableTLSDESC);413414static cl::opt<bool> UniqueSectionNames(415"unique-section-names", cl::desc("Give unique names to every section"),416cl::init(true));417CGBINDOPT(UniqueSectionNames);418419static cl::opt<bool> UniqueBasicBlockSectionNames(420"unique-basic-block-section-names",421cl::desc("Give unique names to every basic block section"),422cl::init(false));423CGBINDOPT(UniqueBasicBlockSectionNames);424425static cl::opt<bool> SeparateNamedSections(426"separate-named-sections",427cl::desc("Use separate unique sections for named sections"),428cl::init(false));429CGBINDOPT(SeparateNamedSections);430431static cl::opt<EABI> EABIVersion(432"meabi", cl::desc("Set EABI type (default depends on triple):"),433cl::init(EABI::Default),434cl::values(435clEnumValN(EABI::Default, "default", "Triple default EABI version"),436clEnumValN(EABI::EABI4, "4", "EABI version 4"),437clEnumValN(EABI::EABI5, "5", "EABI version 5"),438clEnumValN(EABI::GNU, "gnu", "EABI GNU")));439CGBINDOPT(EABIVersion);440441static cl::opt<DebuggerKind> DebuggerTuningOpt(442"debugger-tune", cl::desc("Tune debug info for a particular debugger"),443cl::init(DebuggerKind::Default),444cl::values(445clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),446clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),447clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),448clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));449CGBINDOPT(DebuggerTuningOpt);450451static cl::opt<bool> EnableStackSizeSection(452"stack-size-section",453cl::desc("Emit a section containing stack size metadata"),454cl::init(false));455CGBINDOPT(EnableStackSizeSection);456457static cl::opt<bool> EnableAddrsig(458"addrsig", cl::desc("Emit an address-significance table"),459cl::init(false));460CGBINDOPT(EnableAddrsig);461462static cl::opt<bool> EmitCallSiteInfo(463"emit-call-site-info",464cl::desc(465"Emit call site debug information, if debug information is enabled."),466cl::init(false));467CGBINDOPT(EmitCallSiteInfo);468469static cl::opt<bool> EnableDebugEntryValues(470"debug-entry-values",471cl::desc("Enable debug info for the debug entry values."),472cl::init(false));473CGBINDOPT(EnableDebugEntryValues);474475static cl::opt<bool> EnableMachineFunctionSplitter(476"split-machine-functions",477cl::desc("Split out cold basic blocks from machine functions based on "478"profile information"),479cl::init(false));480CGBINDOPT(EnableMachineFunctionSplitter);481482static cl::opt<bool> ForceDwarfFrameSection(483"force-dwarf-frame-section",484cl::desc("Always emit a debug frame section."), cl::init(false));485CGBINDOPT(ForceDwarfFrameSection);486487static cl::opt<bool> XRayFunctionIndex("xray-function-index",488cl::desc("Emit xray_fn_idx section"),489cl::init(true));490CGBINDOPT(XRayFunctionIndex);491492static cl::opt<bool> DebugStrictDwarf(493"strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));494CGBINDOPT(DebugStrictDwarf);495496static cl::opt<unsigned> AlignLoops("align-loops",497cl::desc("Default alignment for loops"));498CGBINDOPT(AlignLoops);499500static cl::opt<bool> JMCInstrument(501"enable-jmc-instrument",502cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),503cl::init(false));504CGBINDOPT(JMCInstrument);505506static cl::opt<bool> XCOFFReadOnlyPointers(507"mxcoff-roptr",508cl::desc("When set to true, const objects with relocatable address "509"values are put into the RO data section."),510cl::init(false));511CGBINDOPT(XCOFFReadOnlyPointers);512513static cl::opt<bool> DisableIntegratedAS(514"no-integrated-as", cl::desc("Disable integrated assembler"),515cl::init(false));516CGBINDOPT(DisableIntegratedAS);517518#undef CGBINDOPT519520mc::RegisterMCTargetOptionsFlags();521}522523llvm::BasicBlockSection524codegen::getBBSectionsMode(llvm::TargetOptions &Options) {525if (getBBSections() == "all")526return BasicBlockSection::All;527else if (getBBSections() == "labels")528return BasicBlockSection::Labels;529else if (getBBSections() == "none")530return BasicBlockSection::None;531else {532ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =533MemoryBuffer::getFile(getBBSections());534if (!MBOrErr) {535errs() << "Error loading basic block sections function list file: "536<< MBOrErr.getError().message() << "\n";537} else {538Options.BBSectionsFuncListBuf = std::move(*MBOrErr);539}540return BasicBlockSection::List;541}542}543544// Common utility function tightly tied to the options listed here. Initializes545// a TargetOptions object with CodeGen flags and returns it.546TargetOptions547codegen::InitTargetOptionsFromCodeGenFlags(const Triple &TheTriple) {548TargetOptions Options;549Options.AllowFPOpFusion = getFuseFPOps();550Options.UnsafeFPMath = getEnableUnsafeFPMath();551Options.NoInfsFPMath = getEnableNoInfsFPMath();552Options.NoNaNsFPMath = getEnableNoNaNsFPMath();553Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();554Options.ApproxFuncFPMath = getEnableApproxFuncFPMath();555Options.NoTrappingFPMath = getEnableNoTrappingFPMath();556557DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();558559// FIXME: Should have separate input and output flags560Options.setFPDenormalMode(DenormalMode(DenormKind, DenormKind));561562Options.HonorSignDependentRoundingFPMathOption =563getEnableHonorSignDependentRoundingFPMath();564if (getFloatABIForCalls() != FloatABI::Default)565Options.FloatABIType = getFloatABIForCalls();566Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();567Options.NoZerosInBSS = getDontPlaceZerosInBSS();568Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();569Options.StackSymbolOrdering = getStackSymbolOrdering();570Options.UseInitArray = !getUseCtors();571Options.DisableIntegratedAS = getDisableIntegratedAS();572Options.DataSections =573getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());574Options.FunctionSections = getFunctionSections();575Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();576Options.XCOFFTracebackTable = getXCOFFTracebackTable();577Options.BBAddrMap = getEnableBBAddrMap();578Options.BBSections = getBBSectionsMode(Options);579Options.UniqueSectionNames = getUniqueSectionNames();580Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();581Options.SeparateNamedSections = getSeparateNamedSections();582Options.TLSSize = getTLSSize();583Options.EmulatedTLS =584getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());585Options.EnableTLSDESC =586getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());587Options.ExceptionModel = getExceptionModel();588Options.EmitStackSizeSection = getEnableStackSizeSection();589Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();590Options.EmitAddrsig = getEnableAddrsig();591Options.EmitCallSiteInfo = getEmitCallSiteInfo();592Options.EnableDebugEntryValues = getEnableDebugEntryValues();593Options.ForceDwarfFrameSection = getForceDwarfFrameSection();594Options.XRayFunctionIndex = getXRayFunctionIndex();595Options.DebugStrictDwarf = getDebugStrictDwarf();596Options.LoopAlignment = getAlignLoops();597Options.JMCInstrument = getJMCInstrument();598Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();599600Options.MCOptions = mc::InitMCTargetOptionsFromFlags();601602Options.ThreadModel = getThreadModel();603Options.EABIVersion = getEABIVersion();604Options.DebuggerTuning = getDebuggerTuningOpt();605Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();606return Options;607}608609std::string codegen::getCPUStr() {610// If user asked for the 'native' CPU, autodetect here. If autodection fails,611// this will set the CPU to an empty string which tells the target to612// pick a basic default.613if (getMCPU() == "native")614return std::string(sys::getHostCPUName());615616return getMCPU();617}618619std::string codegen::getFeaturesStr() {620SubtargetFeatures Features;621622// If user asked for the 'native' CPU, we need to autodetect features.623// This is necessary for x86 where the CPU might not support all the624// features the autodetected CPU name lists in the target. For example,625// not all Sandybridge processors support AVX.626if (getMCPU() == "native")627for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())628Features.AddFeature(Feature, IsEnabled);629630for (auto const &MAttr : getMAttrs())631Features.AddFeature(MAttr);632633return Features.getString();634}635636std::vector<std::string> codegen::getFeatureList() {637SubtargetFeatures Features;638639// If user asked for the 'native' CPU, we need to autodetect features.640// This is necessary for x86 where the CPU might not support all the641// features the autodetected CPU name lists in the target. For example,642// not all Sandybridge processors support AVX.643if (getMCPU() == "native")644for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())645Features.AddFeature(Feature, IsEnabled);646647for (auto const &MAttr : getMAttrs())648Features.AddFeature(MAttr);649650return Features.getFeatures();651}652653void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {654B.addAttribute(Name, Val ? "true" : "false");655}656657#define HANDLE_BOOL_ATTR(CL, AttrName) \658do { \659if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \660renderBoolStringAttr(NewAttrs, AttrName, *CL); \661} while (0)662663/// Set function attributes of function \p F based on CPU, Features, and command664/// line flags.665void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,666Function &F) {667auto &Ctx = F.getContext();668AttributeList Attrs = F.getAttributes();669AttrBuilder NewAttrs(Ctx);670671if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))672NewAttrs.addAttribute("target-cpu", CPU);673if (!Features.empty()) {674// Append the command line features to any that are already on the function.675StringRef OldFeatures =676F.getFnAttribute("target-features").getValueAsString();677if (OldFeatures.empty())678NewAttrs.addAttribute("target-features", Features);679else {680SmallString<256> Appended(OldFeatures);681Appended.push_back(',');682Appended.append(Features);683NewAttrs.addAttribute("target-features", Appended);684}685}686if (FramePointerUsageView->getNumOccurrences() > 0 &&687!F.hasFnAttribute("frame-pointer")) {688if (getFramePointerUsage() == FramePointerKind::All)689NewAttrs.addAttribute("frame-pointer", "all");690else if (getFramePointerUsage() == FramePointerKind::NonLeaf)691NewAttrs.addAttribute("frame-pointer", "non-leaf");692else if (getFramePointerUsage() == FramePointerKind::Reserved)693NewAttrs.addAttribute("frame-pointer", "reserved");694else if (getFramePointerUsage() == FramePointerKind::None)695NewAttrs.addAttribute("frame-pointer", "none");696}697if (DisableTailCallsView->getNumOccurrences() > 0)698NewAttrs.addAttribute("disable-tail-calls",699toStringRef(getDisableTailCalls()));700if (getStackRealign())701NewAttrs.addAttribute("stackrealign");702703HANDLE_BOOL_ATTR(EnableUnsafeFPMathView, "unsafe-fp-math");704HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");705HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");706HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");707HANDLE_BOOL_ATTR(EnableApproxFuncFPMathView, "approx-func-fp-math");708709if (DenormalFPMathView->getNumOccurrences() > 0 &&710!F.hasFnAttribute("denormal-fp-math")) {711DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();712713// FIXME: Command line flag should expose separate input/output modes.714NewAttrs.addAttribute("denormal-fp-math",715DenormalMode(DenormKind, DenormKind).str());716}717718if (DenormalFP32MathView->getNumOccurrences() > 0 &&719!F.hasFnAttribute("denormal-fp-math-f32")) {720// FIXME: Command line flag should expose separate input/output modes.721DenormalMode::DenormalModeKind DenormKind = getDenormalFP32Math();722723NewAttrs.addAttribute(724"denormal-fp-math-f32",725DenormalMode(DenormKind, DenormKind).str());726}727728if (TrapFuncNameView->getNumOccurrences() > 0)729for (auto &B : F)730for (auto &I : B)731if (auto *Call = dyn_cast<CallInst>(&I))732if (const auto *F = Call->getCalledFunction())733if (F->getIntrinsicID() == Intrinsic::debugtrap ||734F->getIntrinsicID() == Intrinsic::trap)735Call->addFnAttr(736Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));737738// Let NewAttrs override Attrs.739F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));740}741742/// Set function attributes of functions in Module M based on CPU,743/// Features, and command line flags.744void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,745Module &M) {746for (Function &F : M)747setFunctionAttributes(CPU, Features, F);748}749750Expected<std::unique_ptr<TargetMachine>>751codegen::createTargetMachineForTriple(StringRef TargetTriple,752CodeGenOptLevel OptLevel) {753Triple TheTriple(TargetTriple);754std::string Error;755const auto *TheTarget =756TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);757if (!TheTarget)758return createStringError(inconvertibleErrorCode(), Error);759auto *Target = TheTarget->createTargetMachine(760TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),761codegen::InitTargetOptionsFromCodeGenFlags(TheTriple),762codegen::getExplicitRelocModel(), codegen::getExplicitCodeModel(),763OptLevel);764if (!Target)765return createStringError(inconvertibleErrorCode(),766Twine("could not allocate target machine for ") +767TargetTriple);768return std::unique_ptr<TargetMachine>(Target);769}770771772