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 "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
24#include <map>
25#include <memory>
26#include <string>
27#include <vector>
28
29namespace clang {
30
31/// Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure
32/// that this large collection of bitfields is a trivial class type.
33class CodeGenOptionsBase {
34 friend class CompilerInvocation;
35
36public:
37#define CODEGENOPT(Name, Bits, Default) unsigned Name : Bits;
38#define ENUM_CODEGENOPT(Name, Type, Bits, Default)
39#include "clang/Basic/CodeGenOptions.def"
40
41protected:
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.
49class CodeGenOptions : public CodeGenOptionsBase {
50public:
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 };
64
65 enum ObjCDispatchMethodKind {
66 Legacy = 0,
67 NonLegacy = 1,
68 Mixed = 2
69 };
70
71 enum TLSModel {
72 GeneralDynamicTLSModel,
73 LocalDynamicTLSModel,
74 InitialExecTLSModel,
75 LocalExecTLSModel
76 };
77
78 /// Clang versions with different platform ABI conformance.
79 enum class ClangABI {
80 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
81 /// (SVN r257626). This causes <1 x long long> to be passed in an
82 /// integer register instead of an SSE register on x64_64.
83 Ver3_8,
84
85 /// Attempt to be ABI-compatible with code generated by Clang 4.0.x
86 /// (SVN r291814). This causes move operations to be ignored when
87 /// determining whether a class type can be passed or returned directly.
88 Ver4,
89
90 /// Conform to the underlying platform's C and C++ ABIs as closely
91 /// as we can.
92 Latest
93 };
94
95 enum StructReturnConventionKind {
96 SRCK_Default, // No special option was passed.
97 SRCK_OnStack, // Small structs on the stack (-fpcc-struct-return).
98 SRCK_InRegs // Small structs in registers (-freg-struct-return).
99 };
100
101 enum ProfileInstrKind {
102 ProfileNone, // Profile instrumentation is turned off.
103 ProfileClangInstr, // Clang instrumentation to generate execution counts
104 // to use with PGO.
105 ProfileIRInstr, // IR level PGO instrumentation in LLVM.
106 ProfileCSIRInstr, // IR level PGO context sensitive instrumentation in LLVM.
107 };
108
109 enum EmbedBitcodeKind {
110 Embed_Off, // No embedded bitcode.
111 Embed_All, // Embed both bitcode and commandline in the output.
112 Embed_Bitcode, // Embed just the bitcode in the output.
113 Embed_Marker // Embed a marker as a placeholder for bitcode.
114 };
115
116 // This field stores one of the allowed values for the option
117 // -fbasic-block-sections=. The allowed values with this option are:
118 // {"labels", "all", "list=<file>", "none"}.
119 //
120 // "labels": Only generate basic block symbols (labels) for all basic
121 // blocks, do not generate unique sections for basic blocks.
122 // Use the machine basic block id in the symbol name to
123 // associate profile info from virtual address to machine
124 // basic block.
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/labels 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 NonLeaf, // Keep non-leaf frame pointers.
141 All, // Keep all frame pointers.
142 };
143
144 enum FiniteLoopsKind {
145 Language, // Not specified, use language standard.
146 Always, // All loops are assumed to be finite.
147 Never, // No loop is assumed to be finite.
148 };
149
150 /// The code model to use (-mcmodel).
151 std::string CodeModel;
152
153 /// The filename with path we use for coverage data files. The runtime
154 /// allows further manipulation with the GCOV_PREFIX and GCOV_PREFIX_STRIP
155 /// environment variables.
156 std::string CoverageDataFile;
157
158 /// The filename with path we use for coverage notes files.
159 std::string CoverageNotesFile;
160
161 /// Regexes separated by a semi-colon to filter the files to instrument.
162 std::string ProfileFilterFiles;
163
164 /// Regexes separated by a semi-colon to filter the files to not instrument.
165 std::string ProfileExcludeFiles;
166
167 /// The version string to put into coverage files.
168 char CoverageVersion[4];
169
170 /// Enable additional debugging information.
171 std::string DebugPass;
172
173 /// The string to embed in debug information as the current working directory.
174 std::string DebugCompilationDir;
175
176 /// The string to embed in coverage mapping as the current working directory.
177 std::string CoverageCompilationDir;
178
179 /// The string to embed in the debug information for the compile unit, if
180 /// non-empty.
181 std::string DwarfDebugFlags;
182
183 /// The string containing the commandline for the llvm.commandline metadata,
184 /// if non-empty.
185 std::string RecordCommandLine;
186
187 std::map<std::string, std::string> DebugPrefixMap;
188 std::map<std::string, std::string> CoveragePrefixMap;
189
190 /// The ABI to use for passing floating point arguments.
191 std::string FloatABI;
192
193 /// The file to use for dumping bug report by `Debugify` for original
194 /// debug info.
195 std::string DIBugsReportFilePath;
196
197 /// The floating-point denormal mode to use.
198 llvm::DenormalMode FPDenormalMode = llvm::DenormalMode::getIEEE();
199
200 /// The floating-point denormal mode to use, for float.
201 llvm::DenormalMode FP32DenormalMode = llvm::DenormalMode::getIEEE();
202
203 /// The float precision limit to use, if non-empty.
204 std::string LimitFloatPrecision;
205
206 struct BitcodeFileToLink {
207 /// The filename of the bitcode file to link in.
208 std::string Filename;
209 /// If true, we set attributes functions in the bitcode library according to
210 /// our CodeGenOptions, much as we set attrs on functions that we generate
211 /// ourselves.
212 bool PropagateAttrs = false;
213 /// If true, we use LLVM module internalizer.
214 bool Internalize = false;
215 /// Bitwise combination of llvm::Linker::Flags, passed to the LLVM linker.
216 unsigned LinkFlags = 0;
217 };
218
219 /// The files specified here are linked in to the module before optimizations.
220 std::vector<BitcodeFileToLink> LinkBitcodeFiles;
221
222 /// The user provided name for the "main file", if non-empty. This is useful
223 /// in situations where the input file name does not match the original input
224 /// file, for example with -save-temps.
225 std::string MainFileName;
226
227 /// The name for the split debug info file used for the DW_AT_[GNU_]dwo_name
228 /// attribute in the skeleton CU.
229 std::string SplitDwarfFile;
230
231 /// Output filename for the split debug info, not used in the skeleton CU.
232 std::string SplitDwarfOutput;
233
234 /// The name of the relocation model to use.
235 llvm::Reloc::Model RelocationModel;
236
237 /// If not an empty string, trap intrinsics are lowered to calls to this
238 /// function instead of to trap instructions.
239 std::string TrapFuncName;
240
241 /// A list of dependent libraries.
242 std::vector<std::string> DependentLibraries;
243
244 /// A list of linker options to embed in the object file.
245 std::vector<std::string> LinkerOptions;
246
247 /// Name of the profile file to use as output for -fprofile-instr-generate,
248 /// -fprofile-generate, and -fcs-profile-generate.
249 std::string InstrProfileOutput;
250
251 /// Name of the profile file to use with -fprofile-sample-use.
252 std::string SampleProfileFile;
253
254 /// Name of the profile file to use as output for with -fmemory-profile.
255 std::string MemoryProfileOutput;
256
257 /// Name of the profile file to use as input for -fprofile-instr-use
258 std::string ProfileInstrumentUsePath;
259
260 /// Name of the profile remapping file to apply to the profile data supplied
261 /// by -fprofile-sample-use or -fprofile-instr-use.
262 std::string ProfileRemappingFile;
263
264 /// Name of the function summary index file to use for ThinLTO function
265 /// importing.
266 std::string ThinLTOIndexFile;
267
268 /// Name of a file that can optionally be written with minimized bitcode
269 /// to be used as input for the ThinLTO thin link step, which only needs
270 /// the summary and module symbol table (and not, e.g. any debug metadata).
271 std::string ThinLinkBitcodeFile;
272
273 /// Prefix to use for -save-temps output.
274 std::string SaveTempsFilePrefix;
275
276 /// Name of file passed with -fcuda-include-gpubinary option to forward to
277 /// CUDA runtime back-end for incorporating them into host-side object file.
278 std::string CudaGpuBinaryFileName;
279
280 /// The name of the file to which the backend should save YAML optimization
281 /// records.
282 std::string OptRecordFile;
283
284 /// The regex that filters the passes that should be saved to the optimization
285 /// records.
286 std::string OptRecordPasses;
287
288 /// The format used for serializing remarks (default: YAML)
289 std::string OptRecordFormat;
290
291 /// The name of the partition that symbols are assigned to, specified with
292 /// -fsymbol-partition (see https://lld.llvm.org/Partitions.html).
293 std::string SymbolPartition;
294
295 enum RemarkKind {
296 RK_Missing, // Remark argument not present on the command line.
297 RK_Enabled, // Remark enabled via '-Rgroup'.
298 RK_EnabledEverything, // Remark enabled via '-Reverything'.
299 RK_Disabled, // Remark disabled via '-Rno-group'.
300 RK_DisabledEverything, // Remark disabled via '-Rno-everything'.
301 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
302 };
303
304 /// Optimization remark with an optional regular expression pattern.
305 struct OptRemark {
306 RemarkKind Kind;
307 std::string Pattern;
308 std::shared_ptr<llvm::Regex> Regex;
309
310 /// By default, optimization remark is missing.
311 OptRemark() : Kind(RK_Missing), Pattern(""), Regex(nullptr) {}
312
313 /// Returns true iff the optimization remark holds a valid regular
314 /// expression.
315 bool hasValidPattern() const { return Regex != nullptr; }
316
317 /// Matches the given string against the regex, if there is some.
318 bool patternMatches(StringRef String) const {
319 return hasValidPattern() && Regex->match(String);
320 }
321 };
322
323 /// Selected optimizations for which we should enable optimization remarks.
324 /// Transformation passes whose name matches the contained (optional) regular
325 /// expression (and support this feature), will emit a diagnostic whenever
326 /// they perform a transformation.
327 OptRemark OptimizationRemark;
328
329 /// Selected optimizations for which we should enable missed optimization
330 /// remarks. Transformation passes whose name matches the contained (optional)
331 /// regular expression (and support this feature), will emit a diagnostic
332 /// whenever they tried but failed to perform a transformation.
333 OptRemark OptimizationRemarkMissed;
334
335 /// Selected optimizations for which we should enable optimization analyses.
336 /// Transformation passes whose name matches the contained (optional) regular
337 /// expression (and support this feature), will emit a diagnostic whenever
338 /// they want to explain why they decided to apply or not apply a given
339 /// transformation.
340 OptRemark OptimizationRemarkAnalysis;
341
342 /// Set of files defining the rules for the symbol rewriting.
343 std::vector<std::string> RewriteMapFiles;
344
345 /// Set of sanitizer checks that are non-fatal (i.e. execution should be
346 /// continued when possible).
347 SanitizerSet SanitizeRecover;
348
349 /// Set of sanitizer checks that trap rather than diagnose.
350 SanitizerSet SanitizeTrap;
351
352 /// List of backend command-line options for -fembed-bitcode.
353 std::vector<uint8_t> CmdArgs;
354
355 /// A list of all -fno-builtin-* function names (e.g., memset).
356 std::vector<std::string> NoBuiltinFuncs;
357
358 std::vector<std::string> Reciprocals;
359
360 /// The preferred width for auto-vectorization transforms. This is intended to
361 /// override default transforms based on the width of the architected vector
362 /// registers.
363 std::string PreferVectorWidth;
364
365 /// Set of XRay instrumentation kinds to emit.
366 XRayInstrSet XRayInstrumentationBundle;
367
368 std::vector<std::string> DefaultFunctionAttrs;
369
370 /// List of dynamic shared object files to be loaded as pass plugins.
371 std::vector<std::string> PassPlugins;
372
373 /// Path to allowlist file specifying which objects
374 /// (files, functions) should exclusively be instrumented
375 /// by sanitizer coverage pass.
376 std::vector<std::string> SanitizeCoverageAllowlistFiles;
377
378 /// The guard style used for stack protector to get a initial value, this
379 /// value usually be gotten from TLS or get from __stack_chk_guard, or some
380 /// other styles we may implement in the future.
381 std::string StackProtectorGuard;
382
383 /// The TLS base register when StackProtectorGuard is "tls".
384 /// On x86 this can be "fs" or "gs".
385 std::string StackProtectorGuardReg;
386
387 /// Path to ignorelist file specifying which objects
388 /// (files, functions) listed for instrumentation by sanitizer
389 /// coverage pass should actually not be instrumented.
390 std::vector<std::string> SanitizeCoverageIgnorelistFiles;
391
392 /// Executable and command-line used to create a given CompilerInvocation.
393 /// Most of the time this will be the full -cc1 command.
394 const char *Argv0 = nullptr;
395 ArrayRef<const char *> CommandLineArgs;
396
397 /// The minimum hotness value a diagnostic needs in order to be included in
398 /// optimization diagnostics.
399 ///
400 /// The threshold is an Optional value, which maps to one of the 3 states:
401 /// 1. 0 => threshold disabled. All remarks will be printed.
402 /// 2. positive int => manual threshold by user. Remarks with hotness exceed
403 /// threshold will be printed.
404 /// 3. None => 'auto' threshold by user. The actual value is not
405 /// available at command line, but will be synced with
406 /// hotness threshold from profile summary during
407 /// compilation.
408 ///
409 /// If threshold option is not specified, it is disabled by default.
410 Optional<uint64_t> DiagnosticsHotnessThreshold = 0;
411
412public:
413 // Define accessors/mutators for code generation options of enumeration type.
414#define CODEGENOPT(Name, Bits, Default)
415#define ENUM_CODEGENOPT(Name, Type, Bits, Default) \
416 Type get##Name() const { return static_cast<Type>(Name); } \
417 void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
418#include "clang/Basic/CodeGenOptions.def"
419
420 CodeGenOptions();
421
422 const std::vector<std::string> &getNoBuiltinFuncs() const {
423 return NoBuiltinFuncs;
424 }
425
426 /// Check if Clang profile instrumenation is on.
427 bool hasProfileClangInstr() const {
428 return getProfileInstr() == ProfileClangInstr;
429 }
430
431 /// Check if IR level profile instrumentation is on.
432 bool hasProfileIRInstr() const {
433 return getProfileInstr() == ProfileIRInstr;
434 }
435
436 /// Check if CS IR level profile instrumentation is on.
437 bool hasProfileCSIRInstr() const {
438 return getProfileInstr() == ProfileCSIRInstr;
439 }
440
441 /// Check if Clang profile use is on.
442 bool hasProfileClangUse() const {
443 return getProfileUse() == ProfileClangInstr;
444 }
445
446 /// Check if IR level profile use is on.
447 bool hasProfileIRUse() const {
448 return getProfileUse() == ProfileIRInstr ||
449 getProfileUse() == ProfileCSIRInstr;
450 }
451
452 /// Check if CSIR profile use is on.
453 bool hasProfileCSIRUse() const { return getProfileUse() == ProfileCSIRInstr; }
454
455 /// Check if type and variable info should be emitted.
456 bool hasReducedDebugInfo() const {
457 return getDebugInfo() >= codegenoptions::DebugInfoConstructor;
458 }
459
460 /// Check if maybe unused type info should be emitted.
461 bool hasMaybeUnusedDebugInfo() const {
462 return getDebugInfo() >= codegenoptions::UnusedTypeInfo;
463 }
464};
465
466} // end namespace clang
467
468#endif
469