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)
74CGOPT_EXP(uint64_t, LargeDataThreshold)
75CGOPT(ExceptionHandling, ExceptionModel)
77CGOPT(FramePointerKind, FramePointerUsage)
80CGOPT(FloatABI::ABIType, FloatABIForCalls)
81CGOPT(SwiftAsyncFramePointerMode, SwiftAsyncFramePointer)
82CGOPT(bool, DontPlaceZerosInBSS)
83CGOPT(bool, EnableGuaranteedTailCallOpt)
84CGOPT(bool, DisableTailCalls)
85CGOPT(bool, StackSymbolOrdering)
86CGOPT(bool, StackRealign)
87CGOPT(std::string, TrapFuncName)
88CGOPT(bool, UseCtors)
89CGOPT_EXP(bool, DataSections)
90CGOPT_EXP(bool, FunctionSections)
91CGOPT(bool, IgnoreXCOFFVisibility)
92CGOPT(bool, XCOFFTracebackTable)
93CGOPT(bool, EnableBBAddrMap)
94CGOPT(std::string, BBSections)
95CGOPT(unsigned, TLSSize)
96CGOPT_EXP(bool, EmulatedTLS)
97CGOPT_EXP(bool, EnableTLSDESC)
98CGOPT(bool, UniqueSectionNames)
99CGOPT(bool, UniqueBasicBlockSectionNames)
100CGOPT(bool, SeparateNamedSections)
102CGOPT(bool, EnableStackSizeSection)
103CGOPT(bool, EnableAddrsig)
104CGOPT(bool, EnableCallGraphSection)
105CGOPT(bool, EmitCallSiteInfo)
106CGOPT(bool, EnableStaticDataPartitioning)
107CGOPT(bool, EnableDebugEntryValues)
108CGOPT(bool, ForceDwarfFrameSection)
109CGOPT(bool, XRayFunctionIndex)
110CGOPT(bool, DebugStrictDwarf)
111CGOPT(unsigned, AlignLoops)
112CGOPT(bool, JMCInstrument)
113CGOPT(bool, XCOFFReadOnlyPointers)
115
116#define CGBINDOPT(NAME) \
117 do { \
118 NAME##View = std::addressof(NAME); \
119 } while (0)
120
122 static cl::opt<std::string> MArch(
123 "march", cl::desc("Architecture to generate code for (see --version)"));
124 CGBINDOPT(MArch);
125
126 static cl::opt<std::string> MCPU(
127 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"),
128 cl::value_desc("cpu-name"), cl::init(""));
129 CGBINDOPT(MCPU);
130
131 static cl::list<std::string> MAttrs(
132 "mattr", cl::CommaSeparated,
133 cl::desc("Target specific attributes (-mattr=help for details)"),
134 cl::value_desc("a1,+a2,-a3,..."));
135 CGBINDOPT(MAttrs);
136
137 static cl::opt<Reloc::Model> RelocModel(
138 "relocation-model", cl::desc("Choose relocation model"),
140 clEnumValN(Reloc::Static, "static", "Non-relocatable code"),
141 clEnumValN(Reloc::PIC_, "pic",
142 "Fully relocatable, position independent code"),
143 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
144 "Relocatable external references, non-relocatable code"),
146 Reloc::ROPI, "ropi",
147 "Code and read-only data relocatable, accessed PC-relative"),
149 Reloc::RWPI, "rwpi",
150 "Read-write data relocatable, accessed relative to static base"),
151 clEnumValN(Reloc::ROPI_RWPI, "ropi-rwpi",
152 "Combination of ropi and rwpi")));
153 CGBINDOPT(RelocModel);
154
156 "code-model", cl::desc("Choose code model"),
157 cl::values(clEnumValN(CodeModel::Tiny, "tiny", "Tiny code model"),
158 clEnumValN(CodeModel::Small, "small", "Small code model"),
159 clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"),
160 clEnumValN(CodeModel::Medium, "medium", "Medium code model"),
161 clEnumValN(CodeModel::Large, "large", "Large code model")));
163
164 static cl::opt<uint64_t> LargeDataThreshold(
165 "large-data-threshold",
166 cl::desc("Choose large data threshold for x86_64 medium code model"),
167 cl::init(0));
168 CGBINDOPT(LargeDataThreshold);
169
170 static cl::opt<ExceptionHandling> ExceptionModel(
171 "exception-model", cl::desc("exception model"),
175 "default exception handling model"),
176 clEnumValN(ExceptionHandling::None, "none", "no exception handling"),
178 "DWARF-like CFI based exception handling"),
180 "SjLj exception handling"),
181 clEnumValN(ExceptionHandling::ARM, "arm", "ARM EHABI exceptions"),
183 "Windows exception model"),
185 "WebAssembly exception handling"),
187 "Emscripten JavaScript-based exception handling")));
188 CGBINDOPT(ExceptionModel);
189
190 static cl::opt<CodeGenFileType> FileType(
192 cl::desc(
193 "Choose a file type (not all types are supported by all targets):"),
195 "Emit an assembly ('.s') file"),
197 "Emit a native object ('.o') file"),
199 "Emit nothing, for performance testing")));
200 CGBINDOPT(FileType);
201
202 static cl::opt<FramePointerKind> FramePointerUsage(
203 "frame-pointer",
204 cl::desc("Specify frame pointer elimination optimization"),
208 "Disable frame pointer elimination"),
210 "Disable frame pointer elimination for non-leaf frame but "
211 "reserve the register in leaf functions"),
212 clEnumValN(FramePointerKind::NonLeafNoReserve, "non-leaf-no-reserve",
213 "Disable frame pointer elimination for non-leaf frame"),
215 "Enable frame pointer elimination, but reserve the frame "
216 "pointer register"),
218 "Enable frame pointer elimination")));
219 CGBINDOPT(FramePointerUsage);
220
221 static const auto DenormFlagEnumOptions = cl::values(
222 clEnumValN(DenormalMode::IEEE, "ieee", "IEEE 754 denormal numbers"),
223 clEnumValN(DenormalMode::PreserveSign, "preserve-sign",
224 "the sign of a flushed-to-zero number is preserved "
225 "in the sign of 0"),
226 clEnumValN(DenormalMode::PositiveZero, "positive-zero",
227 "denormals are flushed to positive zero"),
229 "denormals have unknown treatment"));
230
231 // FIXME: Doesn't have way to specify separate input and output modes.
232 static cl::opt<DenormalMode::DenormalModeKind> DenormalFPMath(
233 "denormal-fp-math",
234 cl::desc("Select which denormal numbers the code is permitted to require"),
236 DenormFlagEnumOptions);
237 CGBINDOPT(DenormalFPMath);
238
239 static cl::opt<DenormalMode::DenormalModeKind> DenormalFP32Math(
240 "denormal-fp-math-f32",
241 cl::desc("Select which denormal numbers the code is permitted to require for float"),
243 DenormFlagEnumOptions);
244 CGBINDOPT(DenormalFP32Math);
245
246 static cl::opt<FloatABI::ABIType> FloatABIForCalls(
247 "float-abi", cl::desc("Choose float ABI type"),
250 "Target default float ABI type"),
252 "Soft float ABI (implied by -soft-float)"),
254 "Hard float ABI (uses FP registers)")));
255 CGBINDOPT(FloatABIForCalls);
256
257 static cl::opt<SwiftAsyncFramePointerMode> SwiftAsyncFramePointer(
258 "swift-async-fp",
259 cl::desc("Determine when the Swift async frame pointer should be set"),
262 "Determine based on deployment target"),
264 "Always set the bit"),
266 "Never set the bit")));
267 CGBINDOPT(SwiftAsyncFramePointer);
268
269 static cl::opt<bool> DontPlaceZerosInBSS(
270 "nozero-initialized-in-bss",
271 cl::desc("Don't place zero-initialized symbols into bss section"),
272 cl::init(false));
273 CGBINDOPT(DontPlaceZerosInBSS);
274
275 static cl::opt<bool> EnableGuaranteedTailCallOpt(
276 "tailcallopt",
277 cl::desc(
278 "Turn fastcc calls into tail calls by (potentially) changing ABI."),
279 cl::init(false));
280 CGBINDOPT(EnableGuaranteedTailCallOpt);
281
282 static cl::opt<bool> DisableTailCalls(
283 "disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false));
284 CGBINDOPT(DisableTailCalls);
285
286 static cl::opt<bool> StackSymbolOrdering(
287 "stack-symbol-ordering", cl::desc("Order local stack symbols."),
288 cl::init(true));
289 CGBINDOPT(StackSymbolOrdering);
290
291 static cl::opt<bool> StackRealign(
292 "stackrealign",
293 cl::desc("Force align the stack to the minimum alignment"),
294 cl::init(false));
295 CGBINDOPT(StackRealign);
296
297 static cl::opt<std::string> TrapFuncName(
298 "trap-func", cl::Hidden,
299 cl::desc("Emit a call to trap function rather than a trap instruction"),
300 cl::init(""));
301 CGBINDOPT(TrapFuncName);
302
303 static cl::opt<bool> UseCtors("use-ctors",
304 cl::desc("Use .ctors instead of .init_array."),
305 cl::init(false));
306 CGBINDOPT(UseCtors);
307
308 static cl::opt<bool> DataSections(
309 "data-sections", cl::desc("Emit data into separate sections"),
310 cl::init(false));
311 CGBINDOPT(DataSections);
312
313 static cl::opt<bool> FunctionSections(
314 "function-sections", cl::desc("Emit functions into separate sections"),
315 cl::init(false));
316 CGBINDOPT(FunctionSections);
317
318 static cl::opt<bool> IgnoreXCOFFVisibility(
319 "ignore-xcoff-visibility",
320 cl::desc("Not emit the visibility attribute for asm in AIX OS or give "
321 "all symbols 'unspecified' visibility in XCOFF object file"),
322 cl::init(false));
323 CGBINDOPT(IgnoreXCOFFVisibility);
324
325 static cl::opt<bool> XCOFFTracebackTable(
326 "xcoff-traceback-table", cl::desc("Emit the XCOFF traceback table"),
327 cl::init(true));
328 CGBINDOPT(XCOFFTracebackTable);
329
330 static cl::opt<bool> EnableBBAddrMap(
331 "basic-block-address-map",
332 cl::desc("Emit the basic block address map section"), cl::init(false));
333 CGBINDOPT(EnableBBAddrMap);
334
335 static cl::opt<std::string> BBSections(
336 "basic-block-sections",
337 cl::desc("Emit basic blocks into separate sections"),
338 cl::value_desc("all | <function list (file)> | labels | none"),
339 cl::init("none"));
340 CGBINDOPT(BBSections);
341
342 static cl::opt<unsigned> TLSSize(
343 "tls-size", cl::desc("Bit size of immediate TLS offsets"), cl::init(0));
344 CGBINDOPT(TLSSize);
345
346 static cl::opt<bool> EmulatedTLS(
347 "emulated-tls", cl::desc("Use emulated TLS model"), cl::init(false));
348 CGBINDOPT(EmulatedTLS);
349
350 static cl::opt<bool> EnableTLSDESC(
351 "enable-tlsdesc", cl::desc("Enable the use of TLS Descriptors"),
352 cl::init(false));
353 CGBINDOPT(EnableTLSDESC);
354
355 static cl::opt<bool> UniqueSectionNames(
356 "unique-section-names", cl::desc("Give unique names to every section"),
357 cl::init(true));
358 CGBINDOPT(UniqueSectionNames);
359
360 static cl::opt<bool> UniqueBasicBlockSectionNames(
361 "unique-basic-block-section-names",
362 cl::desc("Give unique names to every basic block section"),
363 cl::init(false));
364 CGBINDOPT(UniqueBasicBlockSectionNames);
365
366 static cl::opt<bool> SeparateNamedSections(
367 "separate-named-sections",
368 cl::desc("Use separate unique sections for named sections"),
369 cl::init(false));
370 CGBINDOPT(SeparateNamedSections);
371
373 "vector-library", cl::Hidden, cl::desc("Vector functions library"),
377 "No vector functions library"),
379 "Accelerate framework"),
380 clEnumValN(VectorLibrary::DarwinLibSystemM, "Darwin_libsystem_m",
381 "Darwin libsystem_m"),
383 "GLIBC Vector Math library"),
384 clEnumValN(VectorLibrary::MASSV, "MASSV", "IBM MASS vector library"),
385 clEnumValN(VectorLibrary::SVML, "SVML", "Intel SVML library"),
387 "SIMD Library for Evaluating Elementary Functions"),
389 "Arm Performance Libraries"),
391 "AMD vector math library")));
393
394 static cl::opt<bool> EnableStackSizeSection(
395 "stack-size-section",
396 cl::desc("Emit a section containing stack size metadata"),
397 cl::init(false));
398 CGBINDOPT(EnableStackSizeSection);
399
400 static cl::opt<bool> EnableAddrsig(
401 "addrsig", cl::desc("Emit an address-significance table"),
402 cl::init(false));
403 CGBINDOPT(EnableAddrsig);
404
405 static cl::opt<bool> EnableCallGraphSection(
406 "call-graph-section", cl::desc("Emit a call graph section"),
407 cl::init(false));
408 CGBINDOPT(EnableCallGraphSection);
409
410 static cl::opt<bool> EmitCallSiteInfo(
411 "emit-call-site-info",
412 cl::desc(
413 "Emit call site debug information, if debug information is enabled."),
414 cl::init(false));
415 CGBINDOPT(EmitCallSiteInfo);
416
417 static cl::opt<bool> EnableDebugEntryValues(
418 "debug-entry-values",
419 cl::desc("Enable debug info for the debug entry values."),
420 cl::init(false));
421 CGBINDOPT(EnableDebugEntryValues);
422
423 static cl::opt<bool> EnableStaticDataPartitioning(
424 "partition-static-data-sections",
425 cl::desc("Partition data sections using profile information."),
426 cl::init(false));
427 CGBINDOPT(EnableStaticDataPartitioning);
428
429 static cl::opt<bool> ForceDwarfFrameSection(
430 "force-dwarf-frame-section",
431 cl::desc("Always emit a debug frame section."), cl::init(false));
432 CGBINDOPT(ForceDwarfFrameSection);
433
434 static cl::opt<bool> XRayFunctionIndex("xray-function-index",
435 cl::desc("Emit xray_fn_idx section"),
436 cl::init(true));
437 CGBINDOPT(XRayFunctionIndex);
438
439 static cl::opt<bool> DebugStrictDwarf(
440 "strict-dwarf", cl::desc("use strict dwarf"), cl::init(false));
441 CGBINDOPT(DebugStrictDwarf);
442
443 static cl::opt<unsigned> AlignLoops("align-loops",
444 cl::desc("Default alignment for loops"));
445 CGBINDOPT(AlignLoops);
446
447 static cl::opt<bool> JMCInstrument(
448 "enable-jmc-instrument",
449 cl::desc("Instrument functions with a call to __CheckForDebuggerJustMyCode"),
450 cl::init(false));
451 CGBINDOPT(JMCInstrument);
452
453 static cl::opt<bool> XCOFFReadOnlyPointers(
454 "mxcoff-roptr",
455 cl::desc("When set to true, const objects with relocatable address "
456 "values are put into the RO data section."),
457 cl::init(false));
458 CGBINDOPT(XCOFFReadOnlyPointers);
459
461}
462
464 static cl::opt<std::string> MTune(
465 "mtune",
466 cl::desc("Tune for a specific CPU microarchitecture (-mtune=help for "
467 "details)"),
468 cl::value_desc("tune-cpu-name"), cl::init(""));
469 CGBINDOPT(MTune);
470}
471
473 static cl::opt<SaveStatsMode> SaveStats(
474 "save-stats",
475 cl::desc(
476 "Save LLVM statistics to a file in the current directory"
477 "(`-save-stats`/`-save-stats=cwd`) or the directory of the output"
478 "file (`-save-stats=obj`). (default: cwd)"),
480 "Save to the current working directory"),
483 "Save to the output file directory")),
485 CGBINDOPT(SaveStats);
486}
487
490 if (getBBSections() == "all")
492 else if (getBBSections() == "none")
494 else {
497 if (!MBOrErr) {
498 errs() << "Error loading basic block sections function list file: "
499 << MBOrErr.getError().message() << "\n";
500 } else {
501 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
502 }
504 }
505}
506
507// Common utility function tightly tied to the options listed here. Initializes
508// a TargetOptions object with CodeGen options and returns it.
511 const Triple &TheTriple) {
513 Options.NoZerosInBSS = getDontPlaceZerosInBSS();
514 Options.GuaranteedTailCallOpt = getEnableGuaranteedTailCallOpt();
515 Options.StackSymbolOrdering = getStackSymbolOrdering();
516 Options.UseInitArray = !getUseCtors();
517 Options.DataSections =
518 getExplicitDataSections().value_or(TheTriple.hasDefaultDataSections());
519 Options.FunctionSections = getFunctionSections();
520 Options.IgnoreXCOFFVisibility = getIgnoreXCOFFVisibility();
521 Options.XCOFFTracebackTable = getXCOFFTracebackTable();
522 Options.BBAddrMap = getEnableBBAddrMap();
523 Options.BBSections = getBBSectionsMode(Options);
524 Options.UniqueSectionNames = getUniqueSectionNames();
525 Options.UniqueBasicBlockSectionNames = getUniqueBasicBlockSectionNames();
526 Options.SeparateNamedSections = getSeparateNamedSections();
527 Options.TLSSize = getTLSSize();
528 Options.EmulatedTLS =
529 getExplicitEmulatedTLS().value_or(TheTriple.hasDefaultEmulatedTLS());
530 Options.EnableTLSDESC =
531 getExplicitEnableTLSDESC().value_or(TheTriple.hasDefaultTLSDESC());
532 Options.VecLib = getVectorLibrary();
533 Options.EmitStackSizeSection = getEnableStackSizeSection();
534 Options.EnableStaticDataPartitioning = getEnableStaticDataPartitioning();
535 Options.EmitAddrsig = getEnableAddrsig();
536 Options.EmitCallGraphSection = getEnableCallGraphSection();
537 Options.EmitCallSiteInfo = getEmitCallSiteInfo();
538 Options.EnableDebugEntryValues = getEnableDebugEntryValues();
539 Options.ForceDwarfFrameSection = getForceDwarfFrameSection();
540 Options.XRayFunctionIndex = getXRayFunctionIndex();
541 Options.DebugStrictDwarf = getDebugStrictDwarf();
542 Options.LoopAlignment = getAlignLoops();
543 Options.JMCInstrument = getJMCInstrument();
544 Options.XCOFFReadOnlyPointers = getXCOFFReadOnlyPointers();
545
546 Options.MCOptions = mc::getMCTargetOptions(LibraryOptions);
547
548 Options.SwiftAsyncFramePointer = getSwiftAsyncFramePointer();
549 return Options;
550}
551
552std::string codegen::getCPUStr() {
553 std::string MCPU = getMCPU();
554
555 // If user asked for the 'native' CPU, autodetect here. If auto-detection
556 // fails, this will set the CPU to an empty string which tells the target to
557 // pick a basic default.
558 if (MCPU == "native")
559 return std::string(sys::getHostCPUName());
560
561 return MCPU;
562}
563
565 std::string TuneCPU = getMTune();
566
567 // If user asked for the 'native' tune CPU, autodetect here. If auto-detection
568 // fails, this will set the tune CPU to an empty string which tells the target
569 // to pick a basic default.
570 if (TuneCPU == "native")
571 return std::string(sys::getHostCPUName());
572
573 return TuneCPU;
574}
575
577 SubtargetFeatures Features;
578
579 // If user asked for the 'native' CPU, we need to autodetect features.
580 // This is necessary for x86 where the CPU might not support all the
581 // features the autodetected CPU name lists in the target. For example,
582 // not all Sandybridge processors support AVX.
583 if (getMCPU() == "native")
584 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
585 Features.AddFeature(Feature, IsEnabled);
586
587 for (auto const &MAttr : getMAttrs())
588 Features.AddFeature(MAttr);
589
590 return Features.getString();
591}
592
593std::vector<std::string> codegen::getFeatureList() {
594 SubtargetFeatures Features;
595
596 // If user asked for the 'native' CPU, we need to autodetect features.
597 // This is necessary for x86 where the CPU might not support all the
598 // features the autodetected CPU name lists in the target. For example,
599 // not all Sandybridge processors support AVX.
600 if (getMCPU() == "native")
601 for (const auto &[Feature, IsEnabled] : sys::getHostCPUFeatures())
602 Features.AddFeature(Feature, IsEnabled);
603
604 for (auto const &MAttr : getMAttrs())
605 Features.AddFeature(MAttr);
606
607 return Features.getFeatures();
608}
609
610void codegen::renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val) {
611 B.addAttribute(Name, Val ? "true" : "false");
612}
613
614#define HANDLE_BOOL_ATTR(CL, AttrName) \
615 do { \
616 if (CL->getNumOccurrences() > 0 && !F.hasFnAttribute(AttrName)) \
617 renderBoolStringAttr(NewAttrs, AttrName, *CL); \
618 } while (0)
619
621 StringRef Features, StringRef TuneCPU) {
622 auto &Ctx = F.getContext();
623 AttributeList Attrs = F.getAttributes();
624 AttrBuilder NewAttrs(Ctx);
625
626 if (!CPU.empty() && !F.hasFnAttribute("target-cpu"))
627 NewAttrs.addAttribute("target-cpu", CPU);
628 if (!TuneCPU.empty() && !F.hasFnAttribute("tune-cpu"))
629 NewAttrs.addAttribute("tune-cpu", TuneCPU);
630 if (!Features.empty()) {
631 // Append the command line features to any that are already on the function.
632 StringRef OldFeatures =
633 F.getFnAttribute("target-features").getValueAsString();
634 if (OldFeatures.empty())
635 NewAttrs.addAttribute("target-features", Features);
636 else {
637 SmallString<256> Appended(OldFeatures);
638 Appended.push_back(',');
639 Appended.append(Features);
640 NewAttrs.addAttribute("target-features", Appended);
641 }
642 }
643 if (FramePointerUsageView->getNumOccurrences() > 0 &&
644 !F.hasFnAttribute("frame-pointer")) {
646 NewAttrs.addAttribute("frame-pointer", "all");
648 NewAttrs.addAttribute("frame-pointer", "non-leaf");
650 NewAttrs.addAttribute("frame-pointer", "non-leaf-no-reserve");
652 NewAttrs.addAttribute("frame-pointer", "reserved");
654 NewAttrs.addAttribute("frame-pointer", "none");
655 }
656 if (DisableTailCallsView->getNumOccurrences() > 0)
657 NewAttrs.addAttribute("disable-tail-calls",
659 if (getStackRealign())
660 NewAttrs.addAttribute("stackrealign");
661
662 if ((DenormalFPMathView->getNumOccurrences() > 0 ||
663 DenormalFP32MathView->getNumOccurrences() > 0) &&
664 !F.hasFnAttribute(Attribute::DenormalFPEnv)) {
667
668 DenormalFPEnv FPEnv(DenormalMode{DenormKind, DenormKind},
669 DenormalMode{DenormKindF32, DenormKindF32});
670 // FIXME: Command line flag should expose separate input/output modes.
671 NewAttrs.addDenormalFPEnvAttr(FPEnv);
672 }
673
674 if (TrapFuncNameView->getNumOccurrences() > 0)
675 for (auto &B : F)
676 for (auto &I : B)
677 if (auto *Call = dyn_cast<CallInst>(&I))
678 if (const auto *F = Call->getCalledFunction())
679 if (F->getIntrinsicID() == Intrinsic::debugtrap ||
680 F->getIntrinsicID() == Intrinsic::trap)
681 Call->addFnAttr(
682 Attribute::get(Ctx, "trap-func-name", getTrapFuncName()));
683
684 // Let NewAttrs override Attrs.
685 F.setAttributes(Attrs.addFnAttributes(Ctx, NewAttrs));
686}
687
689 StringRef Features, StringRef TuneCPU) {
690 // Synthesize the "float-abi" module flag from the -float-abi option.
692 if (ABI != FloatABI::Default) {
693 if (auto *Existing =
694 dyn_cast_or_null<MDString>(M.getModuleFlag("float-abi"))) {
695 // The module already records a float ABI; -float-abi must not contradict
696 // it.
697 if (Existing->getString() != FloatABI::getABITypeName(ABI))
699 "-float-abi=" + FloatABI::getABITypeName(ABI) +
700 " conflicts with the \"float-abi\" module flag \"" +
701 Existing->getString() + "\"");
702 } else {
703 M.addModuleFlag(
704 Module::Error, "float-abi",
705 MDString::get(M.getContext(), FloatABI::getABITypeName(ABI)));
706 }
707 }
708
709 // Synthesize the "exception-model" module flag from the -exception-model
710 // option.
712 if (EH != ExceptionHandling::Default) {
713 if (auto *Existing =
714 dyn_cast_or_null<MDString>(M.getModuleFlag("exception-model"))) {
715 // The module already records an exception model; -exception-model must
716 // not contradict it.
717 if (Existing->getString() != getExceptionModelName(EH)) {
719 "-exception-model=" + getExceptionModelName(EH) +
720 " conflicts with the \"exception-model\" module flag \"" +
721 Existing->getString() + "\"");
722 }
723 } else {
724 M.addModuleFlag(Module::Error, "exception-model",
725 MDString::get(M.getContext(), getExceptionModelName(EH)));
726 }
727 }
728
729 // Synthesize the "target-abi" module flag from the -target-abi option.
730 //
731 // FIXME: verifyOptionsConsistency validates consistency for target-abi. We
732 // should consistently handle all ABI module flags either here or there.
733 StringRef ABIName = mc::getABIName(M.getContext().getLibraryOptions());
734 if (!ABIName.empty() && !M.getModuleFlag("target-abi")) {
735 M.addModuleFlag(Module::Error, "target-abi",
736 MDString::get(M.getContext(), ABIName));
737 }
738
739 for (Function &F : M)
740 setFunctionAttributes(F, CPU, Features, TuneCPU);
741}
742
744 const cl::LibraryOptionsContext &LibraryOptions, const Triple &TargetTriple,
745 CodeGenOptLevel OptLevel) {
746 // lookupTarget may mutate the triple, so we need a copy.
747 Triple TheTriple(TargetTriple);
748 std::string Error;
749 const auto *TheTarget =
751 if (!TheTarget)
753 TargetOptions Options = codegen::getTargetOptions(LibraryOptions, TheTriple);
754 Options.MCOptions.LibraryOptions = &LibraryOptions;
755 auto *Target = TheTarget->createTargetMachine(
758 OptLevel);
759 if (!Target)
761 Twine("could not allocate target machine for ") +
762 TheTriple.str());
763 return std::unique_ptr<TargetMachine>(Target);
764}
765
768 return;
769
771}
772
774 auto SaveStatsValue = getSaveStats();
775 if (SaveStatsValue == codegen::SaveStatsMode::None)
776 return 0;
777
778 SmallString<128> StatsFilename;
779 if (SaveStatsValue == codegen::SaveStatsMode::Obj) {
780 StatsFilename = OutputFilename;
782 } else {
783 assert(SaveStatsValue == codegen::SaveStatsMode::Cwd &&
784 "Should have been a valid --save-stats value");
785 }
786
788 llvm::sys::path::append(StatsFilename, BaseName);
789 llvm::sys::path::replace_extension(StatsFilename, "stats");
790
791 auto FileFlags = llvm::sys::fs::OF_TextWithCRLF;
792 std::error_code EC;
793 auto StatsOS =
794 std::make_unique<llvm::raw_fd_ostream>(StatsFilename, EC, FileFlags);
795 if (EC) {
796 WithColor::error(errs(), ToolName)
797 << "Unable to open statistics file: " << EC.message() << "\n";
798 return 1;
799 }
800
802 return 0;
803}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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 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:595
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:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
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:1317
bool hasDefaultDataSections() const
Tests whether the target uses -data-sections as default.
Definition Triple.h:1322
const std::string & str() const
Definition Triple.h:580
bool hasDefaultEmulatedTLS() const
Tests whether the target uses emulated TLS as default.
Definition Triple.h:1311
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:177
@ 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 std::string getTrapFuncName()
LLVM_ABI bool getEnableDebugEntryValues()
LLVM_ABI unsigned getTLSSize()
LLVM_ABI bool getEnableGuaranteedTailCallOpt()
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 Expected< std::unique_ptr< TargetMachine > > createTargetMachineForTriple(const cl::LibraryOptionsContext &LibraryOptions, const Triple &TargetTriple, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default)
Creates a TargetMachine instance with the options defined on the command line.
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 TargetOptions getTargetOptions(const cl::LibraryOptionsContext &LibraryOptions, const llvm::Triple &TheTriple)
Common utility function tightly tied to the options listed here.
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 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 bool getXCOFFTracebackTable()
LLVM_ABI bool getIgnoreXCOFFVisibility()
LLVM_ABI bool getUseCtors()
LLVM_ABI std::vector< std::string > getMAttrs()
LLVM_ABI llvm::BasicBlockSection getBBSectionsMode(llvm::TargetOptions &Options)
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 getXRayFunctionIndex()
LLVM_ABI llvm::ExceptionHandling getExceptionModel()
LLVM_ABI bool getEmitCallSiteInfo()
LLVM_ABI std::optional< bool > getExplicitEmulatedTLS()
LLVM_ABI MCTargetOptions getMCTargetOptions(const cl::LibraryOptionsContext &C)
LLVM_ABI StringRef getABIName(const cl::LibraryOptionsContext &C)
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:802
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:2666
LLVM_ABI StringRef getHostCPUName()
getHostCPUName - Get the LLVM name for the host CPU.
Definition Host.cpp:2047
This is an optimization pass for GlobalISel generic memory operations.
FramePointerKind
Definition CodeGen.h:326
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
StringRef getExceptionModelName(ExceptionHandling EH)
Returns the "exception-model" module flag spelling for an ExceptionHandling value.
Definition CodeGen.h:71
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:309
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:280
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:58
@ Emscripten
Emscripten JavaScript-based exception handling.
Definition CodeGen.h:62
@ None
No exception support.
Definition CodeGen.h:56
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
BasicBlockSection
VectorLibrary
List of known vector-functions libraries.
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.