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