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