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