1//===--- ExecuteCompilerInvocation.cpp ------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file holds ExecuteCompilerInvocation(). It is split into its own file to
11// minimize the impact of pulling in essentially everything else in Clang.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/FrontendTool/Utils.h"
16#include "clang/ARCMigrate/ARCMTActions.h"
17#include "clang/CodeGen/CodeGenAction.h"
18#include "clang/Driver/Options.h"
19#include "clang/Frontend/CompilerInstance.h"
20#include "clang/Frontend/CompilerInvocation.h"
21#include "clang/Frontend/FrontendActions.h"
22#include "clang/Frontend/FrontendDiagnostic.h"
23#include "clang/Frontend/FrontendPluginRegistry.h"
24#include "clang/Frontend/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/DynamicLibrary.h"
30#include "llvm/Support/ErrorHandling.h"
31using namespace clang;
32using namespace llvm::opt;
33
34static std::unique_ptr<FrontendAction>
35CreateFrontendBaseAction(CompilerInstance &CI) {
36  using namespace clang::frontend;
37  StringRef Action("unknown");
38  (void)Action;
39
40  switch (CI.getFrontendOpts().ProgramAction) {
41  case ASTDeclList:            return llvm::make_unique<ASTDeclListAction>();
42  case ASTDump:                return llvm::make_unique<ASTDumpAction>();
43  case ASTPrint:               return llvm::make_unique<ASTPrintAction>();
44  case ASTView:                return llvm::make_unique<ASTViewAction>();
45  case DumpRawTokens:          return llvm::make_unique<DumpRawTokensAction>();
46  case DumpTokens:             return llvm::make_unique<DumpTokensAction>();
47  case EmitAssembly:           return llvm::make_unique<EmitAssemblyAction>();
48  case EmitBC:                 return llvm::make_unique<EmitBCAction>();
49  case EmitHTML:               return llvm::make_unique<HTMLPrintAction>();
50  case EmitLLVM:               return llvm::make_unique<EmitLLVMAction>();
51  case EmitLLVMOnly:           return llvm::make_unique<EmitLLVMOnlyAction>();
52  case EmitCodeGenOnly:        return llvm::make_unique<EmitCodeGenOnlyAction>();
53  case EmitObj:                return llvm::make_unique<EmitObjAction>();
54  case FixIt:                  return llvm::make_unique<FixItAction>();
55  case GenerateModule:         return llvm::make_unique<GenerateModuleAction>();
56  case GeneratePCH:            return llvm::make_unique<GeneratePCHAction>();
57  case GeneratePTH:            return llvm::make_unique<GeneratePTHAction>();
58  case InitOnly:               return llvm::make_unique<InitOnlyAction>();
59  case ParseSyntaxOnly:        return llvm::make_unique<SyntaxOnlyAction>();
60  case ModuleFileInfo:         return llvm::make_unique<DumpModuleInfoAction>();
61  case VerifyPCH:              return llvm::make_unique<VerifyPCHAction>();
62
63  case PluginAction: {
64    for (FrontendPluginRegistry::iterator it =
65           FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
66         it != ie; ++it) {
67      if (it->getName() == CI.getFrontendOpts().ActionName) {
68        std::unique_ptr<PluginASTAction> P(it->instantiate());
69        if ((P->getActionType() != PluginASTAction::ReplaceAction &&
70             P->getActionType() != PluginASTAction::Cmdline) ||
71            !P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()]))
72          return nullptr;
73        return std::move(P);
74      }
75    }
76
77    CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
78      << CI.getFrontendOpts().ActionName;
79    return nullptr;
80  }
81
82  case PrintDeclContext:       return llvm::make_unique<DeclContextPrintAction>();
83  case PrintPreamble:          return llvm::make_unique<PrintPreambleAction>();
84  case PrintPreprocessedInput: {
85    if (CI.getPreprocessorOutputOpts().RewriteIncludes)
86      return llvm::make_unique<RewriteIncludesAction>();
87    return llvm::make_unique<PrintPreprocessedAction>();
88  }
89
90  case RewriteMacros:          return llvm::make_unique<RewriteMacrosAction>();
91  case RewriteTest:            return llvm::make_unique<RewriteTestAction>();
92#ifdef CLANG_ENABLE_OBJC_REWRITER
93  case RewriteObjC:            return llvm::make_unique<RewriteObjCAction>();
94#else
95  case RewriteObjC:            Action = "RewriteObjC"; break;
96#endif
97#ifdef CLANG_ENABLE_ARCMT
98  case MigrateSource:
99    return llvm::make_unique<arcmt::MigrateSourceAction>();
100#else
101  case MigrateSource:          Action = "MigrateSource"; break;
102#endif
103#ifdef CLANG_ENABLE_STATIC_ANALYZER
104  case RunAnalysis:            return llvm::make_unique<ento::AnalysisAction>();
105#else
106  case RunAnalysis:            Action = "RunAnalysis"; break;
107#endif
108  case RunPreprocessorOnly:    return llvm::make_unique<PreprocessOnlyAction>();
109  }
110
111#if !defined(CLANG_ENABLE_ARCMT) || !defined(CLANG_ENABLE_STATIC_ANALYZER) \
112  || !defined(CLANG_ENABLE_OBJC_REWRITER)
113  CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
114  return 0;
115#else
116  llvm_unreachable("Invalid program action!");
117#endif
118}
119
120static std::unique_ptr<FrontendAction>
121CreateFrontendAction(CompilerInstance &CI) {
122  // Create the underlying action.
123  std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
124  if (!Act)
125    return nullptr;
126
127  const FrontendOptions &FEOpts = CI.getFrontendOpts();
128
129  if (FEOpts.FixAndRecompile) {
130    Act = llvm::make_unique<FixItRecompile>(std::move(Act));
131  }
132
133#ifdef CLANG_ENABLE_ARCMT
134  if (CI.getFrontendOpts().ProgramAction != frontend::MigrateSource &&
135      CI.getFrontendOpts().ProgramAction != frontend::GeneratePCH) {
136    // Potentially wrap the base FE action in an ARC Migrate Tool action.
137    switch (FEOpts.ARCMTAction) {
138    case FrontendOptions::ARCMT_None:
139      break;
140    case FrontendOptions::ARCMT_Check:
141      Act = llvm::make_unique<arcmt::CheckAction>(std::move(Act));
142      break;
143    case FrontendOptions::ARCMT_Modify:
144      Act = llvm::make_unique<arcmt::ModifyAction>(std::move(Act));
145      break;
146    case FrontendOptions::ARCMT_Migrate:
147      Act = llvm::make_unique<arcmt::MigrateAction>(std::move(Act),
148                                     FEOpts.MTMigrateDir,
149                                     FEOpts.ARCMTMigrateReportOut,
150                                     FEOpts.ARCMTMigrateEmitARCErrors);
151      break;
152    }
153
154    if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
155      Act = llvm::make_unique<arcmt::ObjCMigrateAction>(std::move(Act),
156                                                        FEOpts.MTMigrateDir,
157                                                        FEOpts.ObjCMTAction);
158    }
159  }
160#endif
161
162  // If there are any AST files to merge, create a frontend action
163  // adaptor to perform the merge.
164  if (!FEOpts.ASTMergeFiles.empty())
165    Act = llvm::make_unique<ASTMergeAction>(std::move(Act),
166                                            FEOpts.ASTMergeFiles);
167
168  return Act;
169}
170
171bool clang::ExecuteCompilerInvocation(CompilerInstance *Clang) {
172  // Honor -help.
173  if (Clang->getFrontendOpts().ShowHelp) {
174    std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
175    Opts->PrintHelp(llvm::outs(), "clang -cc1",
176                    "LLVM 'Clang' Compiler: http://clang.llvm.org",
177                    /*Include=*/ driver::options::CC1Option, /*Exclude=*/ 0);
178    return true;
179  }
180
181  // Honor -version.
182  //
183  // FIXME: Use a better -version message?
184  if (Clang->getFrontendOpts().ShowVersion) {
185    llvm::cl::PrintVersionMessage();
186    return true;
187  }
188
189  // Load any requested plugins.
190  for (unsigned i = 0,
191         e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
192    const std::string &Path = Clang->getFrontendOpts().Plugins[i];
193    std::string Error;
194    if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
195      Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
196        << Path << Error;
197  }
198
199  // Check if any of the loaded plugins replaces the main AST action
200  for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
201                                        ie = FrontendPluginRegistry::end();
202       it != ie; ++it) {
203    std::unique_ptr<PluginASTAction> P(it->instantiate());
204    if (P->getActionType() == PluginASTAction::ReplaceAction) {
205      Clang->getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
206      Clang->getFrontendOpts().ActionName = it->getName();
207      break;
208    }
209  }
210
211  // Honor -mllvm.
212  //
213  // FIXME: Remove this, one day.
214  // This should happen AFTER plugins have been loaded!
215  if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
216    unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
217    auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
218    Args[0] = "clang (LLVM option parsing)";
219    for (unsigned i = 0; i != NumArgs; ++i)
220      Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
221    Args[NumArgs + 1] = nullptr;
222    llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
223  }
224
225#ifdef CLANG_ENABLE_STATIC_ANALYZER
226  // Honor -analyzer-checker-help.
227  // This should happen AFTER plugins have been loaded!
228  if (Clang->getAnalyzerOpts()->ShowCheckerHelp) {
229    ento::printCheckerHelp(llvm::outs(), Clang->getFrontendOpts().Plugins);
230    return true;
231  }
232#endif
233
234  // If there were errors in processing arguments, don't do anything else.
235  if (Clang->getDiagnostics().hasErrorOccurred())
236    return false;
237  // Create and execute the frontend action.
238  std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
239  if (!Act)
240    return false;
241  bool Success = Clang->ExecuteAction(*Act);
242  if (Clang->getFrontendOpts().DisableFree)
243    BuryPointer(std::move(Act));
244  return Success;
245}
246