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