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
14#include "clang/Basic/DiagnosticFrontend.h"
15#include "clang/CodeGen/CodeGenAction.h"
16#include "clang/Config/config.h"
17#include "clang/ExtractAPI/FrontendActions.h"
18#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "clang/Frontend/FrontendActions.h"
21#include "clang/Frontend/FrontendPluginRegistry.h"
22#include "clang/Frontend/Utils.h"
23#include "clang/FrontendTool/Utils.h"
24#include "clang/Options/Options.h"
25#include "clang/Rewrite/Frontend/FrontendActions.h"
26#include "clang/ScalableStaticAnalysisFramework/Frontend/TUSummaryExtractorFrontendAction.h"
27#include "clang/ScalableStaticAnalysisFramework/SSAFForceLinker.h" // IWYU pragma: keep
28#include "clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h"
29#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
30#include "llvm/Option/OptTable.h"
31#include "llvm/Support/BuryPointer.h"
32#include "llvm/Support/DynamicLibrary.h"
33#include "llvm/Support/ErrorHandling.h"
34
35#if CLANG_ENABLE_CIR
36#include "mlir/IR/AsmState.h"
37#include "mlir/IR/MLIRContext.h"
38#include "mlir/Pass/PassManager.h"
39#include "clang/CIR/Dialect/Passes.h"
40#include "clang/CIR/FrontendAction/CIRGenAction.h"
41#endif
42
43using namespace clang;
44using namespace llvm::opt;
45
46namespace clang {
47
48static std::unique_ptr<FrontendAction>
49CreateFrontendBaseAction(CompilerInstance &CI) {
50 using namespace clang::frontend;
51 StringRef Action("unknown");
52 (void)Action;
53
54 unsigned UseCIR = CI.getFrontendOpts().UseClangIRPipeline;
55 frontend::ActionKind Act = CI.getFrontendOpts().ProgramAction;
56 bool EmitsCIR = Act == EmitCIR;
57
58 if (!UseCIR && EmitsCIR)
59 llvm::report_fatal_error(reason: "-emit-cir and only valid when using -fclangir");
60
61 switch (CI.getFrontendOpts().ProgramAction) {
62 case ASTDeclList: return std::make_unique<ASTDeclListAction>();
63 case ASTDump: return std::make_unique<ASTDumpAction>();
64 case ASTPrint: return std::make_unique<ASTPrintAction>();
65 case ASTView: return std::make_unique<ASTViewAction>();
66 case DumpCompilerOptions:
67 return std::make_unique<DumpCompilerOptionsAction>();
68 case DumpRawTokens: return std::make_unique<DumpRawTokensAction>();
69 case DumpTokens: return std::make_unique<DumpTokensAction>();
70 case EmitAssembly:
71#if CLANG_ENABLE_CIR
72 if (UseCIR)
73 return std::make_unique<cir::EmitAssemblyAction>();
74#endif
75 return std::make_unique<EmitAssemblyAction>();
76 case EmitBC:
77#if CLANG_ENABLE_CIR
78 if (UseCIR)
79 return std::make_unique<cir::EmitBCAction>();
80#endif
81 return std::make_unique<EmitBCAction>();
82 case EmitCIR:
83#if CLANG_ENABLE_CIR
84 return std::make_unique<cir::EmitCIRAction>();
85#else
86 CI.getDiagnostics().Report(DiagID: diag::err_fe_cir_not_built);
87 return nullptr;
88#endif
89 case EmitHTML: return std::make_unique<HTMLPrintAction>();
90 case EmitLLVM: {
91#if CLANG_ENABLE_CIR
92 if (UseCIR)
93 return std::make_unique<cir::EmitLLVMAction>();
94#endif
95 return std::make_unique<EmitLLVMAction>();
96 }
97 case EmitLLVMOnly: return std::make_unique<EmitLLVMOnlyAction>();
98 case EmitCodeGenOnly: return std::make_unique<EmitCodeGenOnlyAction>();
99 case EmitObj:
100#if CLANG_ENABLE_CIR
101 if (UseCIR)
102 return std::make_unique<cir::EmitObjAction>();
103#endif
104 return std::make_unique<EmitObjAction>();
105 case ExtractAPI:
106 return std::make_unique<ExtractAPIAction>();
107 case FixIt: return std::make_unique<FixItAction>();
108 case GenerateModule:
109 return std::make_unique<GenerateModuleFromModuleMapAction>();
110 case GenerateModuleInterface:
111 return std::make_unique<GenerateModuleInterfaceAction>();
112 case GenerateReducedModuleInterface:
113 return std::make_unique<GenerateReducedModuleInterfaceAction>();
114 case GenerateHeaderUnit:
115 return std::make_unique<GenerateHeaderUnitAction>();
116 case GeneratePCH: return std::make_unique<GeneratePCHAction>();
117 case GenerateInterfaceStubs:
118 return std::make_unique<GenerateInterfaceStubsAction>();
119 case InitOnly: return std::make_unique<InitOnlyAction>();
120 case ParseSyntaxOnly: return std::make_unique<SyntaxOnlyAction>();
121 case ModuleFileInfo: return std::make_unique<DumpModuleInfoAction>();
122 case VerifyPCH: return std::make_unique<VerifyPCHAction>();
123 case TemplightDump: return std::make_unique<TemplightDumpAction>();
124
125 case PluginAction: {
126 for (const FrontendPluginRegistry::entry &Plugin :
127 FrontendPluginRegistry::entries()) {
128 if (Plugin.getName() == CI.getFrontendOpts().ActionName) {
129 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
130 if ((P->getActionType() != PluginASTAction::ReplaceAction &&
131 P->getActionType() != PluginASTAction::CmdlineAfterMainAction) ||
132 !P->ParseArgs(
133 CI,
134 arg: CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())]))
135 return nullptr;
136 return std::move(P);
137 }
138 }
139
140 CI.getDiagnostics().Report(DiagID: diag::err_fe_invalid_plugin_name)
141 << CI.getFrontendOpts().ActionName;
142 return nullptr;
143 }
144
145 case PrintPreamble: return std::make_unique<PrintPreambleAction>();
146 case PrintPreprocessedInput: {
147 if (CI.getPreprocessorOutputOpts().RewriteIncludes ||
148 CI.getPreprocessorOutputOpts().RewriteImports)
149 return std::make_unique<RewriteIncludesAction>();
150 return std::make_unique<PrintPreprocessedAction>();
151 }
152
153 case RewriteMacros: return std::make_unique<RewriteMacrosAction>();
154 case RewriteTest: return std::make_unique<RewriteTestAction>();
155#if CLANG_ENABLE_OBJC_REWRITER
156 case RewriteObjC: return std::make_unique<RewriteObjCAction>();
157#else
158 case RewriteObjC: Action = "RewriteObjC"; break;
159#endif
160#if CLANG_ENABLE_STATIC_ANALYZER
161 case RunAnalysis: return std::make_unique<ento::AnalysisAction>();
162#else
163 case RunAnalysis: Action = "RunAnalysis"; break;
164#endif
165 case RunPreprocessorOnly: return std::make_unique<PreprocessOnlyAction>();
166 case PrintDependencyDirectivesSourceMinimizerOutput:
167 return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
168 }
169
170#if !CLANG_ENABLE_STATIC_ANALYZER || !CLANG_ENABLE_OBJC_REWRITER
171 CI.getDiagnostics().Report(DiagID: diag::err_fe_action_not_available) << Action;
172 return 0;
173#else
174 llvm_unreachable("Invalid program action!");
175#endif
176}
177
178std::unique_ptr<FrontendAction>
179CreateFrontendAction(CompilerInstance &CI) {
180 // Create the underlying action.
181 std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
182 if (!Act)
183 return nullptr;
184
185 const FrontendOptions &FEOpts = CI.getFrontendOpts();
186
187 if (CI.getLangOpts().HLSL)
188 Act = std::make_unique<HLSLFrontendAction>(args: std::move(Act));
189
190 if (FEOpts.FixAndRecompile) {
191 Act = std::make_unique<FixItRecompile>(args: std::move(Act));
192 }
193
194 // Wrap the base FE action in an extract api action to generate
195 // symbol graph as a biproduct of compilation (enabled with
196 // --emit-symbol-graph option)
197 if (FEOpts.EmitSymbolGraph) {
198 if (FEOpts.SymbolGraphOutputDir.empty()) {
199 CI.getDiagnostics().Report(DiagID: diag::warn_missing_symbol_graph_dir);
200 CI.getFrontendOpts().SymbolGraphOutputDir = ".";
201 }
202 CI.getCodeGenOpts().ClearASTBeforeBackend = false;
203 Act = std::make_unique<WrappingExtractAPIAction>(args: std::move(Act));
204 }
205
206 // If there are any AST files to merge, create a frontend action
207 // adaptor to perform the merge.
208 if (!FEOpts.ASTMergeFiles.empty())
209 Act = std::make_unique<ASTMergeAction>(args: std::move(Act),
210 args: FEOpts.ASTMergeFiles);
211
212 if (!FEOpts.SSAFTUSummaryFile.empty()) {
213 Act = std::make_unique<ssaf::TUSummaryExtractorFrontendAction>(
214 args: std::move(Act));
215 }
216 return Act;
217}
218
219bool ExecuteCompilerInvocation(CompilerInstance *Clang) {
220 unsigned NumErrorsBefore = Clang->getDiagnostics().getNumErrors();
221
222 // Honor -help.
223 if (Clang->getFrontendOpts().ShowHelp) {
224 getDriverOptTable().printHelp(
225 OS&: llvm::outs(), Usage: "clang -cc1 [options] file...",
226 Title: "LLVM 'Clang' Compiler: http://clang.llvm.org",
227 /*ShowHidden=*/false, /*ShowAllAliases=*/false,
228 VisibilityMask: llvm::opt::Visibility(options::CC1Option));
229 return true;
230 }
231
232 // Honor -version.
233 //
234 // FIXME: Use a better -version message?
235 if (Clang->getFrontendOpts().ShowVersion) {
236 llvm::cl::PrintVersionMessage();
237 return true;
238 }
239
240 Clang->LoadRequestedPlugins();
241
242 // Honor -mllvm.
243 //
244 // FIXME: Remove this, one day.
245 // This should happen AFTER plugins have been loaded!
246 if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
247 unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
248 auto Args = std::make_unique<const char*[]>(num: NumArgs + 2);
249 Args[0] = "clang (LLVM option parsing)";
250 for (unsigned i = 0; i != NumArgs; ++i)
251 Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
252 Args[NumArgs + 1] = nullptr;
253 llvm::cl::ParseCommandLineOptions(argc: NumArgs + 1, argv: Args.get(), /*Overview=*/"",
254 /*Errs=*/nullptr,
255 /*VFS=*/&Clang->getVirtualFileSystem());
256 }
257
258#if CLANG_ENABLE_STATIC_ANALYZER
259 // These should happen AFTER plugins have been loaded!
260
261 AnalyzerOptions &AnOpts = Clang->getAnalyzerOpts();
262
263 // Honor -analyzer-checker-help and -analyzer-checker-help-hidden.
264 if (AnOpts.ShowCheckerHelp || AnOpts.ShowCheckerHelpAlpha ||
265 AnOpts.ShowCheckerHelpDeveloper) {
266 ento::printCheckerHelp(OS&: llvm::outs(), CI&: *Clang);
267 return true;
268 }
269
270 // Honor -analyzer-checker-option-help.
271 if (AnOpts.ShowCheckerOptionList || AnOpts.ShowCheckerOptionAlphaList ||
272 AnOpts.ShowCheckerOptionDeveloperList) {
273 ento::printCheckerConfigList(OS&: llvm::outs(), CI&: *Clang);
274 return true;
275 }
276
277 // Honor -analyzer-list-enabled-checkers.
278 if (AnOpts.ShowEnabledCheckerList) {
279 ento::printEnabledCheckerList(OS&: llvm::outs(), CI&: *Clang);
280 return true;
281 }
282
283 // Honor -analyzer-config-help.
284 if (AnOpts.ShowConfigOptionsList) {
285 ento::printAnalyzerConfigList(OS&: llvm::outs());
286 return true;
287 }
288#endif
289
290#if CLANG_ENABLE_CIR
291 if (!Clang->getFrontendOpts().MLIRArgs.empty()) {
292 mlir::registerCIRPasses();
293 mlir::registerMLIRContextCLOptions();
294 mlir::registerPassManagerCLOptions();
295 mlir::registerAsmPrinterCLOptions();
296 unsigned NumArgs = Clang->getFrontendOpts().MLIRArgs.size();
297 auto Args = std::make_unique<const char *[]>(NumArgs + 2);
298 Args[0] = "clang (MLIR option parsing)";
299 for (unsigned i = 0; i != NumArgs; ++i)
300 Args[i + 1] = Clang->getFrontendOpts().MLIRArgs[i].c_str();
301 Args[NumArgs + 1] = nullptr;
302 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(),
303 /*Description=*/"", /*Errs=*/nullptr,
304 &Clang->getVirtualFileSystem());
305 }
306#endif
307
308 // If there were errors in the above, don't do anything else.
309 // This intentionally ignores errors emitted before this function to
310 // accommodate lenient callers that decided to make progress despite errors.
311 if (Clang->getDiagnostics().getNumErrors() != NumErrorsBefore)
312 return false;
313
314 // Create and execute the frontend action.
315 std::unique_ptr<FrontendAction> Act(CreateFrontendAction(CI&: *Clang));
316 if (!Act)
317 return false;
318 bool Success = Clang->ExecuteAction(Act&: *Act);
319 if (Clang->getFrontendOpts().DisableFree)
320 llvm::BuryPointer(Ptr: std::move(Act));
321 return Success;
322}
323
324} // namespace clang
325