cc1_main.cpp revision 1e3c6f4ab525beb31390f6b2f1154bd5c63bfb3f
1//===-- cc1_main.cpp - Clang CC1 Driver -----------------------------------===//
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 is the entry point to the clang -cc1 functionality, which implements the
11// core compiler functionality along with a number of additional tools for
12// demonstration and testing purposes.
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Driver/Arg.h"
18#include "clang/Driver/ArgList.h"
19#include "clang/Driver/CC1Options.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/OptTable.h"
22#include "clang/Frontend/CodeGenAction.h"
23#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/CompilerInvocation.h"
25#include "clang/Frontend/FrontendActions.h"
26#include "clang/Frontend/FrontendDiagnostic.h"
27#include "clang/Frontend/FrontendPluginRegistry.h"
28#include "clang/Frontend/TextDiagnosticBuffer.h"
29#include "clang/Frontend/TextDiagnosticPrinter.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/ADT/OwningPtr.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/Timer.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/System/DynamicLibrary.h"
38#include "llvm/Target/TargetSelect.h"
39#include <cstdio>
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43// Main driver
44//===----------------------------------------------------------------------===//
45
46void LLVMErrorHandler(void *UserData, const std::string &Message) {
47  Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
48
49  Diags.Report(diag::err_fe_error_backend) << Message;
50
51  // We cannot recover from llvm errors.
52  exit(1);
53}
54
55static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
56  using namespace clang::frontend;
57
58  switch (CI.getFrontendOpts().ProgramAction) {
59  default:
60    llvm_unreachable("Invalid program action!");
61
62  case ASTDump:                return new ASTDumpAction();
63  case ASTPrint:               return new ASTPrintAction();
64  case ASTPrintXML:            return new ASTPrintXMLAction();
65  case ASTView:                return new ASTViewAction();
66  case DumpRawTokens:          return new DumpRawTokensAction();
67  case DumpRecordLayouts:      return new DumpRecordAction();
68  case DumpTokens:             return new DumpTokensAction();
69  case EmitAssembly:           return new EmitAssemblyAction();
70  case EmitBC:                 return new EmitBCAction();
71  case EmitHTML:               return new HTMLPrintAction();
72  case EmitLLVM:               return new EmitLLVMAction();
73  case EmitLLVMOnly:           return new EmitLLVMOnlyAction();
74  case EmitObj:                return new EmitObjAction();
75  case FixIt:                  return new FixItAction();
76  case GeneratePCH:            return new GeneratePCHAction();
77  case GeneratePTH:            return new GeneratePTHAction();
78  case InheritanceView:        return new InheritanceViewAction();
79  case InitOnly:               return new InitOnlyAction();
80  case ParseNoop:              return new ParseOnlyAction();
81  case ParsePrintCallbacks:    return new PrintParseAction();
82  case ParseSyntaxOnly:        return new SyntaxOnlyAction();
83
84  case PluginAction: {
85    if (CI.getFrontendOpts().ActionName == "help") {
86      llvm::errs() << "clang -cc1 plugins:\n";
87      for (FrontendPluginRegistry::iterator it =
88             FrontendPluginRegistry::begin(),
89             ie = FrontendPluginRegistry::end();
90           it != ie; ++it)
91        llvm::errs() << "  " << it->getName() << " - " << it->getDesc() << "\n";
92      return 0;
93    }
94
95    for (FrontendPluginRegistry::iterator it =
96           FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
97         it != ie; ++it) {
98      if (it->getName() == CI.getFrontendOpts().ActionName)
99        return it->instantiate();
100    }
101
102    CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
103      << CI.getFrontendOpts().ActionName;
104    return 0;
105  }
106
107  case PrintDeclContext:       return new DeclContextPrintAction();
108  case PrintPreprocessedInput: return new PrintPreprocessedAction();
109  case RewriteMacros:          return new RewriteMacrosAction();
110  case RewriteObjC:            return new RewriteObjCAction();
111  case RewriteTest:            return new RewriteTestAction();
112  case RunAnalysis:            return new AnalysisAction();
113  case RunPreprocessorOnly:    return new PreprocessOnlyAction();
114  }
115}
116
117static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
118  // Create the underlying action.
119  FrontendAction *Act = CreateFrontendBaseAction(CI);
120  if (!Act)
121    return 0;
122
123  // If there are any AST files to merge, create a frontend action
124  // adaptor to perform the merge.
125  if (!CI.getFrontendOpts().ASTMergeFiles.empty())
126    Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
127                             CI.getFrontendOpts().ASTMergeFiles.size());
128
129  return Act;
130}
131
132// FIXME: Define the need for this testing away.
133static int cc1_test(Diagnostic &Diags,
134                    const char **ArgBegin, const char **ArgEnd) {
135  using namespace clang::driver;
136
137  llvm::errs() << "cc1 argv:";
138  for (const char **i = ArgBegin; i != ArgEnd; ++i)
139    llvm::errs() << " \"" << *i << '"';
140  llvm::errs() << "\n";
141
142  // Parse the arguments.
143  OptTable *Opts = createCC1OptTable();
144  unsigned MissingArgIndex, MissingArgCount;
145  InputArgList *Args = Opts->ParseArgs(ArgBegin, ArgEnd,
146                                       MissingArgIndex, MissingArgCount);
147
148  // Check for missing argument error.
149  if (MissingArgCount)
150    Diags.Report(clang::diag::err_drv_missing_argument)
151      << Args->getArgString(MissingArgIndex) << MissingArgCount;
152
153  // Dump the parsed arguments.
154  llvm::errs() << "cc1 parsed options:\n";
155  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
156       it != ie; ++it)
157    (*it)->dump();
158
159  // Create a compiler invocation.
160  llvm::errs() << "cc1 creating invocation.\n";
161  CompilerInvocation Invocation;
162  CompilerInvocation::CreateFromArgs(Invocation, ArgBegin, ArgEnd, Diags);
163
164  // Convert the invocation back to argument strings.
165  std::vector<std::string> InvocationArgs;
166  Invocation.toArgs(InvocationArgs);
167
168  // Dump the converted arguments.
169  llvm::SmallVector<const char*, 32> Invocation2Args;
170  llvm::errs() << "invocation argv :";
171  for (unsigned i = 0, e = InvocationArgs.size(); i != e; ++i) {
172    Invocation2Args.push_back(InvocationArgs[i].c_str());
173    llvm::errs() << " \"" << InvocationArgs[i] << '"';
174  }
175  llvm::errs() << "\n";
176
177  // Convert those arguments to another invocation, and check that we got the
178  // same thing.
179  CompilerInvocation Invocation2;
180  CompilerInvocation::CreateFromArgs(Invocation2, Invocation2Args.begin(),
181                                     Invocation2Args.end(), Diags);
182
183  // FIXME: Implement CompilerInvocation comparison.
184  if (true) {
185    //llvm::errs() << "warning: Invocations differ!\n";
186
187    std::vector<std::string> Invocation2Args;
188    Invocation2.toArgs(Invocation2Args);
189    llvm::errs() << "invocation2 argv:";
190    for (unsigned i = 0, e = Invocation2Args.size(); i != e; ++i)
191      llvm::errs() << " \"" << Invocation2Args[i] << '"';
192    llvm::errs() << "\n";
193  }
194
195  return 0;
196}
197
198int cc1_main(const char **ArgBegin, const char **ArgEnd,
199             const char *Argv0, void *MainAddr) {
200  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
201
202  Clang->setLLVMContext(new llvm::LLVMContext());
203
204  // Run clang -cc1 test.
205  if (ArgBegin != ArgEnd && llvm::StringRef(ArgBegin[0]) == "-cc1test") {
206    TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());
207    Diagnostic Diags(&DiagClient);
208    return cc1_test(Diags, ArgBegin + 1, ArgEnd);
209  }
210
211  // Initialize targets first, so that --version shows registered targets.
212  llvm::InitializeAllTargets();
213  llvm::InitializeAllAsmPrinters();
214  llvm::InitializeAllAsmParsers();
215
216  // Buffer diagnostics from argument parsing so that we can output them using a
217  // well formed diagnostic object.
218  TextDiagnosticBuffer DiagsBuffer;
219  Diagnostic Diags(&DiagsBuffer);
220  CompilerInvocation::CreateFromArgs(Clang->getInvocation(), ArgBegin, ArgEnd,
221                                     Diags);
222
223  // Infer the builtin include path if unspecified.
224  if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
225      Clang->getHeaderSearchOpts().ResourceDir.empty())
226    Clang->getHeaderSearchOpts().ResourceDir =
227      CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
228
229  // Honor -help.
230  if (Clang->getFrontendOpts().ShowHelp) {
231    llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1OptTable());
232    Opts->PrintHelp(llvm::outs(), "clang -cc1",
233                    "LLVM 'Clang' Compiler: http://clang.llvm.org");
234    return 0;
235  }
236
237  // Honor -version.
238  //
239  // FIXME: Use a better -version message?
240  if (Clang->getFrontendOpts().ShowVersion) {
241    llvm::cl::PrintVersionMessage();
242    return 0;
243  }
244
245  // Create the actual diagnostics engine.
246  Clang->createDiagnostics(ArgEnd - ArgBegin, const_cast<char**>(ArgBegin));
247  if (!Clang->hasDiagnostics())
248    return 1;
249
250  // Set an error handler, so that any LLVM backend diagnostics go through our
251  // error handler.
252  llvm::install_fatal_error_handler(LLVMErrorHandler,
253                                  static_cast<void*>(&Clang->getDiagnostics()));
254
255  DiagsBuffer.FlushDiagnostics(Clang->getDiagnostics());
256
257  // Load any requested plugins.
258  for (unsigned i = 0,
259         e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
260    const std::string &Path = Clang->getFrontendOpts().Plugins[i];
261    std::string Error;
262    if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
263      Diags.Report(diag::err_fe_unable_to_load_plugin) << Path << Error;
264  }
265
266  // If there were errors in processing arguments, don't do anything else.
267  bool Success = false;
268  if (!Clang->getDiagnostics().getNumErrors()) {
269    // Create and execute the frontend action.
270    llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
271    if (Act) {
272      Success = Clang->ExecuteAction(*Act);
273      if (Clang->getFrontendOpts().DisableFree)
274        Act.take();
275    }
276  }
277
278  // If any timers were active but haven't been destroyed yet, print their
279  // results now.  This happens in -disable-free mode.
280  llvm::TimerGroup::printAll(llvm::errs());
281
282  // When running with -disable-free, don't do any destruction or shutdown.
283  if (Clang->getFrontendOpts().DisableFree) {
284    if (Clang->getFrontendOpts().ShowStats)
285      llvm::PrintStatistics();
286    Clang.take();
287    return !Success;
288  }
289
290  // Managed static deconstruction. Useful for making things like
291  // -time-passes usable.
292  llvm::llvm_shutdown();
293
294  return !Success;
295}
296