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