blob: 87447c41532ee4dbeacb5e7b7c097501adf700f4 [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//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
28#include "clang/Frontend/PathDiagnosticClients.h"
29#include "clang/Frontend/InitHeaderSearch.h"
30#include "clang/Frontend/TextDiagnosticBuffer.h"
31#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000039#include "clang/Parse/Parser.h"
40#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000041#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "clang/Basic/FileManager.h"
43#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000046#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000050#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000051#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000052#include "llvm/Support/PluginLoader.h"
Chris Lattner47099742009-02-18 01:51:21 +000053#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000054#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000055#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000057using namespace clang;
58
59//===----------------------------------------------------------------------===//
60// Global options.
61//===----------------------------------------------------------------------===//
62
Chris Lattner47099742009-02-18 01:51:21 +000063/// ClangFrontendTimer - The front-end activities should charge time to it with
64/// TimeRegion. The -ftime-report option controls whether this will do
65/// anything.
66llvm::Timer *ClangFrontendTimer = 0;
67
Daniel Dunbard3db4012008-10-16 16:54:18 +000068static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000069
Reid Spencer5f016e22007-07-11 17:01:13 +000070static llvm::cl::opt<bool>
71Verbose("v", llvm::cl::desc("Enable verbose output"));
72static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000073Stats("print-stats",
74 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000075static llvm::cl::opt<bool>
76DisableFree("disable-free",
77 llvm::cl::desc("Disable freeing of memory on exit"),
78 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000079
80enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000081 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000082 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000083 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000084 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000085 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000086 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000087 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000088 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +000089 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000090 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000091 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000092 ASTPrint, // Parse ASTs and print them.
93 ASTDump, // Parse ASTs and dump them.
94 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +000095 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000096 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000097 ParsePrintCallbacks, // Parse and print each callback.
98 ParseSyntaxOnly, // Parse and perform semantic analysis.
99 ParseNoop, // Parse with noop callbacks.
100 RunPreprocessorOnly, // Just lex, no output.
101 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000102 DumpTokens, // Dump out preprocessed tokens.
103 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000104 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000105 GeneratePCH, // Generate precompiled header.
106 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000107};
108
109static llvm::cl::opt<ProgActions>
110ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
111 llvm::cl::init(ParseSyntaxOnly),
112 llvm::cl::values(
113 clEnumValN(RunPreprocessorOnly, "Eonly",
114 "Just run preprocessor, no output (for timings)"),
115 clEnumValN(PrintPreprocessedInput, "E",
116 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000117 clEnumValN(DumpRawTokens, "dump-raw-tokens",
118 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000119 clEnumValN(RunAnalysis, "analyze",
120 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000121 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 "Run preprocessor, dump internal rep of tokens"),
123 clEnumValN(ParseNoop, "parse-noop",
124 "Run parser with noop callbacks (for timings)"),
125 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
126 "Run parser and perform semantic analysis"),
127 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
128 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000129 clEnumValN(EmitHTML, "emit-html",
130 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000131 clEnumValN(ASTPrint, "ast-print",
132 "Build ASTs and then pretty-print them"),
133 clEnumValN(ASTDump, "ast-dump",
134 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000135 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000136 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000137 clEnumValN(PrintDeclContext, "print-decl-contexts",
138 "Print DeclContexts and their Decls."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000139 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000140 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000141 clEnumValN(EmitAssembly, "S",
142 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000144 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000145 clEnumValN(EmitBC, "emit-llvm-bc",
146 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000147 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
148 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000149 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000150 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000151 clEnumValN(RewriteTest, "rewrite-test",
152 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000153 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000154 "Rewrite ObjC into C (code rewriter example)"),
155 clEnumValN(RewriteMacros, "rewrite-macros",
156 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000157 clEnumValN(RewriteBlocks, "rewrite-blocks",
158 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 clEnumValEnd));
160
Ted Kremenekccc76472007-12-19 19:47:59 +0000161
162static llvm::cl::opt<std::string>
163OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000164 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000165 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000166
167//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000168// Code Generator Options
169//===----------------------------------------------------------------------===//
170static llvm::cl::opt<bool>
171GenerateDebugInfo("g",
172 llvm::cl::desc("Generate source level debug information"));
173
Ted Kremenekc2e72992008-12-02 19:57:31 +0000174
175//===----------------------------------------------------------------------===//
176// PTH.
177//===----------------------------------------------------------------------===//
178
179static llvm::cl::opt<std::string>
180TokenCache("token-cache", llvm::cl::value_desc("path"),
181 llvm::cl::desc("Use specified token cache file"));
182
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000183//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000184// Diagnostic Options
185//===----------------------------------------------------------------------===//
186
Ted Kremenek41193e42007-09-26 19:42:19 +0000187static llvm::cl::opt<bool>
188VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000189 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000190
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000191static llvm::cl::opt<std::string>
192HTMLDiag("html-diags",
193 llvm::cl::desc("Generate HTML to report diagnostics"),
194 llvm::cl::value_desc("HTML directory"));
195
Nico Weberfd54ebc2008-08-05 23:33:20 +0000196static llvm::cl::opt<bool>
197NoShowColumn("fno-show-column",
198 llvm::cl::desc("Do not include column number on diagnostics"));
199
200static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000201NoShowLocation("fno-show-source-location",
202 llvm::cl::desc("Do not include source location information with"
203 " diagnostics"));
204
205static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000206NoCaretDiagnostics("fno-caret-diagnostics",
207 llvm::cl::desc("Do not include source line and caret with"
208 " diagnostics"));
209
210
Reid Spencer5f016e22007-07-11 17:01:13 +0000211//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000212// C++ Visualization.
213//===----------------------------------------------------------------------===//
214
215static llvm::cl::opt<std::string>
216InheritanceViewCls("cxx-inheritance-view",
217 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000218 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000219
220//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000221// Builtin Options
222//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000223
224static llvm::cl::opt<bool>
225TimeReport("ftime-report",
226 llvm::cl::desc("Print the amount of time each "
227 "phase of compilation takes"));
228
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000229static llvm::cl::opt<bool>
230Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000231 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000232 "freestanding environment"));
233
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000234static llvm::cl::opt<bool>
235MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000236 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000237 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000238
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000239//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000240// Language Options
241//===----------------------------------------------------------------------===//
242
243enum LangKind {
244 langkind_unspecified,
245 langkind_c,
246 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000247 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000248 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 langkind_cxx,
250 langkind_cxx_cpp,
Chris Lattnerc76d8072009-02-06 06:19:20 +0000251 langkind_cxx_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 langkind_objc,
253 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000254 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000256 langkind_objcxx_cpp,
257 langkind_objcxx_pch
Reid Spencer5f016e22007-07-11 17:01:13 +0000258};
259
Reid Spencer5f016e22007-07-11 17:01:13 +0000260static llvm::cl::opt<LangKind>
261BaseLang("x", llvm::cl::desc("Base language to compile"),
262 llvm::cl::init(langkind_unspecified),
263 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
264 clEnumValN(langkind_cxx, "c++", "C++"),
265 clEnumValN(langkind_objc, "objective-c", "Objective C"),
266 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000267 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000269 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
270 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000272 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
274 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000275 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 "Preprocessed Objective C++"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000277 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek85888962008-10-21 00:54:44 +0000278 "Precompiled C header"),
279 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000280 "Precompiled Objective-C header"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000281 clEnumValN(langkind_cxx_pch, "c++-header",
282 "Precompiled C++ header"),
Ted Kremenekf8901912009-01-09 00:38:08 +0000283 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
284 "Precompiled Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 clEnumValEnd));
286
287static llvm::cl::opt<bool>
288LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
289 llvm::cl::Hidden);
290static llvm::cl::opt<bool>
291LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
292 llvm::cl::Hidden);
293
Ted Kremenek8904f152007-12-05 23:49:08 +0000294/// InitializeBaseLanguage - Handle the -x foo options.
295static void InitializeBaseLanguage() {
296 if (LangObjC)
297 BaseLang = langkind_objc;
298 else if (LangObjCXX)
299 BaseLang = langkind_objcxx;
300}
301
302static LangKind GetLanguage(const std::string &Filename) {
303 if (BaseLang != langkind_unspecified)
304 return BaseLang;
305
306 std::string::size_type DotPos = Filename.rfind('.');
307
308 if (DotPos == std::string::npos) {
309 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000310 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 }
312
Ted Kremenek8904f152007-12-05 23:49:08 +0000313 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
314 // C header: .h
315 // C++ header: .hh or .H;
316 // assembler no preprocessing: .s
317 // assembler: .S
318 if (Ext == "c")
319 return langkind_c;
Chris Lattner1b450b02008-10-28 20:33:42 +0000320 else if (Ext == "S")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000321 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000322 else if (Ext == "i")
323 return langkind_c_cpp;
324 else if (Ext == "ii")
325 return langkind_cxx_cpp;
326 else if (Ext == "m")
327 return langkind_objc;
328 else if (Ext == "mi")
329 return langkind_objc_cpp;
330 else if (Ext == "mm" || Ext == "M")
331 return langkind_objcxx;
332 else if (Ext == "mii")
333 return langkind_objcxx_cpp;
334 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
335 Ext == "c++" || Ext == "cp" || Ext == "cxx")
336 return langkind_cxx;
337 else
338 return langkind_c;
339}
340
341
Ted Kremenek85888962008-10-21 00:54:44 +0000342static void InitializeCOptions(LangOptions &Options) {
343 // Do nothing.
344}
345
346static void InitializeObjCOptions(LangOptions &Options) {
347 Options.ObjC1 = Options.ObjC2 = 1;
348}
349
350
351static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // FIXME: implement -fpreprocessed mode.
353 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000354 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000355
356 // Test for 'PCH'.
357 switch (LK) {
Chris Lattnerc76d8072009-02-06 06:19:20 +0000358 default:
359 break;
360 case langkind_c_pch:
361 LK = langkind_c;
362 PCH = true;
363 break;
364 case langkind_objc_pch:
365 LK = langkind_objc;
366 PCH = true;
367 break;
368 case langkind_cxx_pch:
369 LK = langkind_cxx;
370 PCH = true;
371 break;
372 case langkind_objcxx_pch:
373 LK = langkind_objcxx;
374 PCH = true;
375 break;
Ted Kremenekf8901912009-01-09 00:38:08 +0000376 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000377
Ted Kremenek8904f152007-12-05 23:49:08 +0000378 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000380 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000381 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000382 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 case langkind_c_cpp:
384 NoPreprocess = true;
385 // FALLTHROUGH
386 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000387 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 break;
389 case langkind_cxx_cpp:
390 NoPreprocess = true;
391 // FALLTHROUGH
392 case langkind_cxx:
393 Options.CPlusPlus = 1;
394 break;
395 case langkind_objc_cpp:
396 NoPreprocess = true;
397 // FALLTHROUGH
398 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000399 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 break;
401 case langkind_objcxx_cpp:
402 NoPreprocess = true;
403 // FALLTHROUGH
404 case langkind_objcxx:
405 Options.ObjC1 = Options.ObjC2 = 1;
406 Options.CPlusPlus = 1;
407 break;
408 }
Ted Kremenek85888962008-10-21 00:54:44 +0000409
410 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000411}
412
413/// LangStds - Language standards we support.
414enum LangStds {
415 lang_unspecified,
416 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000417 lang_gnu_START,
418 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000419 lang_cxx98, lang_gnucxx98,
420 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000421};
422
423static llvm::cl::opt<LangStds>
424LangStd("std", llvm::cl::desc("Language standard to compile for"),
425 llvm::cl::init(lang_unspecified),
426 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
427 clEnumValN(lang_c89, "c90", "ISO C 1990"),
428 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
429 clEnumValN(lang_c94, "iso9899:199409",
430 "ISO C 1990 with amendment 1"),
431 clEnumValN(lang_c99, "c99", "ISO C 1999"),
432// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
433 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
434// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
435 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000436 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000438 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 clEnumValN(lang_gnu99, "gnu9x",
440 "ISO C 1999 with GNU extensions"),
441 clEnumValN(lang_cxx98, "c++98",
442 "ISO C++ 1998 with amendments"),
443 clEnumValN(lang_gnucxx98, "gnu++98",
444 "ISO C++ 1998 with amendments and GNU "
445 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000446 clEnumValN(lang_cxx0x, "c++0x",
447 "Upcoming ISO C++ 200x with amendments"),
448 clEnumValN(lang_gnucxx0x, "gnu++0x",
449 "Upcoming ISO C++ 200x with amendments and GNU "
450 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 clEnumValEnd));
452
453static llvm::cl::opt<bool>
454NoOperatorNames("fno-operator-names",
455 llvm::cl::desc("Do not treat C++ operator name keywords as "
456 "synonyms for operators"));
457
Anders Carlssonee98ac52007-10-15 02:50:23 +0000458static llvm::cl::opt<bool>
459PascalStrings("fpascal-strings",
460 llvm::cl::desc("Recognize and construct Pascal-style "
461 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000462
463static llvm::cl::opt<bool>
464MSExtensions("fms-extensions",
465 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000466 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000467
468static llvm::cl::opt<bool>
469WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000470 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000471
472static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000473NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000474 llvm::cl::desc("Disallow implicit conversions between "
475 "vectors with a different number of "
476 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000477
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000478static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000479EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
480 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
481 llvm::cl::ZeroOrMore);
482
483static llvm::cl::opt<bool>
484ObjCNonFragileABI("fobjc-nonfragile-abi",
485 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000486
Daniel Dunbard604c402009-02-04 21:19:06 +0000487static llvm::cl::opt<bool>
488EmitAllDecls("femit-all-decls",
489 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000490
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000491// FIXME: This (and all GCC -f options) really come in -f... and
492// -fno-... forms, and additionally support automagic behavior when
493// they are not defined. For example, -fexceptions defaults to on or
494// off depending on the language. We should support this behavior in
495// some form (perhaps just add a facility for distinguishing when an
496// has its default value from when it has been set to its default
497// value).
498static llvm::cl::opt<bool>
499Exceptions("fexceptions",
500 llvm::cl::desc("Enable support for exception handling."));
501
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000502static llvm::cl::opt<bool>
503GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000504 llvm::cl::desc("Generate output compatible with the standard GNU "
505 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000506
507static llvm::cl::opt<bool>
508NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000509 llvm::cl::desc("Generate output compatible with the NeXT "
510 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000511
Ted Kremenekea644d82008-09-03 21:22:16 +0000512
513
514static llvm::cl::opt<bool>
515Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
516
517static llvm::cl::opt<bool>
518Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
519
Chris Lattner16167a62009-03-02 22:11:07 +0000520static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000521TargetFeatures("mattr", llvm::cl::CommaSeparated,
522 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
523
Chris Lattner16167a62009-03-02 22:11:07 +0000524
525
Reid Spencer5f016e22007-07-11 17:01:13 +0000526// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000527// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000528static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
529 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000530 // Allow the target to set the default the langauge options as it sees fit.
531 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000532
Chris Lattner6328cc32009-03-03 19:56:18 +0000533 // If there are any -mattr options, pass them to the target for validation and
534 // processing. The driver should have already consolidated all the
535 // target-feature settings and passed them to us in the -mattr list. The
536 // -mattr list is treated by the code generator as a diff against the -mcpu
537 // setting, but the driver should pass all enabled options as "+" settings.
538 // This means that the target should only look at + settings.
539 if (!TargetFeatures.empty()
540 // FIXME: The driver is not quite yet ready for this.
541 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000542 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000543 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
544 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000545 if (Opt != -1) {
546 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000547 fprintf(stderr, "invalid feature '%s'\n",
548 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000549 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000550 fprintf(stderr, "feature '%s': %s\n",
551 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000552 exit(1);
553 }
554 }
555
Ted Kremenekea644d82008-09-03 21:22:16 +0000556 if (Ansi) // "The -ansi option is equivalent to -std=c89."
557 LangStd = lang_c89;
558
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 if (LangStd == lang_unspecified) {
560 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000561 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 default: assert(0 && "Unknown base language");
563 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000564 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000566 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 case langkind_objc:
568 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000569 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 LangStd = lang_gnu99;
571 break;
572 case langkind_cxx:
573 case langkind_cxx_cpp:
574 case langkind_objcxx:
575 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000576 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 LangStd = lang_gnucxx98;
578 break;
579 }
580 }
581
582 switch (LangStd) {
583 default: assert(0 && "Unknown language standard!");
584
585 // Fall through from newer standards to older ones. This isn't really right.
586 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000587 case lang_gnucxx0x:
588 case lang_cxx0x:
589 Options.CPlusPlus0x = 1;
590 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 case lang_gnucxx98:
592 case lang_cxx98:
593 Options.CPlusPlus = 1;
594 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000595 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 // FALL THROUGH.
597 case lang_gnu99:
598 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 Options.C99 = 1;
600 Options.HexFloats = 1;
601 // FALL THROUGH.
602 case lang_gnu89:
603 Options.BCPLComment = 1; // Only for C99/C++.
604 // FALL THROUGH.
605 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000606 Options.Digraphs = 1; // C94, C99, C++.
607 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 case lang_c89:
609 break;
610 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000611
612 if (Options.CPlusPlus) {
613 Options.C99 = 0;
614 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
615 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000616
Chris Lattnerd658b562008-04-05 06:32:51 +0000617 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
618 Options.ImplicitInt = 1;
619 else
620 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000621
622 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
623 // is specified, or -std is set to a conforming mode.
Chris Lattner802db9b2008-12-05 00:10:44 +0000624 Options.Trigraphs = LangStd < lang_gnu_START;
625 if (Trigraphs.getPosition())
626 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenekea644d82008-09-03 21:22:16 +0000627
Chris Lattner802db9b2008-12-05 00:10:44 +0000628 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
629 // even if they are normally on for the target. In GNU modes (e.g.
630 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000631 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
632 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner802db9b2008-12-05 00:10:44 +0000633 Options.Blocks = 0;
634
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000636 if (PascalStrings.getPosition())
637 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000638 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000639 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000640 if (NoLaxVectorConversions.getPosition())
641 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000642 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000643 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000644 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000645
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000646 if (Freestanding)
647 Options.Freestanding = 1;
648
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000649 Options.MathErrno = MathErrno;
650
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000651 // Override the default runtime if the user requested it.
652 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000653 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000654 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000655 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000656
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000657 if (ObjCNonFragileABI)
658 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000659
660 if (EmitAllDecls)
661 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000662}
663
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000664static llvm::cl::opt<bool>
665ObjCExclusiveGC("fobjc-gc-only",
666 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000667 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000668
669static llvm::cl::opt<bool>
670ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000671 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000672
673void InitializeGCMode(LangOptions &Options) {
674 if (ObjCExclusiveGC)
675 Options.setGCMode(LangOptions::GCOnly);
676 else if (ObjCEnableGC)
677 Options.setGCMode(LangOptions::HybridGC);
678}
679
Reid Spencer5f016e22007-07-11 17:01:13 +0000680//===----------------------------------------------------------------------===//
681// Our DiagnosticClient implementation
682//===----------------------------------------------------------------------===//
683
684// FIXME: Werror should take a list of things, -Werror=foo,bar
685static llvm::cl::opt<bool>
686WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
687
688static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000689SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
690
691static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000692WarnOnExtensions("pedantic", llvm::cl::init(false),
693 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
694
695static llvm::cl::opt<bool>
696ErrorOnExtensions("pedantic-errors",
697 llvm::cl::desc("Issue an error on uses of GCC extensions"));
698
699static llvm::cl::opt<bool>
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000700SuppressSystemWarnings("suppress-system-warnings",
Chris Lattnerdb766842009-02-06 04:16:41 +0000701 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000702 llvm::cl::init(true));
703
704static llvm::cl::opt<bool>
Daniel Dunbard77b2512009-01-14 18:56:36 +0000705WarnUnusedMacros("Wunused-macros",
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 llvm::cl::desc("Warn for unused macros in the main translation unit"));
707
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000708static llvm::cl::opt<bool>
709WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000710 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000711
Ted Kremenek73da5902007-12-17 17:50:07 +0000712static llvm::cl::opt<bool>
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000713WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
714 llvm::cl::desc("Warn about readonly properties with writable attributes"));
715
716static llvm::cl::opt<bool>
Ted Kremenek73da5902007-12-17 17:50:07 +0000717WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000718 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000719
Chris Lattner116a4b12008-01-23 17:19:46 +0000720static llvm::cl::opt<bool>
721WarnUndefMacros("Wundef",
722 llvm::cl::desc("Warn on use of undefined macros in #if's"));
723
Chris Lattner37d10842008-05-05 21:18:06 +0000724static llvm::cl::opt<bool>
Ted Kremenek358256d2008-05-30 16:42:02 +0000725WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
726 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattner116a4b12008-01-23 17:19:46 +0000727
Steve Narofffe6b0dc2008-10-21 10:37:50 +0000728static llvm::cl::opt<bool>
729WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattnerdb766842009-02-06 04:16:41 +0000730 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
731 " and alignment"),
Steve Narofffe6b0dc2008-10-21 10:37:50 +0000732 llvm::cl::init(true));
733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734/// InitializeDiagnostics - Initialize the diagnostic object, based on the
735/// current command line option settings.
736static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000737 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 Diags.setWarningsAsErrors(WarningsAsErrors);
739 Diags.setWarnOnExtensions(WarnOnExtensions);
740 Diags.setErrorOnExtensions(ErrorOnExtensions);
741
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000742 // Suppress warnings in system headers unless requested not to.
743 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
744
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 // Silence the "macro is not used" warning unless requested.
746 if (!WarnUnusedMacros)
747 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000748
749 // Silence "floating point comparison" warnings unless requested.
750 if (!WarnFloatEqual)
751 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000752
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000753 if (!WarnPropertyReadonlyAttrs)
754 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
755 diag::MAP_IGNORE);
756
Ted Kremenek73da5902007-12-17 17:50:07 +0000757 // Silence "format string is not a string literal" warnings if requested
758 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000759 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
760 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000761 if (!WarnUndefMacros)
762 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000763
Chris Lattner88eccaf2009-01-29 06:55:46 +0000764 if (WarnImplicitFunctionDeclaration)
765 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
766 diag::MAP_WARNING);
767 else
Chris Lattner37d10842008-05-05 21:18:06 +0000768 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
769 diag::MAP_IGNORE);
Chris Lattnerdb766842009-02-06 04:16:41 +0000770
771
772 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Reid Spencer5f016e22007-07-11 17:01:13 +0000773}
774
775//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000776// Target Triple Processing.
777//===----------------------------------------------------------------------===//
778
779static llvm::cl::opt<std::string>
780TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000781 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000782
Chris Lattner42e67372008-03-05 01:18:20 +0000783static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000784Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000785
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000786static llvm::cl::opt<std::string>
787MacOSVersionMin("mmacosx-version-min",
788 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
789
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000790// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
791// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
792static void HandleMacOSVersionMin(std::string &Triple) {
793 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
794 if (DarwinDashIdx == std::string::npos) {
795 fprintf(stderr,
796 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
797 exit(1);
798 }
799 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
800
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000801 // Remove the number.
802 Triple.resize(DarwinNumIdx);
803
804 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
805 bool MacOSVersionMinIsInvalid = false;
806 int VersionNum = 0;
807 if (MacOSVersionMin.size() < 4 ||
808 MacOSVersionMin.substr(0, 3) != "10." ||
809 !isdigit(MacOSVersionMin[3])) {
810 MacOSVersionMinIsInvalid = true;
811 } else {
812 const char *Start = MacOSVersionMin.c_str()+3;
813 char *End = 0;
814 VersionNum = (int)strtol(Start, &End, 10);
815
Chris Lattner079f2c462008-09-30 20:30:12 +0000816 // The version number must be in the range 0-9.
817 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
818
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000819 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
820 Triple += llvm::itostr(VersionNum+4);
821
Chris Lattner079f2c462008-09-30 20:30:12 +0000822 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
823 // Add the period piece (.7) to the end of the triple. This gives us
824 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000825 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000826 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
827 MacOSVersionMinIsInvalid = true;
828 }
829 }
830
831 if (MacOSVersionMinIsInvalid) {
832 fprintf(stderr,
833 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
834 MacOSVersionMin.c_str());
835 exit(1);
836 }
837}
838
839/// CreateTargetTriple - Process the various options that affect the target
840/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000841static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000842 // Initialize base triple. If a -triple option has been specified, use
843 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000844 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000845 if (Triple.empty()) {
846 Triple = LLVM_HOSTTRIPLE;
847
Daniel Dunbara6291902008-12-12 18:34:35 +0000848 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
849 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
850 Triple[2] == '8' && Triple[3] == '6')
851 Triple[1] = '3';
852
Daniel Dunbare553a722008-10-02 01:21:33 +0000853 // On darwin, we want to update the version to match that of the
854 // host.
855 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
856 if (DarwinDashIdx != std::string::npos) {
857 Triple.resize(DarwinDashIdx + strlen("-darwin"));
858
Daniel Dunbara6291902008-12-12 18:34:35 +0000859 // Only add the major part of the os version.
Chris Lattnera05ff452009-01-22 20:57:52 +0000860 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbara6291902008-12-12 18:34:35 +0000861 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000862 }
863 }
Ted Kremenekae360762007-12-03 22:06:55 +0000864
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000865 // If -arch foo was specified, remove the architecture from the triple we have
866 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000867 if (!Arch.empty()) {
868 // Decompose the base triple into "arch" and suffix.
869 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000870
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000871 if (FirstDashIdx == std::string::npos) {
872 fprintf(stderr,
873 "Malformed target triple: \"%s\" ('-' could not be found).\n",
874 Triple.c_str());
875 exit(1);
876 }
Ted Kremenekae360762007-12-03 22:06:55 +0000877
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000878 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
879 }
880
881 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
882 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000883 if (!MacOSVersionMin.empty())
884 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000885
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000886 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000887}
888
889//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000890// Preprocessor Initialization
891//===----------------------------------------------------------------------===//
892
893// FIXME: Preprocessor builtins to support.
894// -A... - Play with #assertions
895// -undef - Undefine all predefined macros
896
897static llvm::cl::list<std::string>
898D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
899 llvm::cl::desc("Predefine the specified macro"));
900static llvm::cl::list<std::string>
901U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
902 llvm::cl::desc("Undefine the specified macro"));
903
Chris Lattner64299f82008-01-10 01:53:41 +0000904static llvm::cl::list<std::string>
905ImplicitIncludes("include", llvm::cl::value_desc("file"),
906 llvm::cl::desc("Include file before parsing"));
907
908
Reid Spencer5f016e22007-07-11 17:01:13 +0000909// Append a #define line to Buf for Macro. Macro should be of the form XXX,
910// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
911// "#define XXX Y z W". To get a #define with no value, use "XXX=".
912static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
913 const char *Command = "#define ") {
914 Buf.insert(Buf.end(), Command, Command+strlen(Command));
915 if (const char *Equal = strchr(Macro, '=')) {
916 // Turn the = into ' '.
917 Buf.insert(Buf.end(), Macro, Equal);
918 Buf.push_back(' ');
919 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
920 } else {
921 // Push "macroname 1".
922 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
923 Buf.push_back(' ');
924 Buf.push_back('1');
925 }
926 Buf.push_back('\n');
927}
928
Chris Lattner64299f82008-01-10 01:53:41 +0000929/// AddImplicitInclude - Add an implicit #include of the specified file to the
930/// predefines buffer.
931static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
932 const char *Inc = "#include \"";
933 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
934 Buf.insert(Buf.end(), File.begin(), File.end());
935 Buf.push_back('"');
936 Buf.push_back('\n');
937}
938
Reid Spencer5f016e22007-07-11 17:01:13 +0000939
Chris Lattner53b0dab2007-10-09 22:10:18 +0000940/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000941/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000942///
Chris Lattner51574ea2008-04-19 23:25:44 +0000943static bool InitializePreprocessor(Preprocessor &PP,
944 bool InitializeSourceMgr,
945 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000946 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000947
Chris Lattner53b0dab2007-10-09 22:10:18 +0000948 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000949 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000950
951 if (InitializeSourceMgr) {
952 if (InFile != "-") {
953 const FileEntry *File = FileMgr.getFile(InFile);
954 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000955 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000956 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000957 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000958 }
959 } else {
960 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
961 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000962 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000963 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000964 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000965 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000966 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000968
Chris Lattneraa391972008-04-19 23:09:31 +0000969 std::vector<char> PredefineBuffer;
970
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000972 unsigned d = 0, D = D_macros.size();
973 unsigned u = 0, U = U_macros.size();
974 while (d < D || u < U) {
975 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
976 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
977 else
978 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
979 }
980
Chris Lattner64299f82008-01-10 01:53:41 +0000981 // FIXME: Read any files specified by -imacros.
982
983 // Add implicit #includes from -include.
984 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
985 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000986
Chris Lattneraa391972008-04-19 23:09:31 +0000987 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000988 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000989 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000990
991 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000992 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000993}
994
995//===----------------------------------------------------------------------===//
996// Preprocessor include path information.
997//===----------------------------------------------------------------------===//
998
999// This tool exports a large number of command line options to control how the
1000// preprocessor searches for header files. At root, however, the Preprocessor
1001// object takes a very simple interface: a list of directories to search for
1002//
1003// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001004// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001005//
Chris Lattner64299f82008-01-10 01:53:41 +00001006// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +00001007
1008static llvm::cl::opt<bool>
1009nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1010
1011// Various command line options. These four add directories to each chain.
1012static llvm::cl::list<std::string>
1013F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1014 llvm::cl::desc("Add directory to framework include search path"));
1015static llvm::cl::list<std::string>
1016I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1017 llvm::cl::desc("Add directory to include search path"));
1018static llvm::cl::list<std::string>
1019idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1020 llvm::cl::desc("Add directory to AFTER include search path"));
1021static llvm::cl::list<std::string>
1022iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1023 llvm::cl::desc("Add directory to QUOTE include search path"));
1024static llvm::cl::list<std::string>
1025isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1026 llvm::cl::desc("Add directory to SYSTEM include search path"));
1027
1028// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1029static llvm::cl::list<std::string>
1030iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1031 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1032static llvm::cl::list<std::string>
1033iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1034 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1035static llvm::cl::list<std::string>
1036iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1037 llvm::cl::Prefix,
1038 llvm::cl::desc("Set directory to include search path with prefix"));
1039
Chris Lattner0c946412007-08-26 17:47:35 +00001040static llvm::cl::opt<std::string>
1041isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1042 llvm::cl::desc("Set the system root directory (usually /)"));
1043
Reid Spencer5f016e22007-07-11 17:01:13 +00001044// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001045
Reid Spencer5f016e22007-07-11 17:01:13 +00001046/// InitializeIncludePaths - Process the -I options and set them in the
1047/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001048void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1049 FileManager &FM, const LangOptions &Lang) {
1050 InitHeaderSearch Init(Headers, Verbose, isysroot);
1051
Ted Kremenekf3721112008-05-31 00:27:00 +00001052 // Handle -I... and -F... options, walking the lists in parallel.
1053 unsigned Iidx = 0, Fidx = 0;
1054 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1055 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001056 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001057 ++Iidx;
1058 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001059 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001060 ++Fidx;
1061 }
1062 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001063
Ted Kremenekf3721112008-05-31 00:27:00 +00001064 // Consume what's left from whatever list was longer.
1065 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001066 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001067 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001068 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001069
1070 // Handle -idirafter... options.
1071 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001072 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1073 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001074
1075 // Handle -iquote... options.
1076 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001077 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001078
1079 // Handle -isystem... options.
1080 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001081 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001082
1083 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1084 // parallel, processing the values in order of occurance to get the right
1085 // prefixes.
1086 {
1087 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1088 unsigned iprefix_idx = 0;
1089 unsigned iwithprefix_idx = 0;
1090 unsigned iwithprefixbefore_idx = 0;
1091 bool iprefix_done = iprefix_vals.empty();
1092 bool iwithprefix_done = iwithprefix_vals.empty();
1093 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1094 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1095 if (!iprefix_done &&
1096 (iwithprefix_done ||
1097 iprefix_vals.getPosition(iprefix_idx) <
1098 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1099 (iwithprefixbefore_done ||
1100 iprefix_vals.getPosition(iprefix_idx) <
1101 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1102 Prefix = iprefix_vals[iprefix_idx];
1103 ++iprefix_idx;
1104 iprefix_done = iprefix_idx == iprefix_vals.size();
1105 } else if (!iwithprefix_done &&
1106 (iwithprefixbefore_done ||
1107 iwithprefix_vals.getPosition(iwithprefix_idx) <
1108 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001109 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1110 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 ++iwithprefix_idx;
1112 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1113 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001114 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1115 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 ++iwithprefixbefore_idx;
1117 iwithprefixbefore_done =
1118 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1119 }
1120 }
1121 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001122
Nico Weber0fca0222008-08-22 09:25:22 +00001123 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001124
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001125 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001126 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001127 llvm::sys::Path::GetMainExecutable(Argv0,
1128 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001129 if (!MainExecutablePath.isEmpty()) {
1130 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1131 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001132
1133 // Get foo/lib/clang/1.0/include
1134 //
1135 // FIXME: Don't embed version here.
1136 MainExecutablePath.appendComponent("lib");
1137 MainExecutablePath.appendComponent("clang");
1138 MainExecutablePath.appendComponent("1.0");
1139 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001140
1141 // We pass true to ignore sysroot so that we *always* look for clang headers
1142 // relative to our executable, never relative to -isysroot.
1143 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1144 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001145 }
1146
Nico Weber0fca0222008-08-22 09:25:22 +00001147 if (!nostdinc)
1148 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001149
1150 // Now that we have collected all of the include paths, merge them all
1151 // together and tell the preprocessor about them.
1152
Nico Weber0fca0222008-08-22 09:25:22 +00001153 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001154}
1155
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001156//===----------------------------------------------------------------------===//
1157// Driver PreprocessorFactory - For lazily generating preprocessors ...
1158//===----------------------------------------------------------------------===//
1159
1160namespace {
1161class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001162 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001163 Diagnostic &Diags;
1164 const LangOptions &LangInfo;
1165 TargetInfo &Target;
1166 SourceManager &SourceMgr;
1167 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001168 bool InitializeSourceMgr;
1169
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001170public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001171 DriverPreprocessorFactory(const std::string &infile,
1172 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001173 TargetInfo &target, SourceManager &SM,
1174 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001175 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1176 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1177
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001178
1179 virtual ~DriverPreprocessorFactory() {}
1180
1181 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001182 llvm::OwningPtr<PTHManager> PTHMgr;
1183
1184 // Use PTH?
1185 if (!TokenCache.empty())
Ted Kremenek8a6aec62009-01-28 20:49:33 +00001186 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenek72b1b152009-01-15 18:47:46 +00001187
1188 // Create the Preprocessor.
1189 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1190 SourceMgr, HeaderInfo,
1191 PTHMgr.get()));
1192
1193 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1194 // That argument is used as the IdentifierInfoLookup argument to
1195 // IdentifierTable's ctor.
1196 if (PTHMgr) {
1197 PTHMgr->setPreprocessor(PP.get());
1198 PP->setPTHManager(PTHMgr.take());
1199 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001200
Chris Lattner51574ea2008-04-19 23:25:44 +00001201 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001202 return NULL;
1203 }
1204
Daniel Dunbar750c3582008-10-24 22:12:41 +00001205 /// FIXME: PP can only handle one callback
1206 if (ProgAction != PrintPreprocessedInput) {
1207 const char* ErrStr;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001208 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001209 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001210 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001211 return NULL;
1212 }
1213 }
1214
Ted Kremenek339b9c22008-04-17 22:31:54 +00001215 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001216 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001217 }
1218};
1219}
Reid Spencer5f016e22007-07-11 17:01:13 +00001220
Reid Spencer5f016e22007-07-11 17:01:13 +00001221//===----------------------------------------------------------------------===//
1222// Basic Parser driver
1223//===----------------------------------------------------------------------===//
1224
Chris Lattner51574ea2008-04-19 23:25:44 +00001225static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001227 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001228
1229 // Parsing the specified input file.
1230 P.ParseTranslationUnit();
1231 delete PA;
1232}
1233
1234//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001235// Code generation options
1236//===----------------------------------------------------------------------===//
1237
1238static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001239OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001240
1241// It might be nice to add bounds to the CommandLine library directly.
1242struct OptLevelParser : public llvm::cl::parser<unsigned> {
1243 bool parse(llvm::cl::Option &O, const char *ArgName,
1244 const std::string &Arg, unsigned &Val) {
1245 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1246 return true;
1247 // FIXME: Support -O4.
1248 if (Val > 3)
1249 return O.error(": '" + Arg + "' invalid optimization level!");
1250 return false;
1251 }
1252};
1253static llvm::cl::opt<unsigned, false, OptLevelParser>
1254OptLevel("O", llvm::cl::Prefix,
1255 llvm::cl::desc("Optimization level"),
1256 llvm::cl::init(0));
1257
Daniel Dunbara034ba82009-02-17 19:47:34 +00001258static llvm::cl::opt<std::string>
1259TargetCPU("mcpu",
1260 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1261
Daniel Dunbar70f92432008-10-23 05:50:47 +00001262static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001263 Opts.OptimizeSize = OptSize;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001264 if (OptSize) {
1265 // -Os implies -O2
1266 // FIXME: Diagnose conflicting options.
1267 Opts.OptimizationLevel = 2;
1268 } else {
1269 Opts.OptimizationLevel = OptLevel;
1270 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001271
1272 // FIXME: There are llvm-gcc options to control these selectively.
1273 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1274 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Daniel Dunbar3ada6ff2009-02-15 20:00:15 +00001275 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001276
1277#ifdef NDEBUG
1278 Opts.VerifyModule = 0;
1279#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001280
1281 Opts.CPU = TargetCPU;
1282 Opts.Features.insert(Opts.Features.end(),
1283 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001284
1285 // Handle -ftime-report.
1286 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001287}
1288
1289//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001290// Main driver
1291//===----------------------------------------------------------------------===//
1292
Ted Kremenekdb094a22007-12-05 18:27:04 +00001293/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1294/// action. These consumers can operate on both ASTs that are freshly
1295/// parsed from source files as well as those deserialized from Bitcode.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001296static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001297 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001298 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001299 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001300 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001301 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001302 default:
1303 return NULL;
1304
1305 case ASTPrint:
1306 return CreateASTPrinter();
1307
1308 case ASTDump:
1309 return CreateASTDumper();
1310
1311 case ASTView:
1312 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001313
Chris Lattner8a5c8092009-02-18 01:20:05 +00001314 case PrintDeclContext:
1315 return CreateDeclContextPrinter();
1316
1317 case EmitHTML:
1318 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001319
Chris Lattner8a5c8092009-02-18 01:20:05 +00001320 case InheritanceView:
1321 return CreateInheritanceViewer(InheritanceViewCls);
1322
1323 case TestSerialization:
1324 return CreateSerializationTest(Diag, FileMgr);
1325
1326 case EmitAssembly:
1327 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001328 case EmitBC:
1329 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001330 BackendAction Act;
1331 if (ProgAction == EmitAssembly)
1332 Act = Backend_EmitAssembly;
1333 else if (ProgAction == EmitLLVM)
1334 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001335 else if (ProgAction == EmitLLVMOnly)
1336 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001337 else
1338 Act = Backend_EmitBC;
1339
1340 CompileOptions Opts;
1341 InitializeCompileOptions(Opts);
1342 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
1343 InFile, OutputFile, GenerateDebugInfo);
1344 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001345
Chris Lattner8a5c8092009-02-18 01:20:05 +00001346 case SerializeAST:
1347 // FIXME: Allow user to tailor where the file is written.
1348 return CreateASTSerializer(InFile, OutputFile, Diag);
1349
1350 case RewriteObjC:
1351 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001352
Chris Lattner8a5c8092009-02-18 01:20:05 +00001353 case RewriteBlocks:
1354 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1355
1356 case RunAnalysis:
1357 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001358 }
1359}
1360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361/// ProcessInputFile - Process a single input file with the specified state.
1362///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001363static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001364 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001365 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001366 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001367
Ted Kremenek85888962008-10-21 00:54:44 +00001368 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001370 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1371 PP.getFileManager(), PP.getLangOptions(),
1372 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001373
1374 if (!Consumer) {
1375 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001376 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001377 return;
1378 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001379
Ted Kremenekdb094a22007-12-05 18:27:04 +00001380 break;
1381
Chris Lattnerc106c102008-10-12 05:03:36 +00001382 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001383 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001384 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001385 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001386 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001387 RawLex.SetKeepWhitespaceMode(true);
1388
1389 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001390 RawLex.LexFromRawLexer(RawTok);
1391 while (RawTok.isNot(tok::eof)) {
1392 PP.DumpToken(RawTok, true);
1393 fprintf(stderr, "\n");
1394 RawLex.LexFromRawLexer(RawTok);
1395 }
1396 ClearSourceMgr = true;
1397 break;
1398 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001400 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001401 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001402 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001403 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 do {
1405 PP.Lex(Tok);
1406 PP.DumpToken(Tok, true);
1407 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001408 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001409 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 break;
1411 }
1412 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001413 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001414 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001416 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 do {
1418 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001419 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001420 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 break;
1422 }
Ted Kremenek85888962008-10-21 00:54:44 +00001423
1424 case GeneratePCH: {
Chris Lattner47099742009-02-18 01:51:21 +00001425 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001426 CacheTokens(PP, OutputFile);
1427 ClearSourceMgr = true;
1428 break;
1429 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001430
Chris Lattner47099742009-02-18 01:51:21 +00001431 case PrintPreprocessedInput: { // -E mode.
1432 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001433 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001434 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 break;
Chris Lattner47099742009-02-18 01:51:21 +00001436 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001437
Chris Lattner47099742009-02-18 01:51:21 +00001438 case ParseNoop: { // -parse-noop
1439 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001440 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001441 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 break;
Chris Lattner47099742009-02-18 01:51:21 +00001443 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001444
Chris Lattner47099742009-02-18 01:51:21 +00001445 case ParsePrintCallbacks: {
1446 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001447 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001448 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 break;
Chris Lattner47099742009-02-18 01:51:21 +00001450 }
1451
1452 case ParseSyntaxOnly: { // -fsyntax-only
1453 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001454 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001455 break;
Chris Lattner47099742009-02-18 01:51:21 +00001456 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001457
1458 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001459 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001460 ClearSourceMgr = true;
1461 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001462
Chris Lattner47099742009-02-18 01:51:21 +00001463 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001464 DoRewriteTest(PP, InFile, OutputFile);
1465 ClearSourceMgr = true;
1466 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001467 }
Chris Lattner47099742009-02-18 01:51:21 +00001468 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001469
1470 if (Consumer) {
1471 TranslationUnit *TU = 0;
1472 if (DisableFree) {
1473 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1474 PP.getSourceManager(),
1475 PP.getTargetInfo(),
1476 PP.getIdentifierTable(),
1477 PP.getSelectorTable(),
1478 /* FreeMemory = */ false);
1479 TU = new TranslationUnit(*Context);
1480 }
1481 ParseAST(PP, Consumer.get(), TU, Stats);
1482 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001483
1484 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001485 if (CheckDiagnostics(PP))
1486 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001487
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001489 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 PP.PrintStats();
1491 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001492 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001493 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 fprintf(stderr, "\n");
1495 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001496
1497 // For a multi-file compilation, some things are ok with nuking the source
1498 // manager tables, other require stable fileid/macroid's across multiple
1499 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001500 if (ClearSourceMgr)
1501 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001502
1503 if (DisableFree)
1504 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001505}
1506
Ted Kremenek20e97482007-12-12 23:41:08 +00001507static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1508 FileManager& FileMgr) {
1509
1510 if (VerifyDiagnostics) {
1511 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1512 exit (1);
1513 }
1514
1515 llvm::sys::Path Filename(InFile);
1516
1517 if (!Filename.isValid()) {
1518 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1519 exit (1);
1520 }
1521
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001522 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001523
1524 if (!TU) {
1525 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1526 InFile.c_str());
1527 exit (1);
1528 }
1529
Ted Kremenek63ea8632007-12-19 19:27:38 +00001530 // Observe that we use the source file name stored in the deserialized
1531 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001532 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001533 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001534 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001535
Ted Kremenek20e97482007-12-12 23:41:08 +00001536 if (!Consumer) {
1537 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1538 exit (1);
1539 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001540
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001541 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001542
Chris Lattnere66b65c2008-02-06 01:42:25 +00001543 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001544 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1545 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001546}
1547
1548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549static llvm::cl::list<std::string>
1550InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1551
Ted Kremenek20e97482007-12-12 23:41:08 +00001552static bool isSerializedFile(const std::string& InFile) {
1553 if (InFile.size() < 4)
1554 return false;
1555
1556 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001557 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001558}
1559
Reid Spencer5f016e22007-07-11 17:01:13 +00001560
1561int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001562 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 llvm::sys::PrintStackTraceOnErrorSignal();
1564
Chris Lattner47099742009-02-18 01:51:21 +00001565 if (TimeReport)
1566 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1567
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 // If no input was specified, read from stdin.
1569 if (InputFilenames.empty())
1570 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001571
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 // Create a file manager object to provide access to and cache the filesystem.
1573 FileManager FileMgr;
1574
Ted Kremenek31e703b2007-12-11 23:28:38 +00001575 // Create the diagnostic client for reporting errors or for
1576 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001577 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001578
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001579 if (!VerifyDiagnostics) {
1580 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001581 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1582 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001583 !NoCaretDiagnostics,
1584 !NoShowLocation);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001585 } else {
1586 // When checking diagnostics, just buffer them up.
1587 TextDiagClient = new TextDiagnosticBuffer();
1588
1589 if (InputFilenames.size() != 1) {
1590 fprintf(stderr,
1591 "-verify only works on single input files for now.\n");
1592 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 }
1594 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001595
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001597 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1598 Diagnostic Diags(DiagClient.get());
Ted Kremenek31e703b2007-12-11 23:28:38 +00001599 InitializeDiagnostics(Diags);
1600
Chris Lattner4f037832007-12-05 23:24:17 +00001601 // -I- is a deprecated GCC feature, scan for it and reject it.
1602 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1603 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001604 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001605 I_dirs.erase(I_dirs.begin()+i);
1606 --i;
1607 }
1608 }
Chris Lattner11215192008-03-14 06:12:05 +00001609
1610 // Get information about the target being compiled for.
1611 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001612 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1613
Chris Lattner11215192008-03-14 06:12:05 +00001614 if (Target == 0) {
1615 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1616 Triple.c_str());
1617 fprintf(stderr, "Please use -triple or -arch.\n");
1618 exit(1);
1619 }
Chris Lattner4f037832007-12-05 23:24:17 +00001620
Daniel Dunbard4270232009-01-20 23:17:32 +00001621 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001622 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001623
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001624 llvm::OwningPtr<SourceManager> SourceMgr;
1625
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001627 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001628
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001629 if (isSerializedFile(InFile)) {
1630 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001631 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001632 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001633 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001634
1635 /// Create a SourceManager object. This tracks and owns all the file
1636 /// buffers allocated to a translation unit.
1637 if (!SourceMgr)
1638 SourceMgr.reset(new SourceManager());
1639 else
1640 SourceMgr->clearIDTables();
1641
1642 // Initialize language options, inferring file types from input filenames.
1643 LangOptions LangInfo;
1644 InitializeBaseLanguage();
1645 LangKind LK = GetLanguage(InFile);
1646 bool PCH = InitializeLangOptions(LangInfo, LK);
1647 InitializeGCMode(LangInfo);
1648 InitializeLanguageStandard(LangInfo, LK, Target.get());
1649
1650 // Process the -I options and set them in the HeaderInfo.
1651 HeaderSearch HeaderInfo(FileMgr);
1652
1653 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1654
1655 // Set up the preprocessor with these options.
1656 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1657 *SourceMgr.get(), HeaderInfo);
1658
1659 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1660
1661 if (!PP)
1662 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001663
Chris Lattnerf63aea32009-03-04 21:40:56 +00001664 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1665 // always reset to using TextDiagClient.
1666 llvm::OwningPtr<DiagnosticClient> TmpClient;
1667
1668 if (!HTMLDiag.empty()) {
1669 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1670 &PPFactory));
1671 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001672 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001673 else
1674 Diags.setClient(TextDiagClient);
1675
1676 // Process the source file.
1677 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1678
1679 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 }
Chris Lattner11215192008-03-14 06:12:05 +00001681
Mike Stump007f2a92009-01-28 02:43:35 +00001682 if (Verbose)
1683 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1684 " hosted on " LLVM_HOSTTRIPLE "\n");
1685
Ted Kremenek7a08e282008-08-07 18:13:12 +00001686 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1688 (NumDiagnostics == 1 ? "" : "s"));
1689
1690 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 FileMgr.PrintStats();
1692 fprintf(stderr, "\n");
1693 }
1694
Daniel Dunbar276373d2008-10-27 22:10:13 +00001695 // If verifying diagnostics and we reached here, all is well.
1696 if (VerifyDiagnostics)
1697 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001698
1699 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001700
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001701 // Managed static deconstruction. Useful for making things like
1702 // -time-passes usable.
1703 llvm::llvm_shutdown();
1704
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001705 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001706}