xref: /llvm-project/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp (revision 6e2d36b60b401a0fd5a25f8eb98cddfd3a7b92b4)
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/ARCMigrate/ARCMTActions.h"
15 #include "clang/CodeGen/CodeGenAction.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/CompilerInvocation.h"
20 #include "clang/Frontend/FrontendActions.h"
21 #include "clang/Frontend/FrontendDiagnostic.h"
22 #include "clang/Frontend/FrontendPluginRegistry.h"
23 #include "clang/Frontend/Utils.h"
24 #include "clang/FrontendTool/Utils.h"
25 #include "clang/Rewrite/Frontend/FrontendActions.h"
26 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
27 #include "llvm/Option/OptTable.h"
28 #include "llvm/Option/Option.h"
29 #include "llvm/Support/BuryPointer.h"
30 #include "llvm/Support/DynamicLibrary.h"
31 #include "llvm/Support/ErrorHandling.h"
32 using namespace clang;
33 using namespace llvm::opt;
34 
35 namespace clang {
36 
37 static std::unique_ptr<FrontendAction>
38 CreateFrontendBaseAction(CompilerInstance &CI) {
39   using namespace clang::frontend;
40   StringRef Action("unknown");
41   (void)Action;
42 
43   switch (CI.getFrontendOpts().ProgramAction) {
44   case ASTDeclList:            return llvm::make_unique<ASTDeclListAction>();
45   case ASTDump:                return llvm::make_unique<ASTDumpAction>();
46   case ASTPrint:               return llvm::make_unique<ASTPrintAction>();
47   case ASTView:                return llvm::make_unique<ASTViewAction>();
48   case DumpCompilerOptions:
49     return llvm::make_unique<DumpCompilerOptionsAction>();
50   case DumpRawTokens:          return llvm::make_unique<DumpRawTokensAction>();
51   case DumpTokens:             return llvm::make_unique<DumpTokensAction>();
52   case EmitAssembly:           return llvm::make_unique<EmitAssemblyAction>();
53   case EmitBC:                 return llvm::make_unique<EmitBCAction>();
54   case EmitHTML:               return llvm::make_unique<HTMLPrintAction>();
55   case EmitLLVM:               return llvm::make_unique<EmitLLVMAction>();
56   case EmitLLVMOnly:           return llvm::make_unique<EmitLLVMOnlyAction>();
57   case EmitCodeGenOnly:        return llvm::make_unique<EmitCodeGenOnlyAction>();
58   case EmitObj:                return llvm::make_unique<EmitObjAction>();
59   case FixIt:                  return llvm::make_unique<FixItAction>();
60   case GenerateModule:
61     return llvm::make_unique<GenerateModuleFromModuleMapAction>();
62   case GenerateModuleInterface:
63     return llvm::make_unique<GenerateModuleInterfaceAction>();
64   case GenerateHeaderModule:
65     return llvm::make_unique<GenerateHeaderModuleAction>();
66   case GeneratePCH:            return llvm::make_unique<GeneratePCHAction>();
67   case InitOnly:               return llvm::make_unique<InitOnlyAction>();
68   case ParseSyntaxOnly:        return llvm::make_unique<SyntaxOnlyAction>();
69   case ModuleFileInfo:         return llvm::make_unique<DumpModuleInfoAction>();
70   case VerifyPCH:              return llvm::make_unique<VerifyPCHAction>();
71   case TemplightDump:          return llvm::make_unique<TemplightDumpAction>();
72 
73   case PluginAction: {
74     for (FrontendPluginRegistry::iterator it =
75            FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
76          it != ie; ++it) {
77       if (it->getName() == CI.getFrontendOpts().ActionName) {
78         std::unique_ptr<PluginASTAction> P(it->instantiate());
79         if ((P->getActionType() != PluginASTAction::ReplaceAction &&
80              P->getActionType() != PluginASTAction::Cmdline) ||
81             !P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()]))
82           return nullptr;
83         return std::move(P);
84       }
85     }
86 
87     CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
88       << CI.getFrontendOpts().ActionName;
89     return nullptr;
90   }
91 
92   case PrintPreamble:          return llvm::make_unique<PrintPreambleAction>();
93   case PrintPreprocessedInput: {
94     if (CI.getPreprocessorOutputOpts().RewriteIncludes ||
95         CI.getPreprocessorOutputOpts().RewriteImports)
96       return llvm::make_unique<RewriteIncludesAction>();
97     return llvm::make_unique<PrintPreprocessedAction>();
98   }
99 
100   case RewriteMacros:          return llvm::make_unique<RewriteMacrosAction>();
101   case RewriteTest:            return llvm::make_unique<RewriteTestAction>();
102 #if CLANG_ENABLE_OBJC_REWRITER
103   case RewriteObjC:            return llvm::make_unique<RewriteObjCAction>();
104 #else
105   case RewriteObjC:            Action = "RewriteObjC"; break;
106 #endif
107 #if CLANG_ENABLE_ARCMT
108   case MigrateSource:
109     return llvm::make_unique<arcmt::MigrateSourceAction>();
110 #else
111   case MigrateSource:          Action = "MigrateSource"; break;
112 #endif
113 #if CLANG_ENABLE_STATIC_ANALYZER
114   case RunAnalysis:            return llvm::make_unique<ento::AnalysisAction>();
115 #else
116   case RunAnalysis:            Action = "RunAnalysis"; break;
117 #endif
118   case RunPreprocessorOnly:    return llvm::make_unique<PreprocessOnlyAction>();
119   case PrintDependencyDirectivesSourceMinimizerOutput:
120     return llvm::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
121   }
122 
123 #if !CLANG_ENABLE_ARCMT || !CLANG_ENABLE_STATIC_ANALYZER \
124   || !CLANG_ENABLE_OBJC_REWRITER
125   CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
126   return 0;
127 #else
128   llvm_unreachable("Invalid program action!");
129 #endif
130 }
131 
132 std::unique_ptr<FrontendAction>
133 CreateFrontendAction(CompilerInstance &CI) {
134   // Create the underlying action.
135   std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
136   if (!Act)
137     return nullptr;
138 
139   const FrontendOptions &FEOpts = CI.getFrontendOpts();
140 
141   if (FEOpts.FixAndRecompile) {
142     Act = llvm::make_unique<FixItRecompile>(std::move(Act));
143   }
144 
145 #if CLANG_ENABLE_ARCMT
146   if (CI.getFrontendOpts().ProgramAction != frontend::MigrateSource &&
147       CI.getFrontendOpts().ProgramAction != frontend::GeneratePCH) {
148     // Potentially wrap the base FE action in an ARC Migrate Tool action.
149     switch (FEOpts.ARCMTAction) {
150     case FrontendOptions::ARCMT_None:
151       break;
152     case FrontendOptions::ARCMT_Check:
153       Act = llvm::make_unique<arcmt::CheckAction>(std::move(Act));
154       break;
155     case FrontendOptions::ARCMT_Modify:
156       Act = llvm::make_unique<arcmt::ModifyAction>(std::move(Act));
157       break;
158     case FrontendOptions::ARCMT_Migrate:
159       Act = llvm::make_unique<arcmt::MigrateAction>(std::move(Act),
160                                      FEOpts.MTMigrateDir,
161                                      FEOpts.ARCMTMigrateReportOut,
162                                      FEOpts.ARCMTMigrateEmitARCErrors);
163       break;
164     }
165 
166     if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
167       Act = llvm::make_unique<arcmt::ObjCMigrateAction>(std::move(Act),
168                                                         FEOpts.MTMigrateDir,
169                                                         FEOpts.ObjCMTAction);
170     }
171   }
172 #endif
173 
174   // If there are any AST files to merge, create a frontend action
175   // adaptor to perform the merge.
176   if (!FEOpts.ASTMergeFiles.empty())
177     Act = llvm::make_unique<ASTMergeAction>(std::move(Act),
178                                             FEOpts.ASTMergeFiles);
179 
180   return Act;
181 }
182 
183 bool ExecuteCompilerInvocation(CompilerInstance *Clang) {
184   // Honor -help.
185   if (Clang->getFrontendOpts().ShowHelp) {
186     std::unique_ptr<OptTable> Opts = driver::createDriverOptTable();
187     Opts->PrintHelp(llvm::outs(), "clang -cc1 [options] file...",
188                     "LLVM 'Clang' Compiler: http://clang.llvm.org",
189                     /*Include=*/driver::options::CC1Option,
190                     /*Exclude=*/0, /*ShowAllAliases=*/false);
191     return true;
192   }
193 
194   // Honor -version.
195   //
196   // FIXME: Use a better -version message?
197   if (Clang->getFrontendOpts().ShowVersion) {
198     llvm::cl::PrintVersionMessage();
199     return true;
200   }
201 
202   // Load any requested plugins.
203   for (unsigned i = 0,
204          e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
205     const std::string &Path = Clang->getFrontendOpts().Plugins[i];
206     std::string Error;
207     if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
208       Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
209         << Path << Error;
210   }
211 
212   // Check if any of the loaded plugins replaces the main AST action
213   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
214                                         ie = FrontendPluginRegistry::end();
215        it != ie; ++it) {
216     std::unique_ptr<PluginASTAction> P(it->instantiate());
217     if (P->getActionType() == PluginASTAction::ReplaceAction) {
218       Clang->getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
219       Clang->getFrontendOpts().ActionName = it->getName();
220       break;
221     }
222   }
223 
224   // Honor -mllvm.
225   //
226   // FIXME: Remove this, one day.
227   // This should happen AFTER plugins have been loaded!
228   if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
229     unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
230     auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
231     Args[0] = "clang (LLVM option parsing)";
232     for (unsigned i = 0; i != NumArgs; ++i)
233       Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
234     Args[NumArgs + 1] = nullptr;
235     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
236   }
237 
238 #if CLANG_ENABLE_STATIC_ANALYZER
239   // These should happen AFTER plugins have been loaded!
240 
241   AnalyzerOptions &AnOpts = *Clang->getAnalyzerOpts();
242   // Honor -analyzer-checker-help and -analyzer-checker-help-hidden.
243   if (AnOpts.ShowCheckerHelp || AnOpts.ShowCheckerHelpAlpha ||
244       AnOpts.ShowCheckerHelpDeveloper) {
245     ento::printCheckerHelp(llvm::outs(),
246                            Clang->getFrontendOpts().Plugins,
247                            AnOpts,
248                            Clang->getDiagnostics(),
249                            Clang->getLangOpts());
250     return true;
251   }
252 
253   // Honor -analyzer-checker-option-help.
254   if (AnOpts.ShowCheckerOptionList || AnOpts.ShowCheckerOptionAlphaList ||
255       AnOpts.ShowCheckerOptionDeveloperList) {
256     ento::printCheckerConfigList(llvm::outs(),
257                                  Clang->getFrontendOpts().Plugins,
258                                  *Clang->getAnalyzerOpts(),
259                                  Clang->getDiagnostics(),
260                                  Clang->getLangOpts());
261     return true;
262   }
263 
264   // Honor -analyzer-list-enabled-checkers.
265   if (AnOpts.ShowEnabledCheckerList) {
266     ento::printEnabledCheckerList(llvm::outs(),
267                                   Clang->getFrontendOpts().Plugins,
268                                   AnOpts,
269                                   Clang->getDiagnostics(),
270                                   Clang->getLangOpts());
271   }
272 
273   // Honor -analyzer-config-help.
274   if (AnOpts.ShowConfigOptionsList) {
275     ento::printAnalyzerConfigList(llvm::outs());
276     return true;
277   }
278 #endif
279 
280   // If there were errors in processing arguments, don't do anything else.
281   if (Clang->getDiagnostics().hasErrorOccurred())
282     return false;
283   // Create and execute the frontend action.
284   std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
285   if (!Act)
286     return false;
287   bool Success = Clang->ExecuteAction(*Act);
288   if (Clang->getFrontendOpts().DisableFree)
289     llvm::BuryPointer(std::move(Act));
290   return Success;
291 }
292 
293 } // namespace clang
294