1 //===-- CommandFlags.cpp - Command Line Flags Interface ---------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains codegen-specific flags that are shared between different
10 // command line tools. The tools "llc" and "opt" both use this file to prevent
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/CommandFlags.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/TargetParser/Host.h"
24 #include "llvm/TargetParser/SubtargetFeature.h"
25 #include "llvm/TargetParser/Triple.h"
30 #define CGOPT(TY, NAME) \
31 static cl::opt<TY> *NAME##View; \
32 TY codegen::get##NAME() { \
33 assert(NAME##View && "RegisterCodeGenFlags not created."); \
37 #define CGLIST(TY, NAME) \
38 static cl::list<TY> *NAME##View; \
39 std::vector<TY> codegen::get##NAME() { \
40 assert(NAME##View && "RegisterCodeGenFlags not created."); \
44 // Temporary macro for incremental transition to std::optional.
45 #define CGOPT_EXP(TY, NAME) \
47 std::optional<TY> codegen::getExplicit##NAME() { \
48 if (NAME##View->getNumOccurrences()) { \
49 TY res = *NAME##View; \
52 return std::nullopt; \
55 CGOPT(std::string, MArch)
56 CGOPT(std::string, MCPU)
57 CGLIST(std::string, MAttrs)
58 CGOPT_EXP(Reloc::Model, RelocModel)
59 CGOPT(ThreadModel::Model, ThreadModel)
60 CGOPT_EXP(CodeModel::Model, CodeModel)
61 CGOPT(ExceptionHandling, ExceptionModel)
62 CGOPT_EXP(CodeGenFileType, FileType)
63 CGOPT(FramePointerKind, FramePointerUsage)
64 CGOPT(bool, EnableUnsafeFPMath)
65 CGOPT(bool, EnableNoInfsFPMath)
66 CGOPT(bool, EnableNoNaNsFPMath)
67 CGOPT(bool, EnableNoSignedZerosFPMath)
68 CGOPT(bool, EnableApproxFuncFPMath)
69 CGOPT(bool, EnableNoTrappingFPMath)
70 CGOPT(bool, EnableAIXExtendedAltivecABI)
71 CGOPT(DenormalMode::DenormalModeKind, DenormalFPMath)
72 CGOPT(DenormalMode::DenormalModeKind, DenormalFP32Math)
73 CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
74 CGOPT(FloatABI::ABIType, FloatABIForCalls)
75 CGOPT(FPOpFusion::FPOpFusionMode, FuseFPOps)
76 CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
77 CGOPT(bool, DontPlaceZerosInBSS)
78 CGOPT(bool, EnableGuaranteedTailCallOpt)
79 CGOPT(bool, DisableTailCalls)
80 CGOPT(bool, StackSymbolOrdering)
81 CGOPT(bool, StackRealign)
82 CGOPT(std::string, TrapFuncName)
84 CGOPT(bool, DisableIntegratedAS)
85 CGOPT(bool, RelaxELFRelocations)
86 CGOPT_EXP(bool, DataSections)
87 CGOPT_EXP(bool, FunctionSections)
88 CGOPT(bool, IgnoreXCOFFVisibility)
89 CGOPT(bool, XCOFFTracebackTable)
90 CGOPT(std::string, BBSections)
91 CGOPT(unsigned, TLSSize)
92 CGOPT_EXP(bool, EmulatedTLS)
93 CGOPT(bool, UniqueSectionNames)
94 CGOPT(bool, UniqueBasicBlockSectionNames)
95 CGOPT(EABI, EABIVersion)
96 CGOPT(DebuggerKind, DebuggerTuningOpt)
97 CGOPT(bool, EnableStackSizeSection)
98 CGOPT(bool, EnableAddrsig)
99 CGOPT(bool, EmitCallSiteInfo)
100 CGOPT(bool, EnableMachineFunctionSplitter)
101 CGOPT(bool, EnableDebugEntryValues)
102 CGOPT(bool, ForceDwarfFrameSection)
103 CGOPT(bool, XRayFunctionIndex)
104 CGOPT(bool, DebugStrictDwarf)
105 CGOPT(unsigned, AlignLoops)
106 CGOPT(bool, JMCInstrument)
107 CGOPT(bool, XCOFFReadOnlyPointers)
109 codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {
110 #define CGBINDOPT(NAME) \
112 NAME##View = std::addressof(NAME); \
115 static cl::opt<std::string> MArch(
116 "march", cl::desc("Architecture to generate code for (see --version)"));
119 static cl::opt<std::string> MCPU(
120 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
121 cl::value_desc("cpu-name"), cl::init(""));
124 static cl::list<std::string> MAttrs(
125 "mattr", cl::CommaSeparated,
126 cl::desc("Target specific attributes (-mattr=help for details)"),
127 cl::value_desc("a1,+a2,-a3,..."));
130 static cl::opt<Reloc::Model> RelocModel(
131 "relocation-model", cl::desc("Choose relocation model"),
133 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
134 clEnumValN(Reloc::PIC_, "pic",
135 "Fully relocatable, position independent code"),
136 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
137 "Relocatable external references, non-relocatable code"),
140 "Code and read-only data relocatable, accessed PC-relative"),
143 "Read-write data relocatable, accessed relative to static base"),
144 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
145 "Combination of ropi and rwpi")));
146 CGBINDOPT(RelocModel);
148 static cl::opt<ThreadModel::Model> ThreadModel(
149 "thread-model", cl::desc("Choose threading model"),
150 cl::init(ThreadModel::POSIX),
152 clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
153 clEnumValN(ThreadModel::Single, "single", "Single thread model")));
154 CGBINDOPT(ThreadModel);
156 static cl::opt<CodeModel::Model> CodeModel(
157 "code-model", cl::desc("Choose code model"),
158 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
159 clEnumValN(CodeModel::Small, "small", "Small code model"),
160 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
161 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
162 clEnumValN(CodeModel::Large, "large", "Large code model")));
163 CGBINDOPT(CodeModel);
165 static cl::opt<ExceptionHandling> ExceptionModel(
166 "exception-model", cl::desc("exception model"),
167 cl::init(ExceptionHandling::None),
169 clEnumValN(ExceptionHandling::None, "default",
170 "default exception handling model"),
171 clEnumValN(ExceptionHandling::DwarfCFI, "dwarf",
172 "DWARF-like CFI based exception handling"),
173 clEnumValN(ExceptionHandling::SjLj, "sjlj",
174 "SjLj exception handling"),
175 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
176 clEnumValN(ExceptionHandling::WinEH, "wineh",
177 "Windows exception model"),
178 clEnumValN(ExceptionHandling::Wasm, "wasm",
179 "WebAssembly exception handling")));
180 CGBINDOPT(ExceptionModel);
182 static cl::opt<CodeGenFileType> FileType(
183 "filetype", cl::init(CGFT_AssemblyFile),
185 "Choose a file type (not all types are supported by all targets):"),
187 clEnumValN(CGFT_AssemblyFile, "asm", "Emit an assembly ('.s') file"),
188 clEnumValN(CGFT_ObjectFile, "obj",
189 "Emit a native object ('.o') file"),
190 clEnumValN(CGFT_Null, "null",
191 "Emit nothing, for performance testing")));
194 static cl::opt<FramePointerKind> FramePointerUsage(
196 cl::desc("Specify frame pointer elimination optimization"),
197 cl::init(FramePointerKind::None),
199 clEnumValN(FramePointerKind::All, "all",
200 "Disable frame pointer elimination"),
201 clEnumValN(FramePointerKind::NonLeaf, "non-leaf",
202 "Disable frame pointer elimination for non-leaf frame"),
203 clEnumValN(FramePointerKind::None, "none",
204 "Enable frame pointer elimination")));
205 CGBINDOPT(FramePointerUsage);
207 static cl::opt<bool> EnableUnsafeFPMath(
208 "enable-unsafe-fp-math",
209 cl::desc("Enable optimizations that may decrease FP precision"),
211 CGBINDOPT(EnableUnsafeFPMath);
213 static cl::opt<bool> EnableNoInfsFPMath(
214 "enable-no-infs-fp-math",
215 cl::desc("Enable FP math optimizations that assume no +-Infs"),
217 CGBINDOPT(EnableNoInfsFPMath);
219 static cl::opt<bool> EnableNoNaNsFPMath(
220 "enable-no-nans-fp-math",
221 cl::desc("Enable FP math optimizations that assume no NaNs"),
223 CGBINDOPT(EnableNoNaNsFPMath);
225 static cl::opt<bool> EnableNoSignedZerosFPMath(
226 "enable-no-signed-zeros-fp-math",
227 cl::desc("Enable FP math optimizations that assume "
228 "the sign of 0 is insignificant"),
230 CGBINDOPT(EnableNoSignedZerosFPMath);
232 static cl::opt<bool> EnableApproxFuncFPMath(
233 "enable-approx-func-fp-math",
234 cl::desc("Enable FP math optimizations that assume approx func"),
236 CGBINDOPT(EnableApproxFuncFPMath);
238 static cl::opt<bool> EnableNoTrappingFPMath(
239 "enable-no-trapping-fp-math",
240 cl::desc("Enable setting the FP exceptions build "
241 "attribute not to use exceptions"),
243 CGBINDOPT(EnableNoTrappingFPMath);
245 static const auto DenormFlagEnumOptions = cl::values(
246 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
247 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
248 "the sign of a flushed-to-zero number is preserved "
250 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
251 "denormals are flushed to positive zero"),
252 clEnumValN(DenormalMode::Dynamic, "dynamic",
253 "denormals have unknown treatment"));
255 // FIXME: Doesn't have way to specify separate input and output modes.
256 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
258 cl::desc("Select which denormal numbers the code is permitted to require"),
259 cl::init(DenormalMode::IEEE),
260 DenormFlagEnumOptions);
261 CGBINDOPT(DenormalFPMath);
263 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
264 "denormal-fp-math-f32",
265 cl::desc("Select which denormal numbers the code is permitted to require for float"),
266 cl::init(DenormalMode::Invalid),
267 DenormFlagEnumOptions);
268 CGBINDOPT(DenormalFP32Math);
270 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
271 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
272 cl::desc("Force codegen to assume rounding mode can change dynamically"),
274 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
276 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
277 "float-abi", cl::desc("Choose float ABI type"),
278 cl::init(FloatABI::Default),
279 cl::values(clEnumValN(FloatABI::Default, "default",
280 "Target default float ABI type"),
281 clEnumValN(FloatABI::Soft, "soft",
282 "Soft float ABI (implied by -soft-float)"),
283 clEnumValN(FloatABI::Hard, "hard",
284 "Hard float ABI (uses FP registers)")));
285 CGBINDOPT(FloatABIForCalls);
287 static cl::opt<FPOpFusion::FPOpFusionMode> FuseFPOps(
288 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
289 cl::init(FPOpFusion::Standard),
291 clEnumValN(FPOpFusion::Fast, "fast",
292 "Fuse FP ops whenever profitable"),
293 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
294 clEnumValN(FPOpFusion::Strict, "off",
295 "Only fuse FP ops when the result won't be affected.")));
296 CGBINDOPT(FuseFPOps);
298 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
300 cl::desc("Determine when the Swift async frame pointer should be set"),
301 cl::init(SwiftAsyncFramePointerMode::Always),
302 cl::values(clEnumValN(SwiftAsyncFramePointerMode::DeploymentBased, "auto",
303 "Determine based on deployment target"),
304 clEnumValN(SwiftAsyncFramePointerMode::Always, "always",
305 "Always set the bit"),
306 clEnumValN(SwiftAsyncFramePointerMode::Never, "never",
307 "Never set the bit")));
308 CGBINDOPT(SwiftAsyncFramePointer);
310 static cl::opt<bool> DontPlaceZerosInBSS(
311 "nozero-initialized-in-bss",
312 cl::desc("Don't place zero-initialized symbols into bss section"),
314 CGBINDOPT(DontPlaceZerosInBSS);
316 static cl::opt<bool> EnableAIXExtendedAltivecABI(
317 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
319 CGBINDOPT(EnableAIXExtendedAltivecABI);
321 static cl::opt<bool> EnableGuaranteedTailCallOpt(
324 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
326 CGBINDOPT(EnableGuaranteedTailCallOpt);
328 static cl::opt<bool> DisableTailCalls(
329 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
330 CGBINDOPT(DisableTailCalls);
332 static cl::opt<bool> StackSymbolOrdering(
333 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
335 CGBINDOPT(StackSymbolOrdering);
337 static cl::opt<bool> StackRealign(
339 cl::desc("Force align the stack to the minimum alignment"),
341 CGBINDOPT(StackRealign);
343 static cl::opt<std::string> TrapFuncName(
344 "trap-func", cl::Hidden,
345 cl::desc("Emit a call to trap function rather than a trap instruction"),
347 CGBINDOPT(TrapFuncName);
349 static cl::opt<bool> UseCtors("use-ctors",
350 cl::desc("Use .ctors instead of .init_array."),
354 static cl::opt<bool> RelaxELFRelocations(
355 "relax-elf-relocations",
357 "Emit GOTPCRELX/REX_GOTPCRELX instead of GOTPCREL on x86-64 ELF"),
359 CGBINDOPT(RelaxELFRelocations);
361 static cl::opt<bool> DataSections(
362 "data-sections", cl::desc("Emit data into separate sections"),
364 CGBINDOPT(DataSections);
366 static cl::opt<bool> FunctionSections(
367 "function-sections", cl::desc("Emit functions into separate sections"),
369 CGBINDOPT(FunctionSections);
371 static cl::opt<bool> IgnoreXCOFFVisibility(
372 "ignore-xcoff-visibility",
373 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
374 "all symbols 'unspecified' visibility in XCOFF object file"),
376 CGBINDOPT(IgnoreXCOFFVisibility);
378 static cl::opt<bool> XCOFFTracebackTable(
379 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
381 CGBINDOPT(XCOFFTracebackTable);
383 static cl::opt<std::string> BBSections(
384 "basic-block-sections",
385 cl::desc("Emit basic blocks into separate sections"),
386 cl::value_desc("all | <function list (file)> | labels | none"),
388 CGBINDOPT(BBSections);
390 static cl::opt<unsigned> TLSSize(
391 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
394 static cl::opt<bool> EmulatedTLS(
395 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
396 CGBINDOPT(EmulatedTLS);
398 static cl::opt<bool> UniqueSectionNames(
399 "unique-section-names", cl::desc("Give unique names to every section"),
401 CGBINDOPT(UniqueSectionNames);
403 static cl::opt<bool> UniqueBasicBlockSectionNames(
404 "unique-basic-block-section-names",
405 cl::desc("Give unique names to every basic block section"),
407 CGBINDOPT(UniqueBasicBlockSectionNames);
409 static cl::opt<EABI> EABIVersion(
410 "meabi", cl::desc("Set EABI type (default depends on triple):"),
411 cl::init(EABI::Default),
413 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
414 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
415 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
416 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
417 CGBINDOPT(EABIVersion);
419 static cl::opt<DebuggerKind> DebuggerTuningOpt(
420 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
421 cl::init(DebuggerKind::Default),
423 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
424 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
425 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
426 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
427 CGBINDOPT(DebuggerTuningOpt);
429 static cl::opt<bool> EnableStackSizeSection(
430 "stack-size-section",
431 cl::desc("Emit a section containing stack size metadata"),
433 CGBINDOPT(EnableStackSizeSection);
435 static cl::opt<bool> EnableAddrsig(
436 "addrsig", cl::desc("Emit an address-significance table"),
438 CGBINDOPT(EnableAddrsig);
440 static cl::opt<bool> EmitCallSiteInfo(
441 "emit-call-site-info",
443 "Emit call site debug information, if debug information is enabled."),
445 CGBINDOPT(EmitCallSiteInfo);
447 static cl::opt<bool> EnableDebugEntryValues(
448 "debug-entry-values",
449 cl::desc("Enable debug info for the debug entry values."),
451 CGBINDOPT(EnableDebugEntryValues);
453 static cl::opt<bool> EnableMachineFunctionSplitter(
454 "split-machine-functions",
455 cl::desc("Split out cold basic blocks from machine functions based on "
456 "profile information"),
458 CGBINDOPT(EnableMachineFunctionSplitter);
460 static cl::opt<bool> ForceDwarfFrameSection(
461 "force-dwarf-frame-section",
462 cl::desc("Always emit a debug frame section."), cl::init(false));
463 CGBINDOPT(ForceDwarfFrameSection);
465 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
466 cl::desc("Emit xray_fn_idx section"),
468 CGBINDOPT(XRayFunctionIndex);
470 static cl::opt<bool> DebugStrictDwarf(
471 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
472 CGBINDOPT(DebugStrictDwarf);
474 static cl::opt<unsigned> AlignLoops("align-loops",
475 cl::desc("Default alignment for loops"));
476 CGBINDOPT(AlignLoops);
478 static cl::opt<bool> JMCInstrument(
479 "enable-jmc-instrument",
480 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
482 CGBINDOPT(JMCInstrument);
484 static cl::opt<bool> XCOFFReadOnlyPointers(
486 cl::desc("When set to true, const objects with relocatable address "
487 "values are put into the RO data section."),
489 CGBINDOPT(XCOFFReadOnlyPointers);
491 static cl::opt<bool> DisableIntegratedAS(
492 "no-integrated-as", cl::desc("Disable integrated assembler"),
494 CGBINDOPT(DisableIntegratedAS);
498 mc::RegisterMCTargetOptionsFlags();
501 llvm::BasicBlockSection
502 codegen::getBBSectionsMode(llvm::TargetOptions &Options) {
503 if (getBBSections() == "all")
504 return BasicBlockSection::All;
505 else if (getBBSections() == "labels")
506 return BasicBlockSection::Labels;
507 else if (getBBSections() == "none")
508 return BasicBlockSection::None;
510 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
511 MemoryBuffer::getFile(getBBSections());
513 errs() << "Error loading basic block sections function list file: "
514 << MBOrErr.getError().message() << "\n";
516 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
518 return BasicBlockSection::List;
522 // Common utility function tightly tied to the options listed here. Initializes
523 // a TargetOptions object with CodeGen flags and returns it.
525 codegen::InitTargetOptionsFromCodeGenFlags(const Triple &TheTriple) {
526 TargetOptions Options;
527 Options.AllowFPOpFusion = getFuseFPOps();
528 Options.UnsafeFPMath = getEnableUnsafeFPMath();
529 Options.NoInfsFPMath = getEnableNoInfsFPMath();
530 Options.NoNaNsFPMath = getEnableNoNaNsFPMath();
531 Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
532 Options.ApproxFuncFPMath = getEnableApproxFuncFPMath();
533 Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
535 DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
537 // FIXME: Should have separate input and output flags
538 Options.setFPDenormalMode(DenormalMode(DenormKind, DenormKind));
540 Options.HonorSignDependentRoundingFPMathOption =
541 getEnableHonorSignDependentRoundingFPMath();
542 if (getFloatABIForCalls() != FloatABI::Default)
543 Options.FloatABIType = getFloatABIForCalls();
544 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
545 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
546 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
547 Options.StackSymbolOrdering = getStackSymbolOrdering();
548 Options.UseInitArray = !getUseCtors();
549 Options.DisableIntegratedAS = getDisableIntegratedAS();
550 Options.RelaxELFRelocations = getRelaxELFRelocations();
551 Options.DataSections =
552 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
553 Options.FunctionSections = getFunctionSections();
554 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
555 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
556 Options.BBSections = getBBSectionsMode(Options);
557 Options.UniqueSectionNames = getUniqueSectionNames();
558 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
559 Options.TLSSize = getTLSSize();
560 Options.EmulatedTLS =
561 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
562 Options.ExceptionModel = getExceptionModel();
563 Options.EmitStackSizeSection = getEnableStackSizeSection();
564 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
565 Options.EmitAddrsig = getEnableAddrsig();
566 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
567 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
568 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
569 Options.XRayFunctionIndex = getXRayFunctionIndex();
570 Options.DebugStrictDwarf = getDebugStrictDwarf();
571 Options.LoopAlignment = getAlignLoops();
572 Options.JMCInstrument = getJMCInstrument();
573 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
575 Options.MCOptions = mc::InitMCTargetOptionsFromFlags();
577 Options.ThreadModel = getThreadModel();
578 Options.EABIVersion = getEABIVersion();
579 Options.DebuggerTuning = getDebuggerTuningOpt();
580 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
584 std::string codegen::getCPUStr() {
585 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
586 // this will set the CPU to an empty string which tells the target to
587 // pick a basic default.
588 if (getMCPU() == "native")
589 return std::string(sys::getHostCPUName());
594 std::string codegen::getFeaturesStr() {
595 SubtargetFeatures Features;
597 // If user asked for the 'native' CPU, we need to autodetect features.
598 // This is necessary for x86 where the CPU might not support all the
599 // features the autodetected CPU name lists in the target. For example,
600 // not all Sandybridge processors support AVX.
601 if (getMCPU() == "native") {
602 StringMap<bool> HostFeatures;
603 if (sys::getHostCPUFeatures(HostFeatures))
604 for (const auto &[Feature, IsEnabled] : HostFeatures)
605 Features.AddFeature(Feature, IsEnabled);
608 for (auto const &MAttr : getMAttrs())
609 Features.AddFeature(MAttr);
611 return Features.getString();
614 std::vector<std::string> codegen::getFeatureList() {
615 SubtargetFeatures Features;
617 // If user asked for the 'native' CPU, we need to autodetect features.
618 // This is necessary for x86 where the CPU might not support all the
619 // features the autodetected CPU name lists in the target. For example,
620 // not all Sandybridge processors support AVX.
621 if (getMCPU() == "native") {
622 StringMap<bool> HostFeatures;
623 if (sys::getHostCPUFeatures(HostFeatures))
624 for (const auto &[Feature, IsEnabled] : HostFeatures)
625 Features.AddFeature(Feature, IsEnabled);
628 for (auto const &MAttr : getMAttrs())
629 Features.AddFeature(MAttr);
631 return Features.getFeatures();
634 void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
635 B.addAttribute(Name, Val ? "true" : "false");
638 #define HANDLE_BOOL_ATTR(CL, AttrName) \
640 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
641 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
644 /// Set function attributes of function \p F based on CPU, Features, and command
646 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
648 auto &Ctx = F.getContext();
649 AttributeList Attrs = F.getAttributes();
650 AttrBuilder NewAttrs(Ctx);
652 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
653 NewAttrs.addAttribute("target-cpu", CPU);
654 if (!Features.empty()) {
655 // Append the command line features to any that are already on the function.
656 StringRef OldFeatures =
657 F.getFnAttribute("target-features").getValueAsString();
658 if (OldFeatures.empty())
659 NewAttrs.addAttribute("target-features", Features);
661 SmallString<256> Appended(OldFeatures);
662 Appended.push_back(',');
663 Appended.append(Features);
664 NewAttrs.addAttribute("target-features", Appended);
667 if (FramePointerUsageView->getNumOccurrences() > 0 &&
668 !F.hasFnAttribute("frame-pointer")) {
669 if (getFramePointerUsage() == FramePointerKind::All)
670 NewAttrs.addAttribute("frame-pointer", "all");
671 else if (getFramePointerUsage() == FramePointerKind::NonLeaf)
672 NewAttrs.addAttribute("frame-pointer", "non-leaf");
673 else if (getFramePointerUsage() == FramePointerKind::None)
674 NewAttrs.addAttribute("frame-pointer", "none");
676 if (DisableTailCallsView->getNumOccurrences() > 0)
677 NewAttrs.addAttribute("disable-tail-calls",
678 toStringRef(getDisableTailCalls()));
679 if (getStackRealign())
680 NewAttrs.addAttribute("stackrealign");
682 HANDLE_BOOL_ATTR(EnableUnsafeFPMathView, "unsafe-fp-math");
683 HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");
684 HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");
685 HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
686 HANDLE_BOOL_ATTR(EnableApproxFuncFPMathView, "approx-func-fp-math");
688 if (DenormalFPMathView->getNumOccurrences() > 0 &&
689 !F.hasFnAttribute("denormal-fp-math")) {
690 DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
692 // FIXME: Command line flag should expose separate input/output modes.
693 NewAttrs.addAttribute("denormal-fp-math",
694 DenormalMode(DenormKind, DenormKind).str());
697 if (DenormalFP32MathView->getNumOccurrences() > 0 &&
698 !F.hasFnAttribute("denormal-fp-math-f32")) {
699 // FIXME: Command line flag should expose separate input/output modes.
700 DenormalMode::DenormalModeKind DenormKind = getDenormalFP32Math();
702 NewAttrs.addAttribute(
703 "denormal-fp-math-f32",
704 DenormalMode(DenormKind, DenormKind).str());
707 if (TrapFuncNameView->getNumOccurrences() > 0)
710 if (auto *Call = dyn_cast<CallInst>(&I))
711 if (const auto *F = Call->getCalledFunction())
712 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
713 F->getIntrinsicID() == Intrinsic::trap)
715 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
717 // Let NewAttrs override Attrs.
718 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
721 /// Set function attributes of functions in Module M based on CPU,
722 /// Features, and command line flags.
723 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
725 for (Function &F : M)
726 setFunctionAttributes(CPU, Features, F);