LLVM 24.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"
29#include "llvm/Support/Path.h"
36#include <cassert>
37#include <memory>
38#include <optional>
39#include <system_error>
40
41using namespace llvm;
42
43#define CGOPT(TY, NAME) \
44 static cl::opt<TY> *NAME##View; \
45 TY codegen::get##NAME() { \
46 assert(NAME##View && "Flag not registered."); \
47 return *NAME##View; \
48 }
49
50#define CGLIST(TY, NAME) \
51 static cl::list<TY> *NAME##View; \
52 std::vector<TY> codegen::get##NAME() { \
53 assert(NAME##View && "Flag not registered."); \
54 return *NAME##View; \
55 }
56
57// Temporary macro for incremental transition to std::optional.
58#define CGOPT_EXP(TY, NAME) \
59 CGOPT(TY, NAME) \
60 std::optional<TY> codegen::getExplicit##NAME() { \
61 if (NAME##View->getNumOccurrences()) { \
62 TY res = *NAME##View; \
63 return res; \
64 } \
65 return std::nullopt; \
66 }
67
68CGOPT(std::string, MArch)
69CGOPT(std::string, MCPU)
70CGOPT(std::string, MTune)
71CGLIST(std::string, MAttrs)
72CGOPT_EXP(Reloc::Model, RelocModel)
75CGOPT_EXP(uint64_t, LargeDataThreshold)
76CGOPT(ExceptionHandling, ExceptionModel)
78CGOPT(FramePointerKind, FramePointerUsage)
79CGOPT(bool, EnableNoTrappingFPMath)
80CGOPT(bool, EnableAIXExtendedAltivecABI)
83CGOPT(bool, EnableHonorSignDependentRoundingFPMath)
84CGOPT(FloatABI::ABIType, FloatABIForCalls)
86CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
87CGOPT(bool, DontPlaceZerosInBSS)
88CGOPT(bool, EnableGuaranteedTailCallOpt)
89CGOPT(bool, DisableTailCalls)
90CGOPT(bool, StackSymbolOrdering)
91CGOPT(bool, StackRealign)
92CGOPT(std::string, TrapFuncName)
93CGOPT(bool, UseCtors)
94CGOPT(bool, DisableIntegratedAS)
95CGOPT_EXP(bool, DataSections)
96CGOPT_EXP(bool, FunctionSections)
97CGOPT(bool, IgnoreXCOFFVisibility)
98CGOPT(bool, XCOFFTracebackTable)
99CGOPT(bool, EnableBBAddrMap)
100CGOPT(std::string, BBSections)
101CGOPT(unsigned, TLSSize)
102CGOPT_EXP(bool, EmulatedTLS)
103CGOPT_EXP(bool, EnableTLSDESC)
104CGOPT(bool, UniqueSectionNames)
105CGOPT(bool, UniqueBasicBlockSectionNames)
106CGOPT(bool, SeparateNamedSections)
107CGOPT(EABI, EABIVersion)
108CGOPT(DebuggerKind, DebuggerTuningOpt)
110CGOPT(bool, EnableStackSizeSection)
111CGOPT(bool, EnableAddrsig)
112CGOPT(bool, EnableCallGraphSection)
113CGOPT(bool, EmitCallSiteInfo)
115CGOPT(bool, EnableStaticDataPartitioning)
116CGOPT(bool, EnableDebugEntryValues)
117CGOPT(bool, ForceDwarfFrameSection)
118CGOPT(bool, XRayFunctionIndex)
119CGOPT(bool, DebugStrictDwarf)
120CGOPT(unsigned, AlignLoops)
121CGOPT(bool, JMCInstrument)
122CGOPT(bool, XCOFFReadOnlyPointers)
124
125#define CGBINDOPT(NAME) \
126 do { \
127 NAME##View = std::addressof(NAME); \
128 } while (0)
129
131 static cl::opt<std::string> MArch(
132 "march", cl::desc("Architecture to generate code for (see --version)"));
133 CGBINDOPT(MArch);
134
135 static cl::opt<std::string> MCPU(
136 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
137 cl::value_desc("cpu-name"), cl::init(""));
138 CGBINDOPT(MCPU);
139
140 static cl::list<std::string> MAttrs(
141 "mattr", cl::CommaSeparated,
142 cl::desc("Target specific attributes (-mattr=help for details)"),
143 cl::value_desc("a1,+a2,-a3,..."));
144 CGBINDOPT(MAttrs);
145
146 static cl::opt<Reloc::Model> RelocModel(
147 "relocation-model", cl::desc("Choose relocation model"),
149 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
150 clEnumValN(Reloc::PIC_, "pic",
151 "Fully relocatable, position independent code"),
152 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
153 "Relocatable external references, non-relocatable code"),
155 Reloc::ROPI, "ropi",
156 "Code and read-only data relocatable, accessed PC-relative"),
158 Reloc::RWPI, "rwpi",
159 "Read-write data relocatable, accessed relative to static base"),
160 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
161 "Combination of ropi and rwpi")));
162 CGBINDOPT(RelocModel);
163
165 "thread-model", cl::desc("Choose threading model"),
168 clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
169 clEnumValN(ThreadModel::Single, "single", "Single thread model")));
171
173 "code-model", cl::desc("Choose code model"),
174 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
175 clEnumValN(CodeModel::Small, "small", "Small code model"),
176 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
177 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
178 clEnumValN(CodeModel::Large, "large", "Large code model")));
180
181 static cl::opt<uint64_t> LargeDataThreshold(
182 "large-data-threshold",
183 cl::desc("Choose large data threshold for x86_64 medium code model"),
184 cl::init(0));
185 CGBINDOPT(LargeDataThreshold);
186
187 static cl::opt<ExceptionHandling> ExceptionModel(
188 "exception-model", cl::desc("exception model"),
192 "default exception handling model"),
194 "DWARF-like CFI based exception handling"),
196 "SjLj exception handling"),
197 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
199 "Windows exception model"),
201 "WebAssembly exception handling")));
202 CGBINDOPT(ExceptionModel);
203
204 static cl::opt<CodeGenFileType> FileType(
206 cl::desc(
207 "Choose a file type (not all types are supported by all targets):"),
209 "Emit an assembly ('.s') file"),
211 "Emit a native object ('.o') file"),
213 "Emit nothing, for performance testing")));
214 CGBINDOPT(FileType);
215
216 static cl::opt<FramePointerKind> FramePointerUsage(
217 "frame-pointer",
218 cl::desc("Specify frame pointer elimination optimization"),
222 "Disable frame pointer elimination"),
224 "Disable frame pointer elimination for non-leaf frame but "
225 "reserve the register in leaf functions"),
226 clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
227 "Disable frame pointer elimination for non-leaf frame"),
229 "Enable frame pointer elimination, but reserve the frame "
230 "pointer register"),
232 "Enable frame pointer elimination")));
233 CGBINDOPT(FramePointerUsage);
234
235 static cl::opt<bool> EnableNoTrappingFPMath(
236 "enable-no-trapping-fp-math",
237 cl::desc("Enable setting the FP exceptions build "
238 "attribute not to use exceptions"),
239 cl::init(false));
240 CGBINDOPT(EnableNoTrappingFPMath);
241
242 static const auto DenormFlagEnumOptions = cl::values(
243 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
244 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
245 "the sign of a flushed-to-zero number is preserved "
246 "in the sign of 0"),
247 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
248 "denormals are flushed to positive zero"),
250 "denormals have unknown treatment"));
251
252 // FIXME: Doesn't have way to specify separate input and output modes.
253 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
254 "denormal-fp-math",
255 cl::desc("Select which denormal numbers the code is permitted to require"),
257 DenormFlagEnumOptions);
258 CGBINDOPT(DenormalFPMath);
259
260 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
261 "denormal-fp-math-f32",
262 cl::desc("Select which denormal numbers the code is permitted to require for float"),
264 DenormFlagEnumOptions);
265 CGBINDOPT(DenormalFP32Math);
266
267 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
268 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
269 cl::desc("Force codegen to assume rounding mode can change dynamically"),
270 cl::init(false));
271 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
272
273 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
274 "float-abi", cl::desc("Choose float ABI type"),
277 "Target default float ABI type"),
279 "Soft float ABI (implied by -soft-float)"),
281 "Hard float ABI (uses FP registers)")));
282 CGBINDOPT(FloatABIForCalls);
283
285 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
289 "Fuse FP ops whenever profitable"),
290 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
292 "Only fuse FP ops when the result won't be affected.")));
293 CGBINDOPT(FuseFPOps);
294
295 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
296 "swift-async-fp",
297 cl::desc("Determine when the Swift async frame pointer should be set"),
300 "Determine based on deployment target"),
302 "Always set the bit"),
304 "Never set the bit")));
305 CGBINDOPT(SwiftAsyncFramePointer);
306
307 static cl::opt<bool> DontPlaceZerosInBSS(
308 "nozero-initialized-in-bss",
309 cl::desc("Don't place zero-initialized symbols into bss section"),
310 cl::init(false));
311 CGBINDOPT(DontPlaceZerosInBSS);
312
313 static cl::opt<bool> EnableAIXExtendedAltivecABI(
314 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
315 cl::init(false));
316 CGBINDOPT(EnableAIXExtendedAltivecABI);
317
318 static cl::opt<bool> EnableGuaranteedTailCallOpt(
319 "tailcallopt",
320 cl::desc(
321 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
322 cl::init(false));
323 CGBINDOPT(EnableGuaranteedTailCallOpt);
324
325 static cl::opt<bool> DisableTailCalls(
326 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
327 CGBINDOPT(DisableTailCalls);
328
329 static cl::opt<bool> StackSymbolOrdering(
330 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
331 cl::init(true));
332 CGBINDOPT(StackSymbolOrdering);
333
334 static cl::opt<bool> StackRealign(
335 "stackrealign",
336 cl::desc("Force align the stack to the minimum alignment"),
337 cl::init(false));
338 CGBINDOPT(StackRealign);
339
340 static cl::opt<std::string> TrapFuncName(
341 "trap-func", cl::Hidden,
342 cl::desc("Emit a call to trap function rather than a trap instruction"),
343 cl::init(""));
344 CGBINDOPT(TrapFuncName);
345
346 static cl::opt<bool> UseCtors("use-ctors",
347 cl::desc("Use .ctors instead of .init_array."),
348 cl::init(false));
349 CGBINDOPT(UseCtors);
350
351 static cl::opt<bool> DataSections(
352 "data-sections", cl::desc("Emit data into separate sections"),
353 cl::init(false));
354 CGBINDOPT(DataSections);
355
356 static cl::opt<bool> FunctionSections(
357 "function-sections", cl::desc("Emit functions into separate sections"),
358 cl::init(false));
359 CGBINDOPT(FunctionSections);
360
361 static cl::opt<bool> IgnoreXCOFFVisibility(
362 "ignore-xcoff-visibility",
363 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
364 "all symbols 'unspecified' visibility in XCOFF object file"),
365 cl::init(false));
366 CGBINDOPT(IgnoreXCOFFVisibility);
367
368 static cl::opt<bool> XCOFFTracebackTable(
369 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
370 cl::init(true));
371 CGBINDOPT(XCOFFTracebackTable);
372
373 static cl::opt<bool> EnableBBAddrMap(
374 "basic-block-address-map",
375 cl::desc("Emit the basic block address map section"), cl::init(false));
376 CGBINDOPT(EnableBBAddrMap);
377
378 static cl::opt<std::string> BBSections(
379 "basic-block-sections",
380 cl::desc("Emit basic blocks into separate sections"),
381 cl::value_desc("all | <function list (file)> | labels | none"),
382 cl::init("none"));
383 CGBINDOPT(BBSections);
384
385 static cl::opt<unsigned> TLSSize(
386 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
387 CGBINDOPT(TLSSize);
388
389 static cl::opt<bool> EmulatedTLS(
390 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
391 CGBINDOPT(EmulatedTLS);
392
393 static cl::opt<bool> EnableTLSDESC(
394 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
395 cl::init(false));
396 CGBINDOPT(EnableTLSDESC);
397
398 static cl::opt<bool> UniqueSectionNames(
399 "unique-section-names", cl::desc("Give unique names to every section"),
400 cl::init(true));
401 CGBINDOPT(UniqueSectionNames);
402
403 static cl::opt<bool> UniqueBasicBlockSectionNames(
404 "unique-basic-block-section-names",
405 cl::desc("Give unique names to every basic block section"),
406 cl::init(false));
407 CGBINDOPT(UniqueBasicBlockSectionNames);
408
409 static cl::opt<bool> SeparateNamedSections(
410 "separate-named-sections",
411 cl::desc("Use separate unique sections for named sections"),
412 cl::init(false));
413 CGBINDOPT(SeparateNamedSections);
414
415 static cl::opt<EABI> EABIVersion(
416 "meabi", cl::desc("Set EABI type (default depends on triple):"),
419 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
420 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
421 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
422 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
423 CGBINDOPT(EABIVersion);
424
425 static cl::opt<DebuggerKind> DebuggerTuningOpt(
426 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
429 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
430 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
431 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
432 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
433 CGBINDOPT(DebuggerTuningOpt);
434
436 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
440 "No vector functions library"),
442 "Accelerate framework"),
443 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
444 "Darwin libsystem_m"),
446 "GLIBC Vector Math library"),
447 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
448 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
450 "SIMD Library for Evaluating Elementary Functions"),
452 "Arm Performance Libraries"),
454 "AMD vector math library")));
456
457 static cl::opt<bool> EnableStackSizeSection(
458 "stack-size-section",
459 cl::desc("Emit a section containing stack size metadata"),
460 cl::init(false));
461 CGBINDOPT(EnableStackSizeSection);
462
463 static cl::opt<bool> EnableAddrsig(
464 "addrsig", cl::desc("Emit an address-significance table"),
465 cl::init(false));
466 CGBINDOPT(EnableAddrsig);
467
468 static cl::opt<bool> EnableCallGraphSection(
469 "call-graph-section", cl::desc("Emit a call graph section"),
470 cl::init(false));
471 CGBINDOPT(EnableCallGraphSection);
472
473 static cl::opt<bool> EmitCallSiteInfo(
474 "emit-call-site-info",
475 cl::desc(
476 "Emit call site debug information, if debug information is enabled."),
477 cl::init(false));
478 CGBINDOPT(EmitCallSiteInfo);
479
480 static cl::opt<bool> EnableDebugEntryValues(
481 "debug-entry-values",
482 cl::desc("Enable debug info for the debug entry values."),
483 cl::init(false));
484 CGBINDOPT(EnableDebugEntryValues);
485
487 "split-machine-functions",
488 cl::desc("Split out cold basic blocks from machine functions based on "
489 "profile information"),
490 cl::init(false));
492
493 static cl::opt<bool> EnableStaticDataPartitioning(
494 "partition-static-data-sections",
495 cl::desc("Partition data sections using profile information."),
496 cl::init(false));
497 CGBINDOPT(EnableStaticDataPartitioning);
498
499 static cl::opt<bool> ForceDwarfFrameSection(
500 "force-dwarf-frame-section",
501 cl::desc("Always emit a debug frame section."), cl::init(false));
502 CGBINDOPT(ForceDwarfFrameSection);
503
504 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
505 cl::desc("Emit xray_fn_idx section"),
506 cl::init(true));
507 CGBINDOPT(XRayFunctionIndex);
508
509 static cl::opt<bool> DebugStrictDwarf(
510 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
511 CGBINDOPT(DebugStrictDwarf);
512
513 static cl::opt<unsigned> AlignLoops("align-loops",
514 cl::desc("Default alignment for loops"));
515 CGBINDOPT(AlignLoops);
516
517 static cl::opt<bool> JMCInstrument(
518 "enable-jmc-instrument",
519 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
520 cl::init(false));
521 CGBINDOPT(JMCInstrument);
522
523 static cl::opt<bool> XCOFFReadOnlyPointers(
524 "mxcoff-roptr",
525 cl::desc("When set to true, const objects with relocatable address "
526 "values are put into the RO data section."),
527 cl::init(false));
528 CGBINDOPT(XCOFFReadOnlyPointers);
529
530 static cl::opt<bool> DisableIntegratedAS(
531 "no-integrated-as", cl::desc("Disable integrated assembler"),
532 cl::init(false));
533 CGBINDOPT(DisableIntegratedAS);
534
536}
537
539 static cl::opt<std::string> MTune(
540 "mtune",
541 cl::desc("Tune for a specific CPU microarchitecture (-mtune=help for "
542 "details)"),
543 cl::value_desc("tune-cpu-name"), cl::init(""));
544 CGBINDOPT(MTune);
545}
546
548 static cl::opt<SaveStatsMode> SaveStats(
549 "save-stats",
550 cl::desc(
551 "Save LLVM statistics to a file in the current directory"
552 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
553 "file (`-save-stats=obj`). (default: cwd)"),
555 "Save to the current working directory"),
558 "Save to the output file directory")),
560 CGBINDOPT(SaveStats);
561}
562
565 if (getBBSections() == "all")
567 else if (getBBSections() == "none")
569 else {
572 if (!MBOrErr) {
573 errs() << "Error loading basic block sections function list file: "
574 << MBOrErr.getError().message() << "\n";
575 } else {
576 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
577 }
579 }
580}
581
582// Common utility function tightly tied to the options listed here. Initializes
583// a TargetOptions object with CodeGen flags and returns it.
587 Options.AllowFPOpFusion = getFuseFPOps();
588 Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
589
590 Options.HonorSignDependentRoundingFPMathOption =
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 auto-detection
642 // fails, 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 std::string TuneCPU = getMTune();
652
653 // If user asked for the 'native' tune CPU, autodetect here. If auto-detection
654 // fails, this will set the tune CPU to an empty string which tells the target
655 // to pick a basic default.
656 if (TuneCPU == "native")
657 return std::string(sys::getHostCPUName());
658
659 return TuneCPU;
660}
661
663 SubtargetFeatures Features;
664
665 // If user asked for the 'native' CPU, we need to autodetect features.
666 // This is necessary for x86 where the CPU might not support all the
667 // features the autodetected CPU name lists in the target. For example,
668 // not all Sandybridge processors support AVX.
669 if (getMCPU() == "native")
670 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
671 Features.AddFeature(Feature, IsEnabled);
672
673 for (auto const &MAttr : getMAttrs())
674 Features.AddFeature(MAttr);
675
676 return Features.getString();
677}
678
679std::vector<std::string> codegen::getFeatureList() {
680 SubtargetFeatures Features;
681
682 // If user asked for the 'native' CPU, we need to autodetect features.
683 // This is necessary for x86 where the CPU might not support all the
684 // features the autodetected CPU name lists in the target. For example,
685 // not all Sandybridge processors support AVX.
686 if (getMCPU() == "native")
687 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
688 Features.AddFeature(Feature, IsEnabled);
689
690 for (auto const &MAttr : getMAttrs())
691 Features.AddFeature(MAttr);
692
693 return Features.getFeatures();
694}
695
696void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
697 B.addAttribute(Name, Val ? "true" : "false");
698}
699
700#define HANDLE_BOOL_ATTR(CL, AttrName) \
701 do { \
702 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
703 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
704 } while (0)
705
707 StringRef Features, StringRef TuneCPU) {
708 auto &Ctx = F.getContext();
709 AttributeList Attrs = F.getAttributes();
710 AttrBuilder NewAttrs(Ctx);
711
712 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
713 NewAttrs.addAttribute("target-cpu", CPU);
714 if (!TuneCPU.empty() && !F.hasFnAttribute("tune-cpu"))
715 NewAttrs.addAttribute("tune-cpu", TuneCPU);
716 if (!Features.empty()) {
717 // Append the command line features to any that are already on the function.
718 StringRef OldFeatures =
719 F.getFnAttribute("target-features").getValueAsString();
720 if (OldFeatures.empty())
721 NewAttrs.addAttribute("target-features", Features);
722 else {
723 SmallString<256> Appended(OldFeatures);
724 Appended.push_back(',');
725 Appended.append(Features);
726 NewAttrs.addAttribute("target-features", Appended);
727 }
728 }
729 if (FramePointerUsageView->getNumOccurrences() > 0 &&
730 !F.hasFnAttribute("frame-pointer")) {
732 NewAttrs.addAttribute("frame-pointer", "all");
734 NewAttrs.addAttribute("frame-pointer", "non-leaf");
736 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
738 NewAttrs.addAttribute("frame-pointer", "reserved");
740 NewAttrs.addAttribute("frame-pointer", "none");
741 }
742 if (DisableTailCallsView->getNumOccurrences() > 0)
743 NewAttrs.addAttribute("disable-tail-calls",
745 if (getStackRealign())
746 NewAttrs.addAttribute("stackrealign");
747
748 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
749 DenormalFP32MathView->getNumOccurrences() > 0) &&
750 !F.hasFnAttribute(Attribute::DenormalFPEnv)) {
753
754 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
755 DenormalMode{DenormKindF32, DenormKindF32});
756 // FIXME: Command line flag should expose separate input/output modes.
757 NewAttrs.addDenormalFPEnvAttr(FPEnv);
758 }
759
760 if (TrapFuncNameView->getNumOccurrences() > 0)
761 for (auto &B : F)
762 for (auto &I : B)
763 if (auto *Call = dyn_cast<CallInst>(&I))
764 if (const auto *F = Call->getCalledFunction())
765 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
766 F->getIntrinsicID() == Intrinsic::trap)
767 Call->addFnAttr(
768 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
769
770 // Let NewAttrs override Attrs.
771 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
772}
773
775 StringRef Features, StringRef TuneCPU) {
776 // Synthesize the "float-abi" module flag from the -float-abi option.
778 if (ABI != FloatABI::Default) {
779 if (auto *Existing =
780 dyn_cast_or_null<MDString>(M.getModuleFlag("float-abi"))) {
781 // The module already records a float ABI; -float-abi must not contradict
782 // it.
783 if (Existing->getString() != FloatABI::getABITypeName(ABI))
785 "-float-abi=" + FloatABI::getABITypeName(ABI) +
786 " conflicts with the \"float-abi\" module flag \"" +
787 Existing->getString() + "\"");
788 } else {
789 M.addModuleFlag(
790 Module::Error, "float-abi",
791 MDString::get(M.getContext(), FloatABI::getABITypeName(ABI)));
792 }
793 }
794
795 for (Function &F : M)
796 setFunctionAttributes(F, CPU, Features, TuneCPU);
797}
798
801 CodeGenOptLevel OptLevel) {
802 // lookupTarget may mutate the triple, so we need a copy.
803 Triple TheTriple(TargetTriple);
804 std::string Error;
805 const auto *TheTarget =
807 if (!TheTarget)
809 auto *Target = TheTarget->createTargetMachine(
813 OptLevel);
814 if (!Target)
816 Twine("could not allocate target machine for ") +
817 TheTriple.str());
818 return std::unique_ptr<TargetMachine>(Target);
819}
820
823 return;
824
826}
827
829 auto SaveStatsValue = getSaveStats();
830 if (SaveStatsValue == codegen::SaveStatsMode::None)
831 return 0;
832
833 SmallString<128> StatsFilename;
834 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
835 StatsFilename = OutputFilename;
837 } else {
838 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
839 "Should have been a valid --save-stats value");
840 }
841
843 llvm::sys::path::append(StatsFilename, BaseName);
844 llvm::sys::path::replace_extension(StatsFilename, "stats");
845
846 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
847 std::error_code EC;
848 auto StatsOS =
849 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
850 if (EC) {
851 WithColor::error(errs(), ToolName)
852 << "Unable to open statistics file: " << EC.message() << "\n";
853 return 1;
854 }
855
857 return 0;
858}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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 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 LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
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
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition Module.h:120
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)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
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:48
bool hasDefaultTLSDESC() const
True if the target uses TLSDESC by default.
Definition Triple.h:1279
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1284
const std::string & str() const
Definition Triple.h:577
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1273
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:84
CallInst * Call
StringRef getABITypeName(ABIType ABI)
Returns the string spelling used by the "float-abi" IR module flag for a Soft or Hard ABIType.
Definition CodeGen.h:127
@ DynamicNoPIC
Definition CodeGen.h:26
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 void setFunctionAttributes(Function &F, StringRef CPU, StringRef Features, StringRef TuneCPU="")
Set function attributes of function F based on CPU, TuneCPU, Features, and command line flags.
LLVM_ABI std::string getTuneCPUStr()
LLVM_ABI std::string getMTune()
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 getEnableStackSizeSection()
LLVM_ABI llvm::EABI getEABIVersion()
LLVM_ABI bool getEnableCallGraphSection()
LLVM_ABI bool getEnableNoTrappingFPMath()
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 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 Expected< std::unique_ptr< TargetMachine > > createTargetMachineForTriple(const Triple &TargetTriple, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default)
Creates a TargetMachine instance with the options defined on the command line.
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:804
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:485
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:491
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
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:467
LLVM_ABI StringMap< bool, MallocAllocator > getHostCPUFeatures()
getHostCPUFeatures - Get the LLVM names for the host CPU features.
Definition Host.cpp:2623
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:2050
This is an optimization pass for GlobalISel generic memory operations.
FramePointerKind
Definition CodeGen.h:185
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
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:178
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:149
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
ExceptionHandling
Definition CodeGen.h:54
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:57
@ None
No exception support.
Definition CodeGen.h:55
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:56
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:59
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:60
BasicBlockSection
VectorLibrary
List of known vector-functions libraries.
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.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
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 LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, 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.