LLVM 23.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
17#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/StringRef.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/Module.h"
28#include "llvm/Support/Path.h"
35#include <cassert>
36#include <memory>
37#include <optional>
38#include <system_error>
39
40using namespace llvm;
41
42#define CGOPT(TY, NAME) \
43 static cl::opt<TY> *NAME##View; \
44 TY codegen::get##NAME() { \
45 assert(NAME##View && "Flag not registered."); \
46 return *NAME##View; \
47 }
48
49#define CGLIST(TY, NAME) \
50 static cl::list<TY> *NAME##View; \
51 std::vector<TY> codegen::get##NAME() { \
52 assert(NAME##View && "Flag not registered."); \
53 return *NAME##View; \
54 }
55
56// Temporary macro for incremental transition to std::optional.
57#define CGOPT_EXP(TY, NAME) \
58 CGOPT(TY, NAME) \
59 std::optional<TY> codegen::getExplicit##NAME() { \
60 if (NAME##View->getNumOccurrences()) { \
61 TY res = *NAME##View; \
62 return res; \
63 } \
64 return std::nullopt; \
65 }
66
67CGOPT(std::string, MArch)
68CGOPT(std::string, MCPU)
69CGLIST(std::string, MAttrs)
70CGOPT_EXP(Reloc::Model, RelocModel)
73CGOPT_EXP(uint64_t, LargeDataThreshold)
74CGOPT(ExceptionHandling, ExceptionModel)
76CGOPT(FramePointerKind, FramePointerUsage)
77CGOPT(bool, EnableNoSignedZerosFPMath)
78CGOPT(bool, EnableNoTrappingFPMath)
79CGOPT(bool, EnableAIXExtendedAltivecABI)
82CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
83CGOPT(FloatABI::ABIType, FloatABIForCalls)
85CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
86CGOPT(bool, DontPlaceZerosInBSS)
87CGOPT(bool, EnableGuaranteedTailCallOpt)
88CGOPT(bool, DisableTailCalls)
89CGOPT(bool, StackSymbolOrdering)
90CGOPT(bool, StackRealign)
91CGOPT(std::string, TrapFuncName)
92CGOPT(bool, UseCtors)
93CGOPT(bool, DisableIntegratedAS)
94CGOPT_EXP(bool, DataSections)
95CGOPT_EXP(bool, FunctionSections)
96CGOPT(bool, IgnoreXCOFFVisibility)
97CGOPT(bool, XCOFFTracebackTable)
98CGOPT(bool, EnableBBAddrMap)
99CGOPT(std::string, BBSections)
100CGOPT(unsigned, TLSSize)
101CGOPT_EXP(bool, EmulatedTLS)
102CGOPT_EXP(bool, EnableTLSDESC)
103CGOPT(bool, UniqueSectionNames)
104CGOPT(bool, UniqueBasicBlockSectionNames)
105CGOPT(bool, SeparateNamedSections)
106CGOPT(EABI, EABIVersion)
107CGOPT(DebuggerKind, DebuggerTuningOpt)
109CGOPT(bool, EnableStackSizeSection)
110CGOPT(bool, EnableAddrsig)
111CGOPT(bool, EnableCallGraphSection)
112CGOPT(bool, EmitCallSiteInfo)
114CGOPT(bool, EnableStaticDataPartitioning)
115CGOPT(bool, EnableDebugEntryValues)
116CGOPT(bool, ForceDwarfFrameSection)
117CGOPT(bool, XRayFunctionIndex)
118CGOPT(bool, DebugStrictDwarf)
119CGOPT(unsigned, AlignLoops)
120CGOPT(bool, JMCInstrument)
121CGOPT(bool, XCOFFReadOnlyPointers)
123
124#define CGBINDOPT(NAME) \
125 do { \
126 NAME##View = std::addressof(NAME); \
127 } while (0)
128
130 static cl::opt<std::string> MArch(
131 "march", cl::desc("Architecture to generate code for (see --version)"));
132 CGBINDOPT(MArch);
133
134 static cl::opt<std::string> MCPU(
135 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
136 cl::value_desc("cpu-name"), cl::init(""));
137 CGBINDOPT(MCPU);
138
139 static cl::list<std::string> MAttrs(
140 "mattr", cl::CommaSeparated,
141 cl::desc("Target specific attributes (-mattr=help for details)"),
142 cl::value_desc("a1,+a2,-a3,..."));
143 CGBINDOPT(MAttrs);
144
145 static cl::opt<Reloc::Model> RelocModel(
146 "relocation-model", cl::desc("Choose relocation model"),
148 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
149 clEnumValN(Reloc::PIC_, "pic",
150 "Fully relocatable, position independent code"),
151 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
152 "Relocatable external references, non-relocatable code"),
154 Reloc::ROPI, "ropi",
155 "Code and read-only data relocatable, accessed PC-relative"),
157 Reloc::RWPI, "rwpi",
158 "Read-write data relocatable, accessed relative to static base"),
159 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
160 "Combination of ropi and rwpi")));
161 CGBINDOPT(RelocModel);
162
164 "thread-model", cl::desc("Choose threading model"),
167 clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
168 clEnumValN(ThreadModel::Single, "single", "Single thread model")));
170
172 "code-model", cl::desc("Choose code model"),
173 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
174 clEnumValN(CodeModel::Small, "small", "Small code model"),
175 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
176 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
177 clEnumValN(CodeModel::Large, "large", "Large code model")));
179
180 static cl::opt<uint64_t> LargeDataThreshold(
181 "large-data-threshold",
182 cl::desc("Choose large data threshold for x86_64 medium code model"),
183 cl::init(0));
184 CGBINDOPT(LargeDataThreshold);
185
186 static cl::opt<ExceptionHandling> ExceptionModel(
187 "exception-model", cl::desc("exception model"),
191 "default exception handling model"),
193 "DWARF-like CFI based exception handling"),
195 "SjLj exception handling"),
196 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
198 "Windows exception model"),
200 "WebAssembly exception handling")));
201 CGBINDOPT(ExceptionModel);
202
203 static cl::opt<CodeGenFileType> FileType(
205 cl::desc(
206 "Choose a file type (not all types are supported by all targets):"),
208 "Emit an assembly ('.s') file"),
210 "Emit a native object ('.o') file"),
212 "Emit nothing, for performance testing")));
213 CGBINDOPT(FileType);
214
215 static cl::opt<FramePointerKind> FramePointerUsage(
216 "frame-pointer",
217 cl::desc("Specify frame pointer elimination optimization"),
221 "Disable frame pointer elimination"),
223 "Disable frame pointer elimination for non-leaf frame but "
224 "reserve the register in leaf functions"),
225 clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
226 "Disable frame pointer elimination for non-leaf frame"),
228 "Enable frame pointer elimination, but reserve the frame "
229 "pointer register"),
231 "Enable frame pointer elimination")));
232 CGBINDOPT(FramePointerUsage);
233
234 static cl::opt<bool> EnableNoSignedZerosFPMath(
235 "enable-no-signed-zeros-fp-math",
236 cl::desc("Enable FP math optimizations that assume "
237 "the sign of 0 is insignificant"),
238 cl::init(false));
239 CGBINDOPT(EnableNoSignedZerosFPMath);
240
241 static cl::opt<bool> EnableNoTrappingFPMath(
242 "enable-no-trapping-fp-math",
243 cl::desc("Enable setting the FP exceptions build "
244 "attribute not to use exceptions"),
245 cl::init(false));
246 CGBINDOPT(EnableNoTrappingFPMath);
247
248 static const auto DenormFlagEnumOptions = cl::values(
249 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
250 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
251 "the sign of a flushed-to-zero number is preserved "
252 "in the sign of 0"),
253 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
254 "denormals are flushed to positive zero"),
256 "denormals have unknown treatment"));
257
258 // FIXME: Doesn't have way to specify separate input and output modes.
259 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
260 "denormal-fp-math",
261 cl::desc("Select which denormal numbers the code is permitted to require"),
263 DenormFlagEnumOptions);
264 CGBINDOPT(DenormalFPMath);
265
266 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
267 "denormal-fp-math-f32",
268 cl::desc("Select which denormal numbers the code is permitted to require for float"),
270 DenormFlagEnumOptions);
271 CGBINDOPT(DenormalFP32Math);
272
273 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
274 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
275 cl::desc("Force codegen to assume rounding mode can change dynamically"),
276 cl::init(false));
277 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
278
279 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
280 "float-abi", cl::desc("Choose float ABI type"),
283 "Target default float ABI type"),
285 "Soft float ABI (implied by -soft-float)"),
287 "Hard float ABI (uses FP registers)")));
288 CGBINDOPT(FloatABIForCalls);
289
291 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
295 "Fuse FP ops whenever profitable"),
296 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
298 "Only fuse FP ops when the result won't be affected.")));
299 CGBINDOPT(FuseFPOps);
300
301 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
302 "swift-async-fp",
303 cl::desc("Determine when the Swift async frame pointer should be set"),
306 "Determine based on deployment target"),
308 "Always set the bit"),
310 "Never set the bit")));
311 CGBINDOPT(SwiftAsyncFramePointer);
312
313 static cl::opt<bool> DontPlaceZerosInBSS(
314 "nozero-initialized-in-bss",
315 cl::desc("Don't place zero-initialized symbols into bss section"),
316 cl::init(false));
317 CGBINDOPT(DontPlaceZerosInBSS);
318
319 static cl::opt<bool> EnableAIXExtendedAltivecABI(
320 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
321 cl::init(false));
322 CGBINDOPT(EnableAIXExtendedAltivecABI);
323
324 static cl::opt<bool> EnableGuaranteedTailCallOpt(
325 "tailcallopt",
326 cl::desc(
327 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
328 cl::init(false));
329 CGBINDOPT(EnableGuaranteedTailCallOpt);
330
331 static cl::opt<bool> DisableTailCalls(
332 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
333 CGBINDOPT(DisableTailCalls);
334
335 static cl::opt<bool> StackSymbolOrdering(
336 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
337 cl::init(true));
338 CGBINDOPT(StackSymbolOrdering);
339
340 static cl::opt<bool> StackRealign(
341 "stackrealign",
342 cl::desc("Force align the stack to the minimum alignment"),
343 cl::init(false));
344 CGBINDOPT(StackRealign);
345
346 static cl::opt<std::string> TrapFuncName(
347 "trap-func", cl::Hidden,
348 cl::desc("Emit a call to trap function rather than a trap instruction"),
349 cl::init(""));
350 CGBINDOPT(TrapFuncName);
351
352 static cl::opt<bool> UseCtors("use-ctors",
353 cl::desc("Use .ctors instead of .init_array."),
354 cl::init(false));
355 CGBINDOPT(UseCtors);
356
357 static cl::opt<bool> DataSections(
358 "data-sections", cl::desc("Emit data into separate sections"),
359 cl::init(false));
360 CGBINDOPT(DataSections);
361
362 static cl::opt<bool> FunctionSections(
363 "function-sections", cl::desc("Emit functions into separate sections"),
364 cl::init(false));
365 CGBINDOPT(FunctionSections);
366
367 static cl::opt<bool> IgnoreXCOFFVisibility(
368 "ignore-xcoff-visibility",
369 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
370 "all symbols 'unspecified' visibility in XCOFF object file"),
371 cl::init(false));
372 CGBINDOPT(IgnoreXCOFFVisibility);
373
374 static cl::opt<bool> XCOFFTracebackTable(
375 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
376 cl::init(true));
377 CGBINDOPT(XCOFFTracebackTable);
378
379 static cl::opt<bool> EnableBBAddrMap(
380 "basic-block-address-map",
381 cl::desc("Emit the basic block address map section"), cl::init(false));
382 CGBINDOPT(EnableBBAddrMap);
383
384 static cl::opt<std::string> BBSections(
385 "basic-block-sections",
386 cl::desc("Emit basic blocks into separate sections"),
387 cl::value_desc("all | <function list (file)> | labels | none"),
388 cl::init("none"));
389 CGBINDOPT(BBSections);
390
391 static cl::opt<unsigned> TLSSize(
392 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
393 CGBINDOPT(TLSSize);
394
395 static cl::opt<bool> EmulatedTLS(
396 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
397 CGBINDOPT(EmulatedTLS);
398
399 static cl::opt<bool> EnableTLSDESC(
400 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
401 cl::init(false));
402 CGBINDOPT(EnableTLSDESC);
403
404 static cl::opt<bool> UniqueSectionNames(
405 "unique-section-names", cl::desc("Give unique names to every section"),
406 cl::init(true));
407 CGBINDOPT(UniqueSectionNames);
408
409 static cl::opt<bool> UniqueBasicBlockSectionNames(
410 "unique-basic-block-section-names",
411 cl::desc("Give unique names to every basic block section"),
412 cl::init(false));
413 CGBINDOPT(UniqueBasicBlockSectionNames);
414
415 static cl::opt<bool> SeparateNamedSections(
416 "separate-named-sections",
417 cl::desc("Use separate unique sections for named sections"),
418 cl::init(false));
419 CGBINDOPT(SeparateNamedSections);
420
421 static cl::opt<EABI> EABIVersion(
422 "meabi", cl::desc("Set EABI type (default depends on triple):"),
425 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
426 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
427 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
428 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
429 CGBINDOPT(EABIVersion);
430
431 static cl::opt<DebuggerKind> DebuggerTuningOpt(
432 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
435 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
436 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
437 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
438 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
439 CGBINDOPT(DebuggerTuningOpt);
440
442 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
446 "No vector functions library"),
448 "Accelerate framework"),
449 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
450 "Darwin libsystem_m"),
452 "GLIBC Vector Math library"),
453 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
454 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
456 "SIMD Library for Evaluating Elementary Functions"),
458 "Arm Performance Libraries"),
460 "AMD vector math library")));
462
463 static cl::opt<bool> EnableStackSizeSection(
464 "stack-size-section",
465 cl::desc("Emit a section containing stack size metadata"),
466 cl::init(false));
467 CGBINDOPT(EnableStackSizeSection);
468
469 static cl::opt<bool> EnableAddrsig(
470 "addrsig", cl::desc("Emit an address-significance table"),
471 cl::init(false));
472 CGBINDOPT(EnableAddrsig);
473
474 static cl::opt<bool> EnableCallGraphSection(
475 "call-graph-section", cl::desc("Emit a call graph section"),
476 cl::init(false));
477 CGBINDOPT(EnableCallGraphSection);
478
479 static cl::opt<bool> EmitCallSiteInfo(
480 "emit-call-site-info",
481 cl::desc(
482 "Emit call site debug information, if debug information is enabled."),
483 cl::init(false));
484 CGBINDOPT(EmitCallSiteInfo);
485
486 static cl::opt<bool> EnableDebugEntryValues(
487 "debug-entry-values",
488 cl::desc("Enable debug info for the debug entry values."),
489 cl::init(false));
490 CGBINDOPT(EnableDebugEntryValues);
491
493 "split-machine-functions",
494 cl::desc("Split out cold basic blocks from machine functions based on "
495 "profile information"),
496 cl::init(false));
498
499 static cl::opt<bool> EnableStaticDataPartitioning(
500 "partition-static-data-sections",
501 cl::desc("Partition data sections using profile information."),
502 cl::init(false));
503 CGBINDOPT(EnableStaticDataPartitioning);
504
505 static cl::opt<bool> ForceDwarfFrameSection(
506 "force-dwarf-frame-section",
507 cl::desc("Always emit a debug frame section."), cl::init(false));
508 CGBINDOPT(ForceDwarfFrameSection);
509
510 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
511 cl::desc("Emit xray_fn_idx section"),
512 cl::init(true));
513 CGBINDOPT(XRayFunctionIndex);
514
515 static cl::opt<bool> DebugStrictDwarf(
516 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
517 CGBINDOPT(DebugStrictDwarf);
518
519 static cl::opt<unsigned> AlignLoops("align-loops",
520 cl::desc("Default alignment for loops"));
521 CGBINDOPT(AlignLoops);
522
523 static cl::opt<bool> JMCInstrument(
524 "enable-jmc-instrument",
525 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
526 cl::init(false));
527 CGBINDOPT(JMCInstrument);
528
529 static cl::opt<bool> XCOFFReadOnlyPointers(
530 "mxcoff-roptr",
531 cl::desc("When set to true, const objects with relocatable address "
532 "values are put into the RO data section."),
533 cl::init(false));
534 CGBINDOPT(XCOFFReadOnlyPointers);
535
536 static cl::opt<bool> DisableIntegratedAS(
537 "no-integrated-as", cl::desc("Disable integrated assembler"),
538 cl::init(false));
539 CGBINDOPT(DisableIntegratedAS);
540
542}
543
545 static cl::opt<SaveStatsMode> SaveStats(
546 "save-stats",
547 cl::desc(
548 "Save LLVM statistics to a file in the current directory"
549 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
550 "file (`-save-stats=obj`). (default: cwd)"),
552 "Save to the current working directory"),
555 "Save to the output file directory")),
557 CGBINDOPT(SaveStats);
558}
559
562 if (getBBSections() == "all")
564 else if (getBBSections() == "none")
566 else {
569 if (!MBOrErr) {
570 errs() << "Error loading basic block sections function list file: "
571 << MBOrErr.getError().message() << "\n";
572 } else {
573 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
574 }
576 }
577}
578
579// Common utility function tightly tied to the options listed here. Initializes
580// a TargetOptions object with CodeGen flags and returns it.
584 Options.AllowFPOpFusion = getFuseFPOps();
585 Options.NoSignedZerosFPMath = getEnableNoSignedZerosFPMath();
586 Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
587
588 Options.HonorSignDependentRoundingFPMathOption =
591 Options.FloatABIType = getFloatABIForCalls();
592 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
593 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
594 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
595 Options.StackSymbolOrdering = getStackSymbolOrdering();
596 Options.UseInitArray = !getUseCtors();
597 Options.DisableIntegratedAS = getDisableIntegratedAS();
598 Options.DataSections =
599 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
600 Options.FunctionSections = getFunctionSections();
601 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
602 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
603 Options.BBAddrMap = getEnableBBAddrMap();
604 Options.BBSections = getBBSectionsMode(Options);
605 Options.UniqueSectionNames = getUniqueSectionNames();
606 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
607 Options.SeparateNamedSections = getSeparateNamedSections();
608 Options.TLSSize = getTLSSize();
609 Options.EmulatedTLS =
610 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
611 Options.EnableTLSDESC =
612 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
613 Options.ExceptionModel = getExceptionModel();
614 Options.VecLib = getVectorLibrary();
615 Options.EmitStackSizeSection = getEnableStackSizeSection();
616 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
617 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
618 Options.EmitAddrsig = getEnableAddrsig();
619 Options.EmitCallGraphSection = getEnableCallGraphSection();
620 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
621 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
622 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
623 Options.XRayFunctionIndex = getXRayFunctionIndex();
624 Options.DebugStrictDwarf = getDebugStrictDwarf();
625 Options.LoopAlignment = getAlignLoops();
626 Options.JMCInstrument = getJMCInstrument();
627 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
628
630
631 Options.ThreadModel = getThreadModel();
632 Options.EABIVersion = getEABIVersion();
633 Options.DebuggerTuning = getDebuggerTuningOpt();
634 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
635 return Options;
636}
637
638std::string codegen::getCPUStr() {
639 std::string MCPU = getMCPU();
640
641 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
642 // this will set the CPU to an empty string which tells the target to
643 // pick a basic default.
644 if (MCPU == "native")
645 return std::string(sys::getHostCPUName());
646
647 return MCPU;
648}
649
651 SubtargetFeatures Features;
652
653 // If user asked for the 'native' CPU, we need to autodetect features.
654 // This is necessary for x86 where the CPU might not support all the
655 // features the autodetected CPU name lists in the target. For example,
656 // not all Sandybridge processors support AVX.
657 if (getMCPU() == "native")
658 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
659 Features.AddFeature(Feature, IsEnabled);
660
661 for (auto const &MAttr : getMAttrs())
662 Features.AddFeature(MAttr);
663
664 return Features.getString();
665}
666
667std::vector<std::string> codegen::getFeatureList() {
668 SubtargetFeatures Features;
669
670 // If user asked for the 'native' CPU, we need to autodetect features.
671 // This is necessary for x86 where the CPU might not support all the
672 // features the autodetected CPU name lists in the target. For example,
673 // not all Sandybridge processors support AVX.
674 if (getMCPU() == "native")
675 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
676 Features.AddFeature(Feature, IsEnabled);
677
678 for (auto const &MAttr : getMAttrs())
679 Features.AddFeature(MAttr);
680
681 return Features.getFeatures();
682}
683
684void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
685 B.addAttribute(Name, Val ? "true" : "false");
686}
687
688#define HANDLE_BOOL_ATTR(CL, AttrName) \
689 do { \
690 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
691 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
692 } while (0)
693
694/// Set function attributes of function \p F based on CPU, Features, and command
695/// line flags.
697 Function &F) {
698 auto &Ctx = F.getContext();
699 AttributeList Attrs = F.getAttributes();
700 AttrBuilder NewAttrs(Ctx);
701
702 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
703 NewAttrs.addAttribute("target-cpu", CPU);
704 if (!Features.empty()) {
705 // Append the command line features to any that are already on the function.
706 StringRef OldFeatures =
707 F.getFnAttribute("target-features").getValueAsString();
708 if (OldFeatures.empty())
709 NewAttrs.addAttribute("target-features", Features);
710 else {
711 SmallString<256> Appended(OldFeatures);
712 Appended.push_back(',');
713 Appended.append(Features);
714 NewAttrs.addAttribute("target-features", Appended);
715 }
716 }
717 if (FramePointerUsageView->getNumOccurrences() > 0 &&
718 !F.hasFnAttribute("frame-pointer")) {
720 NewAttrs.addAttribute("frame-pointer", "all");
722 NewAttrs.addAttribute("frame-pointer", "non-leaf");
724 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
726 NewAttrs.addAttribute("frame-pointer", "reserved");
728 NewAttrs.addAttribute("frame-pointer", "none");
729 }
730 if (DisableTailCallsView->getNumOccurrences() > 0)
731 NewAttrs.addAttribute("disable-tail-calls",
733 if (getStackRealign())
734 NewAttrs.addAttribute("stackrealign");
735
736 HANDLE_BOOL_ATTR(EnableNoSignedZerosFPMathView, "no-signed-zeros-fp-math");
737
738 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
739 DenormalFP32MathView->getNumOccurrences() > 0) &&
740 !F.hasFnAttribute(Attribute::DenormalFPEnv)) {
743
744 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
745 DenormalMode{DenormKindF32, DenormKindF32});
746 // FIXME: Command line flag should expose separate input/output modes.
747 NewAttrs.addDenormalFPEnvAttr(FPEnv);
748 }
749
750 if (TrapFuncNameView->getNumOccurrences() > 0)
751 for (auto &B : F)
752 for (auto &I : B)
753 if (auto *Call = dyn_cast<CallInst>(&I))
754 if (const auto *F = Call->getCalledFunction())
755 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
756 F->getIntrinsicID() == Intrinsic::trap)
757 Call->addFnAttr(
758 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
759
760 // Let NewAttrs override Attrs.
761 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
762}
763
764/// Set function attributes of functions in Module M based on CPU,
765/// Features, and command line flags.
767 Module &M) {
768 for (Function &F : M)
769 setFunctionAttributes(CPU, Features, F);
770}
771
774 CodeGenOptLevel OptLevel) {
775 Triple TheTriple(TargetTriple);
776 std::string Error;
777 const auto *TheTarget =
779 if (!TheTarget)
781 auto *Target = TheTarget->createTargetMachine(
785 OptLevel);
786 if (!Target)
788 Twine("could not allocate target machine for ") +
789 TargetTriple);
790 return std::unique_ptr<TargetMachine>(Target);
791}
792
795 return;
796
798}
799
801 auto SaveStatsValue = getSaveStats();
802 if (SaveStatsValue == codegen::SaveStatsMode::None)
803 return 0;
804
805 SmallString<128> StatsFilename;
806 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
807 StatsFilename = OutputFilename;
809 } else {
810 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
811 "Should have been a valid --save-stats value");
812 }
813
815 llvm::sys::path::append(StatsFilename, BaseName);
816 llvm::sys::path::replace_extension(StatsFilename, "stats");
817
818 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
819 std::error_code EC;
820 auto StatsOS =
821 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
822 if (EC) {
823 WithColor::error(errs(), ToolName)
824 << "Unable to open statistics file: " << EC.message() << "\n";
825 return 1;
826 }
827
829 return 0;
830}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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)
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:54
#define I(x, y, z)
Definition MD5.cpp:57
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
This file defines the SmallString class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
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.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
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)
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:140
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:1233
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1238
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1227
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition WithColor.cpp:83
CallInst * Call
@ DynamicNoPIC
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 ...
initializer< Ty > init(const Ty &Val)
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 llvm::VectorLibrary getVectorLibrary()
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 void MaybeEnableStatistics()
Conditionally enables the collection of LLVM statistics during the tool run, based on the value of th...
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 SaveStatsMode getSaveStats()
LLVM_ABI bool getUniqueBasicBlockSectionNames()
LLVM_ABI FramePointerKind getFramePointerUsage()
LLVM_ABI bool getDontPlaceZerosInBSS()
LLVM_ABI bool getSeparateNamedSections()
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 int MaybeSaveStatistics(StringRef OutputFilename, StringRef ToolName)
Conditionally saves the collected LLVM statistics to the received output file, based on the value of ...
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()
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:764
LLVM_ABI void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition Path.cpp:475
LLVM_ABI void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition Path.cpp:481
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:578
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:457
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition Host.cpp:2542
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:1985
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FramePointerKind
Definition CodeGen.h:118
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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:94
ExceptionHandling
Definition CodeGen.h:53
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:56
@ None
No exception support.
Definition CodeGen.h:54
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:55
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:58
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:59
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
LLVM_ABI void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
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.
@ DeploymentBased
Determine whether to set the bit statically or dynamically based on the deployment target.
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
VectorLibrary
List of known vector-functions libraries.
EABI
Definition CodeGen.h:73
DebuggerKind
Identify a debugger for "tuning" the debug info.
@ SCE
Tune debug info for SCE targets (e.g. PS4).
@ DBX
Tune debug info for dbx.
@ Default
No specific tuning requested.
@ GDB
Tune debug info for gdb.
@ LLDB
Tune debug info for lldb.
LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Represents the full denormal controls for a function, including the default mode and the f32 specific...
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 mc-related command line options.