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