• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- CommandFlags.cpp - Command Line Flags Interface ---------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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
11 // flag duplication.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/CommandFlags.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/MC/SubtargetFeature.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Host.h"
20 
21 using namespace llvm;
22 
23 #define CGOPT(TY, NAME)                                                        \
24   static cl::opt<TY> *NAME##View;                                              \
25   TY codegen::get##NAME() {                                                    \
26     assert(NAME##View && "RegisterCodeGenFlags not created.");                 \
27     return *NAME##View;                                                        \
28   }
29 
30 #define CGLIST(TY, NAME)                                                       \
31   static cl::list<TY> *NAME##View;                                             \
32   std::vector<TY> codegen::get##NAME() {                                       \
33     assert(NAME##View && "RegisterCodeGenFlags not created.");                 \
34     return *NAME##View;                                                        \
35   }
36 
37 #define CGOPT_EXP(TY, NAME)                                                    \
38   CGOPT(TY, NAME)                                                              \
39   Optional<TY> codegen::getExplicit##NAME() {                                  \
40     if (NAME##View->getNumOccurrences()) {                                     \
41       TY res = *NAME##View;                                                    \
42       return res;                                                              \
43     }                                                                          \
44     return None;                                                               \
45   }
46 
CGOPT(std::string,MArch)47 CGOPT(std::string, MArch)
48 CGOPT(std::string, MCPU)
49 CGLIST(std::string, MAttrs)
50 CGOPT_EXP(Reloc::Model, RelocModel)
51 CGOPT(ThreadModel::Model, ThreadModel)
52 CGOPT_EXP(CodeModel::Model, CodeModel)
53 CGOPT(ExceptionHandling, ExceptionModel)
54 CGOPT_EXP(CodeGenFileType, FileType)
55 CGOPT(FramePointer::FP, FramePointerUsage)
56 CGOPT(bool, EnableUnsafeFPMath)
57 CGOPT(bool, EnableNoInfsFPMath)
58 CGOPT(bool, EnableNoNaNsFPMath)
59 CGOPT(bool, EnableNoSignedZerosFPMath)
60 CGOPT(bool, EnableNoTrappingFPMath)
61 CGOPT(bool, EnableAIXExtendedAltivecABI)
62 CGOPT(DenormalMode::DenormalModeKind, DenormalFPMath)
63 CGOPT(DenormalMode::DenormalModeKind, DenormalFP32Math)
64 CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
65 CGOPT(FloatABI::ABIType, FloatABIForCalls)
66 CGOPT(FPOpFusion::FPOpFusionMode, FuseFPOps)
67 CGOPT(bool, DontPlaceZerosInBSS)
68 CGOPT(bool, EnableGuaranteedTailCallOpt)
69 CGOPT(bool, DisableTailCalls)
70 CGOPT(bool, StackSymbolOrdering)
71 CGOPT(unsigned, OverrideStackAlignment)
72 CGOPT(bool, StackRealign)
73 CGOPT(std::string, TrapFuncName)
74 CGOPT(bool, UseCtors)
75 CGOPT(bool, RelaxELFRelocations)
76 CGOPT_EXP(bool, DataSections)
77 CGOPT_EXP(bool, FunctionSections)
78 CGOPT(bool, IgnoreXCOFFVisibility)
79 CGOPT(std::string, BBSections)
80 CGOPT(std::string, StackProtectorGuard)
81 CGOPT(unsigned, StackProtectorGuardOffset)
82 CGOPT(std::string, StackProtectorGuardReg)
83 CGOPT(unsigned, TLSSize)
84 CGOPT(bool, EmulatedTLS)
85 CGOPT(bool, UniqueSectionNames)
86 CGOPT(bool, UniqueBasicBlockSectionNames)
87 CGOPT(EABI, EABIVersion)
88 CGOPT(DebuggerKind, DebuggerTuningOpt)
89 CGOPT(bool, EnableStackSizeSection)
90 CGOPT(bool, EnableAddrsig)
91 CGOPT(bool, EmitCallSiteInfo)
92 CGOPT(bool, EnableMachineFunctionSplitter)
93 CGOPT(bool, EnableDebugEntryValues)
94 CGOPT(bool, PseudoProbeForProfiling)
95 CGOPT(bool, ValueTrackingVariableLocations)
96 CGOPT(bool, ForceDwarfFrameSection)
97 CGOPT(bool, XRayOmitFunctionIndex)
98 
99 codegen::RegisterCodeGenFlags::RegisterCodeGenFlags() {
100 #define CGBINDOPT(NAME)                                                        \
101   do {                                                                         \
102     NAME##View = std::addressof(NAME);                                         \
103   } while (0)
104 
105   static cl::opt<std::string> MArch(
106       "march", cl::desc("Architecture to generate code for (see --version)"));
107   CGBINDOPT(MArch);
108 
109   static cl::opt<std::string> MCPU(
110       "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
111       cl::value_desc("cpu-name"), cl::init(""));
112   CGBINDOPT(MCPU);
113 
114   static cl::list<std::string> MAttrs(
115       "mattr", cl::CommaSeparated,
116       cl::desc("Target specific attributes (-mattr=help for details)"),
117       cl::value_desc("a1,+a2,-a3,..."));
118   CGBINDOPT(MAttrs);
119 
120   static cl::opt<Reloc::Model> RelocModel(
121       "relocation-model", cl::desc("Choose relocation model"),
122       cl::values(
123           clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
124           clEnumValN(Reloc::PIC_, "pic",
125                      "Fully relocatable, position independent code"),
126           clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
127                      "Relocatable external references, non-relocatable code"),
128           clEnumValN(
129               Reloc::ROPI, "ropi",
130               "Code and read-only data relocatable, accessed PC-relative"),
131           clEnumValN(
132               Reloc::RWPI, "rwpi",
133               "Read-write data relocatable, accessed relative to static base"),
134           clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
135                      "Combination of ropi and rwpi")));
136   CGBINDOPT(RelocModel);
137 
138   static cl::opt<ThreadModel::Model> ThreadModel(
139       "thread-model", cl::desc("Choose threading model"),
140       cl::init(ThreadModel::POSIX),
141       cl::values(
142           clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
143           clEnumValN(ThreadModel::Single, "single", "Single thread model")));
144   CGBINDOPT(ThreadModel);
145 
146   static cl::opt<CodeModel::Model> CodeModel(
147       "code-model", cl::desc("Choose code model"),
148       cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
149                  clEnumValN(CodeModel::Small, "small", "Small code model"),
150                  clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
151                  clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
152                  clEnumValN(CodeModel::Large, "large", "Large code model")));
153   CGBINDOPT(CodeModel);
154 
155   static cl::opt<ExceptionHandling> ExceptionModel(
156       "exception-model", cl::desc("exception model"),
157       cl::init(ExceptionHandling::None),
158       cl::values(
159           clEnumValN(ExceptionHandling::None, "default",
160                      "default exception handling model"),
161           clEnumValN(ExceptionHandling::DwarfCFI, "dwarf",
162                      "DWARF-like CFI based exception handling"),
163           clEnumValN(ExceptionHandling::SjLj, "sjlj",
164                      "SjLj exception handling"),
165           clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
166           clEnumValN(ExceptionHandling::WinEH, "wineh",
167                      "Windows exception model"),
168           clEnumValN(ExceptionHandling::Wasm, "wasm",
169                      "WebAssembly exception handling")));
170   CGBINDOPT(ExceptionModel);
171 
172   static cl::opt<CodeGenFileType> FileType(
173       "filetype", cl::init(CGFT_AssemblyFile),
174       cl::desc(
175           "Choose a file type (not all types are supported by all targets):"),
176       cl::values(
177           clEnumValN(CGFT_AssemblyFile, "asm", "Emit an assembly ('.s') file"),
178           clEnumValN(CGFT_ObjectFile, "obj",
179                      "Emit a native object ('.o') file"),
180           clEnumValN(CGFT_Null, "null",
181                      "Emit nothing, for performance testing")));
182   CGBINDOPT(FileType);
183 
184   static cl::opt<FramePointer::FP> FramePointerUsage(
185       "frame-pointer",
186       cl::desc("Specify frame pointer elimination optimization"),
187       cl::init(FramePointer::None),
188       cl::values(
189           clEnumValN(FramePointer::All, "all",
190                      "Disable frame pointer elimination"),
191           clEnumValN(FramePointer::NonLeaf, "non-leaf",
192                      "Disable frame pointer elimination for non-leaf frame"),
193           clEnumValN(FramePointer::None, "none",
194                      "Enable frame pointer elimination")));
195   CGBINDOPT(FramePointerUsage);
196 
197   static cl::opt<bool> EnableUnsafeFPMath(
198       "enable-unsafe-fp-math",
199       cl::desc("Enable optimizations that may decrease FP precision"),
200       cl::init(false));
201   CGBINDOPT(EnableUnsafeFPMath);
202 
203   static cl::opt<bool> EnableNoInfsFPMath(
204       "enable-no-infs-fp-math",
205       cl::desc("Enable FP math optimizations that assume no +-Infs"),
206       cl::init(false));
207   CGBINDOPT(EnableNoInfsFPMath);
208 
209   static cl::opt<bool> EnableNoNaNsFPMath(
210       "enable-no-nans-fp-math",
211       cl::desc("Enable FP math optimizations that assume no NaNs"),
212       cl::init(false));
213   CGBINDOPT(EnableNoNaNsFPMath);
214 
215   static cl::opt<bool> EnableNoSignedZerosFPMath(
216       "enable-no-signed-zeros-fp-math",
217       cl::desc("Enable FP math optimizations that assume "
218                "the sign of 0 is insignificant"),
219       cl::init(false));
220   CGBINDOPT(EnableNoSignedZerosFPMath);
221 
222   static cl::opt<bool> EnableNoTrappingFPMath(
223       "enable-no-trapping-fp-math",
224       cl::desc("Enable setting the FP exceptions build "
225                "attribute not to use exceptions"),
226       cl::init(false));
227   CGBINDOPT(EnableNoTrappingFPMath);
228 
229   static const auto DenormFlagEnumOptions =
230   cl::values(clEnumValN(DenormalMode::IEEE, "ieee",
231                         "IEEE 754 denormal numbers"),
232              clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
233                         "the sign of a  flushed-to-zero number is preserved "
234                         "in the sign of 0"),
235              clEnumValN(DenormalMode::PositiveZero, "positive-zero",
236                         "denormals are flushed to positive zero"));
237 
238   // FIXME: Doesn't have way to specify separate input and output modes.
239   static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
240     "denormal-fp-math",
241     cl::desc("Select which denormal numbers the code is permitted to require"),
242     cl::init(DenormalMode::IEEE),
243     DenormFlagEnumOptions);
244   CGBINDOPT(DenormalFPMath);
245 
246   static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
247     "denormal-fp-math-f32",
248     cl::desc("Select which denormal numbers the code is permitted to require for float"),
249     cl::init(DenormalMode::Invalid),
250     DenormFlagEnumOptions);
251   CGBINDOPT(DenormalFP32Math);
252 
253   static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
254       "enable-sign-dependent-rounding-fp-math", cl::Hidden,
255       cl::desc("Force codegen to assume rounding mode can change dynamically"),
256       cl::init(false));
257   CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
258 
259   static cl::opt<FloatABI::ABIType> FloatABIForCalls(
260       "float-abi", cl::desc("Choose float ABI type"),
261       cl::init(FloatABI::Default),
262       cl::values(clEnumValN(FloatABI::Default, "default",
263                             "Target default float ABI type"),
264                  clEnumValN(FloatABI::Soft, "soft",
265                             "Soft float ABI (implied by -soft-float)"),
266                  clEnumValN(FloatABI::Hard, "hard",
267                             "Hard float ABI (uses FP registers)")));
268   CGBINDOPT(FloatABIForCalls);
269 
270   static cl::opt<FPOpFusion::FPOpFusionMode> FuseFPOps(
271       "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
272       cl::init(FPOpFusion::Standard),
273       cl::values(
274           clEnumValN(FPOpFusion::Fast, "fast",
275                      "Fuse FP ops whenever profitable"),
276           clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
277           clEnumValN(FPOpFusion::Strict, "off",
278                      "Only fuse FP ops when the result won't be affected.")));
279   CGBINDOPT(FuseFPOps);
280 
281   static cl::opt<bool> DontPlaceZerosInBSS(
282       "nozero-initialized-in-bss",
283       cl::desc("Don't place zero-initialized symbols into bss section"),
284       cl::init(false));
285   CGBINDOPT(DontPlaceZerosInBSS);
286 
287   static cl::opt<bool> EnableAIXExtendedAltivecABI(
288       "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
289       cl::init(false));
290   CGBINDOPT(EnableAIXExtendedAltivecABI);
291 
292   static cl::opt<bool> EnableGuaranteedTailCallOpt(
293       "tailcallopt",
294       cl::desc(
295           "Turn fastcc calls into tail calls by (potentially) changing ABI."),
296       cl::init(false));
297   CGBINDOPT(EnableGuaranteedTailCallOpt);
298 
299   static cl::opt<bool> DisableTailCalls(
300       "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
301   CGBINDOPT(DisableTailCalls);
302 
303   static cl::opt<bool> StackSymbolOrdering(
304       "stack-symbol-ordering", cl::desc("Order local stack symbols."),
305       cl::init(true));
306   CGBINDOPT(StackSymbolOrdering);
307 
308   static cl::opt<unsigned> OverrideStackAlignment(
309       "stack-alignment", cl::desc("Override default stack alignment"),
310       cl::init(0));
311   CGBINDOPT(OverrideStackAlignment);
312 
313   static cl::opt<bool> StackRealign(
314       "stackrealign",
315       cl::desc("Force align the stack to the minimum alignment"),
316       cl::init(false));
317   CGBINDOPT(StackRealign);
318 
319   static cl::opt<std::string> TrapFuncName(
320       "trap-func", cl::Hidden,
321       cl::desc("Emit a call to trap function rather than a trap instruction"),
322       cl::init(""));
323   CGBINDOPT(TrapFuncName);
324 
325   static cl::opt<bool> UseCtors("use-ctors",
326                                 cl::desc("Use .ctors instead of .init_array."),
327                                 cl::init(false));
328   CGBINDOPT(UseCtors);
329 
330   static cl::opt<bool> RelaxELFRelocations(
331       "relax-elf-relocations",
332       cl::desc(
333           "Emit GOTPCRELX/REX_GOTPCRELX instead of GOTPCREL on x86-64 ELF"),
334       cl::init(false));
335   CGBINDOPT(RelaxELFRelocations);
336 
337   static cl::opt<bool> DataSections(
338       "data-sections", cl::desc("Emit data into separate sections"),
339       cl::init(false));
340   CGBINDOPT(DataSections);
341 
342   static cl::opt<bool> FunctionSections(
343       "function-sections", cl::desc("Emit functions into separate sections"),
344       cl::init(false));
345   CGBINDOPT(FunctionSections);
346 
347   static cl::opt<bool> IgnoreXCOFFVisibility(
348       "ignore-xcoff-visibility",
349       cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
350                "all symbols 'unspecified' visibility in XCOFF object file"),
351       cl::init(false));
352   CGBINDOPT(IgnoreXCOFFVisibility);
353 
354   static cl::opt<std::string> BBSections(
355       "basic-block-sections",
356       cl::desc("Emit basic blocks into separate sections"),
357       cl::value_desc("all | <function list (file)> | labels | none"),
358       cl::init("none"));
359   CGBINDOPT(BBSections);
360 
361   static cl::opt<std::string> StackProtectorGuard(
362       "stack-protector-guard", cl::desc("Stack protector guard mode"),
363       cl::init("none"));
364   CGBINDOPT(StackProtectorGuard);
365 
366   static cl::opt<std::string> StackProtectorGuardReg(
367       "stack-protector-guard-reg", cl::desc("Stack protector guard register"),
368       cl::init("none"));
369   CGBINDOPT(StackProtectorGuardReg);
370 
371   static cl::opt<unsigned> StackProtectorGuardOffset(
372       "stack-protector-guard-offset", cl::desc("Stack protector guard offset"),
373       cl::init((unsigned)-1));
374   CGBINDOPT(StackProtectorGuardOffset);
375 
376   static cl::opt<unsigned> TLSSize(
377       "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
378   CGBINDOPT(TLSSize);
379 
380   static cl::opt<bool> EmulatedTLS(
381       "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
382   CGBINDOPT(EmulatedTLS);
383 
384   static cl::opt<bool> UniqueSectionNames(
385       "unique-section-names", cl::desc("Give unique names to every section"),
386       cl::init(true));
387   CGBINDOPT(UniqueSectionNames);
388 
389   static cl::opt<bool> UniqueBasicBlockSectionNames(
390       "unique-basic-block-section-names",
391       cl::desc("Give unique names to every basic block section"),
392       cl::init(false));
393   CGBINDOPT(UniqueBasicBlockSectionNames);
394 
395   static cl::opt<EABI> EABIVersion(
396       "meabi", cl::desc("Set EABI type (default depends on triple):"),
397       cl::init(EABI::Default),
398       cl::values(
399           clEnumValN(EABI::Default, "default", "Triple default EABI version"),
400           clEnumValN(EABI::EABI4, "4", "EABI version 4"),
401           clEnumValN(EABI::EABI5, "5", "EABI version 5"),
402           clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
403   CGBINDOPT(EABIVersion);
404 
405   static cl::opt<DebuggerKind> DebuggerTuningOpt(
406       "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
407       cl::init(DebuggerKind::Default),
408       cl::values(
409           clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
410           clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
411           clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
412   CGBINDOPT(DebuggerTuningOpt);
413 
414   static cl::opt<bool> EnableStackSizeSection(
415       "stack-size-section",
416       cl::desc("Emit a section containing stack size metadata"),
417       cl::init(false));
418   CGBINDOPT(EnableStackSizeSection);
419 
420   static cl::opt<bool> EnableAddrsig(
421       "addrsig", cl::desc("Emit an address-significance table"),
422       cl::init(false));
423   CGBINDOPT(EnableAddrsig);
424 
425   static cl::opt<bool> EmitCallSiteInfo(
426       "emit-call-site-info",
427       cl::desc(
428           "Emit call site debug information, if debug information is enabled."),
429       cl::init(false));
430   CGBINDOPT(EmitCallSiteInfo);
431 
432   static cl::opt<bool> EnableDebugEntryValues(
433       "debug-entry-values",
434       cl::desc("Enable debug info for the debug entry values."),
435       cl::init(false));
436   CGBINDOPT(EnableDebugEntryValues);
437 
438   static cl::opt<bool> PseudoProbeForProfiling(
439       "pseudo-probe-for-profiling", cl::desc("Emit pseudo probes for AutoFDO"),
440       cl::init(false));
441   CGBINDOPT(PseudoProbeForProfiling);
442 
443   static cl::opt<bool> ValueTrackingVariableLocations(
444       "experimental-debug-variable-locations",
445       cl::desc("Use experimental new value-tracking variable locations"),
446       cl::init(false));
447   CGBINDOPT(ValueTrackingVariableLocations);
448 
449   static cl::opt<bool> EnableMachineFunctionSplitter(
450       "split-machine-functions",
451       cl::desc("Split out cold basic blocks from machine functions based on "
452                "profile information"),
453       cl::init(false));
454   CGBINDOPT(EnableMachineFunctionSplitter);
455 
456   static cl::opt<bool> ForceDwarfFrameSection(
457       "force-dwarf-frame-section",
458       cl::desc("Always emit a debug frame section."), cl::init(false));
459   CGBINDOPT(ForceDwarfFrameSection);
460 
461   static cl::opt<bool> XRayOmitFunctionIndex(
462       "no-xray-index", cl::desc("Don't emit xray_fn_idx section"),
463       cl::init(false));
464   CGBINDOPT(XRayOmitFunctionIndex);
465 
466 #undef CGBINDOPT
467 
468   mc::RegisterMCTargetOptionsFlags();
469 }
470 
471 llvm::BasicBlockSection
getBBSectionsMode(llvm::TargetOptions & Options)472 codegen::getBBSectionsMode(llvm::TargetOptions &Options) {
473   if (getBBSections() == "all")
474     return BasicBlockSection::All;
475   else if (getBBSections() == "labels")
476     return BasicBlockSection::Labels;
477   else if (getBBSections() == "none")
478     return BasicBlockSection::None;
479   else {
480     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
481         MemoryBuffer::getFile(getBBSections());
482     if (!MBOrErr) {
483       errs() << "Error loading basic block sections function list file: "
484              << MBOrErr.getError().message() << "\n";
485     } else {
486       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
487     }
488     return BasicBlockSection::List;
489   }
490 }
491 
492 llvm::StackProtectorGuards
getStackProtectorGuardMode(llvm::TargetOptions & Options)493 codegen::getStackProtectorGuardMode(llvm::TargetOptions &Options) {
494   if (getStackProtectorGuard() == "tls")
495     return StackProtectorGuards::TLS;
496   if (getStackProtectorGuard() == "global")
497     return StackProtectorGuards::Global;
498   if (getStackProtectorGuard() != "none") {
499     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
500         MemoryBuffer::getFile(getStackProtectorGuard());
501     if (!MBOrErr)
502       errs() << "error illegal stack protector guard mode: "
503              << MBOrErr.getError().message() << "\n";
504     else
505       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
506   }
507   return StackProtectorGuards::None;
508 }
509 
510 // Common utility function tightly tied to the options listed here. Initializes
511 // a TargetOptions object with CodeGen flags and returns it.
512 TargetOptions
InitTargetOptionsFromCodeGenFlags(const Triple & TheTriple)513 codegen::InitTargetOptionsFromCodeGenFlags(const Triple &TheTriple) {
514   TargetOptions Options;
515   Options.AllowFPOpFusion = getFuseFPOps();
516   Options.UnsafeFPMath = getEnableUnsafeFPMath();
517   Options.NoInfsFPMath = getEnableNoInfsFPMath();
518   Options.NoNaNsFPMath = getEnableNoNaNsFPMath();
519   Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
520   Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
521 
522   DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
523 
524   // FIXME: Should have separate input and output flags
525   Options.setFPDenormalMode(DenormalMode(DenormKind, DenormKind));
526 
527   Options.HonorSignDependentRoundingFPMathOption =
528       getEnableHonorSignDependentRoundingFPMath();
529   if (getFloatABIForCalls() != FloatABI::Default)
530     Options.FloatABIType = getFloatABIForCalls();
531   Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
532   Options.NoZerosInBSS = getDontPlaceZerosInBSS();
533   Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
534   Options.StackAlignmentOverride = getOverrideStackAlignment();
535   Options.StackSymbolOrdering = getStackSymbolOrdering();
536   Options.UseInitArray = !getUseCtors();
537   Options.RelaxELFRelocations = getRelaxELFRelocations();
538   Options.DataSections =
539       getExplicitDataSections().getValueOr(TheTriple.hasDefaultDataSections());
540   Options.FunctionSections = getFunctionSections();
541   Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
542   Options.BBSections = getBBSectionsMode(Options);
543   Options.UniqueSectionNames = getUniqueSectionNames();
544   Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
545   Options.StackProtectorGuard = getStackProtectorGuardMode(Options);
546   Options.StackProtectorGuardOffset = getStackProtectorGuardOffset();
547   Options.StackProtectorGuardReg = getStackProtectorGuardReg();
548   Options.TLSSize = getTLSSize();
549   Options.EmulatedTLS = getEmulatedTLS();
550   Options.ExplicitEmulatedTLS = EmulatedTLSView->getNumOccurrences() > 0;
551   Options.ExceptionModel = getExceptionModel();
552   Options.EmitStackSizeSection = getEnableStackSizeSection();
553   Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
554   Options.EmitAddrsig = getEnableAddrsig();
555   Options.EmitCallSiteInfo = getEmitCallSiteInfo();
556   Options.EnableDebugEntryValues = getEnableDebugEntryValues();
557   Options.PseudoProbeForProfiling = getPseudoProbeForProfiling();
558   Options.ValueTrackingVariableLocations = getValueTrackingVariableLocations();
559   Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
560   Options.XRayOmitFunctionIndex = getXRayOmitFunctionIndex();
561 
562   Options.MCOptions = mc::InitMCTargetOptionsFromFlags();
563 
564   Options.ThreadModel = getThreadModel();
565   Options.EABIVersion = getEABIVersion();
566   Options.DebuggerTuning = getDebuggerTuningOpt();
567 
568   return Options;
569 }
570 
getCPUStr()571 std::string codegen::getCPUStr() {
572   // If user asked for the 'native' CPU, autodetect here. If autodection fails,
573   // this will set the CPU to an empty string which tells the target to
574   // pick a basic default.
575   if (getMCPU() == "native")
576     return std::string(sys::getHostCPUName());
577 
578   return getMCPU();
579 }
580 
getFeaturesStr()581 std::string codegen::getFeaturesStr() {
582   SubtargetFeatures Features;
583 
584   // If user asked for the 'native' CPU, we need to autodetect features.
585   // This is necessary for x86 where the CPU might not support all the
586   // features the autodetected CPU name lists in the target. For example,
587   // not all Sandybridge processors support AVX.
588   if (getMCPU() == "native") {
589     StringMap<bool> HostFeatures;
590     if (sys::getHostCPUFeatures(HostFeatures))
591       for (auto &F : HostFeatures)
592         Features.AddFeature(F.first(), F.second);
593   }
594 
595   for (auto const &MAttr : getMAttrs())
596     Features.AddFeature(MAttr);
597 
598   return Features.getString();
599 }
600 
getFeatureList()601 std::vector<std::string> codegen::getFeatureList() {
602   SubtargetFeatures Features;
603 
604   // If user asked for the 'native' CPU, we need to autodetect features.
605   // This is necessary for x86 where the CPU might not support all the
606   // features the autodetected CPU name lists in the target. For example,
607   // not all Sandybridge processors support AVX.
608   if (getMCPU() == "native") {
609     StringMap<bool> HostFeatures;
610     if (sys::getHostCPUFeatures(HostFeatures))
611       for (auto &F : HostFeatures)
612         Features.AddFeature(F.first(), F.second);
613   }
614 
615   for (auto const &MAttr : getMAttrs())
616     Features.AddFeature(MAttr);
617 
618   return Features.getFeatures();
619 }
620 
renderBoolStringAttr(AttrBuilder & B,StringRef Name,bool Val)621 void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
622   B.addAttribute(Name, Val ? "true" : "false");
623 }
624 
625 #define HANDLE_BOOL_ATTR(CL, AttrName)                                         \
626   do {                                                                         \
627     if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName))            \
628       renderBoolStringAttr(NewAttrs, AttrName, *CL);                           \
629   } while (0)
630 
631 /// Set function attributes of function \p F based on CPU, Features, and command
632 /// line flags.
setFunctionAttributes(StringRef CPU,StringRef Features,Function & F)633 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
634                                     Function &F) {
635   auto &Ctx = F.getContext();
636   AttributeList Attrs = F.getAttributes();
637   AttrBuilder NewAttrs;
638 
639   if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
640     NewAttrs.addAttribute("target-cpu", CPU);
641   if (!Features.empty()) {
642     // Append the command line features to any that are already on the function.
643     StringRef OldFeatures =
644         F.getFnAttribute("target-features").getValueAsString();
645     if (OldFeatures.empty())
646       NewAttrs.addAttribute("target-features", Features);
647     else {
648       SmallString<256> Appended(OldFeatures);
649       Appended.push_back(',');
650       Appended.append(Features);
651       NewAttrs.addAttribute("target-features", Appended);
652     }
653   }
654   if (FramePointerUsageView->getNumOccurrences() > 0 &&
655       !F.hasFnAttribute("frame-pointer")) {
656     if (getFramePointerUsage() == FramePointer::All)
657       NewAttrs.addAttribute("frame-pointer", "all");
658     else if (getFramePointerUsage() == FramePointer::NonLeaf)
659       NewAttrs.addAttribute("frame-pointer", "non-leaf");
660     else if (getFramePointerUsage() == FramePointer::None)
661       NewAttrs.addAttribute("frame-pointer", "none");
662   }
663   if (DisableTailCallsView->getNumOccurrences() > 0)
664     NewAttrs.addAttribute("disable-tail-calls",
665                           toStringRef(getDisableTailCalls()));
666   if (getStackRealign())
667     NewAttrs.addAttribute("stackrealign");
668 
669   HANDLE_BOOL_ATTR(EnableUnsafeFPMathView, "unsafe-fp-math");
670   HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");
671   HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");
672   HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
673 
674   if (DenormalFPMathView->getNumOccurrences() > 0 &&
675       !F.hasFnAttribute("denormal-fp-math")) {
676     DenormalMode::DenormalModeKind DenormKind = getDenormalFPMath();
677 
678     // FIXME: Command line flag should expose separate input/output modes.
679     NewAttrs.addAttribute("denormal-fp-math",
680                           DenormalMode(DenormKind, DenormKind).str());
681   }
682 
683   if (DenormalFP32MathView->getNumOccurrences() > 0 &&
684       !F.hasFnAttribute("denormal-fp-math-f32")) {
685     // FIXME: Command line flag should expose separate input/output modes.
686     DenormalMode::DenormalModeKind DenormKind = getDenormalFP32Math();
687 
688     NewAttrs.addAttribute(
689       "denormal-fp-math-f32",
690       DenormalMode(DenormKind, DenormKind).str());
691   }
692 
693   if (TrapFuncNameView->getNumOccurrences() > 0)
694     for (auto &B : F)
695       for (auto &I : B)
696         if (auto *Call = dyn_cast<CallInst>(&I))
697           if (const auto *F = Call->getCalledFunction())
698             if (F->getIntrinsicID() == Intrinsic::debugtrap ||
699                 F->getIntrinsicID() == Intrinsic::trap)
700               Call->addAttribute(
701                   AttributeList::FunctionIndex,
702                   Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
703 
704   // Let NewAttrs override Attrs.
705   F.setAttributes(
706       Attrs.addAttributes(Ctx, AttributeList::FunctionIndex, NewAttrs));
707 }
708 
709 /// Set function attributes of functions in Module M based on CPU,
710 /// Features, and command line flags.
setFunctionAttributes(StringRef CPU,StringRef Features,Module & M)711 void codegen::setFunctionAttributes(StringRef CPU, StringRef Features,
712                                     Module &M) {
713   for (Function &F : M)
714     setFunctionAttributes(CPU, Features, F);
715 }
716