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