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)
69CGOPT(std::string, MTune)
70CGLIST(std::string, MAttrs)
71CGOPT_EXP(Reloc::Model, RelocModel)
74CGOPT_EXP(uint64_t, LargeDataThreshold)
75CGOPT(ExceptionHandling, ExceptionModel)
77CGOPT(FramePointerKind, FramePointerUsage)
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> EnableNoTrappingFPMath(
235 "enable-no-trapping-fp-math",
236 cl::desc("Enable setting the FP exceptions build "
237 "attribute not to use exceptions"),
238 cl::init(false));
239 CGBINDOPT(EnableNoTrappingFPMath);
240
241 static const auto DenormFlagEnumOptions = cl::values(
242 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
243 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
244 "the sign of a flushed-to-zero number is preserved "
245 "in the sign of 0"),
246 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
247 "denormals are flushed to positive zero"),
249 "denormals have unknown treatment"));
250
251 // FIXME: Doesn't have way to specify separate input and output modes.
252 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
253 "denormal-fp-math",
254 cl::desc("Select which denormal numbers the code is permitted to require"),
256 DenormFlagEnumOptions);
257 CGBINDOPT(DenormalFPMath);
258
259 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
260 "denormal-fp-math-f32",
261 cl::desc("Select which denormal numbers the code is permitted to require for float"),
263 DenormFlagEnumOptions);
264 CGBINDOPT(DenormalFP32Math);
265
266 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
267 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
268 cl::desc("Force codegen to assume rounding mode can change dynamically"),
269 cl::init(false));
270 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
271
272 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
273 "float-abi", cl::desc("Choose float ABI type"),
276 "Target default float ABI type"),
278 "Soft float ABI (implied by -soft-float)"),
280 "Hard float ABI (uses FP registers)")));
281 CGBINDOPT(FloatABIForCalls);
282
284 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
288 "Fuse FP ops whenever profitable"),
289 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
291 "Only fuse FP ops when the result won't be affected.")));
292 CGBINDOPT(FuseFPOps);
293
294 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
295 "swift-async-fp",
296 cl::desc("Determine when the Swift async frame pointer should be set"),
299 "Determine based on deployment target"),
301 "Always set the bit"),
303 "Never set the bit")));
304 CGBINDOPT(SwiftAsyncFramePointer);
305
306 static cl::opt<bool> DontPlaceZerosInBSS(
307 "nozero-initialized-in-bss",
308 cl::desc("Don't place zero-initialized symbols into bss section"),
309 cl::init(false));
310 CGBINDOPT(DontPlaceZerosInBSS);
311
312 static cl::opt<bool> EnableAIXExtendedAltivecABI(
313 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
314 cl::init(false));
315 CGBINDOPT(EnableAIXExtendedAltivecABI);
316
317 static cl::opt<bool> EnableGuaranteedTailCallOpt(
318 "tailcallopt",
319 cl::desc(
320 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
321 cl::init(false));
322 CGBINDOPT(EnableGuaranteedTailCallOpt);
323
324 static cl::opt<bool> DisableTailCalls(
325 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
326 CGBINDOPT(DisableTailCalls);
327
328 static cl::opt<bool> StackSymbolOrdering(
329 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
330 cl::init(true));
331 CGBINDOPT(StackSymbolOrdering);
332
333 static cl::opt<bool> StackRealign(
334 "stackrealign",
335 cl::desc("Force align the stack to the minimum alignment"),
336 cl::init(false));
337 CGBINDOPT(StackRealign);
338
339 static cl::opt<std::string> TrapFuncName(
340 "trap-func", cl::Hidden,
341 cl::desc("Emit a call to trap function rather than a trap instruction"),
342 cl::init(""));
343 CGBINDOPT(TrapFuncName);
344
345 static cl::opt<bool> UseCtors("use-ctors",
346 cl::desc("Use .ctors instead of .init_array."),
347 cl::init(false));
348 CGBINDOPT(UseCtors);
349
350 static cl::opt<bool> DataSections(
351 "data-sections", cl::desc("Emit data into separate sections"),
352 cl::init(false));
353 CGBINDOPT(DataSections);
354
355 static cl::opt<bool> FunctionSections(
356 "function-sections", cl::desc("Emit functions into separate sections"),
357 cl::init(false));
358 CGBINDOPT(FunctionSections);
359
360 static cl::opt<bool> IgnoreXCOFFVisibility(
361 "ignore-xcoff-visibility",
362 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
363 "all symbols 'unspecified' visibility in XCOFF object file"),
364 cl::init(false));
365 CGBINDOPT(IgnoreXCOFFVisibility);
366
367 static cl::opt<bool> XCOFFTracebackTable(
368 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
369 cl::init(true));
370 CGBINDOPT(XCOFFTracebackTable);
371
372 static cl::opt<bool> EnableBBAddrMap(
373 "basic-block-address-map",
374 cl::desc("Emit the basic block address map section"), cl::init(false));
375 CGBINDOPT(EnableBBAddrMap);
376
377 static cl::opt<std::string> BBSections(
378 "basic-block-sections",
379 cl::desc("Emit basic blocks into separate sections"),
380 cl::value_desc("all | <function list (file)> | labels | none"),
381 cl::init("none"));
382 CGBINDOPT(BBSections);
383
384 static cl::opt<unsigned> TLSSize(
385 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
386 CGBINDOPT(TLSSize);
387
388 static cl::opt<bool> EmulatedTLS(
389 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
390 CGBINDOPT(EmulatedTLS);
391
392 static cl::opt<bool> EnableTLSDESC(
393 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
394 cl::init(false));
395 CGBINDOPT(EnableTLSDESC);
396
397 static cl::opt<bool> UniqueSectionNames(
398 "unique-section-names", cl::desc("Give unique names to every section"),
399 cl::init(true));
400 CGBINDOPT(UniqueSectionNames);
401
402 static cl::opt<bool> UniqueBasicBlockSectionNames(
403 "unique-basic-block-section-names",
404 cl::desc("Give unique names to every basic block section"),
405 cl::init(false));
406 CGBINDOPT(UniqueBasicBlockSectionNames);
407
408 static cl::opt<bool> SeparateNamedSections(
409 "separate-named-sections",
410 cl::desc("Use separate unique sections for named sections"),
411 cl::init(false));
412 CGBINDOPT(SeparateNamedSections);
413
414 static cl::opt<EABI> EABIVersion(
415 "meabi", cl::desc("Set EABI type (default depends on triple):"),
418 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
419 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
420 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
421 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
422 CGBINDOPT(EABIVersion);
423
424 static cl::opt<DebuggerKind> DebuggerTuningOpt(
425 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
428 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
429 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
430 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
431 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
432 CGBINDOPT(DebuggerTuningOpt);
433
435 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
439 "No vector functions library"),
441 "Accelerate framework"),
442 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
443 "Darwin libsystem_m"),
445 "GLIBC Vector Math library"),
446 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
447 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
449 "SIMD Library for Evaluating Elementary Functions"),
451 "Arm Performance Libraries"),
453 "AMD vector math library")));
455
456 static cl::opt<bool> EnableStackSizeSection(
457 "stack-size-section",
458 cl::desc("Emit a section containing stack size metadata"),
459 cl::init(false));
460 CGBINDOPT(EnableStackSizeSection);
461
462 static cl::opt<bool> EnableAddrsig(
463 "addrsig", cl::desc("Emit an address-significance table"),
464 cl::init(false));
465 CGBINDOPT(EnableAddrsig);
466
467 static cl::opt<bool> EnableCallGraphSection(
468 "call-graph-section", cl::desc("Emit a call graph section"),
469 cl::init(false));
470 CGBINDOPT(EnableCallGraphSection);
471
472 static cl::opt<bool> EmitCallSiteInfo(
473 "emit-call-site-info",
474 cl::desc(
475 "Emit call site debug information, if debug information is enabled."),
476 cl::init(false));
477 CGBINDOPT(EmitCallSiteInfo);
478
479 static cl::opt<bool> EnableDebugEntryValues(
480 "debug-entry-values",
481 cl::desc("Enable debug info for the debug entry values."),
482 cl::init(false));
483 CGBINDOPT(EnableDebugEntryValues);
484
486 "split-machine-functions",
487 cl::desc("Split out cold basic blocks from machine functions based on "
488 "profile information"),
489 cl::init(false));
491
492 static cl::opt<bool> EnableStaticDataPartitioning(
493 "partition-static-data-sections",
494 cl::desc("Partition data sections using profile information."),
495 cl::init(false));
496 CGBINDOPT(EnableStaticDataPartitioning);
497
498 static cl::opt<bool> ForceDwarfFrameSection(
499 "force-dwarf-frame-section",
500 cl::desc("Always emit a debug frame section."), cl::init(false));
501 CGBINDOPT(ForceDwarfFrameSection);
502
503 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
504 cl::desc("Emit xray_fn_idx section"),
505 cl::init(true));
506 CGBINDOPT(XRayFunctionIndex);
507
508 static cl::opt<bool> DebugStrictDwarf(
509 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
510 CGBINDOPT(DebugStrictDwarf);
511
512 static cl::opt<unsigned> AlignLoops("align-loops",
513 cl::desc("Default alignment for loops"));
514 CGBINDOPT(AlignLoops);
515
516 static cl::opt<bool> JMCInstrument(
517 "enable-jmc-instrument",
518 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
519 cl::init(false));
520 CGBINDOPT(JMCInstrument);
521
522 static cl::opt<bool> XCOFFReadOnlyPointers(
523 "mxcoff-roptr",
524 cl::desc("When set to true, const objects with relocatable address "
525 "values are put into the RO data section."),
526 cl::init(false));
527 CGBINDOPT(XCOFFReadOnlyPointers);
528
529 static cl::opt<bool> DisableIntegratedAS(
530 "no-integrated-as", cl::desc("Disable integrated assembler"),
531 cl::init(false));
532 CGBINDOPT(DisableIntegratedAS);
533
535}
536
538 static cl::opt<std::string> MTune(
539 "mtune",
540 cl::desc("Tune for a specific CPU microarchitecture (-mtune=help for "
541 "details)"),
542 cl::value_desc("tune-cpu-name"), cl::init(""));
543 CGBINDOPT(MTune);
544}
545
547 static cl::opt<SaveStatsMode> SaveStats(
548 "save-stats",
549 cl::desc(
550 "Save LLVM statistics to a file in the current directory"
551 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
552 "file (`-save-stats=obj`). (default: cwd)"),
554 "Save to the current working directory"),
557 "Save to the output file directory")),
559 CGBINDOPT(SaveStats);
560}
561
564 if (getBBSections() == "all")
566 else if (getBBSections() == "none")
568 else {
571 if (!MBOrErr) {
572 errs() << "Error loading basic block sections function list file: "
573 << MBOrErr.getError().message() << "\n";
574 } else {
575 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
576 }
578 }
579}
580
581// Common utility function tightly tied to the options listed here. Initializes
582// a TargetOptions object with CodeGen flags and returns it.
586 Options.AllowFPOpFusion = getFuseFPOps();
587 Options.NoTrappingFPMath = getEnableNoTrappingFPMath();
588
589 Options.HonorSignDependentRoundingFPMathOption =
592 Options.FloatABIType = getFloatABIForCalls();
593 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
594 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
595 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
596 Options.StackSymbolOrdering = getStackSymbolOrdering();
597 Options.UseInitArray = !getUseCtors();
598 Options.DisableIntegratedAS = getDisableIntegratedAS();
599 Options.DataSections =
600 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
601 Options.FunctionSections = getFunctionSections();
602 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
603 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
604 Options.BBAddrMap = getEnableBBAddrMap();
605 Options.BBSections = getBBSectionsMode(Options);
606 Options.UniqueSectionNames = getUniqueSectionNames();
607 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
608 Options.SeparateNamedSections = getSeparateNamedSections();
609 Options.TLSSize = getTLSSize();
610 Options.EmulatedTLS =
611 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
612 Options.EnableTLSDESC =
613 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
614 Options.ExceptionModel = getExceptionModel();
615 Options.VecLib = getVectorLibrary();
616 Options.EmitStackSizeSection = getEnableStackSizeSection();
617 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
618 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
619 Options.EmitAddrsig = getEnableAddrsig();
620 Options.EmitCallGraphSection = getEnableCallGraphSection();
621 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
622 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
623 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
624 Options.XRayFunctionIndex = getXRayFunctionIndex();
625 Options.DebugStrictDwarf = getDebugStrictDwarf();
626 Options.LoopAlignment = getAlignLoops();
627 Options.JMCInstrument = getJMCInstrument();
628 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
629
631
632 Options.ThreadModel = getThreadModel();
633 Options.EABIVersion = getEABIVersion();
634 Options.DebuggerTuning = getDebuggerTuningOpt();
635 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
636 return Options;
637}
638
639std::string codegen::getCPUStr() {
640 std::string MCPU = getMCPU();
641
642 // If user asked for the 'native' CPU, autodetect here. If auto-detection
643 // fails, this will set the CPU to an empty string which tells the target to
644 // pick a basic default.
645 if (MCPU == "native")
646 return std::string(sys::getHostCPUName());
647
648 return MCPU;
649}
650
652 std::string TuneCPU = getMTune();
653
654 // If user asked for the 'native' tune CPU, autodetect here. If auto-detection
655 // fails, this will set the tune CPU to an empty string which tells the target
656 // to pick a basic default.
657 if (TuneCPU == "native")
658 return std::string(sys::getHostCPUName());
659
660 return TuneCPU;
661}
662
664 SubtargetFeatures Features;
665
666 // If user asked for the 'native' CPU, we need to autodetect features.
667 // This is necessary for x86 where the CPU might not support all the
668 // features the autodetected CPU name lists in the target. For example,
669 // not all Sandybridge processors support AVX.
670 if (getMCPU() == "native")
671 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
672 Features.AddFeature(Feature, IsEnabled);
673
674 for (auto const &MAttr : getMAttrs())
675 Features.AddFeature(MAttr);
676
677 return Features.getString();
678}
679
680std::vector<std::string> codegen::getFeatureList() {
681 SubtargetFeatures Features;
682
683 // If user asked for the 'native' CPU, we need to autodetect features.
684 // This is necessary for x86 where the CPU might not support all the
685 // features the autodetected CPU name lists in the target. For example,
686 // not all Sandybridge processors support AVX.
687 if (getMCPU() == "native")
688 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
689 Features.AddFeature(Feature, IsEnabled);
690
691 for (auto const &MAttr : getMAttrs())
692 Features.AddFeature(MAttr);
693
694 return Features.getFeatures();
695}
696
697void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
698 B.addAttribute(Name, Val ? "true" : "false");
699}
700
701#define HANDLE_BOOL_ATTR(CL, AttrName) \
702 do { \
703 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
704 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
705 } while (0)
706
708 StringRef Features, StringRef TuneCPU) {
709 auto &Ctx = F.getContext();
710 AttributeList Attrs = F.getAttributes();
711 AttrBuilder NewAttrs(Ctx);
712
713 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
714 NewAttrs.addAttribute("target-cpu", CPU);
715 if (!TuneCPU.empty() && !F.hasFnAttribute("tune-cpu"))
716 NewAttrs.addAttribute("tune-cpu", TuneCPU);
717 if (!Features.empty()) {
718 // Append the command line features to any that are already on the function.
719 StringRef OldFeatures =
720 F.getFnAttribute("target-features").getValueAsString();
721 if (OldFeatures.empty())
722 NewAttrs.addAttribute("target-features", Features);
723 else {
724 SmallString<256> Appended(OldFeatures);
725 Appended.push_back(',');
726 Appended.append(Features);
727 NewAttrs.addAttribute("target-features", Appended);
728 }
729 }
730 if (FramePointerUsageView->getNumOccurrences() > 0 &&
731 !F.hasFnAttribute("frame-pointer")) {
733 NewAttrs.addAttribute("frame-pointer", "all");
735 NewAttrs.addAttribute("frame-pointer", "non-leaf");
737 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
739 NewAttrs.addAttribute("frame-pointer", "reserved");
741 NewAttrs.addAttribute("frame-pointer", "none");
742 }
743 if (DisableTailCallsView->getNumOccurrences() > 0)
744 NewAttrs.addAttribute("disable-tail-calls",
746 if (getStackRealign())
747 NewAttrs.addAttribute("stackrealign");
748
749 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
750 DenormalFP32MathView->getNumOccurrences() > 0) &&
751 !F.hasFnAttribute(Attribute::DenormalFPEnv)) {
754
755 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
756 DenormalMode{DenormKindF32, DenormKindF32});
757 // FIXME: Command line flag should expose separate input/output modes.
758 NewAttrs.addDenormalFPEnvAttr(FPEnv);
759 }
760
761 if (TrapFuncNameView->getNumOccurrences() > 0)
762 for (auto &B : F)
763 for (auto &I : B)
764 if (auto *Call = dyn_cast<CallInst>(&I))
765 if (const auto *F = Call->getCalledFunction())
766 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
767 F->getIntrinsicID() == Intrinsic::trap)
768 Call->addFnAttr(
769 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
770
771 // Let NewAttrs override Attrs.
772 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
773}
774
776 StringRef Features, StringRef TuneCPU) {
777 for (Function &F : M)
778 setFunctionAttributes(F, CPU, Features, TuneCPU);
779}
780
783 CodeGenOptLevel OptLevel) {
784 Triple TheTriple(TargetTriple);
785 std::string Error;
786 const auto *TheTarget =
788 if (!TheTarget)
790 auto *Target = TheTarget->createTargetMachine(
794 OptLevel);
795 if (!Target)
797 Twine("could not allocate target machine for ") +
798 TargetTriple);
799 return std::unique_ptr<TargetMachine>(Target);
800}
801
804 return;
805
807}
808
810 auto SaveStatsValue = getSaveStats();
811 if (SaveStatsValue == codegen::SaveStatsMode::None)
812 return 0;
813
814 SmallString<128> StatsFilename;
815 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
816 StatsFilename = OutputFilename;
818 } else {
819 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
820 "Should have been a valid --save-stats value");
821 }
822
824 llvm::sys::path::append(StatsFilename, BaseName);
825 llvm::sys::path::replace_extension(StatsFilename, "stats");
826
827 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
828 std::error_code EC;
829 auto StatsOS =
830 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
831 if (EC) {
832 WithColor::error(errs(), ToolName)
833 << "Unable to open statistics file: " << EC.message() << "\n";
834 return 1;
835 }
836
838 return 0;
839}
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 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)
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:47
bool hasDefaultTLSDESC() const
True if the target uses TLSDESC by default.
Definition Triple.h:1192
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1197
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1186
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 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 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 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: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: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.
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:1321
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 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.