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