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