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