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