clang 23.0.0git
CompilerInvocation.h
Go to the documentation of this file.
1//===- CompilerInvocation.h - Compiler Invocation Helper Data ---*- 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#ifndef LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
10#define LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
11
16#include "clang/Basic/LLVM.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/IntrusiveRefCntPtr.h"
26#include "llvm/ADT/ScopeExit.h"
27
28#include <memory>
29#include <string>
30
31namespace llvm {
32
33class Triple;
34
35namespace opt {
36
37class ArgList;
38
39} // namespace opt
40
41namespace vfs {
42
43class FileSystem;
44
45} // namespace vfs
46
47} // namespace llvm
48
49namespace clang {
50
54class TargetOptions;
55
56namespace ssaf {
57class SSAFOptions;
58} // namespace ssaf
59
60// This lets us create the DiagnosticsEngine with a properly-filled-out
61// DiagnosticOptions instance.
62std::unique_ptr<DiagnosticOptions>
64
65/// Fill out Opts based on the options given in Args.
66///
67/// Args must have been created from the OptTable returned by
68/// createCC1OptTable().
69///
70/// When errors are encountered, return false and, if Diags is non-null,
71/// report the error(s).
72bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args,
73 DiagnosticsEngine *Diags = nullptr,
74 bool DefaultDiagColor = true);
75
76unsigned getOptimizationLevel(const llvm::opt::ArgList &Args, InputKind IK,
77 DiagnosticsEngine &Diags);
78
79unsigned getOptimizationLevelSize(const llvm::opt::ArgList &Args);
80
81/// The base class of CompilerInvocation. It keeps individual option objects
82/// behind reference-counted pointers, which is useful for clients that want to
83/// keep select option objects alive (even after CompilerInvocation gets
84/// destroyed) without making a copy.
86protected:
87 /// Options controlling the language variant.
88 std::shared_ptr<LangOptions> LangOpts;
89
90 /// Options controlling the target.
91 std::shared_ptr<TargetOptions> TargetOpts;
92
93 /// Options controlling the diagnostic engine.
94 std::shared_ptr<DiagnosticOptions> DiagnosticOpts;
95
96 /// Options controlling the \#include directive.
97 std::shared_ptr<HeaderSearchOptions> HSOpts;
98
99 /// Options controlling the preprocessor (aside from \#include handling).
100 std::shared_ptr<PreprocessorOptions> PPOpts;
101
102 /// Options controlling the static analyzer.
103 std::shared_ptr<AnalyzerOptions> AnalyzerOpts;
104
105 std::shared_ptr<MigratorOptions> MigratorOpts;
106
107 /// Options controlling API notes.
108 std::shared_ptr<APINotesOptions> APINotesOpts;
109
110 /// Options controlling IRgen and the backend.
111 std::shared_ptr<CodeGenOptions> CodeGenOpts;
112
113 /// Options controlling file system operations.
114 std::shared_ptr<FileSystemOptions> FSOpts;
115
116 /// Options controlling the frontend itself.
117 std::shared_ptr<FrontendOptions> FrontendOpts;
118
119 /// Options controlling dependency output.
120 std::shared_ptr<DependencyOutputOptions> DependencyOutputOpts;
121
122 /// Options controlling preprocessed output.
123 std::shared_ptr<PreprocessorOutputOptions> PreprocessorOutputOpts;
124
125 /// Options controlling the Scalable Static Analysis Framework (SSAF).
126 std::shared_ptr<ssaf::SSAFOptions> SSAFOpts;
127
128 /// Dummy tag type whose instance can be passed into the constructor to
129 /// prevent creation of the reference-counted option objects.
131
132 /// Tag for the shallow-copy constructor below.
134
144
145public:
146 /// Const getters.
147 /// @{
148 const LangOptions &getLangOpts() const { return *LangOpts; }
149 const TargetOptions &getTargetOpts() const { return *TargetOpts; }
153 const AnalyzerOptions &getAnalyzerOpts() const { return *AnalyzerOpts; }
154 const MigratorOptions &getMigratorOpts() const { return *MigratorOpts; }
155 const APINotesOptions &getAPINotesOpts() const { return *APINotesOpts; }
156 const CodeGenOptions &getCodeGenOpts() const { return *CodeGenOpts; }
157 const FileSystemOptions &getFileSystemOpts() const { return *FSOpts; }
158 const FrontendOptions &getFrontendOpts() const { return *FrontendOpts; }
165 const ssaf::SSAFOptions &getSSAFOpts() const { return *SSAFOpts; }
166 /// @}
167
168 /// Command line generation.
169 /// @{
170 using StringAllocator = llvm::function_ref<const char *(const Twine &)>;
171 /// Generate cc1-compatible command line arguments from this instance.
172 ///
173 /// \param [out] Args - The generated arguments. Note that the caller is
174 /// responsible for inserting the path to the clang executable and "-cc1" if
175 /// desired.
176 /// \param SA - A function that given a Twine can allocate storage for a given
177 /// command line argument and return a pointer to the newly allocated string.
178 /// The returned pointer is what gets appended to Args.
180 StringAllocator SA) const {
181 generateCC1CommandLine([&](const Twine &Arg) {
182 // No need to allocate static string literals.
183 Args.push_back(Arg.isSingleStringLiteral()
184 ? Arg.getSingleStringRef().data()
185 : SA(Arg));
186 });
187 }
188
189 using ArgumentConsumer = llvm::function_ref<void(const Twine &)>;
190 /// Generate cc1-compatible command line arguments from this instance.
191 ///
192 /// \param Consumer - Callback that gets invoked for every single generated
193 /// command line argument.
194 void generateCC1CommandLine(ArgumentConsumer Consumer) const;
195
196 /// Generate cc1-compatible command line arguments from this instance,
197 /// wrapping the result as a std::vector<std::string>.
198 ///
199 /// This is a (less-efficient) wrapper over generateCC1CommandLine().
200 std::vector<std::string> getCC1CommandLine() const;
201
202private:
203 /// Generate command line options from DiagnosticOptions.
204 static void GenerateDiagnosticArgs(const DiagnosticOptions &Opts,
205 ArgumentConsumer Consumer,
206 bool DefaultDiagColor);
207
208 /// Generate command line options from LangOptions.
209 static void GenerateLangArgs(const LangOptions &Opts,
210 ArgumentConsumer Consumer, const llvm::Triple &T,
211 InputKind IK);
212
213 // Generate command line options from CodeGenOptions.
214 static void GenerateCodeGenArgs(const CodeGenOptions &Opts,
215 ArgumentConsumer Consumer,
216 const llvm::Triple &T,
217 const std::string &OutputFile,
218 const LangOptions *LangOpts);
219 /// @}
220};
221
223
224/// Helper class for holding the data necessary to invoke the compiler.
225///
226/// This class is designed to represent an abstract "invocation" of the
227/// compiler, including data such as the include paths, the code generation
228/// options, the warning flags, and so on.
230public:
239 return *this;
240 }
242
245
246 /// Move-construct/move-assign from a \c CowCompilerInvocation. Steals the
247 /// (potentially copy-on-written) option group pointers without deep-copying;
248 /// \p X is left empty. Useful to receive results of mutating a temporary
249 /// Cow alias back into a \c CompilerInvocation.
250 /// @{
253 /// @}
254
255 /// Const getters.
256 /// @{
257 // Note: These need to be pulled in manually. Otherwise, they get hidden by
258 // the mutable getters with the same names.
273 /// @}
274
275 /// Mutable getters.
276 /// @{
295 /// @}
296
297 /// Invokes the \a Fn with CowCompilerInvocation representing \c this.
298 /// The \a Fn must not directly modify \c this.
299 /// The provided \c CowCompilerInvocation must not escape \a Fn.
300 template <class R>
301 R withCowRef(llvm::function_ref<R(CowCompilerInvocation &)> Fn);
302 template <class R>
303 R withCowRef(llvm::function_ref<R(const CowCompilerInvocation &)> Fn) const;
304
305 /// Create a compiler invocation from a list of input options.
306 /// \returns true on success.
307 ///
308 /// \returns false if an error was encountered while parsing the arguments
309 /// and attempts to recover and continue parsing the rest of the arguments.
310 /// The recovery is best-effort and only guarantees that \p Res will end up in
311 /// one of the vaild-to-access (albeit arbitrary) states.
312 ///
313 /// \param [out] Res - The resulting invocation.
314 /// \param [in] CommandLineArgs - Array of argument strings, this must not
315 /// contain "-cc1".
316 static bool CreateFromArgs(CompilerInvocation &Res,
317 ArrayRef<const char *> CommandLineArgs,
318 DiagnosticsEngine &Diags,
319 const char *Argv0 = nullptr);
320
321 /// Populate \p Opts with the default set of pointer authentication-related
322 /// options given \p LangOpts and \p Triple.
323 ///
324 /// Note: This is intended to be used by tools which must be aware of
325 /// pointer authentication-related code generation, e.g. lldb.
327 const LangOptions &LangOpts,
328 const llvm::Triple &Triple);
329
330 /// Compute the context hash - a string that uniquely identifies compiler
331 /// settings.
332 /// This is currently used mainly for distinguishing different variants of the
333 /// same implicitly-built Clang module.
334 std::string computeContextHash() const;
335
336 /// Check that \p Args can be parsed and re-serialized without change,
337 /// emiting diagnostics for any differences.
338 ///
339 /// This check is only suitable for command-lines that are expected to already
340 /// be canonical.
341 ///
342 /// \return false if there are any errors.
344 DiagnosticsEngine &Diags,
345 const char *Argv0 = nullptr);
346
347 /// Reset all of the options that are not considered when building a
348 /// module.
350
351 /// Disable implicit modules and canonicalize options that are only used by
352 /// implicit modules.
354
355private:
356 static bool CreateFromArgsImpl(CompilerInvocation &Res,
357 ArrayRef<const char *> CommandLineArgs,
358 DiagnosticsEngine &Diags, const char *Argv0);
359
360 /// Parse command line options that map to LangOptions.
361 static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
362 InputKind IK, const llvm::Triple &T,
363 std::vector<std::string> &Includes,
364 DiagnosticsEngine &Diags);
365
366 /// Parse command line options that map to CodeGenOptions.
367 static bool ParseCodeGenArgs(CodeGenOptions &Opts, llvm::opt::ArgList &Args,
368 InputKind IK, DiagnosticsEngine &Diags,
369 const llvm::Triple &T,
370 const std::string &OutputFile,
371 const LangOptions &LangOptsRef);
372};
373
374/// Same as \c CompilerInvocation, but with copy-on-write optimization.
376public:
388
393
396
397 /// Construct a CowCompilerInvocation that aliases the option storage of \p
398 /// X without deep-copying. Subsequent mutations through getMut*Opts() will
399 /// copy-on-write per group as usual, leaving \p X unaffected. The caller
400 /// must guarantee that \p X is not mutated for the lifetime of the
401 /// constructed invocation.
406
407 // Const getters are inherited from the base class.
408
409 /// Mutable getters.
410 /// @{
425 /// @}
426
427 /// The result of mutable visitation.
429 /// Whether to replace the given StringRef with the modified std::string &.
430 bool Replace = false;
431 /// Whether to short-circuit the visitation.
432 bool Terminate = false;
433 };
434
435 /// Visits paths stored in the invocation, allowing the callback to mutate
436 /// them via the out-param. This upholds the same copy-on-write semantics as
437 /// the mutable getters.
438 void visitMutPaths(
439 llvm::function_ref<VisitMutResult(StringRef, std::string &)> Cb);
440
441 /// The result of const visitation.
443 /// Whether to short-circuit the visitation.
444 bool Terminate = false;
445
446 operator VisitMutResult() const { return {/*Replace=*/false, Terminate}; }
447 };
448
449 /// Visits paths stored in the invocation.
450 void visitPaths(llvm::function_ref<VisitConstResult(StringRef)> Cb) const;
451};
452
453template <class R>
455 llvm::function_ref<R(CowCompilerInvocation &)> Fn) {
456 // We use moves to avoid bumping the ref-count of the shared_ptr that holds
457 // individual options. Since we expect \a Fn to actually modify \c CowRef,
458 // this prevents temporary copies.
459 CowCompilerInvocation CowRef = std::move(*this);
460 llvm::scope_exit Mutate([&]() { *this = std::move(CowRef); });
461 return Fn(CowRef);
462}
463
464template <class R>
466 llvm::function_ref<R(const CowCompilerInvocation &)> Fn) const {
467 // We use the shallow constructor. Since \a Fn cannot modify \c CowRef, no
468 // copies will be created, despite the bump to the ref-count of the shared_ptr
469 // that holds individual options.
471 return Fn(CowRef);
472}
473
476
477inline CompilerInvocation &
482
485 DiagnosticsEngine &Diags);
486
488 const CompilerInvocation &CI, DiagnosticsEngine &Diags,
490
493 DiagnosticsEngine &Diags,
495
496} // namespace clang
497
498#endif // LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
Defines the clang::FileSystemOptions interface.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Tracks various options which control how API notes are found and handled.
Stores options for the analyzer from the command line.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::shared_ptr< DiagnosticOptions > DiagnosticOpts
Options controlling the diagnostic engine.
std::shared_ptr< AnalyzerOptions > AnalyzerOpts
Options controlling the static analyzer.
std::shared_ptr< MigratorOptions > MigratorOpts
std::shared_ptr< PreprocessorOutputOptions > PreprocessorOutputOpts
Options controlling preprocessed output.
std::shared_ptr< APINotesOptions > APINotesOpts
Options controlling API notes.
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
const FrontendOptions & getFrontendOpts() const
std::shared_ptr< ssaf::SSAFOptions > SSAFOpts
Options controlling the Scalable Static Analysis Framework (SSAF).
const CodeGenOptions & getCodeGenOpts() const
CompilerInvocationBase(CompilerInvocationBase &&X)=default
llvm::function_ref< const char *(const Twine &)> StringAllocator
Command line generation.
const FileSystemOptions & getFileSystemOpts() const
std::shared_ptr< PreprocessorOptions > PPOpts
Options controlling the preprocessor (aside from #include handling).
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
const ssaf::SSAFOptions & getSSAFOpts() const
std::vector< std::string > getCC1CommandLine() const
Generate cc1-compatible command line arguments from this instance, wrapping the result as a std::vect...
std::shared_ptr< FileSystemOptions > FSOpts
Options controlling file system operations.
const AnalyzerOptions & getAnalyzerOpts() const
const MigratorOptions & getMigratorOpts() const
void generateCC1CommandLine(llvm::SmallVectorImpl< const char * > &Args, StringAllocator SA) const
Generate cc1-compatible command line arguments from this instance.
CompilerInvocationBase & deep_copy_assign(const CompilerInvocationBase &X)
const DependencyOutputOptions & getDependencyOutputOpts() const
CompilerInvocationBase & shallow_copy_assign(const CompilerInvocationBase &X)
CompilerInvocationBase(const CompilerInvocationBase &X)=delete
const TargetOptions & getTargetOpts() const
CompilerInvocationBase & operator=(CompilerInvocationBase &&X)=default
std::shared_ptr< CodeGenOptions > CodeGenOpts
Options controlling IRgen and the backend.
CompilerInvocationBase & operator=(const CompilerInvocationBase &X)=delete
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
const APINotesOptions & getAPINotesOpts() const
const HeaderSearchOptions & getHeaderSearchOpts() const
std::shared_ptr< HeaderSearchOptions > HSOpts
Options controlling the #include directive.
const PreprocessorOptions & getPreprocessorOpts() const
const DiagnosticOptions & getDiagnosticOpts() const
const LangOptions & getLangOpts() const
Const getters.
std::shared_ptr< FrontendOptions > FrontendOpts
Options controlling the frontend itself.
llvm::function_ref< void(const Twine &)> ArgumentConsumer
std::shared_ptr< DependencyOutputOptions > DependencyOutputOpts
Options controlling dependency output.
Helper class for holding the data necessary to invoke the compiler.
PreprocessorOptions & getPreprocessorOpts()
void clearImplicitModuleBuildOptions()
Disable implicit modules and canonicalize options that are only used by implicit modules.
MigratorOptions & getMigratorOpts()
AnalyzerOptions & getAnalyzerOpts()
APINotesOptions & getAPINotesOpts()
static bool CreateFromArgs(CompilerInvocation &Res, ArrayRef< const char * > CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Create a compiler invocation from a list of input options.
ssaf::SSAFOptions & getSSAFOpts()
LangOptions & getLangOpts()
Mutable getters.
static bool checkCC1RoundTrip(ArrayRef< const char * > Args, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Check that Args can be parsed and re-serialized without change, emiting diagnostics for any differenc...
DependencyOutputOptions & getDependencyOutputOpts()
R withCowRef(llvm::function_ref< R(CowCompilerInvocation &)> Fn)
Invokes the Fn with CowCompilerInvocation representing this.
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
FrontendOptions & getFrontendOpts()
CompilerInvocation(const CompilerInvocation &X)
FileSystemOptions & getFileSystemOpts()
CompilerInvocation(CompilerInvocation &&)=default
CompilerInvocation & operator=(const CompilerInvocation &X)
static void setDefaultPointerAuthOptions(PointerAuthOptions &Opts, const LangOptions &LangOpts, const llvm::Triple &Triple)
Populate Opts with the default set of pointer authentication-related options given LangOpts and Tripl...
CodeGenOptions & getCodeGenOpts()
std::string computeContextHash() const
Compute the context hash - a string that uniquely identifies compiler settings.
HeaderSearchOptions & getHeaderSearchOpts()
DiagnosticOptions & getDiagnosticOpts()
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Same as CompilerInvocation, but with copy-on-write optimization.
LangOptions & getMutLangOpts()
Mutable getters.
HeaderSearchOptions & getMutHeaderSearchOpts()
CowCompilerInvocation(CowCompilerInvocation &&)=default
PreprocessorOptions & getMutPreprocessorOpts()
PreprocessorOutputOptions & getMutPreprocessorOutputOpts()
FileSystemOptions & getMutFileSystemOpts()
void visitMutPaths(llvm::function_ref< VisitMutResult(StringRef, std::string &)> Cb)
Visits paths stored in the invocation, allowing the callback to mutate them via the out-param.
CowCompilerInvocation(const CompilerInvocation &X)
DiagnosticOptions & getMutDiagnosticOpts()
CowCompilerInvocation(const CowCompilerInvocation &X)
DependencyOutputOptions & getMutDependencyOutputOpts()
CowCompilerInvocation(ShallowConstructor, const CompilerInvocation &X)
Construct a CowCompilerInvocation that aliases the option storage of X without deep-copying.
void visitPaths(llvm::function_ref< VisitConstResult(StringRef)> Cb) const
Visits paths stored in the invocation.
CowCompilerInvocation & operator=(const CowCompilerInvocation &X)
ssaf::SSAFOptions & getMutSSAFOpts()
CowCompilerInvocation(CompilerInvocation &&X)
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
Keeps track of options that affect how file operations are performed.
FrontendOptions - Options for controlling the behavior of the frontend.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
The kind of a file that we've been handed as an input.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
Options for controlling the target.
The JSON file list parser is used to communicate input to InstallAPI.
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true)
Fill out Opts based on the options given in Args.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromOverlayFiles(ArrayRef< std::string > VFSOverlayFiles, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
std::unique_ptr< DiagnosticOptions > CreateAndPopulateDiagOpts(ArrayRef< const char * > Argv)
unsigned getOptimizationLevel(const llvm::opt::ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
unsigned getOptimizationLevelSize(const llvm::opt::ArgList &Args)
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Dummy tag type whose instance can be passed into the constructor to prevent creation of the reference...
Tag for the shallow-copy constructor below.
bool Terminate
Whether to short-circuit the visitation.
bool Replace
Whether to replace the given StringRef with the modified std::string &.
bool Terminate
Whether to short-circuit the visitation.