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/DebugInfoOptions.h"
17 #include "clang/Basic/Sanitizers.h"
18 #include "clang/Basic/XRayInstr.h"
19 #include "llvm/ADT/FloatingPointMode.h"
20 #include "llvm/Support/CodeGen.h"
21 #include "llvm/Support/Regex.h"
22 #include "llvm/Target/TargetOptions.h"
23 #include <map>
24 #include <memory>
25 #include <string>
26 #include <vector>
27 
28 namespace clang {
29 
30 /// Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure
31 /// that this large collection of bitfields is a trivial class type.
32 class CodeGenOptionsBase {
33 public:
34 #define CODEGENOPT(Name, Bits, Default) unsigned Name : Bits;
35 #define ENUM_CODEGENOPT(Name, Type, Bits, Default)
36 #include "clang/Basic/CodeGenOptions.def"
37 
38 protected:
39 #define CODEGENOPT(Name, Bits, Default)
40 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) unsigned Name : Bits;
41 #include "clang/Basic/CodeGenOptions.def"
42 };
43 
44 /// CodeGenOptions - Track various options which control how the code
45 /// is optimized and passed to the backend.
46 class CodeGenOptions : public CodeGenOptionsBase {
47 public:
48   enum InliningMethod {
49     NormalInlining,     // Use the standard function inlining pass.
50     OnlyHintInlining,   // Inline only (implicitly) hinted functions.
51     OnlyAlwaysInlining  // Only run the always inlining pass.
52   };
53 
54   enum VectorLibrary {
55     NoLibrary,  // Don't use any vector library.
56     Accelerate, // Use the Accelerate framework.
57     LIBMVEC,    // GLIBC vector math library.
58     MASSV,      // IBM MASS vector library.
59     SVML        // Intel short vector math library.
60   };
61 
62   enum ObjCDispatchMethodKind {
63     Legacy = 0,
64     NonLegacy = 1,
65     Mixed = 2
66   };
67 
68   enum TLSModel {
69     GeneralDynamicTLSModel,
70     LocalDynamicTLSModel,
71     InitialExecTLSModel,
72     LocalExecTLSModel
73   };
74 
75   /// Clang versions with different platform ABI conformance.
76   enum class ClangABI {
77     /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
78     /// (SVN r257626). This causes <1 x long long> to be passed in an
79     /// integer register instead of an SSE register on x64_64.
80     Ver3_8,
81 
82     /// Attempt to be ABI-compatible with code generated by Clang 4.0.x
83     /// (SVN r291814). This causes move operations to be ignored when
84     /// determining whether a class type can be passed or returned directly.
85     Ver4,
86 
87     /// Conform to the underlying platform's C and C++ ABIs as closely
88     /// as we can.
89     Latest
90   };
91 
92   enum StructReturnConventionKind {
93     SRCK_Default,  // No special option was passed.
94     SRCK_OnStack,  // Small structs on the stack (-fpcc-struct-return).
95     SRCK_InRegs    // Small structs in registers (-freg-struct-return).
96   };
97 
98   enum ProfileInstrKind {
99     ProfileNone,       // Profile instrumentation is turned off.
100     ProfileClangInstr, // Clang instrumentation to generate execution counts
101                        // to use with PGO.
102     ProfileIRInstr,    // IR level PGO instrumentation in LLVM.
103     ProfileCSIRInstr, // IR level PGO context sensitive instrumentation in LLVM.
104   };
105 
106   enum EmbedBitcodeKind {
107     Embed_Off,      // No embedded bitcode.
108     Embed_All,      // Embed both bitcode and commandline in the output.
109     Embed_Bitcode,  // Embed just the bitcode in the output.
110     Embed_Marker    // Embed a marker as a placeholder for bitcode.
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   enum class FramePointerKind {
130     None,        // Omit all frame pointers.
131     NonLeaf,     // Keep non-leaf frame pointers.
132     All,         // Keep all frame pointers.
133   };
134 
135   /// The code model to use (-mcmodel).
136   std::string CodeModel;
137 
138   /// The filename with path we use for coverage data files. The runtime
139   /// allows further manipulation with the GCOV_PREFIX and GCOV_PREFIX_STRIP
140   /// environment variables.
141   std::string CoverageDataFile;
142 
143   /// The filename with path we use for coverage notes files.
144   std::string CoverageNotesFile;
145 
146   /// Regexes separated by a semi-colon to filter the files to instrument.
147   std::string ProfileFilterFiles;
148 
149   /// Regexes separated by a semi-colon to filter the files to not instrument.
150   std::string ProfileExcludeFiles;
151 
152   /// The version string to put into coverage files.
153   char CoverageVersion[4];
154 
155   /// Enable additional debugging information.
156   std::string DebugPass;
157 
158   /// The string to embed in debug information as the current working directory.
159   std::string DebugCompilationDir;
160 
161   /// The string to embed in the debug information for the compile unit, if
162   /// non-empty.
163   std::string DwarfDebugFlags;
164 
165   /// The string containing the commandline for the llvm.commandline metadata,
166   /// if non-empty.
167   std::string RecordCommandLine;
168 
169   std::map<std::string, std::string> DebugPrefixMap;
170 
171   /// The ABI to use for passing floating point arguments.
172   std::string FloatABI;
173 
174   /// The floating-point denormal mode to use.
175   llvm::DenormalMode FPDenormalMode = llvm::DenormalMode::getIEEE();
176 
177   /// The floating-point denormal mode to use, for float.
178   llvm::DenormalMode FP32DenormalMode = llvm::DenormalMode::getIEEE();
179 
180   /// The float precision limit to use, if non-empty.
181   std::string LimitFloatPrecision;
182 
183   struct BitcodeFileToLink {
184     /// The filename of the bitcode file to link in.
185     std::string Filename;
186     /// If true, we set attributes functions in the bitcode library according to
187     /// our CodeGenOptions, much as we set attrs on functions that we generate
188     /// ourselves.
189     bool PropagateAttrs = false;
190     /// If true, we use LLVM module internalizer.
191     bool Internalize = false;
192     /// Bitwise combination of llvm::Linker::Flags, passed to the LLVM linker.
193     unsigned LinkFlags = 0;
194   };
195 
196   /// The files specified here are linked in to the module before optimizations.
197   std::vector<BitcodeFileToLink> LinkBitcodeFiles;
198 
199   /// The user provided name for the "main file", if non-empty. This is useful
200   /// in situations where the input file name does not match the original input
201   /// file, for example with -save-temps.
202   std::string MainFileName;
203 
204   /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
205   /// attribute in the skeleton CU.
206   std::string SplitDwarfFile;
207 
208   /// Output filename for the split debug info, not used in the skeleton CU.
209   std::string SplitDwarfOutput;
210 
211   /// The name of the relocation model to use.
212   llvm::Reloc::Model RelocationModel;
213 
214   /// If not an empty string, trap intrinsics are lowered to calls to this
215   /// function instead of to trap instructions.
216   std::string TrapFuncName;
217 
218   /// A list of dependent libraries.
219   std::vector<std::string> DependentLibraries;
220 
221   /// A list of linker options to embed in the object file.
222   std::vector<std::string> LinkerOptions;
223 
224   /// Name of the profile file to use as output for -fprofile-instr-generate,
225   /// -fprofile-generate, and -fcs-profile-generate.
226   std::string InstrProfileOutput;
227 
228   /// Name of the profile file to use with -fprofile-sample-use.
229   std::string SampleProfileFile;
230 
231   /// Name of the profile file to use as output for with -fmemory-profile.
232   std::string MemoryProfileOutput;
233 
234   /// Name of the profile file to use as input for -fprofile-instr-use
235   std::string ProfileInstrumentUsePath;
236 
237   /// Name of the profile remapping file to apply to the profile data supplied
238   /// by -fprofile-sample-use or -fprofile-instr-use.
239   std::string ProfileRemappingFile;
240 
241   /// Name of the function summary index file to use for ThinLTO function
242   /// importing.
243   std::string ThinLTOIndexFile;
244 
245   /// Name of a file that can optionally be written with minimized bitcode
246   /// to be used as input for the ThinLTO thin link step, which only needs
247   /// the summary and module symbol table (and not, e.g. any debug metadata).
248   std::string ThinLinkBitcodeFile;
249 
250   /// Prefix to use for -save-temps output.
251   std::string SaveTempsFilePrefix;
252 
253   /// Name of file passed with -fcuda-include-gpubinary option to forward to
254   /// CUDA runtime back-end for incorporating them into host-side object file.
255   std::string CudaGpuBinaryFileName;
256 
257   /// The name of the file to which the backend should save YAML optimization
258   /// records.
259   std::string OptRecordFile;
260 
261   /// The regex that filters the passes that should be saved to the optimization
262   /// records.
263   std::string OptRecordPasses;
264 
265   /// The format used for serializing remarks (default: YAML)
266   std::string OptRecordFormat;
267 
268   /// The name of the partition that symbols are assigned to, specified with
269   /// -fsymbol-partition (see https://lld.llvm.org/Partitions.html).
270   std::string SymbolPartition;
271 
272   /// Regular expression to select optimizations for which we should enable
273   /// optimization remarks. Transformation passes whose name matches this
274   /// expression (and support this feature), will emit a diagnostic
275   /// whenever they perform a transformation. This is enabled by the
276   /// -Rpass=regexp flag.
277   std::shared_ptr<llvm::Regex> OptimizationRemarkPattern;
278 
279   /// Regular expression to select optimizations for which we should enable
280   /// missed optimization remarks. Transformation passes whose name matches this
281   /// expression (and support this feature), will emit a diagnostic
282   /// whenever they tried but failed to perform a transformation. This is
283   /// enabled by the -Rpass-missed=regexp flag.
284   std::shared_ptr<llvm::Regex> OptimizationRemarkMissedPattern;
285 
286   /// Regular expression to select optimizations for which we should enable
287   /// optimization analyses. Transformation passes whose name matches this
288   /// expression (and support this feature), will emit a diagnostic
289   /// whenever they want to explain why they decided to apply or not apply
290   /// a given transformation. This is enabled by the -Rpass-analysis=regexp
291   /// flag.
292   std::shared_ptr<llvm::Regex> OptimizationRemarkAnalysisPattern;
293 
294   /// Set of files defining the rules for the symbol rewriting.
295   std::vector<std::string> RewriteMapFiles;
296 
297   /// Set of sanitizer checks that are non-fatal (i.e. execution should be
298   /// continued when possible).
299   SanitizerSet SanitizeRecover;
300 
301   /// Set of sanitizer checks that trap rather than diagnose.
302   SanitizerSet SanitizeTrap;
303 
304   /// List of backend command-line options for -fembed-bitcode.
305   std::vector<uint8_t> CmdArgs;
306 
307   /// A list of all -fno-builtin-* function names (e.g., memset).
308   std::vector<std::string> NoBuiltinFuncs;
309 
310   std::vector<std::string> Reciprocals;
311 
312   /// The preferred width for auto-vectorization transforms. This is intended to
313   /// override default transforms based on the width of the architected vector
314   /// registers.
315   std::string PreferVectorWidth;
316 
317   /// Set of XRay instrumentation kinds to emit.
318   XRayInstrSet XRayInstrumentationBundle;
319 
320   std::vector<std::string> DefaultFunctionAttrs;
321 
322   /// List of dynamic shared object files to be loaded as pass plugins.
323   std::vector<std::string> PassPlugins;
324 
325   /// Path to allowlist file specifying which objects
326   /// (files, functions) should exclusively be instrumented
327   /// by sanitizer coverage pass.
328   std::vector<std::string> SanitizeCoverageAllowlistFiles;
329 
330   /// The guard style used for stack protector to get a initial value, this
331   /// value usually be gotten from TLS or get from __stack_chk_guard, or some
332   /// other styles we may implement in the future.
333   std::string StackProtectorGuard;
334 
335   /// The TLS base register when StackProtectorGuard is "tls".
336   /// On x86 this can be "fs" or "gs".
337   std::string StackProtectorGuardReg;
338 
339   /// Path to blocklist file specifying which objects
340   /// (files, functions) listed for instrumentation by sanitizer
341   /// coverage pass should actually not be instrumented.
342   std::vector<std::string> SanitizeCoverageBlocklistFiles;
343 
344   /// Executable and command-line used to create a given CompilerInvocation.
345   /// Most of the time this will be the full -cc1 command.
346   const char *Argv0 = nullptr;
347   ArrayRef<const char *> CommandLineArgs;
348 
349   /// The minimum hotness value a diagnostic needs in order to be included in
350   /// optimization diagnostics.
351   ///
352   /// The threshold is an Optional value, which maps to one of the 3 states:
353   /// 1. 0            => threshold disabled. All remarks will be printed.
354   /// 2. positive int => manual threshold by user. Remarks with hotness exceed
355   ///                    threshold will be printed.
356   /// 3. None         => 'auto' threshold by user. The actual value is not
357   ///                    available at command line, but will be synced with
358   ///                    hotness threshold from profile summary during
359   ///                    compilation.
360   ///
361   /// If threshold option is not specified, it is disabled by default.
362   Optional<uint64_t> DiagnosticsHotnessThreshold = 0;
363 
364 public:
365   // Define accessors/mutators for code generation options of enumeration type.
366 #define CODEGENOPT(Name, Bits, Default)
367 #define ENUM_CODEGENOPT(Name, Type, Bits, Default) \
368   Type get##Name() const { return static_cast<Type>(Name); } \
369   void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
370 #include "clang/Basic/CodeGenOptions.def"
371 
372   CodeGenOptions();
373 
374   /// Is this a libc/libm function that is no longer recognized as a
375   /// builtin because a -fno-builtin-* option has been specified?
376   bool isNoBuiltinFunc(const char *Name) const;
377 
getNoBuiltinFuncs()378   const std::vector<std::string> &getNoBuiltinFuncs() const {
379     return NoBuiltinFuncs;
380   }
381 
382   /// Check if Clang profile instrumenation is on.
hasProfileClangInstr()383   bool hasProfileClangInstr() const {
384     return getProfileInstr() == ProfileClangInstr;
385   }
386 
387   /// Check if IR level profile instrumentation is on.
hasProfileIRInstr()388   bool hasProfileIRInstr() const {
389     return getProfileInstr() == ProfileIRInstr;
390   }
391 
392   /// Check if CS IR level profile instrumentation is on.
hasProfileCSIRInstr()393   bool hasProfileCSIRInstr() const {
394     return getProfileInstr() == ProfileCSIRInstr;
395   }
396 
397   /// Check if Clang profile use is on.
hasProfileClangUse()398   bool hasProfileClangUse() const {
399     return getProfileUse() == ProfileClangInstr;
400   }
401 
402   /// Check if IR level profile use is on.
hasProfileIRUse()403   bool hasProfileIRUse() const {
404     return getProfileUse() == ProfileIRInstr ||
405            getProfileUse() == ProfileCSIRInstr;
406   }
407 
408   /// Check if CSIR profile use is on.
hasProfileCSIRUse()409   bool hasProfileCSIRUse() const { return getProfileUse() == ProfileCSIRInstr; }
410 
411   /// Check if type and variable info should be emitted.
hasReducedDebugInfo()412   bool hasReducedDebugInfo() const {
413     return getDebugInfo() >= codegenoptions::DebugInfoConstructor;
414   }
415 
416   /// Check if maybe unused type info should be emitted.
hasMaybeUnusedDebugInfo()417   bool hasMaybeUnusedDebugInfo() const {
418     return getDebugInfo() >= codegenoptions::UnusedTypeInfo;
419   }
420 };
421 
422 }  // end namespace clang
423 
424 #endif
425