blob: 9ecddd8cd55af1c77dbf0470ed515ab01a6645b4 [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//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar68952de2009-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 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 Lattner01de9c82008-09-30 20:16:56 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000046#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000050#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000051#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000052#include "llvm/Support/PluginLoader.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000053#include "llvm/Support/Timer.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
Chris Lattnerefe33382009-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 Dunbar4efedde2008-10-16 16:54:18 +000068static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000069
Chris Lattner4b009652007-07-25 00:24:17 +000070static llvm::cl::opt<bool>
71Verbose("v", llvm::cl::desc("Enable verbose output"));
72static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000073Stats("print-stats",
74 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-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));
Chris Lattner4b009652007-07-25 00:24:17 +000079
80enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000081 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000082 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000083 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000084 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000085 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000086 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000087 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000088 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +000089 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +000090 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000091 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-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 Xu6036bbe2009-01-13 01:29:24 +000095 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000096 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattneraf669fb2008-10-12 05:03:36 +0000102 DumpTokens, // Dump out preprocessed tokens.
103 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000104 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000105 GeneratePCH, // Generate precompiled header.
106 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattneraf669fb2008-10-12 05:03:36 +0000117 clEnumValN(DumpRawTokens, "dump-raw-tokens",
118 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000119 clEnumValN(RunAnalysis, "analyze",
120 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000121 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek24612ae2008-03-18 21:19:49 +0000129 clEnumValN(EmitHTML, "emit-html",
130 "Output input source as HTML"),
Chris Lattner4045a8a2007-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 Lattner664dd082007-10-11 00:37:43 +0000135 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000136 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000137 clEnumValN(PrintDeclContext, "print-decl-contexts",
138 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000139 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000140 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000141 clEnumValN(EmitAssembly, "S",
142 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000143 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000144 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000145 clEnumValN(EmitBC, "emit-llvm-bc",
146 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000147 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
148 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000149 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000150 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000151 clEnumValN(RewriteTest, "rewrite-test",
152 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000153 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-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 Naroff93c18352008-09-18 14:10:13 +0000157 clEnumValN(RewriteBlocks, "rewrite-blocks",
158 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000159 clEnumValEnd));
160
Ted Kremenekd01eae62007-12-19 19:47:59 +0000161
162static llvm::cl::opt<std::string>
163OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000164 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000165 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000166
167//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-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 Kremenek57f25b22008-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 Gupta40e56a12008-05-08 08:54:20 +0000183//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000184// Diagnostic Options
185//===----------------------------------------------------------------------===//
186
Ted Kremenek10389cf2007-09-26 19:42:19 +0000187static llvm::cl::opt<bool>
188VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000189 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000190
Ted Kremenekfd75e312008-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 Weber0e13eaa2008-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 Lattnerb96a04f2009-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 Weber0e13eaa2008-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
Chris Lattner4b009652007-07-25 00:24:17 +0000211//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-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 Dunbar47f0b0f2009-01-14 18:56:36 +0000218 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000219
220//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000221// Builtin Options
222//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-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 Gregor23d23262009-02-14 20:49:29 +0000229static llvm::cl::opt<bool>
230Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000231 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000232 "freestanding environment"));
233
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000234static llvm::cl::opt<bool>
235MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000236 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000237 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000238
Douglas Gregor23d23262009-02-14 20:49:29 +0000239//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000240// Language Options
241//===----------------------------------------------------------------------===//
242
243enum LangKind {
244 langkind_unspecified,
245 langkind_c,
246 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000247 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000248 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000249 langkind_cxx,
250 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000251 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000252 langkind_objc,
253 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000254 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000255 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000256 langkind_objcxx_cpp,
257 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000258};
259
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbarb1488592009-01-29 23:50:47 +0000267 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000268 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000269 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
270 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000271 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000272 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000273 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
274 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000275 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000276 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000277 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000278 "Precompiled C header"),
279 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000280 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000281 clEnumValN(langkind_cxx_pch, "c++-header",
282 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000283 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
284 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek11ad8952007-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 Lattner4eac0502008-01-04 19:12:28 +0000310 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000311 }
312
Ted Kremenek11ad8952007-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 Lattner1cbb3032008-10-28 20:33:42 +0000320 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000321 return langkind_asm_cpp;
Ted Kremenek11ad8952007-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 Kremenek71c6cc62008-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){
Chris Lattner4b009652007-07-25 00:24:17 +0000352 // FIXME: implement -fpreprocessed mode.
353 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000354 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000355
356 // Test for 'PCH'.
357 switch (LK) {
Chris Lattnerb5555ea2009-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 Kremenekceacc812009-01-09 00:38:08 +0000376 }
Chris Lattner4b009652007-07-25 00:24:17 +0000377
Ted Kremenek11ad8952007-12-05 23:49:08 +0000378 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000379 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000380 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000381 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000382 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000383 case langkind_c_cpp:
384 NoPreprocess = true;
385 // FALLTHROUGH
386 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000387 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek71c6cc62008-10-21 00:54:44 +0000399 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek71c6cc62008-10-21 00:54:44 +0000409
410 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000411}
412
413/// LangStds - Language standards we support.
414enum LangStds {
415 lang_unspecified,
416 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000417 lang_gnu_START,
418 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000419 lang_cxx98, lang_gnucxx98,
420 lang_cxx0x, lang_gnucxx0x
421};
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 Greifbe1618a2009-02-28 09:22:15 +0000436 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000437 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000438 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +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++)"),
446 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++)"),
451 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 Carlsson55bfe0d2007-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 Naroff73a07032008-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 Gupta69683532008-05-08 08:28:14 +0000466 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000467
468static llvm::cl::opt<bool>
469WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000470 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000471
472static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000473NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-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 Lattnerd7bc88b2008-12-04 23:20:07 +0000477
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000478static llvm::cl::opt<bool>
Mike Stump9093c742009-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 Jahanian48543f52009-01-21 22:04:16 +0000486
Daniel Dunbar9bae8652009-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 Kremenek2658c4a2008-04-29 04:37:03 +0000490
Daniel Dunbar91692d92008-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 Dunbar1be1df32008-08-11 21:35:06 +0000502static llvm::cl::opt<bool>
503GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000504 llvm::cl::desc("Generate output compatible with the standard GNU "
505 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000506
507static llvm::cl::opt<bool>
508NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000509 llvm::cl::desc("Generate output compatible with the NeXT "
510 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000511
Ted Kremenek88bec0f2008-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 Lattner738d3f62009-03-02 22:11:07 +0000520static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000521TargetFeatures("mattr", llvm::cl::CommaSeparated,
522 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
523
Chris Lattner738d3f62009-03-02 22:11:07 +0000524
525
Chris Lattner4b009652007-07-25 00:24:17 +0000526// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000527// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000528static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
529 TargetInfo *Target) {
Chris Lattnerddae7102008-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 Kremenek88bec0f2008-09-03 21:22:16 +0000532
Chris Lattnerf6790a82009-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 Lattner738d3f62009-03-02 22:11:07 +0000542 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000543 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
544 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000545 if (Opt != -1) {
546 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000547 fprintf(stderr, "invalid feature '%s'\n",
548 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000549 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000550 fprintf(stderr, "feature '%s': %s\n",
551 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000552 exit(1);
553 }
554 }
555
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000556 if (Ansi) // "The -ansi option is equivalent to -std=c89."
557 LangStd = lang_c89;
558
Chris Lattner4b009652007-07-25 00:24:17 +0000559 if (LangStd == lang_unspecified) {
560 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000561 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000562 default: assert(0 && "Unknown base language");
563 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000564 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000565 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000566 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000567 case langkind_objc:
568 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000569 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenekceacc812009-01-09 00:38:08 +0000576 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +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.
587 case lang_gnucxx0x:
588 case lang_cxx0x:
589 Options.CPlusPlus0x = 1;
590 // FALL THROUGH
591 case lang_gnucxx98:
592 case lang_cxx98:
593 Options.CPlusPlus = 1;
594 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000595 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000596 // FALL THROUGH.
597 case lang_gnu99:
598 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner0297c762008-02-25 04:01:39 +0000606 Options.Digraphs = 1; // C94, C99, C++.
607 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000608 case lang_c89:
609 break;
610 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000611
612 if (Options.CPlusPlus) {
613 Options.C99 = 0;
614 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
615 }
Chris Lattner4b009652007-07-25 00:24:17 +0000616
Chris Lattner6ab935b2008-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 Kremenek88bec0f2008-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 Lattner58d5ba52008-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 Kremenek88bec0f2008-09-03 21:22:16 +0000627
Chris Lattner58d5ba52008-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 Carlsson8ffcf732009-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 Lattner58d5ba52008-12-05 00:10:44 +0000633 Options.Blocks = 0;
634
Chris Lattner4b009652007-07-25 00:24:17 +0000635 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000636 if (PascalStrings.getPosition())
637 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000638 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000639 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000640 if (NoLaxVectorConversions.getPosition())
641 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000642 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000643 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000644 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000645
Douglas Gregor23d23262009-02-14 20:49:29 +0000646 if (Freestanding)
647 Options.Freestanding = 1;
648
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000649 Options.MathErrno = MathErrno;
650
Chris Lattnerddae7102008-12-04 22:54:33 +0000651 // Override the default runtime if the user requested it.
652 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000653 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000654 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000655 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000656
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000657 if (ObjCNonFragileABI)
658 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000659
660 if (EmitAllDecls)
661 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000662}
663
Ted Kremenek2658c4a2008-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 Gupta69683532008-05-08 08:28:14 +0000667 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000668
669static llvm::cl::opt<bool>
670ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000671 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner3a22b7c2008-05-29 15:36:45 +0000689SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
690
691static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbar4dbd8572008-09-12 18:10:20 +0000700SuppressSystemWarnings("suppress-system-warnings",
Chris Lattner71af6d62009-02-06 04:16:41 +0000701 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000702 llvm::cl::init(true));
703
704static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000705WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000706 llvm::cl::desc("Warn for unused macros in the main translation unit"));
707
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000708static llvm::cl::opt<bool>
709WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000710 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000711
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000712static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-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 Kremenek4b57bc72007-12-17 17:50:07 +0000717WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000718 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000719
Chris Lattnera616ee32008-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 Lattnerdea31bf2008-05-05 21:18:06 +0000724static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000725WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
726 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000727
Steve Naroffb91afca2008-10-21 10:37:50 +0000728static llvm::cl::opt<bool>
729WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattner71af6d62009-02-06 04:16:41 +0000730 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
731 " and alignment"),
Steve Naroffb91afca2008-10-21 10:37:50 +0000732 llvm::cl::init(true));
733
Chris Lattner4b009652007-07-25 00:24:17 +0000734/// InitializeDiagnostics - Initialize the diagnostic object, based on the
735/// current command line option settings.
736static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000737 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000738 Diags.setWarningsAsErrors(WarningsAsErrors);
739 Diags.setWarnOnExtensions(WarnOnExtensions);
740 Diags.setErrorOnExtensions(ErrorOnExtensions);
741
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000742 // Suppress warnings in system headers unless requested not to.
743 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
744
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek24f59fb2007-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 Kremenek4b57bc72007-12-17 17:50:07 +0000752
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000753 if (!WarnPropertyReadonlyAttrs)
754 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
755 diag::MAP_IGNORE);
756
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000757 // Silence "format string is not a string literal" warnings if requested
758 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000759 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
760 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000761 if (!WarnUndefMacros)
762 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000763
Chris Lattner86a24842009-01-29 06:55:46 +0000764 if (WarnImplicitFunctionDeclaration)
765 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
766 diag::MAP_WARNING);
767 else
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000768 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
769 diag::MAP_IGNORE);
Chris Lattner71af6d62009-02-06 04:16:41 +0000770
771
772 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Chris Lattner4b009652007-07-25 00:24:17 +0000773}
774
775//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000776// Target Triple Processing.
777//===----------------------------------------------------------------------===//
778
779static llvm::cl::opt<std::string>
780TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000781 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000782
Chris Lattnerfc457002008-03-05 01:18:20 +0000783static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000784Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000785
Chris Lattner2b168e02008-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 Lattner01de9c82008-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 Lattner01de9c82008-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 Lattnerd376f6d2008-09-30 20:30:12 +0000816 // The version number must be in the range 0-9.
817 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
818
Chris Lattner01de9c82008-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 Lattnerd376f6d2008-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 Lattner01de9c82008-09-30 20:16:56 +0000825 Triple += End;
Chris Lattner01de9c82008-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 Lattnerf3d79c32008-03-09 01:35:13 +0000841static std::string CreateTargetTriple() {
Ted Kremenek40499482007-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 Lattner210c0cc2007-12-12 05:01:48 +0000844 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000845 if (Triple.empty()) {
846 Triple = LLVM_HOSTTRIPLE;
847
Daniel Dunbar81caece2008-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 Dunbarabe2e542008-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 Dunbar81caece2008-12-12 18:34:35 +0000859 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000860 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000861 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000862 }
863 }
Ted Kremenek40499482007-12-03 22:06:55 +0000864
Chris Lattnerf3d79c32008-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 Lattner2b168e02008-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 Lattnerf3d79c32008-03-09 01:35:13 +0000870
Chris Lattner2b168e02008-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 Kremenek40499482007-12-03 22:06:55 +0000877
Chris Lattner2b168e02008-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 Lattner01de9c82008-09-30 20:16:56 +0000883 if (!MacOSVersionMin.empty())
884 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000885
Chris Lattner2b168e02008-09-30 01:13:12 +0000886 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000887}
888
889//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner008da782008-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner008da782008-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
Chris Lattner4b009652007-07-25 00:24:17 +0000939
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000940/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000941/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000942///
Chris Lattner9d818a22008-04-19 23:25:44 +0000943static bool InitializePreprocessor(Preprocessor &PP,
944 bool InitializeSourceMgr,
945 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000946 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000947
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000948 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000949 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-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 Lattnerf4f776a2009-01-17 06:22:33 +0000955 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000956 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000957 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000958 }
959 } else {
960 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
961 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000962 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000963 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000964 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000965 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000966 }
Chris Lattner4b009652007-07-25 00:24:17 +0000967 }
Sam Bishop61a20782008-04-14 14:41:57 +0000968
Chris Lattner47b6a162008-04-19 23:09:31 +0000969 std::vector<char> PredefineBuffer;
970
Chris Lattner4b009652007-07-25 00:24:17 +0000971 // Add macros from the command line.
Sam Bishop61a20782008-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 Lattner008da782008-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 Lattnerd1f21e12007-10-09 22:10:18 +0000986
Chris Lattner47b6a162008-04-19 23:09:31 +0000987 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000988 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000989 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000990
991 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000992 return false;
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerae3dcc02007-08-26 17:47:35 +00001004// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001005//
Chris Lattner008da782008-01-10 01:53:41 +00001006// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerae3dcc02007-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
Chris Lattner4b009652007-07-25 00:24:17 +00001044// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001045
Chris Lattner4b009652007-07-25 00:24:17 +00001046/// InitializeIncludePaths - Process the -I options and set them in the
1047/// HeaderSearch object.
Nico Weber770e3882008-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 Kremenekb4d41e12008-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 Weber770e3882008-08-22 09:25:22 +00001056 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001057 ++Iidx;
1058 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001059 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001060 ++Fidx;
1061 }
1062 }
Chris Lattner4b009652007-07-25 00:24:17 +00001063
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001064 // Consume what's left from whatever list was longer.
1065 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001066 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001067 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001068 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001069
1070 // Handle -idirafter... options.
1071 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001072 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1073 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001074
1075 // Handle -iquote... options.
1076 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001077 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001078
1079 // Handle -isystem... options.
1080 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001081 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +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 Weber770e3882008-08-22 09:25:22 +00001109 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1110 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001111 ++iwithprefix_idx;
1112 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1113 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001114 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1115 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001116 ++iwithprefixbefore_idx;
1117 iwithprefixbefore_done =
1118 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1119 }
1120 }
1121 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001122
Nico Weber770e3882008-08-22 09:25:22 +00001123 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001124
Daniel Dunbar4e604292009-02-21 20:52:41 +00001125 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001126 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001127 llvm::sys::Path::GetMainExecutable(Argv0,
1128 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-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 Dunbar4e604292009-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 Lattner99a72652009-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 Lattner3ee4a2f2008-03-03 03:16:03 +00001145 }
1146
Nico Weber770e3882008-08-22 09:25:22 +00001147 if (!nostdinc)
1148 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +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 Weber770e3882008-08-22 09:25:22 +00001153 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001154}
1155
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001156//===----------------------------------------------------------------------===//
1157// Driver PreprocessorFactory - For lazily generating preprocessors ...
1158//===----------------------------------------------------------------------===//
1159
1160namespace {
1161class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001162 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001163 Diagnostic &Diags;
1164 const LangOptions &LangInfo;
1165 TargetInfo &Target;
1166 SourceManager &SourceMgr;
1167 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001168 bool InitializeSourceMgr;
1169
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001170public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001171 DriverPreprocessorFactory(const std::string &infile,
1172 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001173 TargetInfo &target, SourceManager &SM,
1174 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001175 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1176 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1177
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001178
1179 virtual ~DriverPreprocessorFactory() {}
1180
1181 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001182 llvm::OwningPtr<PTHManager> PTHMgr;
1183
1184 // Use PTH?
1185 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001186 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-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 Kremenek4e9899f2008-04-17 22:31:54 +00001200
Chris Lattner9d818a22008-04-19 23:25:44 +00001201 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001202 return NULL;
1203 }
1204
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001205 /// FIXME: PP can only handle one callback
1206 if (ProgAction != PrintPreprocessedInput) {
1207 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001208 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001209 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001210 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001211 return NULL;
1212 }
1213 }
1214
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001215 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001216 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001217 }
1218};
1219}
Chris Lattner4b009652007-07-25 00:24:17 +00001220
Chris Lattner4b009652007-07-25 00:24:17 +00001221//===----------------------------------------------------------------------===//
1222// Basic Parser driver
1223//===----------------------------------------------------------------------===//
1224
Chris Lattner9d818a22008-04-19 23:25:44 +00001225static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001226 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001227 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001228
1229 // Parsing the specified input file.
1230 P.ParseTranslationUnit();
1231 delete PA;
1232}
1233
1234//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001235// Code generation options
1236//===----------------------------------------------------------------------===//
1237
1238static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001239OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-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 Dunbar9101a632009-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 Dunbaraa7a0662008-10-23 05:50:47 +00001262static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001263 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-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 Dunbar721cbf12008-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 Dunbar6670e332009-02-15 20:00:15 +00001275 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001276
1277#ifdef NDEBUG
1278 Opts.VerifyModule = 0;
1279#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001280
1281 Opts.CPU = TargetCPU;
1282 Opts.Features.insert(Opts.Features.end(),
1283 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001284
1285 // Handle -ftime-report.
1286 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001287}
1288
1289//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001290// Main driver
1291//===----------------------------------------------------------------------===//
1292
Ted Kremeneka36aaef2007-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 Lattner7f902922009-02-18 01:20:05 +00001296static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001297 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001298 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001299 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001300 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001301 switch (ProgAction) {
Chris Lattner7f902922009-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 Xu6036bbe2009-01-13 01:29:24 +00001313
Chris Lattner7f902922009-02-18 01:20:05 +00001314 case PrintDeclContext:
1315 return CreateDeclContextPrinter();
1316
1317 case EmitHTML:
1318 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001319
Chris Lattner7f902922009-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 Dunbard999a8e2009-02-26 22:39:37 +00001328 case EmitBC:
1329 case EmitLLVMOnly: {
Chris Lattner7f902922009-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 Dunbard999a8e2009-02-26 22:39:37 +00001335 else if (ProgAction == EmitLLVMOnly)
1336 Act = Backend_EmitNothing;
Chris Lattner7f902922009-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 Sanghyeon550a1eb2007-12-24 01:52:34 +00001345
Chris Lattner7f902922009-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 Naroff93c18352008-09-18 14:10:13 +00001352
Chris Lattner7f902922009-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 Kremeneka36aaef2007-12-05 18:27:04 +00001358 }
1359}
1360
Chris Lattner4b009652007-07-25 00:24:17 +00001361/// ProcessInputFile - Process a single input file with the specified state.
1362///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001363static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001364 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001365 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001366 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001367
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001368 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001369 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001370 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1371 PP.getFileManager(), PP.getLangOptions(),
1372 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001373
1374 if (!Consumer) {
1375 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001376 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001377 return;
1378 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001379
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001380 break;
1381
Chris Lattneraf669fb2008-10-12 05:03:36 +00001382 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001383 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001384 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001385 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001386 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001387 RawLex.SetKeepWhitespaceMode(true);
1388
1389 Token RawTok;
Chris Lattneraf669fb2008-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 }
Chris Lattner4b009652007-07-25 00:24:17 +00001399 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001400 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001401 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001402 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001403 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001404 do {
1405 PP.Lex(Tok);
1406 PP.DumpToken(Tok, true);
1407 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001408 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001409 ClearSourceMgr = true;
1410 break;
1411 }
1412 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001413 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001414 Token Tok;
1415 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001416 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001417 do {
1418 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001419 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001420 ClearSourceMgr = true;
1421 break;
1422 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001423
1424 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001425 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001426 CacheTokens(PP, OutputFile);
1427 ClearSourceMgr = true;
1428 break;
1429 }
Chris Lattner4b009652007-07-25 00:24:17 +00001430
Chris Lattnerefe33382009-02-18 01:51:21 +00001431 case PrintPreprocessedInput: { // -E mode.
1432 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001433 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001434 ClearSourceMgr = true;
1435 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001436 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001437
Chris Lattnerefe33382009-02-18 01:51:21 +00001438 case ParseNoop: { // -parse-noop
1439 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001440 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001441 ClearSourceMgr = true;
1442 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001443 }
Chris Lattner4b009652007-07-25 00:24:17 +00001444
Chris Lattnerefe33382009-02-18 01:51:21 +00001445 case ParsePrintCallbacks: {
1446 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001447 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001448 ClearSourceMgr = true;
1449 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001450 }
1451
1452 case ParseSyntaxOnly: { // -fsyntax-only
1453 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001454 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001455 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001456 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001457
1458 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001459 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001460 ClearSourceMgr = true;
1461 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001462
Chris Lattnerefe33382009-02-18 01:51:21 +00001463 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001464 DoRewriteTest(PP, InFile, OutputFile);
1465 ClearSourceMgr = true;
1466 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001467 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001468 }
Ted Kremenek88eebed2009-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 Dunbar849bfc62008-10-27 22:03:52 +00001483
1484 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001485 if (CheckDiagnostics(PP))
1486 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001487
Chris Lattner4b009652007-07-25 00:24:17 +00001488 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001489 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001490 PP.PrintStats();
1491 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001492 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001493 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001494 fprintf(stderr, "\n");
1495 }
1496
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 Lattner968982d2007-12-15 20:48:40 +00001500 if (ClearSourceMgr)
1501 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001502
1503 if (DisableFree)
1504 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001505}
1506
Ted Kremenek80d53372007-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 Kremenek863b01f2008-04-23 16:25:39 +00001522 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-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 Kremenekab749372007-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 Kremenek0c7cd7a2007-12-20 19:47:16 +00001532 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001533 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001534 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001535
Ted Kremenek80d53372007-12-12 23:41:08 +00001536 if (!Consumer) {
1537 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1538 exit (1);
1539 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001540
Ted Kremenek863b01f2008-04-23 16:25:39 +00001541 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001542
Chris Lattner8d72ee02008-02-06 01:42:25 +00001543 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001544 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1545 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001546}
1547
1548
Chris Lattner4b009652007-07-25 00:24:17 +00001549static llvm::cl::list<std::string>
1550InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1551
Ted Kremenek80d53372007-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;
1557
1558 return s[0] == '.' &&
1559 s[1] == 'a' &&
1560 s[2] == 's' &&
1561 s[3] == 't';
1562}
1563
Chris Lattner4b009652007-07-25 00:24:17 +00001564
1565int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001566 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001567 llvm::sys::PrintStackTraceOnErrorSignal();
1568
Chris Lattnerefe33382009-02-18 01:51:21 +00001569 if (TimeReport)
1570 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1571
1572
Chris Lattner4b009652007-07-25 00:24:17 +00001573 // If no input was specified, read from stdin.
1574 if (InputFilenames.empty())
1575 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001576
Chris Lattner4b009652007-07-25 00:24:17 +00001577 // Create a file manager object to provide access to and cache the filesystem.
1578 FileManager FileMgr;
1579
Ted Kremenekb240e822007-12-11 23:28:38 +00001580 // Create the diagnostic client for reporting errors or for
1581 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001582 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001583
Ted Kremenek5c341732008-08-07 17:49:57 +00001584 if (!VerifyDiagnostics) {
1585 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001586 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1587 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001588 !NoCaretDiagnostics,
1589 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001590 } else {
1591 // When checking diagnostics, just buffer them up.
1592 TextDiagClient = new TextDiagnosticBuffer();
1593
1594 if (InputFilenames.size() != 1) {
1595 fprintf(stderr,
1596 "-verify only works on single input files for now.\n");
1597 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001598 }
1599 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001600
Chris Lattner4b009652007-07-25 00:24:17 +00001601 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001602 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1603 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001604 InitializeDiagnostics(Diags);
1605
Chris Lattner45a56e02007-12-05 23:24:17 +00001606 // -I- is a deprecated GCC feature, scan for it and reject it.
1607 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1608 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001609 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001610 I_dirs.erase(I_dirs.begin()+i);
1611 --i;
1612 }
1613 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001614
1615 // Get information about the target being compiled for.
1616 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001617 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1618
Chris Lattner2c77d852008-03-14 06:12:05 +00001619 if (Target == 0) {
1620 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1621 Triple.c_str());
1622 fprintf(stderr, "Please use -triple or -arch.\n");
1623 exit(1);
1624 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001625
Daniel Dunbar9c321102009-01-20 23:17:32 +00001626 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001627 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001628
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001629 llvm::OwningPtr<SourceManager> SourceMgr;
1630
Chris Lattner4b009652007-07-25 00:24:17 +00001631 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001632 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001633
Ted Kremenek5c341732008-08-07 17:49:57 +00001634 if (isSerializedFile(InFile)) {
1635 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001636 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001637 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001638 else {
1639 /// Create a SourceManager object. This tracks and owns all the file
1640 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001641 if (!SourceMgr)
1642 SourceMgr.reset(new SourceManager());
1643 else
1644 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001645
Ted Kremenek80d53372007-12-12 23:41:08 +00001646 // Initialize language options, inferring file types from input filenames.
1647 LangOptions LangInfo;
1648 InitializeBaseLanguage();
1649 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001650 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001651 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001652 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001653
Ted Kremenek80d53372007-12-12 23:41:08 +00001654 // Process the -I options and set them in the HeaderInfo.
1655 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001656
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001657 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001658
Ted Kremenek80d53372007-12-12 23:41:08 +00001659 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001660 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001661 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001662
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001663 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1664
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001665 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001666 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001667
1668 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1669 // always reset to using TextDiagClient.
1670 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001671
Ted Kremenek5c341732008-08-07 17:49:57 +00001672 if (!HTMLDiag.empty()) {
1673 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1674 &PPFactory));
1675 Diags.setClient(TmpClient.get());
1676 }
1677 else
1678 Diags.setClient(TextDiagClient);
1679
1680 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001681 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1682
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001683 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001684 }
Chris Lattner4b009652007-07-25 00:24:17 +00001685 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001686
Mike Stump91d01352009-01-28 02:43:35 +00001687 if (Verbose)
1688 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1689 " hosted on " LLVM_HOSTTRIPLE "\n");
1690
Ted Kremenekec6c5252008-08-07 18:13:12 +00001691 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001692 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1693 (NumDiagnostics == 1 ? "" : "s"));
1694
1695 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001696 FileMgr.PrintStats();
1697 fprintf(stderr, "\n");
1698 }
1699
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001700 // If verifying diagnostics and we reached here, all is well.
1701 if (VerifyDiagnostics)
1702 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001703
1704 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001705
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001706 // Managed static deconstruction. Useful for making things like
1707 // -time-passes usable.
1708 llvm::llvm_shutdown();
1709
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001710 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001711}