LLVM 22.0.0git
CommandFlags.cpp
Go to the documentation of this file.
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
18#include "llvm/IR/Intrinsics.h"
19#include "llvm/IR/Module.h"
28#include <optional>
29
30using namespace llvm;
31
32#define CGOPT(TY, NAME) \
33 static cl::opt<TY> *NAME##View; \
34 TY codegen::get##NAME() { \
35 assert(NAME##View && "RegisterCodeGenFlags not created."); \
36 return *NAME##View; \
37 }
38
39#define CGLIST(TY, NAME) \
40 static cl::list<TY> *NAME##View; \
41 std::vector<TY> codegen::get##NAME() { \
42 assert(NAME##View && "RegisterCodeGenFlags not created."); \
43 return *NAME##View; \
44 }
45
46// Temporary macro for incremental transition to std::optional.
47#define CGOPT_EXP(TY, NAME) \
48 CGOPT(TY, NAME) \
49 std::optional<TY> codegen::getExplicit##NAME() { \
50 if (NAME##View->getNumOccurrences()) { \
51 TY res = *NAME##View; \
52 return res; \
53 } \
54 return std::nullopt; \
55 }
56
57CGOPT(std::string, MArch)
58CGOPT(std::string, MCPU)
59CGLIST(std::string, MAttrs)
60CGOPT_EXP(Reloc::Model, RelocModel)
61CGOPT(ThreadModel::Model, ThreadModel)
63CGOPT_EXP(uint64_t, LargeDataThreshold)
64CGOPT(ExceptionHandling, ExceptionModel)
66CGOPT(FramePointerKind, FramePointerUsage)
67CGOPT(bool, EnableUnsafeFPMath)
68CGOPT(bool, EnableNoInfsFPMath)
69CGOPT(bool, EnableNoNaNsFPMath)
70CGOPT(bool, EnableNoSignedZerosFPMath)
71CGOPT(bool, EnableNoTrappingFPMath)
72CGOPT(bool, EnableAIXExtendedAltivecABI)
75CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
76CGOPT(FloatABI::ABIType, FloatABIForCalls)
78CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
79CGOPT(bool, DontPlaceZerosInBSS)
80CGOPT(bool, EnableGuaranteedTailCallOpt)
81CGOPT(bool, DisableTailCalls)
82CGOPT(bool, StackSymbolOrdering)
83CGOPT(bool, StackRealign)
84CGOPT(std::string, TrapFuncName)
85CGOPT(bool, UseCtors)
86CGOPT(bool, DisableIntegratedAS)
87CGOPT_EXP(bool, DataSections)
88CGOPT_EXP(bool, FunctionSections)
89CGOPT(bool, IgnoreXCOFFVisibility)
90CGOPT(bool, XCOFFTracebackTable)
91CGOPT(bool, EnableBBAddrMap)
92CGOPT(std::string, BBSections)
93CGOPT(unsigned, TLSSize)
94CGOPT_EXP(bool, EmulatedTLS)
95CGOPT_EXP(bool, EnableTLSDESC)
96CGOPT(bool, UniqueSectionNames)
97CGOPT(bool, UniqueBasicBlockSectionNames)
98CGOPT(bool, SeparateNamedSections)
99CGOPT(EABI, EABIVersion)
100CGOPT(DebuggerKind, DebuggerTuningOpt)
101CGOPT(bool, EnableStackSizeSection)
102CGOPT(bool, EnableAddrsig)
103CGOPT(bool, EnableCallGraphSection)
104CGOPT(bool, EmitCallSiteInfo)
106CGOPT(bool, EnableStaticDataPartitioning)
107CGOPT(bool, EnableDebugEntryValues)
108CGOPT(bool, ForceDwarfFrameSection)
109CGOPT(bool, XRayFunctionIndex)
110CGOPT(bool, DebugStrictDwarf)
111CGOPT(unsigned, AlignLoops)
112CGOPT(bool, JMCInstrument)
113CGOPT(bool, XCOFFReadOnlyPointers)
114
116#define CGBINDOPT(NAME) \
117 do { \
118 NAME##View = std::addressof(NAME); \
119 } while (0)
120
121 static cl::opt<std::string> MArch(
122 "march", cl::desc("Architecture to generate code for (see --version)"));
123 CGBINDOPT(MArch);
124
125 static cl::opt<std::string> MCPU(
126 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
127 cl::value_desc("cpu-name"), cl::init(""));
128 CGBINDOPT(MCPU);
129
130 static cl::list<std::string> MAttrs(
131 "mattr", cl::CommaSeparated,
132 cl::desc("Target specific attributes (-mattr=help for details)"),
133 cl::value_desc("a1,+a2,-a3,..."));
134 CGBINDOPT(MAttrs);
135
136 static cl::opt<Reloc::Model> RelocModel(
137 "relocation-model", cl::desc("Choose relocation model"),
139 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
140 clEnumValN(Reloc::PIC_, "pic",
141 "Fully relocatable, position independent code"),
142 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
143 "Relocatable external references, non-relocatable code"),
145 Reloc::ROPI, "ropi",
146 "Code and read-only data relocatable, accessed PC-relative"),
148 Reloc::RWPI, "rwpi",
149 "Read-write data relocatable, accessed relative to static base"),
150 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
151 "Combination of ropi and rwpi")));
152 CGBINDOPT(RelocModel);
153
154 static cl::opt<ThreadModel::Model> ThreadModel(
155 "thread-model", cl::desc("Choose threading model"),
158 clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
159 clEnumValN(ThreadModel::Single, "single", "Single thread model")));
160 CGBINDOPT(ThreadModel);
161
162 static cl::opt<CodeModel::Model> CodeModel(
163 "code-model", cl::desc("Choose code model"),
164 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
165 clEnumValN(CodeModel::Small, "small", "Small code model"),
166 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
167 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
168 clEnumValN(CodeModel::Large, "large", "Large code model")));
169 CGBINDOPT(CodeModel);
170
171 static cl::opt<uint64_t> LargeDataThreshold(
172 "large-data-threshold",
173 cl::desc("Choose large data threshold for x86_64 medium code model"),
174 cl::init(0));
175 CGBINDOPT(LargeDataThreshold);
176
177 static cl::opt<ExceptionHandling> ExceptionModel(
178 "exception-model", cl::desc("exception model"),
179 cl::init(ExceptionHandling::None),
181 clEnumValN(ExceptionHandling::None, "default",
182 "default exception handling model"),
183 clEnumValN(ExceptionHandling::DwarfCFI, "dwarf",
184 "DWARF-like CFI based exception handling"),
185 clEnumValN(ExceptionHandling::SjLj, "sjlj",
186 "SjLj exception handling"),
187 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
188 clEnumValN(ExceptionHandling::WinEH, "wineh",
189 "Windows exception model"),
190 clEnumValN(ExceptionHandling::Wasm, "wasm",
191 "WebAssembly exception handling")));
192 CGBINDOPT(ExceptionModel);
193
194 static cl::opt<CodeGenFileType> FileType(
195 "filetype", cl::init(CodeGenFileType::AssemblyFile),
196 cl::desc(
197 "Choose a file type (not all types are supported by all targets):"),
198 cl::values(clEnumValN(CodeGenFileType::AssemblyFile, "asm",
199 "Emit an assembly ('.s') file"),
200 clEnumValN(CodeGenFileType::ObjectFile, "obj",
201 "Emit a native object ('.o') file"),
202 clEnumValN(CodeGenFileType::Null, "null",
203 "Emit nothing, for performance testing")));
204 CGBINDOPT(FileType);
205
206 static cl::opt<FramePointerKind> FramePointerUsage(
207 "frame-pointer",
208 cl::desc("Specify frame pointer elimination optimization"),
209 cl::init(FramePointerKind::None),
211 clEnumValN(FramePointerKind::All, "all",
212 "Disable frame pointer elimination"),
213 clEnumValN(FramePointerKind::NonLeaf, "non-leaf",
214 "Disable frame pointer elimination for non-leaf frame"),
215 clEnumValN(FramePointerKind::Reserved, "reserved",
216 "Enable frame pointer elimination, but reserve the frame "
217 "pointer register"),
218 clEnumValN(FramePointerKind::None, "none",
219 "Enable frame pointer elimination")));
220 CGBINDOPT(FramePointerUsage);
221
222 static cl::opt<bool> EnableUnsafeFPMath(
223 "enable-unsafe-fp-math",
224 cl::desc("Enable optimizations that may decrease FP precision"),
225 cl::init(false));
226 CGBINDOPT(EnableUnsafeFPMath);
227
228 static cl::opt<bool> EnableNoInfsFPMath(
229 "enable-no-infs-fp-math",
230 cl::desc("Enable FP math optimizations that assume no +-Infs"),
231 cl::init(false));
232 CGBINDOPT(EnableNoInfsFPMath);
233
234 static cl::opt<bool> EnableNoNaNsFPMath(
235 "enable-no-nans-fp-math",
236 cl::desc("Enable FP math optimizations that assume no NaNs"),
237 cl::init(false));
238 CGBINDOPT(EnableNoNaNsFPMath);
239
240 static cl::opt<bool> EnableNoSignedZerosFPMath(
241 "enable-no-signed-zeros-fp-math",
242 cl::desc("Enable FP math optimizations that assume "
243 "the sign of 0 is insignificant"),
244 cl::init(false));
245 CGBINDOPT(EnableNoSignedZerosFPMath);
246
247 static cl::opt<bool> EnableNoTrappingFPMath(
248 "enable-no-trapping-fp-math",
249 cl::desc("Enable setting the FP exceptions build "
250 "attribute not to use exceptions"),
251 cl::init(false));
252 CGBINDOPT(EnableNoTrappingFPMath);
253
254 static const auto DenormFlagEnumOptions = cl::values(
255 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
256 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
257 "the sign of a flushed-to-zero number is preserved "
258 "in the sign of 0"),
259 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
260 "denormals are flushed to positive zero"),
262 "denormals have unknown treatment"));
263
264 // FIXME: Doesn't have way to specify separate input and output modes.
265 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
266 "denormal-fp-math",
267 cl::desc("Select which denormal numbers the code is permitted to require"),
269 DenormFlagEnumOptions);
270 CGBINDOPT(DenormalFPMath);
271
272 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
273 "denormal-fp-math-f32",
274 cl::desc("Select which denormal numbers the code is permitted to require for float"),
276 DenormFlagEnumOptions);
277 CGBINDOPT(DenormalFP32Math);
278
279 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
280 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
281 cl::desc("Force codegen to assume rounding mode can change dynamically"),
282 cl::init(false));
283 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
284
285 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
286 "float-abi", cl::desc("Choose float ABI type"),
289 "Target default float ABI type"),
291 "Soft float ABI (implied by -soft-float)"),
293 "Hard float ABI (uses FP registers)")));
294 CGBINDOPT(FloatABIForCalls);
295
297 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
301 "Fuse FP ops whenever profitable"),
302 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
304 "Only fuse FP ops when the result won't be affected.")));
305 CGBINDOPT(FuseFPOps);
306
307 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
308 "swift-async-fp",
309 cl::desc("Determine when the Swift async frame pointer should be set"),
310 cl::init(SwiftAsyncFramePointerMode::Always),
311 cl::values(clEnumValN(SwiftAsyncFramePointerMode::DeploymentBased, "auto",
312 "Determine based on deployment target"),
313 clEnumValN(SwiftAsyncFramePointerMode::Always, "always",
314 "Always set the bit"),
315 clEnumValN(SwiftAsyncFramePointerMode::Never, "never",
316 "Never set the bit")));
317 CGBINDOPT(SwiftAsyncFramePointer);
318
319 static cl::opt<bool> DontPlaceZerosInBSS(
320 "nozero-initialized-in-bss",
321 cl::desc("Don't place zero-initialized symbols into bss section"),
322 cl::init(false));
323 CGBINDOPT(DontPlaceZerosInBSS);
324
325 static cl::opt<bool> EnableAIXExtendedAltivecABI(
326 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
327 cl::init(false));
328 CGBINDOPT(EnableAIXExtendedAltivecABI);
329
330 static cl::opt<bool> EnableGuaranteedTailCallOpt(
331 "tailcallopt",
332 cl::desc(
333 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
334 cl::init(false));
335 CGBINDOPT(EnableGuaranteedTailCallOpt);
336
337 static cl::opt<bool> DisableTailCalls(
338 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
339 CGBINDOPT(DisableTailCalls);
340
341 static cl::opt<bool> StackSymbolOrdering(
342 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
343 cl::init(true));
344 CGBINDOPT(StackSymbolOrdering);
345
346 static cl::opt<bool> StackRealign(
347 "stackrealign",
348 cl::desc("Force align the stack to the minimum alignment"),
349 cl::init(false));
350 CGBINDOPT(StackRealign);
351
352 static cl::opt<std::string> TrapFuncName(
353 "trap-func", cl::Hidden,
354 cl::desc("Emit a call to trap function rather than a trap instruction"),
355 cl::init(""));
356 CGBINDOPT(TrapFuncName);
357
358 static cl::opt<bool> UseCtors("use-ctors",
359 cl::desc("Use .ctors instead of .init_array."),
360 cl::init(false));
361 CGBINDOPT(UseCtors);
362
363 static cl::opt<bool> DataSections(
364 "data-sections", cl::desc("Emit data into separate sections"),
365 cl::init(false));
366 CGBINDOPT(DataSections);
367
368 static cl::opt<bool> FunctionSections(
369 "function-sections", cl::desc("Emit functions into separate sections"),
370 cl::init(false));
371 CGBINDOPT(FunctionSections);
372
373 static cl::opt<bool> IgnoreXCOFFVisibility(
374 "ignore-xcoff-visibility",
375 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
376 "all symbols 'unspecified' visibility in XCOFF object file"),
377 cl::init(false));
378 CGBINDOPT(IgnoreXCOFFVisibility);
379
380 static cl::opt<bool> XCOFFTracebackTable(
381 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
382 cl::init(true));
383 CGBINDOPT(XCOFFTracebackTable);
384
385 static cl::opt<bool> EnableBBAddrMap(
386 "basic-block-address-map",
387 cl::desc("Emit the basic block address map section"), cl::init(false));
388 CGBINDOPT(EnableBBAddrMap);
389
390 static cl::opt<std::string> BBSections(
391 "basic-block-sections",
392 cl::desc("Emit basic blocks into separate sections"),
393 cl::value_desc("all | <function list (file)> | labels | none"),
394 cl::init("none"));
395 CGBINDOPT(BBSections);
396
397 static cl::opt<unsigned> TLSSize(
398 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
399 CGBINDOPT(TLSSize);
400
401 static cl::opt<bool> EmulatedTLS(
402 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
403 CGBINDOPT(EmulatedTLS);
404
405 static cl::opt<bool> EnableTLSDESC(
406 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
407 cl::init(false));
408 CGBINDOPT(EnableTLSDESC);
409
410 static cl::opt<bool> UniqueSectionNames(
411 "unique-section-names", cl::desc("Give unique names to every section"),
412 cl::init(true));
413 CGBINDOPT(UniqueSectionNames);
414
415 static cl::opt<bool> UniqueBasicBlockSectionNames(
416 "unique-basic-block-section-names",
417 cl::desc("Give unique names to every basic block section"),
418 cl::init(false));
419 CGBINDOPT(UniqueBasicBlockSectionNames);
420
421 static cl::opt<bool> SeparateNamedSections(
422 "separate-named-sections",
423 cl::desc("Use separate unique sections for named sections"),
424 cl::init(false));
425 CGBINDOPT(SeparateNamedSections);
426
427 static cl::opt<EABI> EABIVersion(
428 "meabi", cl::desc("Set EABI type (default depends on triple):"),
429 cl::init(EABI::Default),
431 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
432 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
433 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
434 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
435 CGBINDOPT(EABIVersion);
436
437 static cl::opt<DebuggerKind> DebuggerTuningOpt(
438 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
439 cl::init(DebuggerKind::Default),
441 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
442 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
443 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
444 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
445 CGBINDOPT(DebuggerTuningOpt);
446
447 static cl::opt<bool> EnableStackSizeSection(
448 "stack-size-section",
449 cl::desc("Emit a section containing stack size metadata"),
450 cl::init(false));
451 CGBINDOPT(EnableStackSizeSection);
452
453 static cl::opt<bool> EnableAddrsig(
454 "addrsig", cl::desc("Emit an address-significance table"),
455 cl::init(false));
456 CGBINDOPT(EnableAddrsig);
457
458 static cl::opt<bool> EnableCallGraphSection(
459 "call-graph-section", cl::desc("Emit a call graph section"),
460 cl::init(false));
461 CGBINDOPT(EnableCallGraphSection);
462
463 static cl::opt<bool> EmitCallSiteInfo(
464 "emit-call-site-info",
465 cl::desc(
466 "Emit call site debug information, if debug information is enabled."),
467 cl::init(false));
468 CGBINDOPT(EmitCallSiteInfo);
469
470 static cl::opt<bool> EnableDebugEntryValues(
471 "debug-entry-values",
472 cl::desc("Enable debug info for the debug entry values."),
473 cl::init(false));
474 CGBINDOPT(EnableDebugEntryValues);
475
477 "split-machine-functions",
478 cl::desc("Split out cold basic blocks from machine functions based on "
479 "profile information"),
480 cl::init(false));
482
483 static cl::opt<bool> EnableStaticDataPartitioning(
484 "partition-static-data-sections",
485 cl::desc("Partition data sections using profile information."),
486 cl::init(false));
487 CGBINDOPT(EnableStaticDataPartitioning);
488
489 static cl::opt<bool> ForceDwarfFrameSection(
490 "force-dwarf-frame-section",
491 cl::desc("Always emit a debug frame section."), cl::init(false));
492 CGBINDOPT(ForceDwarfFrameSection);
493
494 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
495 cl::desc("Emit xray_fn_idx section"),
496 cl::init(true));
497 CGBINDOPT(XRayFunctionIndex);
498
499 static cl::opt<bool> DebugStrictDwarf(
500 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
501 CGBINDOPT(DebugStrictDwarf);
502
503 static cl::opt<unsigned> AlignLoops("align-loops",
504 cl::desc("Default alignment for loops"));
505 CGBINDOPT(AlignLoops);
506
507 static cl::opt<bool> JMCInstrument(
508 "enable-jmc-instrument",
509 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
510 cl::init(false));
511 CGBINDOPT(JMCInstrument);
512
513 static cl::opt<bool> XCOFFReadOnlyPointers(
514 "mxcoff-roptr",
515 cl::desc("When set to true, const objects with relocatable address "
516 "values are put into the RO data section."),
517 cl::init(false));
518 CGBINDOPT(XCOFFReadOnlyPointers);
519
520 static cl::opt<bool> DisableIntegratedAS(
521 "no-integrated-as", cl::desc("Disable integrated assembler"),
522 cl::init(false));
523 CGBINDOPT(DisableIntegratedAS);
524
525#undef CGBINDOPT
526
528}
529
532 if (getBBSections() == "all")
533 return BasicBlockSection::All;
534 else if (getBBSections() == "none")
535 return BasicBlockSection::None;
536 else {
539 if (!MBOrErr) {
540 errs() << "Error loading basic block sections function list file: "
541 << MBOrErr.getError().message() << "\n";
542 } else {
543 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
544 }
545 return BasicBlockSection::List;
546 }
547}
548
549// Common utility function tightly tied to the options listed here. Initializes
550// a TargetOptions object with CodeGen flags and returns it.
554 Options.AllowFPOpFusion = getFuseFPOps();
555 Options.UnsafeFPMath = getEnableUnsafeFPMath();
556 Options.NoInfsFPMath = getEnableNoInfsFPMath();
557 Options.NoNaNsFPMath = getEnableNoNaNsFPMath();
558 Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
559 Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
560
562
563 // FIXME: Should have separate input and output flags
564 Options.setFPDenormalMode(DenormalMode(DenormKind, DenormKind));
565
566 Options.HonorSignDependentRoundingFPMathOption =
569 Options.FloatABIType = getFloatABIForCalls();
570 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
571 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
572 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
573 Options.StackSymbolOrdering = getStackSymbolOrdering();
574 Options.UseInitArray = !getUseCtors();
575 Options.DisableIntegratedAS = getDisableIntegratedAS();
576 Options.DataSections =
577 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
578 Options.FunctionSections = getFunctionSections();
579 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
580 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
581 Options.BBAddrMap = getEnableBBAddrMap();
582 Options.BBSections = getBBSectionsMode(Options);
583 Options.UniqueSectionNames = getUniqueSectionNames();
584 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
585 Options.SeparateNamedSections = getSeparateNamedSections();
586 Options.TLSSize = getTLSSize();
587 Options.EmulatedTLS =
588 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
589 Options.EnableTLSDESC =
590 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
591 Options.ExceptionModel = getExceptionModel();
592 Options.EmitStackSizeSection = getEnableStackSizeSection();
593 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
594 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
595 Options.EmitAddrsig = getEnableAddrsig();
596 Options.EmitCallGraphSection = getEnableCallGraphSection();
597 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
598 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
599 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
600 Options.XRayFunctionIndex = getXRayFunctionIndex();
601 Options.DebugStrictDwarf = getDebugStrictDwarf();
602 Options.LoopAlignment = getAlignLoops();
603 Options.JMCInstrument = getJMCInstrument();
604 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
605
607
608 Options.ThreadModel = getThreadModel();
609 Options.EABIVersion = getEABIVersion();
610 Options.DebuggerTuning = getDebuggerTuningOpt();
611 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
612 return Options;
613}
614
615std::string codegen::getCPUStr() {
616 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
617 // this will set the CPU to an empty string which tells the target to
618 // pick a basic default.
619 if (getMCPU() == "native")
620 return std::string(sys::getHostCPUName());
621
622 return getMCPU();
623}
624
626 SubtargetFeatures Features;
627
628 // If user asked for the 'native' CPU, we need to autodetect features.
629 // This is necessary for x86 where the CPU might not support all the
630 // features the autodetected CPU name lists in the target. For example,
631 // not all Sandybridge processors support AVX.
632 if (getMCPU() == "native")
633 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
634 Features.AddFeature(Feature, IsEnabled);
635
636 for (auto const &MAttr : getMAttrs())
637 Features.AddFeature(MAttr);
638
639 return Features.getString();
640}
641
642std::vector<std::string> codegen::getFeatureList() {
643 SubtargetFeatures Features;
644
645 // If user asked for the 'native' CPU, we need to autodetect features.
646 // This is necessary for x86 where the CPU might not support all the
647 // features the autodetected CPU name lists in the target. For example,
648 // not all Sandybridge processors support AVX.
649 if (getMCPU() == "native")
650 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
651 Features.AddFeature(Feature, IsEnabled);
652
653 for (auto const &MAttr : getMAttrs())
654 Features.AddFeature(MAttr);
655
656 return Features.getFeatures();
657}
658
660 B.addAttribute(Name, Val ? "true" : "false");
661}
662
663#define HANDLE_BOOL_ATTR(CL, AttrName) \
664 do { \
665 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
666 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
667 } while (0)
668
669/// Set function attributes of function \p F based on CPU, Features, and command
670/// line flags.
672 Function &F) {
673 auto &Ctx = F.getContext();
674 AttributeList Attrs = F.getAttributes();
675 AttrBuilder NewAttrs(Ctx);
676
677 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
678 NewAttrs.addAttribute("target-cpu", CPU);
679 if (!Features.empty()) {
680 // Append the command line features to any that are already on the function.
681 StringRef OldFeatures =
682 F.getFnAttribute("target-features").getValueAsString();
683 if (OldFeatures.empty())
684 NewAttrs.addAttribute("target-features", Features);
685 else {
686 SmallString<256> Appended(OldFeatures);
687 Appended.push_back(',');
688 Appended.append(Features);
689 NewAttrs.addAttribute("target-features", Appended);
690 }
691 }
692 if (FramePointerUsageView->getNumOccurrences() > 0 &&
693 !F.hasFnAttribute("frame-pointer")) {
694 if (getFramePointerUsage() == FramePointerKind::All)
695 NewAttrs.addAttribute("frame-pointer", "all");
696 else if (getFramePointerUsage() == FramePointerKind::NonLeaf)
697 NewAttrs.addAttribute("frame-pointer", "non-leaf");
698 else if (getFramePointerUsage() == FramePointerKind::Reserved)
699 NewAttrs.addAttribute("frame-pointer", "reserved");
700 else if (getFramePointerUsage() == FramePointerKind::None)
701 NewAttrs.addAttribute("frame-pointer", "none");
702 }
703 if (DisableTailCallsView->getNumOccurrences() > 0)
704 NewAttrs.addAttribute("disable-tail-calls",
705 toStringRef(getDisableTailCalls()));
706 if (getStackRealign())
707 NewAttrs.addAttribute("stackrealign");
708
709 HANDLE_BOOL_ATTR(EnableUnsafeFPMathView, "unsafe-fp-math");
710 HANDLE_BOOL_ATTR(EnableNoInfsFPMathView, "no-infs-fp-math");
711 HANDLE_BOOL_ATTR(EnableNoNaNsFPMathView, "no-nans-fp-math");
712 HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
713
714 if (DenormalFPMathView->getNumOccurrences() > 0 &&
715 !F.hasFnAttribute("denormal-fp-math")) {
717
718 // FIXME: Command line flag should expose separate input/output modes.
719 NewAttrs.addAttribute("denormal-fp-math",
720 DenormalMode(DenormKind, DenormKind).str());
721 }
722
723 if (DenormalFP32MathView->getNumOccurrences() > 0 &&
724 !F.hasFnAttribute("denormal-fp-math-f32")) {
725 // FIXME: Command line flag should expose separate input/output modes.
727
728 NewAttrs.addAttribute(
729 "denormal-fp-math-f32",
730 DenormalMode(DenormKind, DenormKind).str());
731 }
732
733 if (TrapFuncNameView->getNumOccurrences() > 0)
734 for (auto &B : F)
735 for (auto &I : B)
736 if (auto *Call = dyn_cast<CallInst>(&I))
737 if (const auto *F = Call->getCalledFunction())
738 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
739 F->getIntrinsicID() == Intrinsic::trap)
740 Call->addFnAttr(
741 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
742
743 // Let NewAttrs override Attrs.
744 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
745}
746
747/// Set function attributes of functions in Module M based on CPU,
748/// Features, and command line flags.
750 Module &M) {
751 for (Function &F : M)
752 setFunctionAttributes(CPU, Features, F);
753}
754
757 CodeGenOptLevel OptLevel) {
758 Triple TheTriple(TargetTriple);
759 std::string Error;
760 const auto *TheTarget =
762 if (!TheTarget)
764 auto *Target = TheTarget->createTargetMachine(
768 OptLevel);
769 if (!Target)
771 Twine("could not allocate target machine for ") +
772 TargetTriple);
773 return std::unique_ptr<TargetMachine>(Target);
774}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define CGLIST(TY, NAME)
#define CGOPT_EXP(TY, NAME)
#define CGBINDOPT(NAME)
#define CGOPT(TY, NAME)
#define HANDLE_BOOL_ATTR(CL, AttrName)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:687
std::string Name
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains some functions that are useful when dealing with strings.
static cl::opt< bool > EnableMachineFunctionSplitter("enable-split-machine-functions", cl::Hidden, cl::desc("Split out cold blocks from machine functions based on profile " "information."))
Enable the machine function splitter pass.
LLVM_ABI AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:95
Represents either an error or a value T.
Definition: ErrorOr.h:56
std::error_code getError() const
Definition: ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
Tagged union holding either a T or a Error.
Definition: Error.h:485
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition: SmallString.h:68
void push_back(const T &Elt)
Definition: SmallVector.h:414
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
Manages the enabling and disabling of subtarget specific features.
const std::vector< std::string > & getFeatures() const
Returns the vector of individual subtarget features.
LLVM_ABI std::string getString() const
Returns features as a string.
LLVM_ABI void AddFeature(StringRef String, bool Enable=true)
Adds Features.
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
bool hasDefaultTLSDESC() const
True if the target uses TLSDESC by default.
Definition: Triple.h:1173
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition: Triple.h:1178
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition: Triple.h:1167
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
@ DynamicNoPIC
Definition: CodeGen.h:25
@ ROPI_RWPI
Definition: CodeGen.h:25
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:712
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
@ CommaSeparated
Definition: CommandLine.h:164
LLVM_ABI bool getEnableMachineFunctionSplitter()
LLVM_ABI bool getEnableHonorSignDependentRoundingFPMath()
LLVM_ABI std::string getTrapFuncName()
LLVM_ABI bool getEnableDebugEntryValues()
LLVM_ABI unsigned getTLSSize()
LLVM_ABI bool getEnableGuaranteedTailCallOpt()
LLVM_ABI llvm::FPOpFusion::FPOpFusionMode getFuseFPOps()
LLVM_ABI std::optional< CodeModel::Model > getExplicitCodeModel()
LLVM_ABI bool getFunctionSections()
LLVM_ABI bool getDisableTailCalls()
LLVM_ABI std::string getCPUStr()
LLVM_ABI bool getXCOFFReadOnlyPointers()
LLVM_ABI std::string getFeaturesStr()
LLVM_ABI bool getUniqueSectionNames()
LLVM_ABI DenormalMode::DenormalModeKind getDenormalFPMath()
LLVM_ABI llvm::FloatABI::ABIType getFloatABIForCalls()
LLVM_ABI void renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val)
LLVM_ABI bool getDebugStrictDwarf()
LLVM_ABI bool getForceDwarfFrameSection()
LLVM_ABI bool getStackRealign()
LLVM_ABI std::string getMCPU()
LLVM_ABI bool getJMCInstrument()
LLVM_ABI bool getEnableAddrsig()
LLVM_ABI bool getStackSymbolOrdering()
LLVM_ABI SwiftAsyncFramePointerMode getSwiftAsyncFramePointer()
LLVM_ABI bool getEnableBBAddrMap()
LLVM_ABI std::vector< std::string > getFeatureList()
LLVM_ABI bool getEnableStaticDataPartitioning()
LLVM_ABI std::string getMArch()
LLVM_ABI DenormalMode::DenormalModeKind getDenormalFP32Math()
LLVM_ABI bool getEnableNoSignedZerosFPMath()
LLVM_ABI bool getEnableStackSizeSection()
LLVM_ABI llvm::EABI getEABIVersion()
LLVM_ABI bool getEnableCallGraphSection()
LLVM_ABI bool getEnableNoTrappingFPMath()
LLVM_ABI Expected< std::unique_ptr< TargetMachine > > createTargetMachineForTriple(StringRef TargetTriple, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default)
Creates a TargetMachine instance with the options defined on the command line.
LLVM_ABI bool getUniqueBasicBlockSectionNames()
LLVM_ABI FramePointerKind getFramePointerUsage()
LLVM_ABI bool getDontPlaceZerosInBSS()
LLVM_ABI bool getSeparateNamedSections()
LLVM_ABI bool getEnableNoInfsFPMath()
LLVM_ABI bool getEnableUnsafeFPMath()
LLVM_ABI bool getEnableNoNaNsFPMath()
LLVM_ABI std::optional< bool > getExplicitDataSections()
LLVM_ABI ThreadModel::Model getThreadModel()
LLVM_ABI bool getXCOFFTracebackTable()
LLVM_ABI bool getIgnoreXCOFFVisibility()
LLVM_ABI bool getDisableIntegratedAS()
LLVM_ABI bool getUseCtors()
LLVM_ABI llvm::DebuggerKind getDebuggerTuningOpt()
LLVM_ABI std::vector< std::string > getMAttrs()
LLVM_ABI void setFunctionAttributes(StringRef CPU, StringRef Features, Function &F)
Set function attributes of function F based on CPU, Features, and command line flags.
LLVM_ABI llvm::BasicBlockSection getBBSectionsMode(llvm::TargetOptions &Options)
LLVM_ABI TargetOptions InitTargetOptionsFromCodeGenFlags(const llvm::Triple &TheTriple)
Common utility function tightly tied to the options listed here.
LLVM_ABI std::string getBBSections()
LLVM_ABI std::optional< bool > getExplicitEnableTLSDESC()
LLVM_ABI unsigned getAlignLoops()
LLVM_ABI std::optional< Reloc::Model > getExplicitRelocModel()
LLVM_ABI bool getEnableAIXExtendedAltivecABI()
LLVM_ABI bool getXRayFunctionIndex()
LLVM_ABI llvm::ExceptionHandling getExceptionModel()
LLVM_ABI bool getEmitCallSiteInfo()
LLVM_ABI std::optional< bool > getExplicitEmulatedTLS()
LLVM_ABI MCTargetOptions InitMCTargetOptionsFromFlags()
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition: Host.cpp:2400
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition: Host.cpp:1956
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FramePointerKind
Definition: CodeGen.h:118
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
ExceptionHandling
Definition: CodeGen.h:53
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1305
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:111
SwiftAsyncFramePointerMode
Indicates when and how the Swift async frame pointer bit should be set.
Definition: TargetOptions.h:97
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:82
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
BasicBlockSection
Definition: TargetOptions.h:55
EABI
Definition: CodeGen.h:73
DebuggerKind
Identify a debugger for "tuning" the debug info.
Definition: TargetOptions.h:80
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind
Represent handled modes for denormal (aka subnormal) modes in the floating point environment.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Create this object with static storage to register codegen-related command line options.
Definition: CommandFlags.h:161
Create this object with static storage to register mc-related command line options.