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 FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
35  using namespace clang::frontend;
36  StringRef Action("unknown");
37  (void)Action;
38
39  switch (CI.getFrontendOpts().ProgramAction) {
40  case ASTDeclList:            return new ASTDeclListAction();
41  case ASTDump:                return new ASTDumpAction();
42  case ASTPrint:               return new ASTPrintAction();
43  case ASTView:                return new ASTViewAction();
44  case DumpRawTokens:          return new DumpRawTokensAction();
45  case DumpTokens:             return new DumpTokensAction();
46  case EmitAssembly:           return new EmitAssemblyAction();
47  case EmitBC:                 return new EmitBCAction();
48#ifdef CLANG_ENABLE_REWRITER
49  case EmitHTML:               return new HTMLPrintAction();
50#else
51  case EmitHTML:               Action = "EmitHTML"; break;
52#endif
53  case EmitLLVM:               return new EmitLLVMAction();
54  case EmitLLVMOnly:           return new EmitLLVMOnlyAction();
55  case EmitCodeGenOnly:        return new EmitCodeGenOnlyAction();
56  case EmitObj:                return new EmitObjAction();
57#ifdef CLANG_ENABLE_REWRITER
58  case FixIt:                  return new FixItAction();
59#else
60  case FixIt:                  Action = "FixIt"; break;
61#endif
62  case GenerateModule:         return new GenerateModuleAction;
63  case GeneratePCH:            return new GeneratePCHAction;
64  case GeneratePTH:            return new GeneratePTHAction();
65  case InitOnly:               return new InitOnlyAction();
66  case ParseSyntaxOnly:        return new SyntaxOnlyAction();
67  case ModuleFileInfo:         return new DumpModuleInfoAction();
68  case VerifyPCH:              return new VerifyPCHAction();
69
70  case PluginAction: {
71    for (FrontendPluginRegistry::iterator it =
72           FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
73         it != ie; ++it) {
74      if (it->getName() == CI.getFrontendOpts().ActionName) {
75        std::unique_ptr<PluginASTAction> P(it->instantiate());
76        if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
77          return nullptr;
78        return P.release();
79      }
80    }
81
82    CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
83      << CI.getFrontendOpts().ActionName;
84    return nullptr;
85  }
86
87  case PrintDeclContext:       return new DeclContextPrintAction();
88  case PrintPreamble:          return new PrintPreambleAction();
89  case PrintPreprocessedInput: {
90    if (CI.getPreprocessorOutputOpts().RewriteIncludes) {
91#ifdef CLANG_ENABLE_REWRITER
92      return new RewriteIncludesAction();
93#else
94      Action = "RewriteIncludesAction";
95      break;
96#endif
97    }
98    return new PrintPreprocessedAction();
99  }
100
101#ifdef CLANG_ENABLE_REWRITER
102  case RewriteMacros:          return new RewriteMacrosAction();
103  case RewriteObjC:            return new RewriteObjCAction();
104  case RewriteTest:            return new RewriteTestAction();
105#else
106  case RewriteMacros:          Action = "RewriteMacros"; break;
107  case RewriteObjC:            Action = "RewriteObjC"; break;
108  case RewriteTest:            Action = "RewriteTest"; break;
109#endif
110#ifdef CLANG_ENABLE_ARCMT
111  case MigrateSource:          return new arcmt::MigrateSourceAction();
112#else
113  case MigrateSource:          Action = "MigrateSource"; break;
114#endif
115#ifdef CLANG_ENABLE_STATIC_ANALYZER
116  case RunAnalysis:            return new ento::AnalysisAction();
117#else
118  case RunAnalysis:            Action = "RunAnalysis"; break;
119#endif
120  case RunPreprocessorOnly:    return new PreprocessOnlyAction();
121  }
122
123#if !defined(CLANG_ENABLE_ARCMT) || !defined(CLANG_ENABLE_STATIC_ANALYZER) \
124  || !defined(CLANG_ENABLE_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
132static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
133  // Create the underlying action.
134  FrontendAction *Act = CreateFrontendBaseAction(CI);
135  if (!Act)
136    return nullptr;
137
138  const FrontendOptions &FEOpts = CI.getFrontendOpts();
139
140#ifdef CLANG_ENABLE_REWRITER
141  if (FEOpts.FixAndRecompile) {
142    Act = new FixItRecompile(Act);
143  }
144#endif
145
146#ifdef CLANG_ENABLE_ARCMT
147  if (CI.getFrontendOpts().ProgramAction != frontend::MigrateSource &&
148      CI.getFrontendOpts().ProgramAction != frontend::GeneratePCH) {
149    // Potentially wrap the base FE action in an ARC Migrate Tool action.
150    switch (FEOpts.ARCMTAction) {
151    case FrontendOptions::ARCMT_None:
152      break;
153    case FrontendOptions::ARCMT_Check:
154      Act = new arcmt::CheckAction(Act);
155      break;
156    case FrontendOptions::ARCMT_Modify:
157      Act = new arcmt::ModifyAction(Act);
158      break;
159    case FrontendOptions::ARCMT_Migrate:
160      Act = new arcmt::MigrateAction(Act,
161                                     FEOpts.MTMigrateDir,
162                                     FEOpts.ARCMTMigrateReportOut,
163                                     FEOpts.ARCMTMigrateEmitARCErrors);
164      break;
165    }
166
167    if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
168      Act = new arcmt::ObjCMigrateAction(Act, 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 = new ASTMergeAction(Act, FEOpts.ASTMergeFiles);
178
179  return Act;
180}
181
182bool clang::ExecuteCompilerInvocation(CompilerInstance *Clang) {
183  // Honor -help.
184  if (Clang->getFrontendOpts().ShowHelp) {
185    std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
186    Opts->PrintHelp(llvm::outs(), "clang -cc1",
187                    "LLVM 'Clang' Compiler: http://clang.llvm.org",
188                    /*Include=*/ driver::options::CC1Option, /*Exclude=*/ 0);
189    return true;
190  }
191
192  // Honor -version.
193  //
194  // FIXME: Use a better -version message?
195  if (Clang->getFrontendOpts().ShowVersion) {
196    llvm::cl::PrintVersionMessage();
197    return true;
198  }
199
200  // Load any requested plugins.
201  for (unsigned i = 0,
202         e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
203    const std::string &Path = Clang->getFrontendOpts().Plugins[i];
204    std::string Error;
205    if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
206      Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
207        << Path << Error;
208  }
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 = llvm::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#ifdef CLANG_ENABLE_STATIC_ANALYZER
225  // Honor -analyzer-checker-help.
226  // This should happen AFTER plugins have been loaded!
227  if (Clang->getAnalyzerOpts()->ShowCheckerHelp) {
228    ento::printCheckerHelp(llvm::outs(), Clang->getFrontendOpts().Plugins);
229    return true;
230  }
231#endif
232
233  // If there were errors in processing arguments, don't do anything else.
234  if (Clang->getDiagnostics().hasErrorOccurred())
235    return false;
236  // Create and execute the frontend action.
237  std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
238  if (!Act)
239    return false;
240  bool Success = Clang->ExecuteAction(*Act);
241  if (Clang->getFrontendOpts().DisableFree)
242    BuryPointer(Act.release());
243  return Success;
244}
245