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, 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_EXP(bool, DataSections)
94CGOPT_EXP(bool, FunctionSections)
95CGOPT(bool, IgnoreXCOFFVisibility)
96CGOPT(bool, XCOFFTracebackTable)
97CGOPT(bool, EnableBBAddrMap)
98CGOPT(std::string, BBSections)
99CGOPT(unsigned, TLSSize)
100CGOPT_EXP(bool, EmulatedTLS)
101CGOPT_EXP(bool, EnableTLSDESC)
102CGOPT(bool, UniqueSectionNames)
103CGOPT(bool, UniqueBasicBlockSectionNames)
104CGOPT(bool, SeparateNamedSections)
105CGOPT(EABI, EABIVersion)
106CGOPT(DebuggerKind, DebuggerTuningOpt)
108CGOPT(bool, EnableStackSizeSection)
109CGOPT(bool, EnableAddrsig)
110CGOPT(bool, EnableCallGraphSection)
111CGOPT(bool, EmitCallSiteInfo)
113CGOPT(bool, EnableStaticDataPartitioning)
114CGOPT(bool, EnableDebugEntryValues)
115CGOPT(bool, ForceDwarfFrameSection)
116CGOPT(bool, XRayFunctionIndex)
117CGOPT(bool, DebugStrictDwarf)
118CGOPT(unsigned, AlignLoops)
119CGOPT(bool, JMCInstrument)
120CGOPT(bool, XCOFFReadOnlyPointers)
122
123#define CGBINDOPT(NAME) \
124 do { \
125 NAME##View = std::addressof(NAME); \
126 } while (0)
127
129 static cl::opt<std::string> MArch(
130 "march", cl::desc("Architecture to generate code for (see --version)"));
131 CGBINDOPT(MArch);
132
133 static cl::opt<std::string> MCPU(
134 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
135 cl::value_desc("cpu-name"), cl::init(""));
136 CGBINDOPT(MCPU);
137
138 static cl::list<std::string> MAttrs(
139 "mattr", cl::CommaSeparated,
140 cl::desc("Target specific attributes (-mattr=help for details)"),
141 cl::value_desc("a1,+a2,-a3,..."));
142 CGBINDOPT(MAttrs);
143
144 static cl::opt<Reloc::Model> RelocModel(
145 "relocation-model", cl::desc("Choose relocation model"),
147 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
148 clEnumValN(Reloc::PIC_, "pic",
149 "Fully relocatable, position independent code"),
150 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
151 "Relocatable external references, non-relocatable code"),
153 Reloc::ROPI, "ropi",
154 "Code and read-only data relocatable, accessed PC-relative"),
156 Reloc::RWPI, "rwpi",
157 "Read-write data relocatable, accessed relative to static base"),
158 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
159 "Combination of ropi and rwpi")));
160 CGBINDOPT(RelocModel);
161
163 "thread-model", cl::desc("Choose threading model"),
166 clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"),
167 clEnumValN(ThreadModel::Single, "single", "Single thread model")));
169
171 "code-model", cl::desc("Choose code model"),
172 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
173 clEnumValN(CodeModel::Small, "small", "Small code model"),
174 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
175 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
176 clEnumValN(CodeModel::Large, "large", "Large code model")));
178
179 static cl::opt<uint64_t> LargeDataThreshold(
180 "large-data-threshold",
181 cl::desc("Choose large data threshold for x86_64 medium code model"),
182 cl::init(0));
183 CGBINDOPT(LargeDataThreshold);
184
185 static cl::opt<ExceptionHandling> ExceptionModel(
186 "exception-model", cl::desc("exception model"),
190 "default exception handling model"),
192 "DWARF-like CFI based exception handling"),
194 "SjLj exception handling"),
195 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
197 "Windows exception model"),
199 "WebAssembly exception handling")));
200 CGBINDOPT(ExceptionModel);
201
202 static cl::opt<CodeGenFileType> FileType(
204 cl::desc(
205 "Choose a file type (not all types are supported by all targets):"),
207 "Emit an assembly ('.s') file"),
209 "Emit a native object ('.o') file"),
211 "Emit nothing, for performance testing")));
212 CGBINDOPT(FileType);
213
214 static cl::opt<FramePointerKind> FramePointerUsage(
215 "frame-pointer",
216 cl::desc("Specify frame pointer elimination optimization"),
220 "Disable frame pointer elimination"),
222 "Disable frame pointer elimination for non-leaf frame but "
223 "reserve the register in leaf functions"),
224 clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
225 "Disable frame pointer elimination for non-leaf frame"),
227 "Enable frame pointer elimination, but reserve the frame "
228 "pointer register"),
230 "Enable frame pointer elimination")));
231 CGBINDOPT(FramePointerUsage);
232
233 static const auto DenormFlagEnumOptions = cl::values(
234 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
235 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
236 "the sign of a flushed-to-zero number is preserved "
237 "in the sign of 0"),
238 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
239 "denormals are flushed to positive zero"),
241 "denormals have unknown treatment"));
242
243 // FIXME: Doesn't have way to specify separate input and output modes.
244 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
245 "denormal-fp-math",
246 cl::desc("Select which denormal numbers the code is permitted to require"),
248 DenormFlagEnumOptions);
249 CGBINDOPT(DenormalFPMath);
250
251 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
252 "denormal-fp-math-f32",
253 cl::desc("Select which denormal numbers the code is permitted to require for float"),
255 DenormFlagEnumOptions);
256 CGBINDOPT(DenormalFP32Math);
257
258 static cl::opt<bool> EnableHonorSignDependentRoundingFPMath(
259 "enable-sign-dependent-rounding-fp-math", cl::Hidden,
260 cl::desc("Force codegen to assume rounding mode can change dynamically"),
261 cl::init(false));
262 CGBINDOPT(EnableHonorSignDependentRoundingFPMath);
263
264 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
265 "float-abi", cl::desc("Choose float ABI type"),
268 "Target default float ABI type"),
270 "Soft float ABI (implied by -soft-float)"),
272 "Hard float ABI (uses FP registers)")));
273 CGBINDOPT(FloatABIForCalls);
274
276 "fp-contract", cl::desc("Enable aggressive formation of fused FP ops"),
280 "Fuse FP ops whenever profitable"),
281 clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."),
283 "Only fuse FP ops when the result won't be affected.")));
284 CGBINDOPT(FuseFPOps);
285
286 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
287 "swift-async-fp",
288 cl::desc("Determine when the Swift async frame pointer should be set"),
291 "Determine based on deployment target"),
293 "Always set the bit"),
295 "Never set the bit")));
296 CGBINDOPT(SwiftAsyncFramePointer);
297
298 static cl::opt<bool> DontPlaceZerosInBSS(
299 "nozero-initialized-in-bss",
300 cl::desc("Don't place zero-initialized symbols into bss section"),
301 cl::init(false));
302 CGBINDOPT(DontPlaceZerosInBSS);
303
304 static cl::opt<bool> EnableAIXExtendedAltivecABI(
305 "vec-extabi", cl::desc("Enable the AIX Extended Altivec ABI."),
306 cl::init(false));
307 CGBINDOPT(EnableAIXExtendedAltivecABI);
308
309 static cl::opt<bool> EnableGuaranteedTailCallOpt(
310 "tailcallopt",
311 cl::desc(
312 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
313 cl::init(false));
314 CGBINDOPT(EnableGuaranteedTailCallOpt);
315
316 static cl::opt<bool> DisableTailCalls(
317 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
318 CGBINDOPT(DisableTailCalls);
319
320 static cl::opt<bool> StackSymbolOrdering(
321 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
322 cl::init(true));
323 CGBINDOPT(StackSymbolOrdering);
324
325 static cl::opt<bool> StackRealign(
326 "stackrealign",
327 cl::desc("Force align the stack to the minimum alignment"),
328 cl::init(false));
329 CGBINDOPT(StackRealign);
330
331 static cl::opt<std::string> TrapFuncName(
332 "trap-func", cl::Hidden,
333 cl::desc("Emit a call to trap function rather than a trap instruction"),
334 cl::init(""));
335 CGBINDOPT(TrapFuncName);
336
337 static cl::opt<bool> UseCtors("use-ctors",
338 cl::desc("Use .ctors instead of .init_array."),
339 cl::init(false));
340 CGBINDOPT(UseCtors);
341
342 static cl::opt<bool> DataSections(
343 "data-sections", cl::desc("Emit data into separate sections"),
344 cl::init(false));
345 CGBINDOPT(DataSections);
346
347 static cl::opt<bool> FunctionSections(
348 "function-sections", cl::desc("Emit functions into separate sections"),
349 cl::init(false));
350 CGBINDOPT(FunctionSections);
351
352 static cl::opt<bool> IgnoreXCOFFVisibility(
353 "ignore-xcoff-visibility",
354 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
355 "all symbols 'unspecified' visibility in XCOFF object file"),
356 cl::init(false));
357 CGBINDOPT(IgnoreXCOFFVisibility);
358
359 static cl::opt<bool> XCOFFTracebackTable(
360 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
361 cl::init(true));
362 CGBINDOPT(XCOFFTracebackTable);
363
364 static cl::opt<bool> EnableBBAddrMap(
365 "basic-block-address-map",
366 cl::desc("Emit the basic block address map section"), cl::init(false));
367 CGBINDOPT(EnableBBAddrMap);
368
369 static cl::opt<std::string> BBSections(
370 "basic-block-sections",
371 cl::desc("Emit basic blocks into separate sections"),
372 cl::value_desc("all | <function list (file)> | labels | none"),
373 cl::init("none"));
374 CGBINDOPT(BBSections);
375
376 static cl::opt<unsigned> TLSSize(
377 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
378 CGBINDOPT(TLSSize);
379
380 static cl::opt<bool> EmulatedTLS(
381 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
382 CGBINDOPT(EmulatedTLS);
383
384 static cl::opt<bool> EnableTLSDESC(
385 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
386 cl::init(false));
387 CGBINDOPT(EnableTLSDESC);
388
389 static cl::opt<bool> UniqueSectionNames(
390 "unique-section-names", cl::desc("Give unique names to every section"),
391 cl::init(true));
392 CGBINDOPT(UniqueSectionNames);
393
394 static cl::opt<bool> UniqueBasicBlockSectionNames(
395 "unique-basic-block-section-names",
396 cl::desc("Give unique names to every basic block section"),
397 cl::init(false));
398 CGBINDOPT(UniqueBasicBlockSectionNames);
399
400 static cl::opt<bool> SeparateNamedSections(
401 "separate-named-sections",
402 cl::desc("Use separate unique sections for named sections"),
403 cl::init(false));
404 CGBINDOPT(SeparateNamedSections);
405
406 static cl::opt<EABI> EABIVersion(
407 "meabi", cl::desc("Set EABI type (default depends on triple):"),
410 clEnumValN(EABI::Default, "default", "Triple default EABI version"),
411 clEnumValN(EABI::EABI4, "4", "EABI version 4"),
412 clEnumValN(EABI::EABI5, "5", "EABI version 5"),
413 clEnumValN(EABI::GNU, "gnu", "EABI GNU")));
414 CGBINDOPT(EABIVersion);
415
416 static cl::opt<DebuggerKind> DebuggerTuningOpt(
417 "debugger-tune", cl::desc("Tune debug info for a particular debugger"),
420 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
421 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
422 clEnumValN(DebuggerKind::DBX, "dbx", "dbx"),
423 clEnumValN(DebuggerKind::SCE, "sce", "SCE targets (e.g. PS4)")));
424 CGBINDOPT(DebuggerTuningOpt);
425
427 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
431 "No vector functions library"),
433 "Accelerate framework"),
434 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
435 "Darwin libsystem_m"),
437 "GLIBC Vector Math library"),
438 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
439 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
441 "SIMD Library for Evaluating Elementary Functions"),
443 "Arm Performance Libraries"),
445 "AMD vector math library")));
447
448 static cl::opt<bool> EnableStackSizeSection(
449 "stack-size-section",
450 cl::desc("Emit a section containing stack size metadata"),
451 cl::init(false));
452 CGBINDOPT(EnableStackSizeSection);
453
454 static cl::opt<bool> EnableAddrsig(
455 "addrsig", cl::desc("Emit an address-significance table"),
456 cl::init(false));
457 CGBINDOPT(EnableAddrsig);
458
459 static cl::opt<bool> EnableCallGraphSection(
460 "call-graph-section", cl::desc("Emit a call graph section"),
461 cl::init(false));
462 CGBINDOPT(EnableCallGraphSection);
463
464 static cl::opt<bool> EmitCallSiteInfo(
465 "emit-call-site-info",
466 cl::desc(
467 "Emit call site debug information, if debug information is enabled."),
468 cl::init(false));
469 CGBINDOPT(EmitCallSiteInfo);
470
471 static cl::opt<bool> EnableDebugEntryValues(
472 "debug-entry-values",
473 cl::desc("Enable debug info for the debug entry values."),
474 cl::init(false));
475 CGBINDOPT(EnableDebugEntryValues);
476
478 "split-machine-functions",
479 cl::desc("Split out cold basic blocks from machine functions based on "
480 "profile information"),
481 cl::init(false));
483
484 static cl::opt<bool> EnableStaticDataPartitioning(
485 "partition-static-data-sections",
486 cl::desc("Partition data sections using profile information."),
487 cl::init(false));
488 CGBINDOPT(EnableStaticDataPartitioning);
489
490 static cl::opt<bool> ForceDwarfFrameSection(
491 "force-dwarf-frame-section",
492 cl::desc("Always emit a debug frame section."), cl::init(false));
493 CGBINDOPT(ForceDwarfFrameSection);
494
495 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
496 cl::desc("Emit xray_fn_idx section"),
497 cl::init(true));
498 CGBINDOPT(XRayFunctionIndex);
499
500 static cl::opt<bool> DebugStrictDwarf(
501 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
502 CGBINDOPT(DebugStrictDwarf);
503
504 static cl::opt<unsigned> AlignLoops("align-loops",
505 cl::desc("Default alignment for loops"));
506 CGBINDOPT(AlignLoops);
507
508 static cl::opt<bool> JMCInstrument(
509 "enable-jmc-instrument",
510 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
511 cl::init(false));
512 CGBINDOPT(JMCInstrument);
513
514 static cl::opt<bool> XCOFFReadOnlyPointers(
515 "mxcoff-roptr",
516 cl::desc("When set to true, const objects with relocatable address "
517 "values are put into the RO data section."),
518 cl::init(false));
519 CGBINDOPT(XCOFFReadOnlyPointers);
520
522}
523
525 static cl::opt<std::string> MTune(
526 "mtune",
527 cl::desc("Tune for a specific CPU microarchitecture (-mtune=help for "
528 "details)"),
529 cl::value_desc("tune-cpu-name"), cl::init(""));
530 CGBINDOPT(MTune);
531}
532
534 static cl::opt<SaveStatsMode> SaveStats(
535 "save-stats",
536 cl::desc(
537 "Save LLVM statistics to a file in the current directory"
538 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
539 "file (`-save-stats=obj`). (default: cwd)"),
541 "Save to the current working directory"),
544 "Save to the output file directory")),
546 CGBINDOPT(SaveStats);
547}
548
551 if (getBBSections() == "all")
553 else if (getBBSections() == "none")
555 else {
558 if (!MBOrErr) {
559 errs() << "Error loading basic block sections function list file: "
560 << MBOrErr.getError().message() << "\n";
561 } else {
562 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
563 }
565 }
566}
567
568// Common utility function tightly tied to the options listed here. Initializes
569// a TargetOptions object with CodeGen flags and returns it.
573 Options.AllowFPOpFusion = getFuseFPOps();
574
575 Options.HonorSignDependentRoundingFPMathOption =
577 Options.EnableAIXExtendedAltivecABI = getEnableAIXExtendedAltivecABI();
578 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
579 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
580 Options.StackSymbolOrdering = getStackSymbolOrdering();
581 Options.UseInitArray = !getUseCtors();
582 Options.DataSections =
583 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
584 Options.FunctionSections = getFunctionSections();
585 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
586 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
587 Options.BBAddrMap = getEnableBBAddrMap();
588 Options.BBSections = getBBSectionsMode(Options);
589 Options.UniqueSectionNames = getUniqueSectionNames();
590 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
591 Options.SeparateNamedSections = getSeparateNamedSections();
592 Options.TLSSize = getTLSSize();
593 Options.EmulatedTLS =
594 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
595 Options.EnableTLSDESC =
596 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
597 Options.ExceptionModel = getExceptionModel();
598 Options.VecLib = getVectorLibrary();
599 Options.EmitStackSizeSection = getEnableStackSizeSection();
600 Options.EnableMachineFunctionSplitter = getEnableMachineFunctionSplitter();
601 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
602 Options.EmitAddrsig = getEnableAddrsig();
603 Options.EmitCallGraphSection = getEnableCallGraphSection();
604 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
605 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
606 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
607 Options.XRayFunctionIndex = getXRayFunctionIndex();
608 Options.DebugStrictDwarf = getDebugStrictDwarf();
609 Options.LoopAlignment = getAlignLoops();
610 Options.JMCInstrument = getJMCInstrument();
611 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
612
614
615 Options.ThreadModel = getThreadModel();
616 Options.EABIVersion = getEABIVersion();
617 Options.DebuggerTuning = getDebuggerTuningOpt();
618 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
619 return Options;
620}
621
622std::string codegen::getCPUStr() {
623 std::string MCPU = getMCPU();
624
625 // If user asked for the 'native' CPU, autodetect here. If auto-detection
626 // fails, this will set the CPU to an empty string which tells the target to
627 // pick a basic default.
628 if (MCPU == "native")
629 return std::string(sys::getHostCPUName());
630
631 return MCPU;
632}
633
635 std::string TuneCPU = getMTune();
636
637 // If user asked for the 'native' tune CPU, autodetect here. If auto-detection
638 // fails, this will set the tune CPU to an empty string which tells the target
639 // to pick a basic default.
640 if (TuneCPU == "native")
641 return std::string(sys::getHostCPUName());
642
643 return TuneCPU;
644}
645
647 SubtargetFeatures Features;
648
649 // If user asked for the 'native' CPU, we need to autodetect features.
650 // This is necessary for x86 where the CPU might not support all the
651 // features the autodetected CPU name lists in the target. For example,
652 // not all Sandybridge processors support AVX.
653 if (getMCPU() == "native")
654 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
655 Features.AddFeature(Feature, IsEnabled);
656
657 for (auto const &MAttr : getMAttrs())
658 Features.AddFeature(MAttr);
659
660 return Features.getString();
661}
662
663std::vector<std::string> codegen::getFeatureList() {
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.getFeatures();
678}
679
680void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
681 B.addAttribute(Name, Val ? "true" : "false");
682}
683
684#define HANDLE_BOOL_ATTR(CL, AttrName) \
685 do { \
686 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
687 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
688 } while (0)
689
691 StringRef Features, StringRef TuneCPU) {
692 auto &Ctx = F.getContext();
693 AttributeList Attrs = F.getAttributes();
694 AttrBuilder NewAttrs(Ctx);
695
696 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
697 NewAttrs.addAttribute("target-cpu", CPU);
698 if (!TuneCPU.empty() && !F.hasFnAttribute("tune-cpu"))
699 NewAttrs.addAttribute("tune-cpu", TuneCPU);
700 if (!Features.empty()) {
701 // Append the command line features to any that are already on the function.
702 StringRef OldFeatures =
703 F.getFnAttribute("target-features").getValueAsString();
704 if (OldFeatures.empty())
705 NewAttrs.addAttribute("target-features", Features);
706 else {
707 SmallString<256> Appended(OldFeatures);
708 Appended.push_back(',');
709 Appended.append(Features);
710 NewAttrs.addAttribute("target-features", Appended);
711 }
712 }
713 if (FramePointerUsageView->getNumOccurrences() > 0 &&
714 !F.hasFnAttribute("frame-pointer")) {
716 NewAttrs.addAttribute("frame-pointer", "all");
718 NewAttrs.addAttribute("frame-pointer", "non-leaf");
720 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
722 NewAttrs.addAttribute("frame-pointer", "reserved");
724 NewAttrs.addAttribute("frame-pointer", "none");
725 }
726 if (DisableTailCallsView->getNumOccurrences() > 0)
727 NewAttrs.addAttribute("disable-tail-calls",
729 if (getStackRealign())
730 NewAttrs.addAttribute("stackrealign");
731
732 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
733 DenormalFP32MathView->getNumOccurrences() > 0) &&
734 !F.hasFnAttribute(Attribute::DenormalFPEnv)) {
737
738 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
739 DenormalMode{DenormKindF32, DenormKindF32});
740 // FIXME: Command line flag should expose separate input/output modes.
741 NewAttrs.addDenormalFPEnvAttr(FPEnv);
742 }
743
744 if (TrapFuncNameView->getNumOccurrences() > 0)
745 for (auto &B : F)
746 for (auto &I : B)
747 if (auto *Call = dyn_cast<CallInst>(&I))
748 if (const auto *F = Call->getCalledFunction())
749 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
750 F->getIntrinsicID() == Intrinsic::trap)
751 Call->addFnAttr(
752 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
753
754 // Let NewAttrs override Attrs.
755 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
756}
757
759 StringRef Features, StringRef TuneCPU) {
760 // Synthesize the "float-abi" module flag from the -float-abi option.
762 if (ABI != FloatABI::Default) {
763 if (auto *Existing =
764 dyn_cast_or_null<MDString>(M.getModuleFlag("float-abi"))) {
765 // The module already records a float ABI; -float-abi must not contradict
766 // it.
767 if (Existing->getString() != FloatABI::getABITypeName(ABI))
769 "-float-abi=" + FloatABI::getABITypeName(ABI) +
770 " conflicts with the \"float-abi\" module flag \"" +
771 Existing->getString() + "\"");
772 } else {
773 M.addModuleFlag(
774 Module::Error, "float-abi",
775 MDString::get(M.getContext(), FloatABI::getABITypeName(ABI)));
776 }
777 }
778
779 for (Function &F : M)
780 setFunctionAttributes(F, CPU, Features, TuneCPU);
781}
782
785 CodeGenOptLevel OptLevel) {
786 // lookupTarget may mutate the triple, so we need a copy.
787 Triple TheTriple(TargetTriple);
788 std::string Error;
789 const auto *TheTarget =
791 if (!TheTarget)
793 auto *Target = TheTarget->createTargetMachine(
797 OptLevel);
798 if (!Target)
800 Twine("could not allocate target machine for ") +
801 TheTriple.str());
802 return std::unique_ptr<TargetMachine>(Target);
803}
804
807 return;
808
810}
811
813 auto SaveStatsValue = getSaveStats();
814 if (SaveStatsValue == codegen::SaveStatsMode::None)
815 return 0;
816
817 SmallString<128> StatsFilename;
818 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
819 StatsFilename = OutputFilename;
821 } else {
822 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
823 "Should have been a valid --save-stats value");
824 }
825
827 llvm::sys::path::append(StatsFilename, BaseName);
828 llvm::sys::path::replace_extension(StatsFilename, "stats");
829
830 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
831 std::error_code EC;
832 auto StatsOS =
833 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
834 if (EC) {
835 WithColor::error(errs(), ToolName)
836 << "Unable to open statistics file: " << EC.message() << "\n";
837 return 1;
838 }
839
841 return 0;
842}
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:68
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition Module.h:121
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:1280
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1285
const std::string & str() const
Definition Triple.h:578
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1274
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 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 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:2619
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:2046
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.