clang 24.0.0git
ExecuteCompilerInvocation.cpp
Go to the documentation of this file.
1//===--- ExecuteCompilerInvocation.cpp ------------------------------------===//
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 holds ExecuteCompilerInvocation(). It is split into its own file to
10// minimize the impact of pulling in essentially everything else in Clang.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/Config/config.h"
29#include "clang/ScalableStaticAnalysis/SSAFForceLinker.h" // IWYU pragma: keep
33#include "llvm/Option/OptTable.h"
34#include "llvm/Support/BuryPointer.h"
35#include "llvm/Support/DynamicLibrary.h"
36#include "llvm/Support/ErrorHandling.h"
37
38#if CLANG_ENABLE_CIR
39#include "mlir/IR/AsmState.h"
40#include "mlir/IR/MLIRContext.h"
41#include "mlir/Pass/PassManager.h"
44#endif
45
46using namespace clang;
47using namespace llvm::opt;
48
49namespace clang {
50
51static std::unique_ptr<FrontendAction>
53 using namespace clang::frontend;
54 StringRef Action("unknown");
55 (void)Action;
56
57 unsigned UseCIR = CI.getFrontendOpts().UseClangIRPipeline;
59 bool EmitsCIR = Act == EmitCIR || Act == EmitCIRBC;
60
61 if (!UseCIR && EmitsCIR)
62 llvm::report_fatal_error(
63 "-emit-cir and -emit-cir-bc only valid when using -fclangir");
64
65 switch (CI.getFrontendOpts().ProgramAction) {
66 case ASTDeclList: return std::make_unique<ASTDeclListAction>();
67 case ASTDump: return std::make_unique<ASTDumpAction>();
68 case ASTPrint: return std::make_unique<ASTPrintAction>();
69 case ASTView: return std::make_unique<ASTViewAction>();
71 return std::make_unique<DumpCompilerOptionsAction>();
72 case DumpRawTokens: return std::make_unique<DumpRawTokensAction>();
73 case DumpTokens: return std::make_unique<DumpTokensAction>();
74 case EmitAssembly:
75#if CLANG_ENABLE_CIR
76 if (UseCIR)
77 return std::make_unique<cir::EmitAssemblyAction>();
78#endif
79 return std::make_unique<EmitAssemblyAction>();
80 case EmitBC:
81#if CLANG_ENABLE_CIR
82 if (UseCIR)
83 return std::make_unique<cir::EmitBCAction>();
84#endif
85 return std::make_unique<EmitBCAction>();
86 case EmitCIR:
87#if CLANG_ENABLE_CIR
88 return std::make_unique<cir::EmitCIRAction>();
89#else
90 CI.getDiagnostics().Report(diag::err_fe_cir_not_built);
91 return nullptr;
92#endif
93 case EmitCIRBC:
94#if CLANG_ENABLE_CIR
95 return std::make_unique<cir::EmitCIRBCAction>();
96#else
97 CI.getDiagnostics().Report(diag::err_fe_cir_not_built);
98 return nullptr;
99#endif
100 case EmitHTML: return std::make_unique<HTMLPrintAction>();
101 case EmitLLVM: {
102#if CLANG_ENABLE_CIR
103 if (UseCIR)
104 return std::make_unique<cir::EmitLLVMAction>();
105#endif
106 return std::make_unique<EmitLLVMAction>();
107 }
108 case EmitLLVMOnly: return std::make_unique<EmitLLVMOnlyAction>();
109 case EmitCodeGenOnly: return std::make_unique<EmitCodeGenOnlyAction>();
110 case EmitObj:
111#if CLANG_ENABLE_CIR
112 if (UseCIR)
113 return std::make_unique<cir::EmitObjAction>();
114#endif
115 return std::make_unique<EmitObjAction>();
116 case ExtractAPI:
117 return std::make_unique<ExtractAPIAction>();
118 case FixIt: return std::make_unique<FixItAction>();
119 case GenerateModule:
120 return std::make_unique<GenerateModuleFromModuleMapAction>();
122 return std::make_unique<GenerateModuleInterfaceAction>();
124 return std::make_unique<GenerateReducedModuleInterfaceAction>();
126 return std::make_unique<GenerateHeaderUnitAction>();
127 case GeneratePCH: return std::make_unique<GeneratePCHAction>();
129 return std::make_unique<GenerateInterfaceStubsAction>();
130 case InitOnly: return std::make_unique<InitOnlyAction>();
131 case ParseSyntaxOnly: return std::make_unique<SyntaxOnlyAction>();
132 case ModuleFileInfo: return std::make_unique<DumpModuleInfoAction>();
133 case VerifyPCH:
134 return std::make_unique<VerifyPCHAction>();
135
136 case PluginAction: {
137 for (const FrontendPluginRegistry::entry &Plugin :
138 FrontendPluginRegistry::entries()) {
139 if (Plugin.getName() == CI.getFrontendOpts().ActionName) {
140 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
141 if ((P->getActionType() != PluginASTAction::ReplaceAction &&
142 P->getActionType() != PluginASTAction::CmdlineAfterMainAction) ||
143 !P->ParseArgs(
144 CI,
145 CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())]))
146 return nullptr;
147 return std::move(P);
148 }
149 }
150
151 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
153 return nullptr;
154 }
155
156 case PrintPreamble: return std::make_unique<PrintPreambleAction>();
160 return std::make_unique<RewriteIncludesAction>();
161 return std::make_unique<PrintPreprocessedAction>();
162 }
163
164 case RewriteMacros: return std::make_unique<RewriteMacrosAction>();
165 case RewriteTest: return std::make_unique<RewriteTestAction>();
166#if CLANG_ENABLE_OBJC_REWRITER
167 case RewriteObjC: return std::make_unique<RewriteObjCAction>();
168#else
169 case RewriteObjC: Action = "RewriteObjC"; break;
170#endif
171#if CLANG_ENABLE_STATIC_ANALYZER
172 case RunAnalysis: return std::make_unique<ento::AnalysisAction>();
173#else
174 case RunAnalysis: Action = "RunAnalysis"; break;
175#endif
176 case RunPreprocessorOnly: return std::make_unique<PreprocessOnlyAction>();
178 return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
179 }
180
181#if !CLANG_ENABLE_STATIC_ANALYZER || !CLANG_ENABLE_OBJC_REWRITER
182 CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
183 return 0;
184#else
185 llvm_unreachable("Invalid program action!");
186#endif
187}
188
189std::unique_ptr<FrontendAction>
191 // Create the underlying action.
192 std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
193 if (!Act)
194 return nullptr;
195
196 const FrontendOptions &FEOpts = CI.getFrontendOpts();
197
198 if (CI.getLangOpts().HLSL)
199 Act = std::make_unique<HLSLFrontendAction>(std::move(Act));
200
201 if (FEOpts.FixAndRecompile) {
202 Act = std::make_unique<FixItRecompile>(std::move(Act));
203 }
204
205 // Wrap the base FE action in an extract api action to generate
206 // symbol graph as a biproduct of compilation (enabled with
207 // --emit-symbol-graph option)
208 if (FEOpts.EmitSymbolGraph) {
209 if (FEOpts.SymbolGraphOutputDir.empty()) {
210 CI.getDiagnostics().Report(diag::warn_missing_symbol_graph_dir);
212 }
213 CI.getCodeGenOpts().ClearASTBeforeBackend = false;
214 Act = std::make_unique<WrappingExtractAPIAction>(std::move(Act));
215 }
216
217 // If there are any AST files to merge, create a frontend action
218 // adaptor to perform the merge.
219 if (!FEOpts.ASTMergeFiles.empty())
220 Act = std::make_unique<ASTMergeAction>(std::move(Act),
221 FEOpts.ASTMergeFiles);
222
223 if (!CI.getSSAFOpts().TUSummaryFile.empty()) {
224 Act = std::make_unique<ssaf::TUSummaryExtractorFrontendAction>(
225 std::move(Act));
226 }
227 // Enter the source-transformation action when the transformation option is
228 // set, and also when only an output option (--ssaf-src-edit-file= /
229 // --ssaf-transformation-report-file=) is set — the action's
230 // reportOrphanOptionMisuse then diagnoses that as a reverse orphan rather
231 // than silently ignoring the option.
232 if (!CI.getSSAFOpts().SourceTransformation.empty() ||
233 !CI.getSSAFOpts().SrcEditFile.empty() ||
235 Act = std::make_unique<ssaf::SourceTransformationFrontendAction>(
236 std::move(Act));
237 }
238 return Act;
239}
240
242 unsigned NumErrorsBefore = Clang->getDiagnostics().getNumErrors();
243
244 // Honor -help.
245 if (Clang->getFrontendOpts().ShowHelp) {
246 getDriverOptTable().printHelp(
247 llvm::outs(), "clang -cc1 [options] file...",
248 "LLVM 'Clang' Compiler: http://clang.llvm.org",
249 /*ShowHidden=*/false, /*ShowAllAliases=*/false,
250 llvm::opt::Visibility(options::CC1Option));
251 return true;
252 }
253
254 // Honor -version.
255 //
256 // FIXME: Use a better -version message?
257 if (Clang->getFrontendOpts().ShowVersion) {
258 llvm::cl::PrintVersionMessage();
259 return true;
260 }
261
262 Clang->LoadRequestedPlugins();
263
264 Clang->parseLLVMArgs();
265
266#if CLANG_ENABLE_STATIC_ANALYZER
267 // These should happen AFTER plugins have been loaded!
268
269 AnalyzerOptions &AnOpts = Clang->getAnalyzerOpts();
270
271 // Honor -analyzer-checker-help and -analyzer-checker-help-hidden.
272 if (AnOpts.ShowCheckerHelp || AnOpts.ShowCheckerHelpAlpha ||
274 ento::printCheckerHelp(llvm::outs(), *Clang);
275 return true;
276 }
277
278 // Honor -analyzer-checker-option-help.
281 ento::printCheckerConfigList(llvm::outs(), *Clang);
282 return true;
283 }
284
285 // Honor -analyzer-list-enabled-checkers.
286 if (AnOpts.ShowEnabledCheckerList) {
287 ento::printEnabledCheckerList(llvm::outs(), *Clang);
288 return true;
289 }
290
291 // Honor -analyzer-config-help.
292 if (AnOpts.ShowConfigOptionsList) {
293 ento::printAnalyzerConfigList(llvm::outs());
294 return true;
295 }
296#endif
297
298#if CLANG_ENABLE_CIR
299 if (!Clang->getFrontendOpts().MLIRArgs.empty()) {
300 mlir::registerCIRPasses();
301 mlir::registerMLIRContextCLOptions();
302 mlir::registerPassManagerCLOptions();
303 mlir::registerAsmPrinterCLOptions();
304 unsigned NumArgs = Clang->getFrontendOpts().MLIRArgs.size();
305 auto Args = std::make_unique<const char *[]>(NumArgs + 2);
306 Args[0] = "clang (MLIR option parsing)";
307 for (unsigned i = 0; i != NumArgs; ++i)
308 Args[i + 1] = Clang->getFrontendOpts().MLIRArgs[i].c_str();
309 Args[NumArgs + 1] = nullptr;
310 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(),
311 /*Description=*/"", /*Errs=*/nullptr,
312 &Clang->getVirtualFileSystem());
313 }
314#endif
315
316 // If there were errors in the above, don't do anything else.
317 // This intentionally ignores errors emitted before this function to
318 // accommodate lenient callers that decided to make progress despite errors.
319 if (Clang->getDiagnostics().getNumErrors() != NumErrorsBefore)
320 return false;
321
322 // Create and execute the frontend action.
323 std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
324 if (!Act)
325 return false;
326 bool Success = Clang->ExecuteAction(*Act);
327 if (Clang->getFrontendOpts().DisableFree)
328 llvm::BuryPointer(std::move(Act));
329 return Success;
330}
331
332} // namespace clang
This file defines the ExtractAPIAction and WrappingExtractAPIAction frontend actions.
This file pulls in all built-in SSAF extractor and format registrations by referencing their anchor s...
Stores options for the analyzer from the command line.
unsigned ShowCheckerOptionDeveloperList
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
AnalyzerOptions & getAnalyzerOpts()
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
ssaf::SSAFOptions & getSSAFOpts()
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
FrontendOptions & getFrontendOpts()
void parseLLVMArgs()
Parse and apply LLVM command line arguments from FrontendOptions.
llvm::vfs::FileSystem & getVirtualFileSystem() const
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
CodeGenOptions & getCodeGenOpts()
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getNumErrors() const
Definition Diagnostic.h:927
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned EmitSymbolGraph
Whether to emit symbol graph files as a side effect of compilation.
std::map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
std::vector< std::string > MLIRArgs
A list of arguments to forward to MLIR's option processing; this should only be used for debugging an...
unsigned ShowHelp
Show the -help text.
unsigned FixAndRecompile
Apply fixes and recompile.
unsigned UseClangIRPipeline
Use Clang IR pipeline to emit code.
std::string ActionName
The name of the action to run when using a plugin action.
unsigned ShowVersion
Show the -version text.
std::vector< std::string > ASTMergeFiles
The list of AST files to merge.
unsigned DisableFree
Disable memory freeing on exit.
frontend::ActionKind ProgramAction
The frontend action to perform.
@ ReplaceAction
Replace the main action.
@ CmdlineAfterMainAction
Execute the action after the main action if on the command line.
unsigned RewriteIncludes
Preprocess include directives only.
unsigned RewriteImports
Include contents of transitively-imported modules.
std::string SrcEditFile
Path of the source-edit output file produced by the source transformation.
Definition SSAFOptions.h:52
std::string TransformationReportFile
Path of the transformation-report output file produced by the source transformation.
Definition SSAFOptions.h:57
std::string SourceTransformation
Name of the SSAF source transformation to run.
Definition SSAFOptions.h:38
std::string TUSummaryFile
The TU summary output file with the file extension representing the serialization format.
Definition SSAFOptions.h:27
void printEnabledCheckerList(llvm::raw_ostream &OS, CompilerInstance &CI)
void printCheckerHelp(llvm::raw_ostream &OS, CompilerInstance &CI)
void printAnalyzerConfigList(llvm::raw_ostream &OS)
void printCheckerConfigList(llvm::raw_ostream &OS, CompilerInstance &CI)
@ GenerateHeaderUnit
Generate a C++20 header unit module from a header file.
@ VerifyPCH
Load and verify that a PCH file is usable.
@ PrintPreprocessedInput
-E mode.
@ RewriteTest
Rewriter playground.
@ ParseSyntaxOnly
Parse and perform semantic analysis.
@ EmitBC
Emit a .bc file.
@ GenerateModuleInterface
Generate pre-compiled module from a standard C++ module interface unit.
@ EmitLLVM
Emit a .ll file.
@ PrintPreamble
Print the "preamble" of the input file.
@ InitOnly
Only execute frontend initialization.
@ ASTView
Parse ASTs and view them in Graphviz.
@ PluginAction
Run a plugin action,.
@ EmitObj
Emit a .o file.
@ DumpRawTokens
Dump out raw tokens.
@ PrintDependencyDirectivesSourceMinimizerOutput
Print the output of the dependency directives source minimizer.
@ RewriteObjC
ObjC->C Rewriter.
@ RunPreprocessorOnly
Just lex, no output.
@ EmitCIR
Emit a .cir file.
@ DumpCompilerOptions
Dump the compiler configuration.
@ RunAnalysis
Run one or more source code analyses.
@ ASTPrint
Parse ASTs and print them.
@ GenerateReducedModuleInterface
Generate reduced module interface for a standard C++ module interface unit.
@ GenerateInterfaceStubs
Generate Interface Stub Files.
@ ASTDump
Parse ASTs and dump them.
@ EmitCIRBC
Emit a .cirbc file (ClangIR bytecode).
@ DumpTokens
Dump out preprocessed tokens.
@ FixIt
Parse and apply any fixits to the source.
@ EmitAssembly
Emit a .s file.
@ EmitCodeGenOnly
Generate machine code, but don't emit anything.
@ RewriteMacros
Expand macros but not #includes.
@ EmitHTML
Translate input source into HTML.
@ GeneratePCH
Generate pre-compiled header.
@ EmitLLVMOnly
Generate LLVM IR, but do not emit anything.
@ GenerateModule
Generate pre-compiled module from a module map.
@ ASTDeclList
Parse ASTs and list Decl nodes.
Top level wrappers for InstallAPI frontend operations.
static std::unique_ptr< FrontendAction > CreateFrontendBaseAction(CompilerInstance &CI)
@ Success
Annotation was successful.
Definition Parser.h:65
bool ExecuteCompilerInvocation(CompilerInstance *Clang)
ExecuteCompilerInvocation - Execute the given actions described by the compiler invocation object in ...
std::unique_ptr< FrontendAction > CreateFrontendAction(CompilerInstance &CI)
Construct the FrontendAction of a compiler invocation based on the options specified for the compiler...
const llvm::opt::OptTable & getDriverOptTable()