blob: a22e0d2b900e54c3763b79d87859138a02f4850a [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +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//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000027#include "clang/Driver/CompileOptions.h"
Ted Kremenek21b88b72008-11-03 22:31:48 +000028#include "clang/Driver/PathDiagnosticClients.h"
Nico Weber770e3882008-08-22 09:25:22 +000029#include "clang/Driver/InitHeaderSearch.h"
Nico Weber0e13eaa2008-08-05 23:33:20 +000030#include "clang/Driver/TextDiagnosticBuffer.h"
31#include "clang/Driver/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000039#include "clang/Parse/Parser.h"
40#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000041#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000042#include "clang/Basic/FileManager.h"
43#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/TargetInfo.h"
Chris Lattner93d4d982009-02-18 01:12:43 +000045#include "llvm/Pass.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000046#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000047#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000050#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000051#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000052#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000053#include "llvm/Support/PluginLoader.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000054#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000055#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000056#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000057using namespace clang;
58
59//===----------------------------------------------------------------------===//
60// Global options.
61//===----------------------------------------------------------------------===//
62
Daniel Dunbar4efedde2008-10-16 16:54:18 +000063static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000064
Chris Lattner4b009652007-07-25 00:24:17 +000065static llvm::cl::opt<bool>
66Verbose("v", llvm::cl::desc("Enable verbose output"));
67static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000068Stats("print-stats",
69 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000070static llvm::cl::opt<bool>
71DisableFree("disable-free",
72 llvm::cl::desc("Disable freeing of memory on exit"),
73 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000074
75enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000076 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000077 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000078 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000079 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000080 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000081 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000082 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000083 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000084 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000085 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000086 ASTPrint, // Parse ASTs and print them.
87 ASTDump, // Parse ASTs and dump them.
88 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000089 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000090 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000091 ParsePrintCallbacks, // Parse and print each callback.
92 ParseSyntaxOnly, // Parse and perform semantic analysis.
93 ParseNoop, // Parse with noop callbacks.
94 RunPreprocessorOnly, // Just lex, no output.
95 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000096 DumpTokens, // Dump out preprocessed tokens.
97 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +000098 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +000099 GeneratePCH, // Generate precompiled header.
100 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000101};
102
103static llvm::cl::opt<ProgActions>
104ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
105 llvm::cl::init(ParseSyntaxOnly),
106 llvm::cl::values(
107 clEnumValN(RunPreprocessorOnly, "Eonly",
108 "Just run preprocessor, no output (for timings)"),
109 clEnumValN(PrintPreprocessedInput, "E",
110 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000111 clEnumValN(DumpRawTokens, "dump-raw-tokens",
112 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000113 clEnumValN(RunAnalysis, "analyze",
114 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000115 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000116 "Run preprocessor, dump internal rep of tokens"),
117 clEnumValN(ParseNoop, "parse-noop",
118 "Run parser with noop callbacks (for timings)"),
119 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
120 "Run parser and perform semantic analysis"),
121 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
122 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000123 clEnumValN(EmitHTML, "emit-html",
124 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000125 clEnumValN(ASTPrint, "ast-print",
126 "Build ASTs and then pretty-print them"),
127 clEnumValN(ASTDump, "ast-dump",
128 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000129 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000130 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000131 clEnumValN(PrintDeclContext, "print-decl-contexts",
132 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000133 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000134 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000135 clEnumValN(EmitAssembly, "S",
136 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000137 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000138 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000139 clEnumValN(EmitBC, "emit-llvm-bc",
140 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000141 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000142 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000143 clEnumValN(RewriteTest, "rewrite-test",
144 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000145 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000146 "Rewrite ObjC into C (code rewriter example)"),
147 clEnumValN(RewriteMacros, "rewrite-macros",
148 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000149 clEnumValN(RewriteBlocks, "rewrite-blocks",
150 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000151 clEnumValEnd));
152
Ted Kremenekd01eae62007-12-19 19:47:59 +0000153
154static llvm::cl::opt<std::string>
155OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000156 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000157 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000158
159//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000160// Code Generator Options
161//===----------------------------------------------------------------------===//
162static llvm::cl::opt<bool>
163GenerateDebugInfo("g",
164 llvm::cl::desc("Generate source level debug information"));
165
Ted Kremenek57f25b22008-12-02 19:57:31 +0000166
167//===----------------------------------------------------------------------===//
168// PTH.
169//===----------------------------------------------------------------------===//
170
171static llvm::cl::opt<std::string>
172TokenCache("token-cache", llvm::cl::value_desc("path"),
173 llvm::cl::desc("Use specified token cache file"));
174
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000175//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000176// Diagnostic Options
177//===----------------------------------------------------------------------===//
178
Ted Kremenek10389cf2007-09-26 19:42:19 +0000179static llvm::cl::opt<bool>
180VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000181 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000182
Ted Kremenekfd75e312008-03-27 06:17:42 +0000183static llvm::cl::opt<std::string>
184HTMLDiag("html-diags",
185 llvm::cl::desc("Generate HTML to report diagnostics"),
186 llvm::cl::value_desc("HTML directory"));
187
Nico Weber0e13eaa2008-08-05 23:33:20 +0000188static llvm::cl::opt<bool>
189NoShowColumn("fno-show-column",
190 llvm::cl::desc("Do not include column number on diagnostics"));
191
192static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000193NoShowLocation("fno-show-source-location",
194 llvm::cl::desc("Do not include source location information with"
195 " diagnostics"));
196
197static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000198NoCaretDiagnostics("fno-caret-diagnostics",
199 llvm::cl::desc("Do not include source line and caret with"
200 " diagnostics"));
201
202
Chris Lattner4b009652007-07-25 00:24:17 +0000203//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000204// C++ Visualization.
205//===----------------------------------------------------------------------===//
206
207static llvm::cl::opt<std::string>
208InheritanceViewCls("cxx-inheritance-view",
209 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000210 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000211
212//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000213// Builtin Options
214//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000215
216static llvm::cl::opt<bool>
217TimeReport("ftime-report",
218 llvm::cl::desc("Print the amount of time each "
219 "phase of compilation takes"));
220
Douglas Gregor23d23262009-02-14 20:49:29 +0000221static llvm::cl::opt<bool>
222Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000223 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000224 "freestanding environment"));
225
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000226static llvm::cl::opt<bool>
227MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000228 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000229 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000230
Douglas Gregor23d23262009-02-14 20:49:29 +0000231//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000232// Language Options
233//===----------------------------------------------------------------------===//
234
235enum LangKind {
236 langkind_unspecified,
237 langkind_c,
238 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000239 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000240 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000241 langkind_cxx,
242 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000243 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000244 langkind_objc,
245 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000246 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000247 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000248 langkind_objcxx_cpp,
249 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000250};
251
252/* TODO: GCC also accepts:
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000253 assembler, ada, f77*, ratfor (!), f95, java, treelang
Chris Lattner4b009652007-07-25 00:24:17 +0000254 */
255static llvm::cl::opt<LangKind>
256BaseLang("x", llvm::cl::desc("Base language to compile"),
257 llvm::cl::init(langkind_unspecified),
258 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
259 clEnumValN(langkind_cxx, "c++", "C++"),
260 clEnumValN(langkind_objc, "objective-c", "Objective C"),
261 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000262 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000263 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000264 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
265 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000266 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000267 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000268 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
269 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000270 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000271 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000272 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000273 "Precompiled C header"),
274 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000275 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000276 clEnumValN(langkind_cxx_pch, "c++-header",
277 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000278 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
279 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000280 clEnumValEnd));
281
282static llvm::cl::opt<bool>
283LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
284 llvm::cl::Hidden);
285static llvm::cl::opt<bool>
286LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
287 llvm::cl::Hidden);
288
Ted Kremenek11ad8952007-12-05 23:49:08 +0000289/// InitializeBaseLanguage - Handle the -x foo options.
290static void InitializeBaseLanguage() {
291 if (LangObjC)
292 BaseLang = langkind_objc;
293 else if (LangObjCXX)
294 BaseLang = langkind_objcxx;
295}
296
297static LangKind GetLanguage(const std::string &Filename) {
298 if (BaseLang != langkind_unspecified)
299 return BaseLang;
300
301 std::string::size_type DotPos = Filename.rfind('.');
302
303 if (DotPos == std::string::npos) {
304 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000305 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000306 }
307
Ted Kremenek11ad8952007-12-05 23:49:08 +0000308 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
309 // C header: .h
310 // C++ header: .hh or .H;
311 // assembler no preprocessing: .s
312 // assembler: .S
313 if (Ext == "c")
314 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000315 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000316 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000317 else if (Ext == "i")
318 return langkind_c_cpp;
319 else if (Ext == "ii")
320 return langkind_cxx_cpp;
321 else if (Ext == "m")
322 return langkind_objc;
323 else if (Ext == "mi")
324 return langkind_objc_cpp;
325 else if (Ext == "mm" || Ext == "M")
326 return langkind_objcxx;
327 else if (Ext == "mii")
328 return langkind_objcxx_cpp;
329 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
330 Ext == "c++" || Ext == "cp" || Ext == "cxx")
331 return langkind_cxx;
332 else
333 return langkind_c;
334}
335
336
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000337static void InitializeCOptions(LangOptions &Options) {
338 // Do nothing.
339}
340
341static void InitializeObjCOptions(LangOptions &Options) {
342 Options.ObjC1 = Options.ObjC2 = 1;
343}
344
345
346static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000347 // FIXME: implement -fpreprocessed mode.
348 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000349 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000350
351 // Test for 'PCH'.
352 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000353 default:
354 break;
355 case langkind_c_pch:
356 LK = langkind_c;
357 PCH = true;
358 break;
359 case langkind_objc_pch:
360 LK = langkind_objc;
361 PCH = true;
362 break;
363 case langkind_cxx_pch:
364 LK = langkind_cxx;
365 PCH = true;
366 break;
367 case langkind_objcxx_pch:
368 LK = langkind_objcxx;
369 PCH = true;
370 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000371 }
Chris Lattner4b009652007-07-25 00:24:17 +0000372
Ted Kremenek11ad8952007-12-05 23:49:08 +0000373 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000374 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000375 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000376 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000377 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000378 case langkind_c_cpp:
379 NoPreprocess = true;
380 // FALLTHROUGH
381 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000382 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000383 break;
384 case langkind_cxx_cpp:
385 NoPreprocess = true;
386 // FALLTHROUGH
387 case langkind_cxx:
388 Options.CPlusPlus = 1;
389 break;
390 case langkind_objc_cpp:
391 NoPreprocess = true;
392 // FALLTHROUGH
393 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000394 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000395 break;
396 case langkind_objcxx_cpp:
397 NoPreprocess = true;
398 // FALLTHROUGH
399 case langkind_objcxx:
400 Options.ObjC1 = Options.ObjC2 = 1;
401 Options.CPlusPlus = 1;
402 break;
403 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000404
405 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000406}
407
408/// LangStds - Language standards we support.
409enum LangStds {
410 lang_unspecified,
411 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000412 lang_gnu_START,
413 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000414 lang_cxx98, lang_gnucxx98,
415 lang_cxx0x, lang_gnucxx0x
416};
417
418static llvm::cl::opt<LangStds>
419LangStd("std", llvm::cl::desc("Language standard to compile for"),
420 llvm::cl::init(lang_unspecified),
421 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
422 clEnumValN(lang_c89, "c90", "ISO C 1990"),
423 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
424 clEnumValN(lang_c94, "iso9899:199409",
425 "ISO C 1990 with amendment 1"),
426 clEnumValN(lang_c99, "c99", "ISO C 1999"),
427// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
428 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
429// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
430 clEnumValN(lang_gnu89, "gnu89",
431 "ISO C 1990 with GNU extensions (default for C)"),
432 clEnumValN(lang_gnu99, "gnu99",
433 "ISO C 1999 with GNU extensions"),
434 clEnumValN(lang_gnu99, "gnu9x",
435 "ISO C 1999 with GNU extensions"),
436 clEnumValN(lang_cxx98, "c++98",
437 "ISO C++ 1998 with amendments"),
438 clEnumValN(lang_gnucxx98, "gnu++98",
439 "ISO C++ 1998 with amendments and GNU "
440 "extensions (default for C++)"),
441 clEnumValN(lang_cxx0x, "c++0x",
442 "Upcoming ISO C++ 200x with amendments"),
443 clEnumValN(lang_gnucxx0x, "gnu++0x",
444 "Upcoming ISO C++ 200x with amendments and GNU "
445 "extensions (default for C++)"),
446 clEnumValEnd));
447
448static llvm::cl::opt<bool>
449NoOperatorNames("fno-operator-names",
450 llvm::cl::desc("Do not treat C++ operator name keywords as "
451 "synonyms for operators"));
452
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000453static llvm::cl::opt<bool>
454PascalStrings("fpascal-strings",
455 llvm::cl::desc("Recognize and construct Pascal-style "
456 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000457
458static llvm::cl::opt<bool>
459MSExtensions("fms-extensions",
460 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000461 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000462
463static llvm::cl::opt<bool>
464WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000465 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000466
467static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000468NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000469 llvm::cl::desc("Disallow implicit conversions between "
470 "vectors with a different number of "
471 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000472
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000473static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000474EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
475 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
476 llvm::cl::ZeroOrMore);
477
478static llvm::cl::opt<bool>
479ObjCNonFragileABI("fobjc-nonfragile-abi",
480 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000481
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000482static llvm::cl::opt<bool>
483EmitAllDecls("femit-all-decls",
484 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000485
Daniel Dunbar91692d92008-08-11 17:36:14 +0000486// FIXME: This (and all GCC -f options) really come in -f... and
487// -fno-... forms, and additionally support automagic behavior when
488// they are not defined. For example, -fexceptions defaults to on or
489// off depending on the language. We should support this behavior in
490// some form (perhaps just add a facility for distinguishing when an
491// has its default value from when it has been set to its default
492// value).
493static llvm::cl::opt<bool>
494Exceptions("fexceptions",
495 llvm::cl::desc("Enable support for exception handling."));
496
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000497static llvm::cl::opt<bool>
498GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000499 llvm::cl::desc("Generate output compatible with the standard GNU "
500 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000501
502static llvm::cl::opt<bool>
503NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000504 llvm::cl::desc("Generate output compatible with the NeXT "
505 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000506
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000507
508
509static llvm::cl::opt<bool>
510Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
511
512static llvm::cl::opt<bool>
513Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
514
Chris Lattner4b009652007-07-25 00:24:17 +0000515// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000516// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000517static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
518 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000519 // Allow the target to set the default the langauge options as it sees fit.
520 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000521
522 if (Ansi) // "The -ansi option is equivalent to -std=c89."
523 LangStd = lang_c89;
524
Chris Lattner4b009652007-07-25 00:24:17 +0000525 if (LangStd == lang_unspecified) {
526 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000527 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000528 default: assert(0 && "Unknown base language");
529 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000530 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000531 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000532 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000533 case langkind_objc:
534 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000535 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000536 LangStd = lang_gnu99;
537 break;
538 case langkind_cxx:
539 case langkind_cxx_cpp:
540 case langkind_objcxx:
541 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000542 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000543 LangStd = lang_gnucxx98;
544 break;
545 }
546 }
547
548 switch (LangStd) {
549 default: assert(0 && "Unknown language standard!");
550
551 // Fall through from newer standards to older ones. This isn't really right.
552 // FIXME: Enable specifically the right features based on the language stds.
553 case lang_gnucxx0x:
554 case lang_cxx0x:
555 Options.CPlusPlus0x = 1;
556 // FALL THROUGH
557 case lang_gnucxx98:
558 case lang_cxx98:
559 Options.CPlusPlus = 1;
560 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000561 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000562 // FALL THROUGH.
563 case lang_gnu99:
564 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000565 Options.C99 = 1;
566 Options.HexFloats = 1;
567 // FALL THROUGH.
568 case lang_gnu89:
569 Options.BCPLComment = 1; // Only for C99/C++.
570 // FALL THROUGH.
571 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000572 Options.Digraphs = 1; // C94, C99, C++.
573 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000574 case lang_c89:
575 break;
576 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000577
578 if (Options.CPlusPlus) {
579 Options.C99 = 0;
580 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
581 }
Chris Lattner4b009652007-07-25 00:24:17 +0000582
Chris Lattner6ab935b2008-04-05 06:32:51 +0000583 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
584 Options.ImplicitInt = 1;
585 else
586 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000587
588 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
589 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000590 Options.Trigraphs = LangStd < lang_gnu_START;
591 if (Trigraphs.getPosition())
592 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000593
Chris Lattner58d5ba52008-12-05 00:10:44 +0000594 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
595 // even if they are normally on for the target. In GNU modes (e.g.
596 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000597 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
598 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000599 Options.Blocks = 0;
600
Chris Lattner4b009652007-07-25 00:24:17 +0000601 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000602 if (PascalStrings.getPosition())
603 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000604 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000605 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000606 if (NoLaxVectorConversions.getPosition())
607 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000608 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000609 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000610 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000611
Douglas Gregor23d23262009-02-14 20:49:29 +0000612 if (Freestanding)
613 Options.Freestanding = 1;
614
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000615 Options.MathErrno = MathErrno;
616
Chris Lattnerddae7102008-12-04 22:54:33 +0000617 // Override the default runtime if the user requested it.
618 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000619 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000620 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000621 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000622
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000623 if (ObjCNonFragileABI)
624 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000625
626 if (EmitAllDecls)
627 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000628}
629
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000630static llvm::cl::opt<bool>
631ObjCExclusiveGC("fobjc-gc-only",
632 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000633 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000634
635static llvm::cl::opt<bool>
636ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000637 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000638
639void InitializeGCMode(LangOptions &Options) {
640 if (ObjCExclusiveGC)
641 Options.setGCMode(LangOptions::GCOnly);
642 else if (ObjCEnableGC)
643 Options.setGCMode(LangOptions::HybridGC);
644}
645
Chris Lattner4b009652007-07-25 00:24:17 +0000646//===----------------------------------------------------------------------===//
647// Our DiagnosticClient implementation
648//===----------------------------------------------------------------------===//
649
650// FIXME: Werror should take a list of things, -Werror=foo,bar
651static llvm::cl::opt<bool>
652WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
653
654static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000655SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
656
657static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000658WarnOnExtensions("pedantic", llvm::cl::init(false),
659 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
660
661static llvm::cl::opt<bool>
662ErrorOnExtensions("pedantic-errors",
663 llvm::cl::desc("Issue an error on uses of GCC extensions"));
664
665static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000666SuppressSystemWarnings("suppress-system-warnings",
Chris Lattner71af6d62009-02-06 04:16:41 +0000667 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000668 llvm::cl::init(true));
669
670static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000671WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000672 llvm::cl::desc("Warn for unused macros in the main translation unit"));
673
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000674static llvm::cl::opt<bool>
675WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000676 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000677
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000678static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000679WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
680 llvm::cl::desc("Warn about readonly properties with writable attributes"));
681
682static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000683WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000684 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000685
Chris Lattnera616ee32008-01-23 17:19:46 +0000686static llvm::cl::opt<bool>
687WarnUndefMacros("Wundef",
688 llvm::cl::desc("Warn on use of undefined macros in #if's"));
689
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000690static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000691WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
692 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000693
Steve Naroffb91afca2008-10-21 10:37:50 +0000694static llvm::cl::opt<bool>
695WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattner71af6d62009-02-06 04:16:41 +0000696 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
697 " and alignment"),
Steve Naroffb91afca2008-10-21 10:37:50 +0000698 llvm::cl::init(true));
699
Chris Lattner4b009652007-07-25 00:24:17 +0000700/// InitializeDiagnostics - Initialize the diagnostic object, based on the
701/// current command line option settings.
702static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000703 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000704 Diags.setWarningsAsErrors(WarningsAsErrors);
705 Diags.setWarnOnExtensions(WarnOnExtensions);
706 Diags.setErrorOnExtensions(ErrorOnExtensions);
707
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000708 // Suppress warnings in system headers unless requested not to.
709 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
710
Chris Lattner4b009652007-07-25 00:24:17 +0000711 // Silence the "macro is not used" warning unless requested.
712 if (!WarnUnusedMacros)
713 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000714
715 // Silence "floating point comparison" warnings unless requested.
716 if (!WarnFloatEqual)
717 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000718
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000719 if (!WarnPropertyReadonlyAttrs)
720 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
721 diag::MAP_IGNORE);
722
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000723 // Silence "format string is not a string literal" warnings if requested
724 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000725 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
726 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000727 if (!WarnUndefMacros)
728 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000729
Chris Lattner86a24842009-01-29 06:55:46 +0000730 if (WarnImplicitFunctionDeclaration)
731 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
732 diag::MAP_WARNING);
733 else
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000734 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
735 diag::MAP_IGNORE);
Chris Lattner71af6d62009-02-06 04:16:41 +0000736
737
738 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Chris Lattner4b009652007-07-25 00:24:17 +0000739}
740
741//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000742// Target Triple Processing.
743//===----------------------------------------------------------------------===//
744
745static llvm::cl::opt<std::string>
746TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000747 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000748
Chris Lattnerfc457002008-03-05 01:18:20 +0000749static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000750Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000751
Chris Lattner2b168e02008-09-30 01:13:12 +0000752static llvm::cl::opt<std::string>
753MacOSVersionMin("mmacosx-version-min",
754 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
755
Chris Lattner01de9c82008-09-30 20:16:56 +0000756// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
757// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
758static void HandleMacOSVersionMin(std::string &Triple) {
759 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
760 if (DarwinDashIdx == std::string::npos) {
761 fprintf(stderr,
762 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
763 exit(1);
764 }
765 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
766
Chris Lattner01de9c82008-09-30 20:16:56 +0000767 // Remove the number.
768 Triple.resize(DarwinNumIdx);
769
770 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
771 bool MacOSVersionMinIsInvalid = false;
772 int VersionNum = 0;
773 if (MacOSVersionMin.size() < 4 ||
774 MacOSVersionMin.substr(0, 3) != "10." ||
775 !isdigit(MacOSVersionMin[3])) {
776 MacOSVersionMinIsInvalid = true;
777 } else {
778 const char *Start = MacOSVersionMin.c_str()+3;
779 char *End = 0;
780 VersionNum = (int)strtol(Start, &End, 10);
781
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000782 // The version number must be in the range 0-9.
783 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
784
Chris Lattner01de9c82008-09-30 20:16:56 +0000785 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
786 Triple += llvm::itostr(VersionNum+4);
787
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000788 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
789 // Add the period piece (.7) to the end of the triple. This gives us
790 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000791 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000792 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
793 MacOSVersionMinIsInvalid = true;
794 }
795 }
796
797 if (MacOSVersionMinIsInvalid) {
798 fprintf(stderr,
799 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
800 MacOSVersionMin.c_str());
801 exit(1);
802 }
803}
804
805/// CreateTargetTriple - Process the various options that affect the target
806/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000807static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000808 // Initialize base triple. If a -triple option has been specified, use
809 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000810 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000811 if (Triple.empty()) {
812 Triple = LLVM_HOSTTRIPLE;
813
Daniel Dunbar81caece2008-12-12 18:34:35 +0000814 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
815 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
816 Triple[2] == '8' && Triple[3] == '6')
817 Triple[1] = '3';
818
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000819 // On darwin, we want to update the version to match that of the
820 // host.
821 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
822 if (DarwinDashIdx != std::string::npos) {
823 Triple.resize(DarwinDashIdx + strlen("-darwin"));
824
Daniel Dunbar81caece2008-12-12 18:34:35 +0000825 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000826 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000827 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000828 }
829 }
Ted Kremenek40499482007-12-03 22:06:55 +0000830
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000831 // If -arch foo was specified, remove the architecture from the triple we have
832 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000833 if (!Arch.empty()) {
834 // Decompose the base triple into "arch" and suffix.
835 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000836
Chris Lattner2b168e02008-09-30 01:13:12 +0000837 if (FirstDashIdx == std::string::npos) {
838 fprintf(stderr,
839 "Malformed target triple: \"%s\" ('-' could not be found).\n",
840 Triple.c_str());
841 exit(1);
842 }
Ted Kremenek40499482007-12-03 22:06:55 +0000843
Chris Lattner2b168e02008-09-30 01:13:12 +0000844 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
845 }
846
847 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
848 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000849 if (!MacOSVersionMin.empty())
850 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000851
Chris Lattner2b168e02008-09-30 01:13:12 +0000852 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000853}
854
855//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000856// Preprocessor Initialization
857//===----------------------------------------------------------------------===//
858
859// FIXME: Preprocessor builtins to support.
860// -A... - Play with #assertions
861// -undef - Undefine all predefined macros
862
863static llvm::cl::list<std::string>
864D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
865 llvm::cl::desc("Predefine the specified macro"));
866static llvm::cl::list<std::string>
867U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
868 llvm::cl::desc("Undefine the specified macro"));
869
Chris Lattner008da782008-01-10 01:53:41 +0000870static llvm::cl::list<std::string>
871ImplicitIncludes("include", llvm::cl::value_desc("file"),
872 llvm::cl::desc("Include file before parsing"));
873
874
Chris Lattner4b009652007-07-25 00:24:17 +0000875// Append a #define line to Buf for Macro. Macro should be of the form XXX,
876// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
877// "#define XXX Y z W". To get a #define with no value, use "XXX=".
878static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
879 const char *Command = "#define ") {
880 Buf.insert(Buf.end(), Command, Command+strlen(Command));
881 if (const char *Equal = strchr(Macro, '=')) {
882 // Turn the = into ' '.
883 Buf.insert(Buf.end(), Macro, Equal);
884 Buf.push_back(' ');
885 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
886 } else {
887 // Push "macroname 1".
888 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
889 Buf.push_back(' ');
890 Buf.push_back('1');
891 }
892 Buf.push_back('\n');
893}
894
Chris Lattner008da782008-01-10 01:53:41 +0000895/// AddImplicitInclude - Add an implicit #include of the specified file to the
896/// predefines buffer.
897static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
898 const char *Inc = "#include \"";
899 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
900 Buf.insert(Buf.end(), File.begin(), File.end());
901 Buf.push_back('"');
902 Buf.push_back('\n');
903}
904
Chris Lattner4b009652007-07-25 00:24:17 +0000905
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000906/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000907/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000908///
Chris Lattner9d818a22008-04-19 23:25:44 +0000909static bool InitializePreprocessor(Preprocessor &PP,
910 bool InitializeSourceMgr,
911 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000912 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000913
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000914 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000915 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000916
917 if (InitializeSourceMgr) {
918 if (InFile != "-") {
919 const FileEntry *File = FileMgr.getFile(InFile);
920 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000921 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000922 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000923 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000924 }
925 } else {
926 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
927 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000928 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000929 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000930 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000931 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000932 }
Chris Lattner4b009652007-07-25 00:24:17 +0000933 }
Sam Bishop61a20782008-04-14 14:41:57 +0000934
Chris Lattner47b6a162008-04-19 23:09:31 +0000935 std::vector<char> PredefineBuffer;
936
Chris Lattner4b009652007-07-25 00:24:17 +0000937 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000938 unsigned d = 0, D = D_macros.size();
939 unsigned u = 0, U = U_macros.size();
940 while (d < D || u < U) {
941 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
942 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
943 else
944 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
945 }
946
Chris Lattner008da782008-01-10 01:53:41 +0000947 // FIXME: Read any files specified by -imacros.
948
949 // Add implicit #includes from -include.
950 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
951 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000952
Chris Lattner47b6a162008-04-19 23:09:31 +0000953 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000954 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000955 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000956
957 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000958 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000959}
960
961//===----------------------------------------------------------------------===//
962// Preprocessor include path information.
963//===----------------------------------------------------------------------===//
964
965// This tool exports a large number of command line options to control how the
966// preprocessor searches for header files. At root, however, the Preprocessor
967// object takes a very simple interface: a list of directories to search for
968//
969// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000970// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000971//
Chris Lattner008da782008-01-10 01:53:41 +0000972// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000973
974static llvm::cl::opt<bool>
975nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
976
977// Various command line options. These four add directories to each chain.
978static llvm::cl::list<std::string>
979F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
980 llvm::cl::desc("Add directory to framework include search path"));
981static llvm::cl::list<std::string>
982I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
983 llvm::cl::desc("Add directory to include search path"));
984static llvm::cl::list<std::string>
985idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
986 llvm::cl::desc("Add directory to AFTER include search path"));
987static llvm::cl::list<std::string>
988iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
989 llvm::cl::desc("Add directory to QUOTE include search path"));
990static llvm::cl::list<std::string>
991isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
992 llvm::cl::desc("Add directory to SYSTEM include search path"));
993
994// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
995static llvm::cl::list<std::string>
996iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
997 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
998static llvm::cl::list<std::string>
999iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1000 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1001static llvm::cl::list<std::string>
1002iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1003 llvm::cl::Prefix,
1004 llvm::cl::desc("Set directory to include search path with prefix"));
1005
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001006static llvm::cl::opt<std::string>
1007isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1008 llvm::cl::desc("Set the system root directory (usually /)"));
1009
Chris Lattner4b009652007-07-25 00:24:17 +00001010// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001011
Chris Lattner4b009652007-07-25 00:24:17 +00001012/// InitializeIncludePaths - Process the -I options and set them in the
1013/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001014void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1015 FileManager &FM, const LangOptions &Lang) {
1016 InitHeaderSearch Init(Headers, Verbose, isysroot);
1017
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001018 // Handle -I... and -F... options, walking the lists in parallel.
1019 unsigned Iidx = 0, Fidx = 0;
1020 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1021 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001022 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001023 ++Iidx;
1024 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001025 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001026 ++Fidx;
1027 }
1028 }
Chris Lattner4b009652007-07-25 00:24:17 +00001029
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001030 // Consume what's left from whatever list was longer.
1031 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001032 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001033 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001034 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001035
1036 // Handle -idirafter... options.
1037 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001038 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1039 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001040
1041 // Handle -iquote... options.
1042 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001043 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001044
1045 // Handle -isystem... options.
1046 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001047 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001048
1049 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1050 // parallel, processing the values in order of occurance to get the right
1051 // prefixes.
1052 {
1053 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1054 unsigned iprefix_idx = 0;
1055 unsigned iwithprefix_idx = 0;
1056 unsigned iwithprefixbefore_idx = 0;
1057 bool iprefix_done = iprefix_vals.empty();
1058 bool iwithprefix_done = iwithprefix_vals.empty();
1059 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1060 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1061 if (!iprefix_done &&
1062 (iwithprefix_done ||
1063 iprefix_vals.getPosition(iprefix_idx) <
1064 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1065 (iwithprefixbefore_done ||
1066 iprefix_vals.getPosition(iprefix_idx) <
1067 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1068 Prefix = iprefix_vals[iprefix_idx];
1069 ++iprefix_idx;
1070 iprefix_done = iprefix_idx == iprefix_vals.size();
1071 } else if (!iwithprefix_done &&
1072 (iwithprefixbefore_done ||
1073 iwithprefix_vals.getPosition(iwithprefix_idx) <
1074 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001075 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1076 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001077 ++iwithprefix_idx;
1078 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1079 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001080 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1081 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001082 ++iwithprefixbefore_idx;
1083 iwithprefixbefore_done =
1084 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1085 }
1086 }
1087 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001088
Nico Weber770e3882008-08-22 09:25:22 +00001089 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001090
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001091 // Add the clang headers, which are relative to the clang driver.
1092 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001093 llvm::sys::Path::GetMainExecutable(Argv0,
1094 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001095 if (!MainExecutablePath.isEmpty()) {
1096 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1097 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1098 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001099 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1100 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001101 }
1102
Nico Weber770e3882008-08-22 09:25:22 +00001103 if (!nostdinc)
1104 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001105
1106 // Now that we have collected all of the include paths, merge them all
1107 // together and tell the preprocessor about them.
1108
Nico Weber770e3882008-08-22 09:25:22 +00001109 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001110}
1111
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001112//===----------------------------------------------------------------------===//
1113// Driver PreprocessorFactory - For lazily generating preprocessors ...
1114//===----------------------------------------------------------------------===//
1115
1116namespace {
1117class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001118 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001119 Diagnostic &Diags;
1120 const LangOptions &LangInfo;
1121 TargetInfo &Target;
1122 SourceManager &SourceMgr;
1123 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001124 bool InitializeSourceMgr;
1125
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001126public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001127 DriverPreprocessorFactory(const std::string &infile,
1128 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001129 TargetInfo &target, SourceManager &SM,
1130 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001131 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1132 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1133
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001134
1135 virtual ~DriverPreprocessorFactory() {}
1136
1137 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001138 llvm::OwningPtr<PTHManager> PTHMgr;
1139
1140 // Use PTH?
1141 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001142 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001143
1144 // Create the Preprocessor.
1145 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1146 SourceMgr, HeaderInfo,
1147 PTHMgr.get()));
1148
1149 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1150 // That argument is used as the IdentifierInfoLookup argument to
1151 // IdentifierTable's ctor.
1152 if (PTHMgr) {
1153 PTHMgr->setPreprocessor(PP.get());
1154 PP->setPTHManager(PTHMgr.take());
1155 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001156
Chris Lattner9d818a22008-04-19 23:25:44 +00001157 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001158 return NULL;
1159 }
1160
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001161 /// FIXME: PP can only handle one callback
1162 if (ProgAction != PrintPreprocessedInput) {
1163 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001164 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001165 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001166 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001167 return NULL;
1168 }
1169 }
1170
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001171 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001172 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001173 }
1174};
1175}
Chris Lattner4b009652007-07-25 00:24:17 +00001176
Chris Lattner4b009652007-07-25 00:24:17 +00001177//===----------------------------------------------------------------------===//
1178// Basic Parser driver
1179//===----------------------------------------------------------------------===//
1180
Chris Lattner9d818a22008-04-19 23:25:44 +00001181static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001182 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001183 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001184
1185 // Parsing the specified input file.
1186 P.ParseTranslationUnit();
1187 delete PA;
1188}
1189
1190//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001191// Code generation options
1192//===----------------------------------------------------------------------===//
1193
1194static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001195OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001196
1197// It might be nice to add bounds to the CommandLine library directly.
1198struct OptLevelParser : public llvm::cl::parser<unsigned> {
1199 bool parse(llvm::cl::Option &O, const char *ArgName,
1200 const std::string &Arg, unsigned &Val) {
1201 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1202 return true;
1203 // FIXME: Support -O4.
1204 if (Val > 3)
1205 return O.error(": '" + Arg + "' invalid optimization level!");
1206 return false;
1207 }
1208};
1209static llvm::cl::opt<unsigned, false, OptLevelParser>
1210OptLevel("O", llvm::cl::Prefix,
1211 llvm::cl::desc("Optimization level"),
1212 llvm::cl::init(0));
1213
Daniel Dunbar9101a632009-02-17 19:47:34 +00001214static llvm::cl::opt<std::string>
1215TargetCPU("mcpu",
1216 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1217
1218static llvm::cl::list<std::string>
1219TargetFeatures("mattr",
1220 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
1221
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001222static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001223 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001224 if (OptSize) {
1225 // -Os implies -O2
1226 // FIXME: Diagnose conflicting options.
1227 Opts.OptimizationLevel = 2;
1228 } else {
1229 Opts.OptimizationLevel = OptLevel;
1230 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001231
1232 // FIXME: There are llvm-gcc options to control these selectively.
1233 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1234 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Daniel Dunbar6670e332009-02-15 20:00:15 +00001235 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001236
1237#ifdef NDEBUG
1238 Opts.VerifyModule = 0;
1239#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001240
1241 Opts.CPU = TargetCPU;
1242 Opts.Features.insert(Opts.Features.end(),
1243 TargetFeatures.begin(), TargetFeatures.end());
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001244}
1245
1246//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001247// Main driver
1248//===----------------------------------------------------------------------===//
1249
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001250/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1251/// action. These consumers can operate on both ASTs that are freshly
1252/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001253static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001254 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001255 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001256 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001257 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001258 switch (ProgAction) {
1259 default:
1260 return NULL;
1261
1262 case ASTPrint:
1263 return CreateASTPrinter();
1264
1265 case ASTDump:
1266 return CreateASTDumper();
1267
1268 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001269 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001270
1271 case PrintDeclContext:
1272 return CreateDeclContextPrinter();
Ted Kremenek24612ae2008-03-18 21:19:49 +00001273
1274 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001275 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001276
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001277 case InheritanceView:
1278 return CreateInheritanceViewer(InheritanceViewCls);
1279
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001280 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001281 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001282
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001283 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001284 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001285 case EmitBC: {
1286 BackendAction Act;
1287 if (ProgAction == EmitAssembly) {
1288 Act = Backend_EmitAssembly;
1289 } else if (ProgAction == EmitLLVM) {
1290 Act = Backend_EmitLL;
1291 } else {
1292 Act = Backend_EmitBC;
1293 }
1294 CompileOptions Opts;
1295 InitializeCompileOptions(Opts);
1296 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001297 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001298 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001299
Ted Kremenekbde30332007-12-19 17:25:59 +00001300 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001301 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001302 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001303
Steve Naroff44e81222008-04-14 22:03:09 +00001304 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001305 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001306
1307 case RewriteBlocks:
1308 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001309
1310 case RunAnalysis:
Ted Kremenek99ec8f42009-02-17 04:27:41 +00001311 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001312 }
1313}
1314
Chris Lattner4b009652007-07-25 00:24:17 +00001315/// ProcessInputFile - Process a single input file with the specified state.
1316///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001317static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001318 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001319 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001320 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001321
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001322 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001323 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001324 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1325 PP.getFileManager(), PP.getLangOptions(),
1326 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001327
1328 if (!Consumer) {
1329 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001330 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001331 return;
1332 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001333
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001334 break;
1335
Chris Lattneraf669fb2008-10-12 05:03:36 +00001336 case DumpRawTokens: {
1337 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001338 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001339 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001340 RawLex.SetKeepWhitespaceMode(true);
1341
1342 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001343 RawLex.LexFromRawLexer(RawTok);
1344 while (RawTok.isNot(tok::eof)) {
1345 PP.DumpToken(RawTok, true);
1346 fprintf(stderr, "\n");
1347 RawLex.LexFromRawLexer(RawTok);
1348 }
1349 ClearSourceMgr = true;
1350 break;
1351 }
Chris Lattner4b009652007-07-25 00:24:17 +00001352 case DumpTokens: { // Token dump mode.
1353 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001354 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001355 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001356 do {
1357 PP.Lex(Tok);
1358 PP.DumpToken(Tok, true);
1359 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001360 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001361 ClearSourceMgr = true;
1362 break;
1363 }
1364 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1365 Token Tok;
1366 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001367 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001368 do {
1369 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001370 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001371 ClearSourceMgr = true;
1372 break;
1373 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001374
1375 case GeneratePCH: {
1376 CacheTokens(PP, OutputFile);
1377 ClearSourceMgr = true;
1378 break;
1379 }
Chris Lattner4b009652007-07-25 00:24:17 +00001380
1381 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001382 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001383 ClearSourceMgr = true;
1384 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001385
Chris Lattner4b009652007-07-25 00:24:17 +00001386 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001387 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001388 ClearSourceMgr = true;
1389 break;
1390
1391 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001392 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001393 ClearSourceMgr = true;
1394 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001395
Ted Kremenek6856c632007-09-26 18:39:29 +00001396 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001397 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001398 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001399
1400 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001401 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001402 ClearSourceMgr = true;
1403 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001404
1405 case RewriteTest:
1406 DoRewriteTest(PP, InFile, OutputFile);
1407 ClearSourceMgr = true;
1408 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001409 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001410
1411 if (Consumer) {
1412 TranslationUnit *TU = 0;
1413 if (DisableFree) {
1414 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1415 PP.getSourceManager(),
1416 PP.getTargetInfo(),
1417 PP.getIdentifierTable(),
1418 PP.getSelectorTable(),
1419 /* FreeMemory = */ false);
1420 TU = new TranslationUnit(*Context);
1421 }
1422 ParseAST(PP, Consumer.get(), TU, Stats);
1423 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001424
1425 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001426 if (CheckDiagnostics(PP))
1427 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001428
Chris Lattner4b009652007-07-25 00:24:17 +00001429 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001430 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001431 PP.PrintStats();
1432 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001433 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001434 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001435 fprintf(stderr, "\n");
1436 }
1437
1438 // For a multi-file compilation, some things are ok with nuking the source
1439 // manager tables, other require stable fileid/macroid's across multiple
1440 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001441 if (ClearSourceMgr)
1442 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001443
1444 if (DisableFree)
1445 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001446}
1447
Ted Kremenek80d53372007-12-12 23:41:08 +00001448static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1449 FileManager& FileMgr) {
1450
1451 if (VerifyDiagnostics) {
1452 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1453 exit (1);
1454 }
1455
1456 llvm::sys::Path Filename(InFile);
1457
1458 if (!Filename.isValid()) {
1459 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1460 exit (1);
1461 }
1462
Ted Kremenek863b01f2008-04-23 16:25:39 +00001463 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001464
1465 if (!TU) {
1466 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1467 InFile.c_str());
1468 exit (1);
1469 }
1470
Ted Kremenekab749372007-12-19 19:27:38 +00001471 // Observe that we use the source file name stored in the deserialized
1472 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001473 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001474 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001475 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001476
Ted Kremenek80d53372007-12-12 23:41:08 +00001477 if (!Consumer) {
1478 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1479 exit (1);
1480 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001481
Ted Kremenek863b01f2008-04-23 16:25:39 +00001482 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001483
Chris Lattner8d72ee02008-02-06 01:42:25 +00001484 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001485 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1486 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001487}
1488
1489
Chris Lattner4b009652007-07-25 00:24:17 +00001490static llvm::cl::list<std::string>
1491InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1492
Ted Kremenek80d53372007-12-12 23:41:08 +00001493static bool isSerializedFile(const std::string& InFile) {
1494 if (InFile.size() < 4)
1495 return false;
1496
1497 const char* s = InFile.c_str()+InFile.size()-4;
1498
1499 return s[0] == '.' &&
1500 s[1] == 'a' &&
1501 s[2] == 's' &&
1502 s[3] == 't';
1503}
1504
Chris Lattner4b009652007-07-25 00:24:17 +00001505
1506int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001507 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001508 llvm::sys::PrintStackTraceOnErrorSignal();
1509
1510 // If no input was specified, read from stdin.
1511 if (InputFilenames.empty())
1512 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001513
1514 // Handle -ftime-report.
1515 if (TimeReport)
1516 llvm::TimePassesIsEnabled = true;
Ted Kremenekb240e822007-12-11 23:28:38 +00001517
Chris Lattner4b009652007-07-25 00:24:17 +00001518 // Create a file manager object to provide access to and cache the filesystem.
1519 FileManager FileMgr;
1520
Ted Kremenekb240e822007-12-11 23:28:38 +00001521 // Create the diagnostic client for reporting errors or for
1522 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001523 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001524
Ted Kremenek5c341732008-08-07 17:49:57 +00001525 if (!VerifyDiagnostics) {
1526 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001527 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1528 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001529 !NoCaretDiagnostics,
1530 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001531 } else {
1532 // When checking diagnostics, just buffer them up.
1533 TextDiagClient = new TextDiagnosticBuffer();
1534
1535 if (InputFilenames.size() != 1) {
1536 fprintf(stderr,
1537 "-verify only works on single input files for now.\n");
1538 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001539 }
1540 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001541
Chris Lattner4b009652007-07-25 00:24:17 +00001542 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001543 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1544 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001545 InitializeDiagnostics(Diags);
1546
Chris Lattner45a56e02007-12-05 23:24:17 +00001547 // -I- is a deprecated GCC feature, scan for it and reject it.
1548 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1549 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001550 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001551 I_dirs.erase(I_dirs.begin()+i);
1552 --i;
1553 }
1554 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001555
1556 // Get information about the target being compiled for.
1557 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001558 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1559
Chris Lattner2c77d852008-03-14 06:12:05 +00001560 if (Target == 0) {
1561 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1562 Triple.c_str());
1563 fprintf(stderr, "Please use -triple or -arch.\n");
1564 exit(1);
1565 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001566
Daniel Dunbar9c321102009-01-20 23:17:32 +00001567 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001568 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001569
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001570 llvm::OwningPtr<SourceManager> SourceMgr;
1571
Chris Lattner4b009652007-07-25 00:24:17 +00001572 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001573 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001574
Ted Kremenek5c341732008-08-07 17:49:57 +00001575 if (isSerializedFile(InFile)) {
1576 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001577 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001578 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001579 else {
1580 /// Create a SourceManager object. This tracks and owns all the file
1581 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001582 if (!SourceMgr)
1583 SourceMgr.reset(new SourceManager());
1584 else
1585 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001586
Ted Kremenek80d53372007-12-12 23:41:08 +00001587 // Initialize language options, inferring file types from input filenames.
1588 LangOptions LangInfo;
1589 InitializeBaseLanguage();
1590 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001591 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001592 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001593 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001594
Ted Kremenek80d53372007-12-12 23:41:08 +00001595 // Process the -I options and set them in the HeaderInfo.
1596 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001597
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001598 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001599
Ted Kremenek80d53372007-12-12 23:41:08 +00001600 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001601 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001602 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001603
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001604 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1605
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001606 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001607 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001608
1609 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1610 // always reset to using TextDiagClient.
1611 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001612
Ted Kremenek5c341732008-08-07 17:49:57 +00001613 if (!HTMLDiag.empty()) {
1614 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1615 &PPFactory));
1616 Diags.setClient(TmpClient.get());
1617 }
1618 else
1619 Diags.setClient(TextDiagClient);
1620
1621 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001622 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1623
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001624 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001625 }
Chris Lattner4b009652007-07-25 00:24:17 +00001626 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001627
Mike Stump91d01352009-01-28 02:43:35 +00001628 if (Verbose)
1629 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1630 " hosted on " LLVM_HOSTTRIPLE "\n");
1631
Ted Kremenekec6c5252008-08-07 18:13:12 +00001632 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001633 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1634 (NumDiagnostics == 1 ? "" : "s"));
1635
1636 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001637 FileMgr.PrintStats();
1638 fprintf(stderr, "\n");
1639 }
1640
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001641 // If verifying diagnostics and we reached here, all is well.
1642 if (VerifyDiagnostics)
1643 return 0;
1644
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001645 // Managed static deconstruction. Useful for making things like
1646 // -time-passes usable.
1647 llvm::llvm_shutdown();
1648
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001649 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001650}