blob: 1b9578c743bcad6ec9c97d87722d9c78681f00d0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000017
Daniel Dunbar0498cfc2009-11-10 19:51:53 +000018#include "Options.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000019#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclGroup.h"
23#include "clang/Analysis/PathDiagnostic.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Basic/Version.h"
28#include "clang/CodeGen/ModuleBuilder.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000029#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000030#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000031#include "clang/Frontend/AnalysisConsumer.h"
Daniel Dunbardbf75fe2009-11-11 08:13:24 +000032#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000033#include "clang/Frontend/CommandLineSourceLoc.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000034#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbar0e0bae82009-11-11 21:43:12 +000035#include "clang/Frontend/DependencyOutputOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000036#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000037#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000039#include "clang/Frontend/PathDiagnosticClients.h"
40#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000041#include "clang/Frontend/PreprocessorOutputOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000042#include "clang/Frontend/TextDiagnosticBuffer.h"
43#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000044#include "clang/Frontend/Utils.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000045#include "clang/Lex/HeaderSearch.h"
46#include "clang/Lex/LexDiagnostic.h"
47#include "clang/Parse/Parser.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000048#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000049#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000050#include "clang/Sema/SemaDiagnostic.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000051#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000053#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000055#include "llvm/ADT/StringMap.h"
Daniel Dunbar227b2382009-11-09 22:45:57 +000056#include "llvm/ADT/StringSwitch.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000059#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000060#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000061#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000062#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000063#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000065#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000066#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000067#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000070#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000071#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000072#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000073# include <sys/types.h>
74#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000075
Reid Spencer5f016e22007-07-11 17:01:13 +000076using namespace clang;
77
78//===----------------------------------------------------------------------===//
Daniel Dunbaraa576142009-11-12 15:23:20 +000079// Code Completion Options
Reid Spencer5f016e22007-07-11 17:01:13 +000080//===----------------------------------------------------------------------===//
81
Daniel Dunbaraa576142009-11-12 15:23:20 +000082enum CodeCompletionPrinter {
83 CCP_Debug,
84 CCP_CIndex
85};
86
87static llvm::cl::opt<ParsedSourceLocation>
88CodeCompletionAt("code-completion-at",
89 llvm::cl::value_desc("file:line:column"),
90 llvm::cl::desc("Dump code-completion information at a location"));
91
92static llvm::cl::opt<CodeCompletionPrinter>
93CodeCompletionPrinter("code-completion-printer",
94 llvm::cl::desc("Choose output type:"),
95 llvm::cl::init(CCP_Debug),
96 llvm::cl::values(
97 clEnumValN(CCP_Debug, "debug",
98 "Debug code-completion results"),
99 clEnumValN(CCP_CIndex, "cindex",
100 "Code-completion results for the CIndex library"),
101 clEnumValEnd));
Chris Lattner47099742009-02-18 01:51:21 +0000102
Reid Spencer5f016e22007-07-11 17:01:13 +0000103static llvm::cl::opt<bool>
Daniel Dunbaraa576142009-11-12 15:23:20 +0000104CodeCompletionWantsMacros("code-completion-macros",
105 llvm::cl::desc("Include macros in code-completion results"));
106
107/// \brief Buld a new code-completion consumer that prints the results of
108/// code completion to standard output.
109static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
110 switch (CodeCompletionPrinter.getValue()) {
111 case CCP_Debug:
112 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
113 llvm::outs());
114
115 case CCP_CIndex:
116 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
117 llvm::outs());
118 };
119
120 return 0;
121}
122
123//===----------------------------------------------------------------------===//
124// Frontend Actions
125//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000126
127enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000128 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000129 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000130 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000131 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +0000132 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000133 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000135 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000136 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000137 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000138 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000139 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000140 ASTDump, // Parse ASTs and dump them.
141 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000142 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000143 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 ParsePrintCallbacks, // Parse and print each callback.
145 ParseSyntaxOnly, // Parse and perform semantic analysis.
146 ParseNoop, // Parse with noop callbacks.
147 RunPreprocessorOnly, // Just lex, no output.
148 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000149 DumpTokens, // Dump out preprocessed tokens.
150 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000151 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000152 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000153 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000154 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000155};
156
Mike Stump1eb44332009-09-09 15:08:12 +0000157static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000158ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
159 llvm::cl::init(ParseSyntaxOnly),
160 llvm::cl::values(
161 clEnumValN(RunPreprocessorOnly, "Eonly",
162 "Just run preprocessor, no output (for timings)"),
163 clEnumValN(PrintPreprocessedInput, "E",
164 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000165 clEnumValN(DumpRawTokens, "dump-raw-tokens",
166 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000167 clEnumValN(RunAnalysis, "analyze",
168 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000169 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 "Run preprocessor, dump internal rep of tokens"),
171 clEnumValN(ParseNoop, "parse-noop",
172 "Run parser with noop callbacks (for timings)"),
173 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
174 "Run parser and perform semantic analysis"),
175 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
176 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000177 clEnumValN(EmitHTML, "emit-html",
178 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000179 clEnumValN(ASTPrint, "ast-print",
180 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000181 clEnumValN(ASTPrintXML, "ast-print-xml",
182 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000183 clEnumValN(ASTDump, "ast-dump",
184 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000185 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000186 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000187 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000188 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000189 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
190 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000191 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000192 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000193 clEnumValN(GeneratePCH, "emit-pch",
194 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000195 clEnumValN(EmitAssembly, "S",
196 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000198 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000199 clEnumValN(EmitBC, "emit-llvm-bc",
200 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000201 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
202 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000203 clEnumValN(RewriteTest, "rewrite-test",
204 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000205 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000206 "Rewrite ObjC into C (code rewriter example)"),
207 clEnumValN(RewriteMacros, "rewrite-macros",
208 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000209 clEnumValN(RewriteBlocks, "rewrite-blocks",
210 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 clEnumValEnd));
212
Daniel Dunbaraa576142009-11-12 15:23:20 +0000213//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000214// Language Options
215//===----------------------------------------------------------------------===//
216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217static llvm::cl::opt<LangKind>
218BaseLang("x", llvm::cl::desc("Base language to compile"),
219 llvm::cl::init(langkind_unspecified),
220 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000221 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 clEnumValN(langkind_cxx, "c++", "C++"),
223 clEnumValN(langkind_objc, "objective-c", "Objective C"),
224 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000225 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000226 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000227 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
228 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000230 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
232 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000233 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000235 clEnumValN(langkind_c, "c-header",
236 "C header"),
237 clEnumValN(langkind_objc, "objective-c-header",
238 "Objective-C header"),
239 clEnumValN(langkind_cxx, "c++-header",
240 "C++ header"),
241 clEnumValN(langkind_objcxx, "objective-c++-header",
242 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000243 clEnumValN(langkind_ast, "ast",
244 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 clEnumValEnd));
246
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000247static llvm::cl::opt<std::string>
248TargetTriple("triple",
249 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
250
Daniel Dunbar56749082009-11-11 07:26:12 +0000251static llvm::cl::opt<std::string>
252TargetABI("target-abi",
253 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000254
255//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000256// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000257//===----------------------------------------------------------------------===//
258
Douglas Gregore1d918e2009-04-10 23:10:45 +0000259static bool InitializeSourceManager(Preprocessor &PP,
Daniel Dunbar26266882009-11-12 23:52:32 +0000260 const FrontendOptions &FEOpts,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000261 const std::string &InFile) {
262 // Figure out where to get and map in the main file.
263 SourceManager &SourceMgr = PP.getSourceManager();
264 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000265
Daniel Dunbar26266882009-11-12 23:52:32 +0000266 if (FEOpts.EmptyInputOnly) {
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000267 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000268 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000269 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
270 SourceMgr.createMainFileIDForMemBuffer(SB);
271 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000272 const FileEntry *File = FileMgr.getFile(InFile);
273 if (File) SourceMgr.createMainFileID(File, SourceLocation());
274 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000275 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000276 return true;
277 }
278 } else {
279 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000280 SourceMgr.createMainFileIDForMemBuffer(SB);
281 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000282 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000283 return true;
284 }
285 }
286
287 return false;
288}
289
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000290//===----------------------------------------------------------------------===//
291// Preprocessor construction
292//===----------------------------------------------------------------------===//
Chris Lattner5f9eae52008-03-01 08:07:28 +0000293
Daniel Dunbar750156a2009-11-07 04:19:57 +0000294std::string GetBuiltinIncludePath(const char *Argv0) {
295 llvm::sys::Path P =
296 llvm::sys::Path::GetMainExecutable(Argv0,
297 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000298
Daniel Dunbar750156a2009-11-07 04:19:57 +0000299 if (!P.isEmpty()) {
300 P.eraseComponent(); // Remove /clang from foo/bin/clang
301 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000302
Daniel Dunbar750156a2009-11-07 04:19:57 +0000303 // Get foo/lib/clang/<version>/include
304 P.appendComponent("lib");
305 P.appendComponent("clang");
306 P.appendComponent(CLANG_VERSION_STRING);
307 P.appendComponent("include");
308 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000309
Daniel Dunbar750156a2009-11-07 04:19:57 +0000310 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000311}
312
Daniel Dunbar90b18272009-11-04 23:56:25 +0000313static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000314CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000315 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000316 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000317 const DependencyOutputOptions &DepOpts,
318 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000319 FileManager &FileMgr) {
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000320 // Create a PTH manager if we are using some form of a token cache.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000321 PTHManager *PTHMgr = 0;
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000322 if (!PPOpts.getTokenCache().empty())
323 PTHMgr = PTHManager::Create(PPOpts.getTokenCache(), Diags);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000324
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000325 // FIXME: Don't fail like this.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000326 if (Diags.hasErrorOccurred())
327 exit(1);
328
329 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000330 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000331 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000332 SourceMgr, *HeaderInfo, PTHMgr,
333 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000334
335 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
336 // That argument is used as the IdentifierInfoLookup argument to
337 // IdentifierTable's ctor.
338 if (PTHMgr) {
339 PTHMgr->setPreprocessor(PP);
340 PP->setPTHManager(PTHMgr);
341 }
342
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000343 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000344
Daniel Dunbarca11f612009-11-11 21:44:00 +0000345 // Handle generating dependencies, if requested.
346 if (!DepOpts.OutputFile.empty())
347 AttachDependencyFileGen(*PP, DepOpts);
348
Daniel Dunbar90b18272009-11-04 23:56:25 +0000349 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000350}
Reid Spencer5f016e22007-07-11 17:01:13 +0000351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352//===----------------------------------------------------------------------===//
353// Basic Parser driver
354//===----------------------------------------------------------------------===//
355
Chris Lattner51574ea2008-04-19 23:25:44 +0000356static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000358 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Parsing the specified input file.
361 P.ParseTranslationUnit();
362 delete PA;
363}
364
365//===----------------------------------------------------------------------===//
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000366// Dump Build Information
Chris Lattner75a97cb2009-04-17 21:05:01 +0000367//===----------------------------------------------------------------------===//
368
Daniel Dunbar227b2382009-11-09 22:45:57 +0000369static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000370 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000371 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000372 std::string ErrorInfo;
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000373 llvm::raw_ostream *OS =
374 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000375 if (!ErrorInfo.empty()) {
376 llvm::errs() << "error opening -dump-build-information file '"
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000377 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000378 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000379 return;
380 }
381
Daniel Dunbaraea36412009-11-11 09:38:24 +0000382 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000383 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000384 (*OS) << argv[i] << ' ';
385 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000387 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000388 DiagnosticClient *Logger =
389 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000390 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000391}
392
Chris Lattner75a97cb2009-04-17 21:05:01 +0000393//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000394// Main driver
395//===----------------------------------------------------------------------===//
396
Daniel Dunbaraa576142009-11-12 15:23:20 +0000397/// ClangFrontendTimer - The front-end activities should charge time to it with
398/// TimeRegion. The -ftime-report option controls whether this will do
399/// anything.
400llvm::Timer *ClangFrontendTimer = 0;
401
Daniel Dunbare29709f2009-11-09 20:55:08 +0000402static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
403 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000404 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000405 bool Binary,
406 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000407 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000408 std::string OutFile;
Daniel Dunbar26266882009-11-12 23:52:32 +0000409 if (!CompOpts.getFrontendOpts().OutputFile.empty())
410 OutFile = CompOpts.getFrontendOpts().OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +0000411 else if (InFile == "-") {
412 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000413 } else if (Extension) {
414 llvm::sys::Path Path(InFile);
415 Path.eraseSuffix();
416 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000417 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000418 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000419 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000420 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000421
Chris Lattner92bcc272009-08-23 02:59:41 +0000422 std::string Error;
423 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000424 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000425 if (!Error.empty()) {
426 // FIXME: Don't fail this way.
427 llvm::errs() << "ERROR: " << Error << "\n";
428 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner92bcc272009-08-23 02:59:41 +0000431 if (OutFile != "-")
432 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000433
434 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000435}
436
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000437/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000438/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000439static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000440 FileManager &FileMgr,
441 const std::vector<ParsedSourceLocation> &Locs) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000442 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000443
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000444 for (unsigned i = 0, e = Locs.size(); i != e; ++i) {
445 if (const FileEntry *File = FileMgr.getFile(Locs[i].FileName)) {
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000446 RequestedSourceLocation Requested;
447 Requested.File = File;
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000448 Requested.Line = Locs[i].Line;
449 Requested.Column = Locs[i].Column;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000450 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000451 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000452 } else {
453 llvm::errs() << "FIX-IT could not find file \""
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000454 << Locs[i].FileName << "\"\n";
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000455 }
456 }
457
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000458 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000459}
460
Daniel Dunbare29709f2009-11-09 20:55:08 +0000461static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
462 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000463 const std::string &InFile,
464 ProgActions PA,
465 llvm::OwningPtr<llvm::raw_ostream> &OS,
466 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000467 llvm::LLVMContext& Context) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000468 const FrontendOptions &FEOpts = CompOpts.getFrontendOpts();
469
Ted Kremenek85888962008-10-21 00:54:44 +0000470 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000472 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000473
474 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000475 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000476 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Douglas Gregoree75c052009-05-21 20:55:50 +0000478 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000479 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000480 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000481
Eli Friedman66d6f042009-05-18 22:20:00 +0000482 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000483 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000484
Eli Friedman66d6f042009-05-18 22:20:00 +0000485 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000486 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000487
Anders Carlsson78762eb2009-09-24 18:54:49 +0000488 case DumpRecordLayouts:
489 return CreateRecordLayoutDumper();
490
Eli Friedman66d6f042009-05-18 22:20:00 +0000491 case InheritanceView:
Daniel Dunbar26266882009-11-12 23:52:32 +0000492 return CreateInheritanceViewer(FEOpts.ViewClassInheritance);
Eli Friedman66d6f042009-05-18 22:20:00 +0000493
494 case EmitAssembly:
495 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000496 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000497 case EmitLLVMOnly: {
498 BackendAction Act;
499 if (ProgAction == EmitAssembly) {
500 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000501 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000502 } else if (ProgAction == EmitLLVM) {
503 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000504 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000505 } else if (ProgAction == EmitLLVMOnly) {
506 Act = Backend_EmitNothing;
507 } else {
508 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000509 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000510 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000511
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000512 // Fix-its can change semantics, disallow with any IRgen action.
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000513 if (FEOpts.FixItAll || !FEOpts.FixItLocations.empty()) {
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000514 PP.getDiagnostics().Report(diag::err_fe_no_fixit_and_codegen);
515 return 0;
516 }
517
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000518 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000519 CompOpts.getCodeGenOpts(), InFile, OS.get(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000520 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000521 }
522
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000523 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000524 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000525 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Daniel Dunbar69079432009-11-12 07:28:44 +0000526 PP.getLangOptions(),
527 CompOpts.getDiagnosticOpts().NoRewriteMacros);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000528
529 case RewriteBlocks:
530 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
531 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000532
533 case ParseSyntaxOnly:
534 return new ASTConsumer();
535
536 case PrintDeclContext:
537 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000538 }
539}
540
Daniel Dunbar975790e2009-11-12 02:53:20 +0000541/// ReadPCHFile - Load a PCH file from disk, and initialize the preprocessor for
542/// reading from the PCH file.
543///
544/// \return The AST source, or null on failure.
545static ExternalASTSource *ReadPCHFile(llvm::StringRef Path,
546 const CompilerInvocation &CompOpts,
547 Preprocessor &PP,
548 ASTContext &Context) {
549 // If the user specified -isysroot, it will be used for relocatable PCH files.
550 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
551 if (isysrootPCH[0] == '\0')
552 isysrootPCH = 0;
553
554 llvm::OwningPtr<PCHReader> Reader;
555 Reader.reset(new PCHReader(PP, &Context, isysrootPCH));
556
557 switch (Reader->ReadPCH(Path)) {
558 case PCHReader::Success:
559 // Set the predefines buffer as suggested by the PCH reader. Typically, the
560 // predefines buffer will be empty.
561 PP.setPredefines(Reader->getSuggestedPredefines());
562 return Reader.take();
563
564 case PCHReader::Failure:
565 // Unrecoverable failure: don't even try to process the input file.
566 break;
567
568 case PCHReader::IgnorePCH:
569 // No suitable PCH file could be found. Return an error.
570 break;
571 }
572
573 return 0;
574}
575
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000576/// ProcessInputFile - Process a single input file with the specified state.
577///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000578static void ProcessInputFile(const CompilerInvocation &CompOpts,
579 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000580 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000581 const FrontendOptions &FEOpts = CompOpts.getFrontendOpts();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000582 llvm::OwningPtr<llvm::raw_ostream> OS;
583 llvm::OwningPtr<ASTConsumer> Consumer;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000584 FixItRewriter *FixItRewrite = 0;
585 bool CompleteTranslationUnit = true;
586 llvm::sys::Path OutPath;
587
588 switch (PA) {
589 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000590 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000591 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000592 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000593 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000594 return;
595 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000596 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000597
598 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000599 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000600 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000601 break;
602
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000603 case RunAnalysis:
Daniel Dunbar26266882009-11-12 23:52:32 +0000604 Consumer.reset(CreateAnalysisConsumer(PP, FEOpts.OutputFile,
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000605 CompOpts.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000606 break;
607
Daniel Dunbarf7973292009-11-11 08:13:32 +0000608 case GeneratePCH: {
609 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
Daniel Dunbar26266882009-11-12 23:52:32 +0000610 bool Relocatable = FEOpts.RelocatablePCH;
611 if (Relocatable && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000612 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
Daniel Dunbar26266882009-11-12 23:52:32 +0000613 Relocatable = false;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Daniel Dunbare29709f2009-11-09 20:55:08 +0000616 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar26266882009-11-12 23:52:32 +0000617 if (Relocatable)
Daniel Dunbarf7973292009-11-11 08:13:32 +0000618 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000619 else
620 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000621 CompleteTranslationUnit = false;
622 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000623 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000624
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000625 // Do any necessary set up for non-consumer actions.
626 case DumpRawTokens:
627 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000628 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000629 case ParseNoop:
630 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000632 case GeneratePTH:
Daniel Dunbar26266882009-11-12 23:52:32 +0000633 if (FEOpts.OutputFile.empty() || FEOpts.OutputFile == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000634 // FIXME: Don't fail this way.
635 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000636 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000637 ::exit(1);
638 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000639 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000640 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000641
Chris Lattnercc7dea82009-04-27 22:02:30 +0000642 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000643 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000644 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000645 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000646 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000647 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000648 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000649
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000650 // Check if we want a fix-it rewriter.
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000651 if (FEOpts.FixItAll || !FEOpts.FixItLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000652 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000653 PP.getSourceManager(),
654 PP.getLangOptions());
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000655 if (!FEOpts.FixItLocations.empty() &&
656 !AddFixItLocations(FixItRewrite, PP.getFileManager(),
657 FEOpts.FixItLocations)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000658 // All of the fix-it locations were bad. Don't fix anything.
659 delete FixItRewrite;
660 FixItRewrite = 0;
661 }
662 }
663
664 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000665 llvm::OwningPtr<ExternalASTSource> Source;
666 const std::string &ImplicitPCHInclude =
667 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000668 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000669 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
670 PP.getSourceManager(),
671 PP.getTargetInfo(),
672 PP.getIdentifierTable(),
673 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000674 PP.getBuiltinInfo(),
Daniel Dunbar26266882009-11-12 23:52:32 +0000675 /* FreeMemory = */ !FEOpts.DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000676 /* size_reserve = */0));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000677
678 if (!ImplicitPCHInclude.empty()) {
679 Source.reset(ReadPCHFile(ImplicitPCHInclude, CompOpts, PP,
680 *ContextOwner));
681 if (!Source)
682 return;
683
684 // Attach the PCH reader to the AST context as an external AST source, so
685 // that declarations will be deserialized from the PCH file as needed.
686 ContextOwner->setExternalSource(Source);
687 } else {
688 // Initialize builtin info when not using PCH.
689 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
690 PP.getLangOptions().NoBuiltin);
691 }
692
693 // Initialize the main file entry. This needs to be delayed until after PCH
694 // has loaded.
Daniel Dunbar26266882009-11-12 23:52:32 +0000695 if (InitializeSourceManager(PP, CompOpts.getFrontendOpts(), InFile))
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000696 return;
697
Douglas Gregor81b747b2009-09-17 21:32:03 +0000698 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
699 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000700
Douglas Gregorb657f112009-09-22 21:11:38 +0000701 if (!CodeCompletionAt.FileName.empty()) {
702 // Tell the source manager to chop off the given file at a specific
703 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000704 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000705 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
706 // Truncate the named file at the given line/column.
707 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
708 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000709
Douglas Gregorb657f112009-09-22 21:11:38 +0000710 // Set up the creation routine for code-completion.
711 CreateCodeCompleter = BuildPrintingCodeCompleter;
712 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000713 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000714 << CodeCompletionAt.FileName;
715 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000716 }
717
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000718 // Run the AST consumer action.
Daniel Dunbar26266882009-11-12 23:52:32 +0000719 ParseAST(PP, Consumer.get(), *ContextOwner.get(), FEOpts.ShowStats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000720 CompleteTranslationUnit,
721 CreateCodeCompleter, CreateCodeCompleterData);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000722 } else {
723 // Initialize builtin info.
724 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
725 PP.getLangOptions().NoBuiltin);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000726
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000727 // Initialize the main file entry. This needs to be delayed until after PCH
728 // has loaded.
Daniel Dunbar26266882009-11-12 23:52:32 +0000729 if (InitializeSourceManager(PP, CompOpts.getFrontendOpts(), InFile))
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000730 return;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000731
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000732 // Run the preprocessor actions.
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000733 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000734 switch (PA) {
735 default:
736 assert(0 && "unexpected program action");
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000737
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000738 case DumpRawTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000739 SourceManager &SM = PP.getSourceManager();
740 // Start lexing the specified input file.
741 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
742 RawLex.SetKeepWhitespaceMode(true);
743
744 Token RawTok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000745 RawLex.LexFromRawLexer(RawTok);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000746 while (RawTok.isNot(tok::eof)) {
747 PP.DumpToken(RawTok, true);
748 fprintf(stderr, "\n");
749 RawLex.LexFromRawLexer(RawTok);
750 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000751 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000752 }
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000753
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000754 case DumpTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000755 Token Tok;
756 // Start preprocessing the specified input file.
757 PP.EnterMainSourceFile();
758 do {
759 PP.Lex(Tok);
760 PP.DumpToken(Tok, true);
761 fprintf(stderr, "\n");
762 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000763 break;
764 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000765
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000766 case GeneratePTH:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000767 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000768 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000769
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000770 case ParseNoop:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000771 ParseFile(PP, new MinimalAction(PP));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000772 break;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000773
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000774 case ParsePrintCallbacks:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000775 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000776 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000777
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000778 case PrintPreprocessedInput:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000779 DoPrintPreprocessedInput(PP, OS.get(),
780 CompOpts.getPreprocessorOutputOpts());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000781 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000782
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000783 case RewriteMacros:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000784 RewriteMacrosInInput(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000785 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000786
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000787 case RewriteTest:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000788 DoRewriteTest(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000789 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000790
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000791 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000792 Token Tok;
793 // Start parsing the specified input file.
794 PP.EnterMainSourceFile();
795 do {
796 PP.Lex(Tok);
797 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000798 break;
799 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000800 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000801 }
802
Chris Lattner1aee61a2009-04-27 21:25:27 +0000803 if (FixItRewrite)
Daniel Dunbar26266882009-11-12 23:52:32 +0000804 FixItRewrite->WriteFixedFile(InFile, FEOpts.OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000805
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000806 // Release the consumer and the AST, in that order since the consumer may
807 // perform actions in its destructor which require the context.
Daniel Dunbar26266882009-11-12 23:52:32 +0000808 if (FEOpts.DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000809 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000810 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000811 } else {
812 Consumer.reset();
813 ContextOwner.reset();
814 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000815
Daniel Dunbar26266882009-11-12 23:52:32 +0000816 if (CompOpts.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000817 if (CheckDiagnostics(PP))
818 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000819
Daniel Dunbar26266882009-11-12 23:52:32 +0000820 if (FEOpts.ShowStats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000821 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 PP.PrintStats();
823 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000824 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000825 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000826 fprintf(stderr, "\n");
827 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000828
Eli Friedman66d6f042009-05-18 22:20:00 +0000829 // Always delete the output stream because we don't want to leak file
830 // handles. Also, we don't want to try to erase an open file.
831 OS.reset();
832
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000833 // If we had errors, try to erase the output file.
834 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000835 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000836}
837
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000838/// ProcessInputFile - Process a single AST input file with the specified state.
839///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000840static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
841 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000842 Diagnostic &Diags, FileManager &FileMgr,
843 llvm::LLVMContext& Context) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000844 const FrontendOptions &FEOpts = CompOpts.getFrontendOpts();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000845 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000846 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000847 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000848 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000849 return;
850 }
851
852 Preprocessor &PP = AST->getPreprocessor();
853
854 llvm::OwningPtr<llvm::raw_ostream> OS;
855 llvm::sys::Path OutPath;
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000856 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000857 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000858 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000859 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000860 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000861 return;
862 }
863
Daniel Dunbara674bf42009-09-21 03:03:56 +0000864 // Set the main file ID to an empty file.
865 //
866 // FIXME: We probably shouldn't need this, but for now this is the simplest
867 // way to reuse the logic in ParseAST.
868 const char *EmptyStr = "";
869 llvm::MemoryBuffer *SB =
870 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
871 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000872
Daniel Dunbara674bf42009-09-21 03:03:56 +0000873 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000874 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbar26266882009-11-12 23:52:32 +0000875 ParseAST(PP, Consumer.get(), AST->getASTContext(), FEOpts.ShowStats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000876 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000877
878 // Release the consumer and the AST, in that order since the consumer may
879 // perform actions in its destructor which require the context.
Daniel Dunbar26266882009-11-12 23:52:32 +0000880 if (FEOpts.DisableFree) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000881 Consumer.take();
882 AST.take();
883 } else {
884 Consumer.reset();
885 AST.reset();
886 }
887
888 // Always delete the output stream because we don't want to leak file
889 // handles. Also, we don't want to try to erase an open file.
890 OS.reset();
891
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000892 // If we had errors, try to erase the output file.
893 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000894 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000895}
896
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000897static void LLVMErrorHandler(void *UserData, const std::string &Message) {
898 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
899
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000900 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000901
902 // We cannot recover from llvm errors.
903 exit(1);
904}
905
Daniel Dunbar26266882009-11-12 23:52:32 +0000906static LangKind GetLanguage(const std::vector<std::string> &Inputs) {
Daniel Dunbar227b2382009-11-09 22:45:57 +0000907 // If -x was given, that's the language.
908 if (BaseLang != langkind_unspecified)
909 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000910
Daniel Dunbar227b2382009-11-09 22:45:57 +0000911 // Otherwise guess it from the input filenames;
912 LangKind LK = langkind_unspecified;
Daniel Dunbar26266882009-11-12 23:52:32 +0000913 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
914 llvm::StringRef Name(Inputs[i]);
Daniel Dunbar227b2382009-11-09 22:45:57 +0000915 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
916 .Case("ast", langkind_ast)
917 .Case("c", langkind_c)
918 .Cases("S", "s", langkind_asm_cpp)
919 .Case("i", langkind_c_cpp)
920 .Case("ii", langkind_cxx_cpp)
921 .Case("m", langkind_objc)
922 .Case("mi", langkind_objc_cpp)
923 .Cases("mm", "M", langkind_objcxx)
924 .Case("mii", langkind_objcxx_cpp)
925 .Case("C", langkind_cxx)
926 .Cases("C", "cc", "cp", langkind_cxx)
927 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
928 .Case("cl", langkind_ocl)
929 .Default(langkind_c);
930
931 if (LK != langkind_unspecified && ThisKind != LK) {
932 llvm::errs() << "error: cannot have multiple input files of distinct "
933 << "language kinds without -x\n";
934 exit(1);
935 }
936
937 LK = ThisKind;
938 }
939
940 return LK;
941}
942
Daniel Dunbar227b2382009-11-09 22:45:57 +0000943static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000944 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +0000945 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000946 TargetInfo &Target,
Daniel Dunbar26266882009-11-12 23:52:32 +0000947 bool &IsAST) {
Daniel Dunbar227b2382009-11-09 22:45:57 +0000948 Opts.getDiagnosticOpts() = DiagOpts;
949
Daniel Dunbar26266882009-11-12 23:52:32 +0000950 // Initialize frontend options.
951 InitializeFrontendOptions(Opts.getFrontendOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000952
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000953 // Initialize backend options, which may also be used to key some language
954 // options.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000955 InitializeCodeGenOptions(Opts.getCodeGenOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000956
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000957 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000958 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000959 // FIXME: These aren't used during operations on ASTs. Split onto a separate
960 // code path to make this obvious.
Daniel Dunbar26266882009-11-12 23:52:32 +0000961 LangKind LK = GetLanguage(Opts.getFrontendOpts().InputFilenames);
962 IsAST = LK == langkind_ast;
963 if (!IsAST)
Daniel Dunbar56749082009-11-11 07:26:12 +0000964 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000965 Opts.getCodeGenOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000966
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000967 // Initialize the static analyzer options.
968 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
969
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000970 // Initialize the dependency output options (-M...).
971 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
972
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000973 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000974 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
975 GetBuiltinIncludePath(Argv0),
Daniel Dunbarf7973292009-11-11 08:13:32 +0000976 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000977
978 // Initialize the other preprocessor options.
979 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000980
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000981 // Initialize the preprocessed output options.
982 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
983
Daniel Dunbar26266882009-11-12 23:52:32 +0000984 // Finalize some code generation options which are derived from other places.
985 if (Opts.getLangOpts().NoBuiltin)
986 Opts.getCodeGenOpts().SimplifyLibCalls = 0;
987 if (Opts.getLangOpts().CPlusPlus)
988 Opts.getCodeGenOpts().NoCommon = 1;
989 Opts.getCodeGenOpts().TimePasses = Opts.getFrontendOpts().ShowTimers;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000990}
991
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000992static Diagnostic *CreateDiagnosticEngine(const DiagnosticOptions &Opts,
993 int argc, char **argv) {
994 // Create the diagnostic client for reporting errors or for
995 // implementing -verify.
996 llvm::OwningPtr<DiagnosticClient> DiagClient;
Daniel Dunbar26266882009-11-12 23:52:32 +0000997 if (Opts.VerifyDiagnostics) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000998 // When checking diagnostics, just buffer them up.
999 DiagClient.reset(new TextDiagnosticBuffer());
1000 } else {
1001 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
1002 }
1003
Daniel Dunbar11e729d2009-11-12 07:28:21 +00001004 if (!Opts.DumpBuildInformation.empty())
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001005 SetUpBuildDumpLog(Opts, argc, argv, DiagClient);
1006
1007 // Configure our handling of diagnostics.
1008 Diagnostic *Diags = new Diagnostic(DiagClient.take());
Daniel Dunbar69079432009-11-12 07:28:44 +00001009 if (ProcessWarningOptions(*Diags, Opts))
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001010 return 0;
1011
1012 // Set an error handler, so that any LLVM backend diagnostics go through our
1013 // error handler.
1014 llvm::llvm_install_error_handler(LLVMErrorHandler,
1015 static_cast<void*>(Diags));
1016
1017 return Diags;
1018}
1019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001022 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001023 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001024
Daniel Dunbar4d861512009-09-03 04:54:12 +00001025 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001026 llvm::InitializeAllTargets();
1027 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001028
1029 llvm::cl::ParseCommandLineOptions(argc, argv,
1030 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001032 // Construct the diagnostic engine first, so that we can build a diagnostic
1033 // client to use for any errors during option handling.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001034 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001035 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001036 llvm::OwningPtr<Diagnostic>
1037 Diags(CreateDiagnosticEngine(DiagOpts, argc, argv));
1038 if (!Diags)
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001039 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001040
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001041 // FIXME: Hack to make sure we release the diagnostic client, the engine
1042 // should (optionally?) take ownership of it.
1043 llvm::OwningPtr<DiagnosticClient> DiagClient(Diags->getClient());
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001044
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001045 // Initialize base triple. If a -triple option has been specified, use
1046 // that triple. Otherwise, default to the host triple.
1047 llvm::Triple Triple(TargetTriple);
1048 if (Triple.getTriple().empty())
1049 Triple = llvm::Triple(llvm::sys::getHostTriple());
1050
Chris Lattner11215192008-03-14 06:12:05 +00001051 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001052 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001053 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Chris Lattner11215192008-03-14 06:12:05 +00001054 if (Target == 0) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001055 Diags->Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001056 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Daniel Dunbar73b79592009-09-14 00:02:12 +00001059 // Set the target ABI if specified.
Daniel Dunbaraa576142009-11-12 15:23:20 +00001060 if (!TargetABI.empty() &&!Target->setABI(TargetABI)) {
1061 Diags->Report(diag::err_fe_unknown_target_abi) << TargetABI;
1062 return 1;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001063 }
1064
Daniel Dunbar26266882009-11-12 23:52:32 +00001065 // Now that we have initialized the diagnostics engine and the target, finish
1066 // setting up the compiler invocation.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001067 //
1068 // FIXME: We should move .ast inputs to taking a separate path, they are
1069 // really quite different.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001070 CompilerInvocation CompOpts;
Daniel Dunbar26266882009-11-12 23:52:32 +00001071 bool IsAST;
1072 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, IsAST);
1073
Daniel Dunbar1417c742009-11-12 23:52:46 +00001074 // Validate/process some options.
1075 if (CompOpts.getHeaderSearchOpts().Verbose)
1076 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1077 << " based upon " << PACKAGE_STRING
1078 << " hosted on " << llvm::sys::getHostTriple() << "\n";
1079
Daniel Dunbar26266882009-11-12 23:52:32 +00001080 if (CompOpts.getFrontendOpts().ShowTimers)
1081 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1082
1083 if (CompOpts.getDiagnosticOpts().VerifyDiagnostics &&
1084 CompOpts.getFrontendOpts().InputFilenames.size() > 1) {
1085 fprintf(stderr, "-verify only works on single input files.\n");
1086 return 1;
1087 }
1088
1089 // C++ visualization?
1090 if (!CompOpts.getFrontendOpts().ViewClassInheritance.empty())
1091 ProgAction = InheritanceView;
Daniel Dunbar227b2382009-11-09 22:45:57 +00001092
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001093 // Create the source manager.
1094 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Chris Lattner2c78b872009-04-14 23:22:57 +00001096 // Create a file manager object to provide access to and cache the filesystem.
1097 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001098
Daniel Dunbar26266882009-11-12 23:52:32 +00001099 for (unsigned i = 0, e = CompOpts.getFrontendOpts().InputFilenames.size();
1100 i != e; ++i) {
1101 const std::string &InFile = CompOpts.getFrontendOpts().InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001103 // AST inputs are handled specially.
Daniel Dunbar26266882009-11-12 23:52:32 +00001104 if (IsAST) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001105 ProcessASTInputFile(CompOpts, InFile, ProgAction, *Diags, FileMgr,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001106 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001107 continue;
1108 }
1109
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001110 // Reset the ID tables if we are reusing the SourceManager.
1111 if (i)
1112 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Chris Lattnerf63aea32009-03-04 21:40:56 +00001114 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001115 llvm::OwningPtr<Preprocessor>
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001116 PP(CreatePreprocessor(*Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001117 CompOpts.getPreprocessorOpts(),
Daniel Dunbar961c76e2009-11-11 21:44:42 +00001118 CompOpts.getHeaderSearchOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001119 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001120 *Target, SourceMgr, FileMgr));
1121
Chris Lattnerf63aea32009-03-04 21:40:56 +00001122 // Process the source file.
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001123 Diags->getClient()->BeginSourceFile(CompOpts.getLangOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001124 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001125 Diags->getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 }
Chris Lattner11215192008-03-14 06:12:05 +00001127
Daniel Dunbar9253e492009-11-10 00:46:12 +00001128 if (CompOpts.getDiagnosticOpts().ShowCarets)
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001129 if (unsigned NumDiagnostics = Diags->getNumDiagnostics())
Mike Stumpfc0fed32009-04-28 01:19:10 +00001130 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1131 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Daniel Dunbar26266882009-11-12 23:52:32 +00001133 if (CompOpts.getFrontendOpts().ShowStats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 FileMgr.PrintStats();
1135 fprintf(stderr, "\n");
1136 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001137
1138 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Daniel Dunbar276373d2008-10-27 22:10:13 +00001140 // If verifying diagnostics and we reached here, all is well.
Daniel Dunbar26266882009-11-12 23:52:32 +00001141 if (CompOpts.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001142 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001144 // Managed static deconstruction. Useful for making things like
1145 // -time-passes usable.
1146 llvm::llvm_shutdown();
1147
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001148 return (Diags->getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001149}