1 //===--- CodeGenOptions.h ---------------------------------------*- 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 defines the CodeGenOptions interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_BASIC_CODEGENOPTIONS_H 14 #define LLVM_CLANG_BASIC_CODEGENOPTIONS_H 15 16 #include "clang/Basic/CFProtectionOptions.h" 17 #include "clang/Basic/PointerAuthOptions.h" 18 #include "clang/Basic/Sanitizers.h" 19 #include "clang/Basic/XRayInstr.h" 20 #include "llvm/ADT/FloatingPointMode.h" 21 #include "llvm/Frontend/Debug/Options.h" 22 #include "llvm/Frontend/Driver/CodeGenOptions.h" 23 #include "llvm/Support/CodeGen.h" 24 #include "llvm/Support/Regex.h" 25 #include "llvm/Target/TargetOptions.h" 26 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h" 27 #include <map> 28 #include <memory> 29 #include <string> 30 #include <vector> 31 32 namespace llvm { 33 class PassBuilder; 34 } 35 namespace clang { 36 37 /// Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure 38 /// that this large collection of bitfields is a trivial class type. 39 class CodeGenOptionsBase { 40 friend class CompilerInvocation; 41 friend class CompilerInvocationBase; 42 43 public: 44 /// For ASTs produced with different option value, signifies their level of 45 /// compatibility. 46 enum class CompatibilityKind { 47 /// Does affect the construction of the AST in a way that does prevent 48 /// module interoperability. 49 Affecting, 50 /// Does not affect the construction of the AST in any way (that is, the 51 /// value can be different between an implicit module and the user of that 52 /// module). 53 Benign, 54 }; 55 56 #define CODEGENOPT(Name, Bits, Default, Compatibility) unsigned Name : Bits; 57 #define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) 58 #include "clang/Basic/CodeGenOptions.def" 59 60 protected: 61 #define CODEGENOPT(Name, Bits, Default, Compatibility) 62 #define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \ 63 unsigned Name : Bits; 64 #include "clang/Basic/CodeGenOptions.def" 65 }; 66 67 /// CodeGenOptions - Track various options which control how the code 68 /// is optimized and passed to the backend. 69 class CodeGenOptions : public CodeGenOptionsBase { 70 public: 71 enum InliningMethod { 72 NormalInlining, // Use the standard function inlining pass. 73 OnlyHintInlining, // Inline only (implicitly) hinted functions. 74 OnlyAlwaysInlining // Only run the always inlining pass. 75 }; 76 77 enum ObjCDispatchMethodKind { 78 Legacy = 0, 79 NonLegacy = 1, 80 Mixed = 2 81 }; 82 83 enum TLSModel { 84 GeneralDynamicTLSModel, 85 LocalDynamicTLSModel, 86 InitialExecTLSModel, 87 LocalExecTLSModel 88 }; 89 90 enum StructReturnConventionKind { 91 SRCK_Default, // No special option was passed. 92 SRCK_OnStack, // Small structs on the stack (-fpcc-struct-return). 93 SRCK_InRegs // Small structs in registers (-freg-struct-return). 94 }; 95 96 enum EmbedBitcodeKind { 97 Embed_Off, // No embedded bitcode. 98 Embed_All, // Embed both bitcode and commandline in the output. 99 Embed_Bitcode, // Embed just the bitcode in the output. 100 Embed_Marker // Embed a marker as a placeholder for bitcode. 101 }; 102 103 enum class ExtendVariableLivenessKind { 104 None, 105 This, 106 All, 107 }; 108 109 enum InlineAsmDialectKind { 110 IAD_ATT, 111 IAD_Intel, 112 }; 113 114 enum DebugSrcHashKind { 115 DSH_MD5, 116 DSH_SHA1, 117 DSH_SHA256, 118 DSH_NONE, 119 }; 120 121 // This field stores one of the allowed values for the option 122 // -fbasic-block-sections=. The allowed values with this option are: 123 // {"all", "list=<file>", "none"}. 124 // 125 // "all" : Generate basic block sections for all basic blocks. 126 // "list=<file>": Generate basic block sections for a subset of basic blocks. 127 // The functions and the machine basic block ids are specified 128 // in the file. 129 // "none": Disable sections for basic blocks. 130 std::string BBSections; 131 132 // If set, override the default value of MCAsmInfo::BinutilsVersion. If 133 // DisableIntegratedAS is specified, the assembly output will consider GNU as 134 // support. "none" means that all ELF features can be used, regardless of 135 // binutils support. 136 std::string BinutilsVersion; 137 138 enum class FramePointerKind { 139 None, // Omit all frame pointers. 140 Reserved, // Maintain valid frame pointer chain. 141 NonLeaf, // Keep non-leaf frame pointers. 142 All, // Keep all frame pointers. 143 }; 144 getFramePointerKindName(FramePointerKind Kind)145 static StringRef getFramePointerKindName(FramePointerKind Kind) { 146 switch (Kind) { 147 case FramePointerKind::None: 148 return "none"; 149 case FramePointerKind::Reserved: 150 return "reserved"; 151 case FramePointerKind::NonLeaf: 152 return "non-leaf"; 153 case FramePointerKind::All: 154 return "all"; 155 } 156 157 llvm_unreachable("invalid FramePointerKind"); 158 } 159 160 enum class SwiftAsyncFramePointerKind { 161 Auto, // Choose Swift async extended frame info based on deployment target. 162 Always, // Unconditionally emit Swift async extended frame info. 163 Never, // Don't emit Swift async extended frame info. 164 Default = Always, 165 }; 166 167 enum FiniteLoopsKind { 168 Language, // Not specified, use language standard. 169 Always, // All loops are assumed to be finite. 170 Never, // No loop is assumed to be finite. 171 }; 172 173 enum AssignmentTrackingOpts { 174 Disabled, 175 Enabled, 176 Forced, 177 }; 178 179 /// The code model to use (-mcmodel). 180 std::string CodeModel; 181 182 /// The code model-specific large data threshold to use 183 /// (-mlarge-data-threshold). 184 uint64_t LargeDataThreshold; 185 186 /// The filename with path we use for coverage data files. The runtime 187 /// allows further manipulation with the GCOV_PREFIX and GCOV_PREFIX_STRIP 188 /// environment variables. 189 std::string CoverageDataFile; 190 191 /// The filename with path we use for coverage notes files. 192 std::string CoverageNotesFile; 193 194 /// Regexes separated by a semi-colon to filter the files to instrument. 195 std::string ProfileFilterFiles; 196 197 /// Regexes separated by a semi-colon to filter the files to not instrument. 198 std::string ProfileExcludeFiles; 199 200 /// The version string to put into coverage files. 201 char CoverageVersion[4] = {'0', '0', '0', '0'}; 202 203 /// Enable additional debugging information. 204 std::string DebugPass; 205 206 /// The string to embed in debug information as the current working directory. 207 std::string DebugCompilationDir; 208 209 /// The string to embed in coverage mapping as the current working directory. 210 std::string CoverageCompilationDir; 211 212 /// The string to embed in the debug information for the compile unit, if 213 /// non-empty. 214 std::string DwarfDebugFlags; 215 216 /// The string containing the commandline for the llvm.commandline metadata, 217 /// if non-empty. 218 std::string RecordCommandLine; 219 220 llvm::SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap; 221 222 /// Prefix replacement map for source-based code coverage to remap source 223 /// file paths in coverage mapping. 224 llvm::SmallVector<std::pair<std::string, std::string>, 0> CoveragePrefixMap; 225 226 /// The ABI to use for passing floating point arguments. 227 std::string FloatABI; 228 229 /// The file to use for dumping bug report by `Debugify` for original 230 /// debug info. 231 std::string DIBugsReportFilePath; 232 233 /// The floating-point denormal mode to use. 234 llvm::DenormalMode FPDenormalMode = llvm::DenormalMode::getIEEE(); 235 236 /// The floating-point denormal mode to use, for float. 237 llvm::DenormalMode FP32DenormalMode = llvm::DenormalMode::getIEEE(); 238 239 /// The float precision limit to use, if non-empty. 240 std::string LimitFloatPrecision; 241 242 struct BitcodeFileToLink { 243 /// The filename of the bitcode file to link in. 244 std::string Filename; 245 /// If true, we set attributes functions in the bitcode library according to 246 /// our CodeGenOptions, much as we set attrs on functions that we generate 247 /// ourselves. 248 bool PropagateAttrs = false; 249 /// If true, we use LLVM module internalizer. 250 bool Internalize = false; 251 /// Bitwise combination of llvm::Linker::Flags, passed to the LLVM linker. 252 unsigned LinkFlags = 0; 253 }; 254 255 /// The files specified here are linked in to the module before optimizations. 256 std::vector<BitcodeFileToLink> LinkBitcodeFiles; 257 258 /// The user provided name for the "main file", if non-empty. This is useful 259 /// in situations where the input file name does not match the original input 260 /// file, for example with -save-temps. 261 std::string MainFileName; 262 263 /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name 264 /// attribute in the skeleton CU. 265 std::string SplitDwarfFile; 266 267 /// Output filename for the split debug info, not used in the skeleton CU. 268 std::string SplitDwarfOutput; 269 270 /// Output filename used in the COFF debug information. 271 std::string ObjectFilenameForDebug; 272 273 /// The name of the relocation model to use. 274 llvm::Reloc::Model RelocationModel; 275 276 /// If not an empty string, trap intrinsics are lowered to calls to this 277 /// function instead of to trap instructions. 278 std::string TrapFuncName; 279 280 /// A list of dependent libraries. 281 std::vector<std::string> DependentLibraries; 282 283 /// A list of linker options to embed in the object file. 284 std::vector<std::string> LinkerOptions; 285 286 /// Name of the profile file to use as output for -fprofile-instr-generate, 287 /// -fprofile-generate, and -fcs-profile-generate. 288 std::string InstrProfileOutput; 289 290 /// Name of the patchable function entry section with 291 /// -fpatchable-function-entry. 292 std::string PatchableFunctionEntrySection; 293 294 /// Name of the profile file to use with -fprofile-sample-use. 295 std::string SampleProfileFile; 296 297 /// Name of the profile file to use as output for with -fmemory-profile. 298 std::string MemoryProfileOutput; 299 300 /// Name of the profile file to use as input for -fmemory-profile-use. 301 std::string MemoryProfileUsePath; 302 303 /// Name of the profile file to use as input for -fprofile-instr-use 304 std::string ProfileInstrumentUsePath; 305 306 /// Name of the profile remapping file to apply to the profile data supplied 307 /// by -fprofile-sample-use or -fprofile-instr-use. 308 std::string ProfileRemappingFile; 309 310 /// Name of the function summary index file to use for ThinLTO function 311 /// importing. 312 std::string ThinLTOIndexFile; 313 314 /// Name of a file that can optionally be written with minimized bitcode 315 /// to be used as input for the ThinLTO thin link step, which only needs 316 /// the summary and module symbol table (and not, e.g. any debug metadata). 317 std::string ThinLinkBitcodeFile; 318 319 /// Prefix to use for -save-temps output. 320 std::string SaveTempsFilePrefix; 321 322 /// Name of file passed with -fcuda-include-gpubinary option to forward to 323 /// CUDA runtime back-end for incorporating them into host-side object file. 324 std::string CudaGpuBinaryFileName; 325 326 /// List of filenames passed in using the -fembed-offload-object option. These 327 /// are offloading binaries containing device images and metadata. 328 std::vector<std::string> OffloadObjects; 329 330 /// The name of the file to which the backend should save YAML optimization 331 /// records. 332 std::string OptRecordFile; 333 334 /// The regex that filters the passes that should be saved to the optimization 335 /// records. 336 std::string OptRecordPasses; 337 338 /// The format used for serializing remarks (default: YAML) 339 std::string OptRecordFormat; 340 341 /// The name of the partition that symbols are assigned to, specified with 342 /// -fsymbol-partition (see https://lld.llvm.org/Partitions.html). 343 std::string SymbolPartition; 344 345 /// If non-empty, allow the compiler to assume that the given source file 346 /// identifier is unique at link time. 347 std::string UniqueSourceFileIdentifier; 348 349 enum RemarkKind { 350 RK_Missing, // Remark argument not present on the command line. 351 RK_Enabled, // Remark enabled via '-Rgroup'. 352 RK_EnabledEverything, // Remark enabled via '-Reverything'. 353 RK_Disabled, // Remark disabled via '-Rno-group'. 354 RK_DisabledEverything, // Remark disabled via '-Rno-everything'. 355 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'. 356 }; 357 358 /// Optimization remark with an optional regular expression pattern. 359 struct OptRemark { 360 RemarkKind Kind = RK_Missing; 361 std::string Pattern; 362 std::shared_ptr<llvm::Regex> Regex; 363 364 /// By default, optimization remark is missing. 365 OptRemark() = default; 366 367 /// Returns true iff the optimization remark holds a valid regular 368 /// expression. hasValidPatternOptRemark369 bool hasValidPattern() const { return Regex != nullptr; } 370 371 /// Matches the given string against the regex, if there is some. patternMatchesOptRemark372 bool patternMatches(StringRef String) const { 373 return hasValidPattern() && Regex->match(String); 374 } 375 }; 376 377 /// Selected optimizations for which we should enable optimization remarks. 378 /// Transformation passes whose name matches the contained (optional) regular 379 /// expression (and support this feature), will emit a diagnostic whenever 380 /// they perform a transformation. 381 OptRemark OptimizationRemark; 382 383 /// Selected optimizations for which we should enable missed optimization 384 /// remarks. Transformation passes whose name matches the contained (optional) 385 /// regular expression (and support this feature), will emit a diagnostic 386 /// whenever they tried but failed to perform a transformation. 387 OptRemark OptimizationRemarkMissed; 388 389 /// Selected optimizations for which we should enable optimization analyses. 390 /// Transformation passes whose name matches the contained (optional) regular 391 /// expression (and support this feature), will emit a diagnostic whenever 392 /// they want to explain why they decided to apply or not apply a given 393 /// transformation. 394 OptRemark OptimizationRemarkAnalysis; 395 396 /// Set of sanitizer checks that are non-fatal (i.e. execution should be 397 /// continued when possible). 398 SanitizerSet SanitizeRecover; 399 400 /// Set of sanitizer checks that trap rather than diagnose. 401 SanitizerSet SanitizeTrap; 402 403 /// Set of sanitizer checks that can merge handlers (smaller code size at 404 /// the expense of debuggability). 405 SanitizerSet SanitizeMergeHandlers; 406 407 /// Set of thresholds in a range [0.0, 1.0]: the top hottest code responsible 408 /// for the given fraction of PGO counters will be excluded from sanitization 409 /// (0.0 [default] to skip none, 1.0 to skip all). 410 SanitizerMaskCutoffs SanitizeSkipHotCutoffs; 411 412 /// Set of sanitizer checks, for which the instrumentation will be annotated 413 /// with extra debug info. 414 SanitizerSet SanitizeAnnotateDebugInfo; 415 416 std::optional<double> AllowRuntimeCheckSkipHotCutoff; 417 418 /// List of backend command-line options for -fembed-bitcode. 419 std::vector<uint8_t> CmdArgs; 420 421 /// A list of all -fno-builtin-* function names (e.g., memset). 422 std::vector<std::string> NoBuiltinFuncs; 423 424 std::vector<std::string> Reciprocals; 425 426 /// Configuration for pointer-signing. 427 PointerAuthOptions PointerAuth; 428 429 /// The preferred width for auto-vectorization transforms. This is intended to 430 /// override default transforms based on the width of the architected vector 431 /// registers. 432 std::string PreferVectorWidth; 433 434 /// Set of XRay instrumentation kinds to emit. 435 XRayInstrSet XRayInstrumentationBundle; 436 437 std::vector<std::string> DefaultFunctionAttrs; 438 439 /// List of dynamic shared object files to be loaded as pass plugins. 440 std::vector<std::string> PassPlugins; 441 442 /// List of pass builder callbacks. 443 std::vector<std::function<void(llvm::PassBuilder &)>> PassBuilderCallbacks; 444 445 /// List of global variables explicitly specified by the user as toc-data. 446 std::vector<std::string> TocDataVarsUserSpecified; 447 448 /// List of global variables that over-ride the toc-data default. 449 std::vector<std::string> NoTocDataVars; 450 451 /// Path to allowlist file specifying which objects 452 /// (files, functions) should exclusively be instrumented 453 /// by sanitizer coverage pass. 454 std::vector<std::string> SanitizeCoverageAllowlistFiles; 455 456 /// The guard style used for stack protector to get a initial value, this 457 /// value usually be gotten from TLS or get from __stack_chk_guard, or some 458 /// other styles we may implement in the future. 459 std::string StackProtectorGuard; 460 461 /// The TLS base register when StackProtectorGuard is "tls", or register used 462 /// to store the stack canary for "sysreg". 463 /// On x86 this can be "fs" or "gs". 464 /// On AArch64 this can only be "sp_el0". 465 std::string StackProtectorGuardReg; 466 467 /// Specify a symbol to be the guard value. 468 std::string StackProtectorGuardSymbol; 469 470 /// Path to ignorelist file specifying which objects 471 /// (files, functions) listed for instrumentation by sanitizer 472 /// coverage pass should actually not be instrumented. 473 std::vector<std::string> SanitizeCoverageIgnorelistFiles; 474 475 /// Path to ignorelist file specifying which objects 476 /// (files, functions) listed for instrumentation by sanitizer 477 /// binary metadata pass should not be instrumented. 478 std::vector<std::string> SanitizeMetadataIgnorelistFiles; 479 480 /// Name of the stack usage file (i.e., .su file) if user passes 481 /// -fstack-usage. If empty, it can be implied that -fstack-usage is not 482 /// passed on the command line. 483 std::string StackUsageOutput; 484 485 /// Executable and command-line used to create a given CompilerInvocation. 486 /// Most of the time this will be the full -cc1 command. 487 const char *Argv0 = nullptr; 488 std::vector<std::string> CommandLineArgs; 489 490 /// The minimum hotness value a diagnostic needs in order to be included in 491 /// optimization diagnostics. 492 /// 493 /// The threshold is an Optional value, which maps to one of the 3 states: 494 /// 1. 0 => threshold disabled. All remarks will be printed. 495 /// 2. positive int => manual threshold by user. Remarks with hotness exceed 496 /// threshold will be printed. 497 /// 3. None => 'auto' threshold by user. The actual value is not 498 /// available at command line, but will be synced with 499 /// hotness threshold from profile summary during 500 /// compilation. 501 /// 502 /// If threshold option is not specified, it is disabled by default. 503 std::optional<uint64_t> DiagnosticsHotnessThreshold = 0; 504 505 /// The maximum percentage profiling weights can deviate from the expected 506 /// values in order to be included in misexpect diagnostics. 507 std::optional<uint32_t> DiagnosticsMisExpectTolerance = 0; 508 509 /// The name of a file to use with \c .secure_log_unique directives. 510 std::string AsSecureLogFile; 511 512 /// A list of functions that are replacable by the loader. 513 std::vector<std::string> LoaderReplaceableFunctionNames; 514 /// The name of a file that contains functions which will be compiled for 515 /// hotpatching. See -fms-secure-hotpatch-functions-file. 516 std::string MSSecureHotPatchFunctionsFile; 517 518 /// A list of functions which will be compiled for hotpatching. 519 /// See -fms-secure-hotpatch-functions-list. 520 std::vector<std::string> MSSecureHotPatchFunctionsList; 521 522 public: 523 // Define accessors/mutators for code generation options of enumeration type. 524 #define CODEGENOPT(Name, Bits, Default, Compatibility) 525 #define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \ 526 Type get##Name() const { return static_cast<Type>(Name); } \ 527 void set##Name(Type Value) { Name = static_cast<unsigned>(Value); } 528 #include "clang/Basic/CodeGenOptions.def" 529 530 CodeGenOptions(); 531 getNoBuiltinFuncs()532 const std::vector<std::string> &getNoBuiltinFuncs() const { 533 return NoBuiltinFuncs; 534 } 535 536 /// Check if Clang profile instrumenation is on. hasProfileClangInstr()537 bool hasProfileClangInstr() const { 538 return getProfileInstr() == 539 llvm::driver::ProfileInstrKind::ProfileClangInstr; 540 } 541 542 /// Check if IR level profile instrumentation is on. hasProfileIRInstr()543 bool hasProfileIRInstr() const { 544 return getProfileInstr() == llvm::driver::ProfileInstrKind::ProfileIRInstr; 545 } 546 547 /// Check if CS IR level profile instrumentation is on. hasProfileCSIRInstr()548 bool hasProfileCSIRInstr() const { 549 return getProfileInstr() == 550 llvm::driver::ProfileInstrKind::ProfileCSIRInstr; 551 } 552 553 /// Check if any form of instrumentation is on. hasProfileInstr()554 bool hasProfileInstr() const { 555 return getProfileInstr() != llvm::driver::ProfileInstrKind::ProfileNone; 556 } 557 558 /// Check if Clang profile use is on. hasProfileClangUse()559 bool hasProfileClangUse() const { 560 return getProfileUse() == llvm::driver::ProfileInstrKind::ProfileClangInstr; 561 } 562 563 /// Check if IR level profile use is on. hasProfileIRUse()564 bool hasProfileIRUse() const { 565 return getProfileUse() == llvm::driver::ProfileInstrKind::ProfileIRInstr || 566 getProfileUse() == llvm::driver::ProfileInstrKind::ProfileCSIRInstr; 567 } 568 569 /// Check if CSIR profile use is on. hasProfileCSIRUse()570 bool hasProfileCSIRUse() const { 571 return getProfileUse() == llvm::driver::ProfileInstrKind::ProfileCSIRInstr; 572 } 573 574 /// Check if type and variable info should be emitted. hasReducedDebugInfo()575 bool hasReducedDebugInfo() const { 576 return getDebugInfo() >= llvm::codegenoptions::DebugInfoConstructor; 577 } 578 579 /// Check if maybe unused type info should be emitted. hasMaybeUnusedDebugInfo()580 bool hasMaybeUnusedDebugInfo() const { 581 return getDebugInfo() >= llvm::codegenoptions::UnusedTypeInfo; 582 } 583 584 // Check if any one of SanitizeCoverage* is enabled. hasSanitizeCoverage()585 bool hasSanitizeCoverage() const { 586 return SanitizeCoverageType || SanitizeCoverageIndirectCalls || 587 SanitizeCoverageTraceCmp || SanitizeCoverageTraceLoads || 588 SanitizeCoverageTraceStores || SanitizeCoverageControlFlow; 589 } 590 591 // Check if any one of SanitizeBinaryMetadata* is enabled. hasSanitizeBinaryMetadata()592 bool hasSanitizeBinaryMetadata() const { 593 return SanitizeBinaryMetadataCovered || SanitizeBinaryMetadataAtomics || 594 SanitizeBinaryMetadataUAR; 595 } 596 597 /// Reset all of the options that are not considered when building a 598 /// module. 599 void resetNonModularOptions(StringRef ModuleFormat); 600 601 // Is the given function name one of the functions that can be replaced by the 602 // loader? isLoaderReplaceableFunctionName(StringRef FuncName)603 bool isLoaderReplaceableFunctionName(StringRef FuncName) const { 604 return llvm::is_contained(LoaderReplaceableFunctionNames, FuncName); 605 } 606 }; 607 608 } // end namespace clang 609 610 #endif 611