blob: e15ae3ea6731c23bc6cb08490d383a3c4428ff6b [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 Lattner2b2d0c42009-03-04 21:41:39 +000053#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000054#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000055#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000056#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000057#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000058using namespace clang;
59
60//===----------------------------------------------------------------------===//
61// Global options.
62//===----------------------------------------------------------------------===//
63
Chris Lattnerefe33382009-02-18 01:51:21 +000064/// ClangFrontendTimer - The front-end activities should charge time to it with
65/// TimeRegion. The -ftime-report option controls whether this will do
66/// anything.
67llvm::Timer *ClangFrontendTimer = 0;
68
Daniel Dunbar4efedde2008-10-16 16:54:18 +000069static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000070
Chris Lattner4b009652007-07-25 00:24:17 +000071static llvm::cl::opt<bool>
72Verbose("v", llvm::cl::desc("Enable verbose output"));
73static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000074Stats("print-stats",
75 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000076static llvm::cl::opt<bool>
77DisableFree("disable-free",
78 llvm::cl::desc("Disable freeing of memory on exit"),
79 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000080
81enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000082 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000083 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000084 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000085 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000086 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000087 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000088 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000089 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +000090 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +000091 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000092 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000093 ASTPrint, // Parse ASTs and print them.
94 ASTDump, // Parse ASTs and dump them.
95 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000096 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000097 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000098 ParsePrintCallbacks, // Parse and print each callback.
99 ParseSyntaxOnly, // Parse and perform semantic analysis.
100 ParseNoop, // Parse with noop callbacks.
101 RunPreprocessorOnly, // Just lex, no output.
102 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000103 DumpTokens, // Dump out preprocessed tokens.
104 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000105 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000106 GeneratePCH, // Generate precompiled header.
107 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000108};
109
110static llvm::cl::opt<ProgActions>
111ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
112 llvm::cl::init(ParseSyntaxOnly),
113 llvm::cl::values(
114 clEnumValN(RunPreprocessorOnly, "Eonly",
115 "Just run preprocessor, no output (for timings)"),
116 clEnumValN(PrintPreprocessedInput, "E",
117 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000118 clEnumValN(DumpRawTokens, "dump-raw-tokens",
119 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000120 clEnumValN(RunAnalysis, "analyze",
121 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000122 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000123 "Run preprocessor, dump internal rep of tokens"),
124 clEnumValN(ParseNoop, "parse-noop",
125 "Run parser with noop callbacks (for timings)"),
126 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
127 "Run parser and perform semantic analysis"),
128 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
129 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000130 clEnumValN(EmitHTML, "emit-html",
131 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000132 clEnumValN(ASTPrint, "ast-print",
133 "Build ASTs and then pretty-print them"),
134 clEnumValN(ASTDump, "ast-dump",
135 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000136 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000137 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000138 clEnumValN(PrintDeclContext, "print-decl-contexts",
139 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000140 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000141 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000142 clEnumValN(EmitAssembly, "S",
143 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000144 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000145 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000146 clEnumValN(EmitBC, "emit-llvm-bc",
147 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000148 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
149 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000150 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000151 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000152 clEnumValN(RewriteTest, "rewrite-test",
153 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000154 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000155 "Rewrite ObjC into C (code rewriter example)"),
156 clEnumValN(RewriteMacros, "rewrite-macros",
157 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000158 clEnumValN(RewriteBlocks, "rewrite-blocks",
159 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000160 clEnumValEnd));
161
Ted Kremenekd01eae62007-12-19 19:47:59 +0000162
163static llvm::cl::opt<std::string>
164OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000165 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000166 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000167
168//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000169// Code Generator Options
170//===----------------------------------------------------------------------===//
171static llvm::cl::opt<bool>
172GenerateDebugInfo("g",
173 llvm::cl::desc("Generate source level debug information"));
174
Ted Kremenek57f25b22008-12-02 19:57:31 +0000175
176//===----------------------------------------------------------------------===//
177// PTH.
178//===----------------------------------------------------------------------===//
179
180static llvm::cl::opt<std::string>
181TokenCache("token-cache", llvm::cl::value_desc("path"),
182 llvm::cl::desc("Use specified token cache file"));
183
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000184//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000185// Diagnostic Options
186//===----------------------------------------------------------------------===//
187
Ted Kremenek10389cf2007-09-26 19:42:19 +0000188static llvm::cl::opt<bool>
189VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000190 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000191
Ted Kremenekfd75e312008-03-27 06:17:42 +0000192static llvm::cl::opt<std::string>
193HTMLDiag("html-diags",
194 llvm::cl::desc("Generate HTML to report diagnostics"),
195 llvm::cl::value_desc("HTML directory"));
196
Nico Weber0e13eaa2008-08-05 23:33:20 +0000197static llvm::cl::opt<bool>
198NoShowColumn("fno-show-column",
199 llvm::cl::desc("Do not include column number on diagnostics"));
200
201static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000202NoShowLocation("fno-show-source-location",
203 llvm::cl::desc("Do not include source location information with"
204 " diagnostics"));
205
206static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000207NoCaretDiagnostics("fno-caret-diagnostics",
208 llvm::cl::desc("Do not include source line and caret with"
209 " diagnostics"));
210
211
Chris Lattner4b009652007-07-25 00:24:17 +0000212//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000213// C++ Visualization.
214//===----------------------------------------------------------------------===//
215
216static llvm::cl::opt<std::string>
217InheritanceViewCls("cxx-inheritance-view",
218 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000219 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000220
221//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000222// Builtin Options
223//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000224
225static llvm::cl::opt<bool>
226TimeReport("ftime-report",
227 llvm::cl::desc("Print the amount of time each "
228 "phase of compilation takes"));
229
Douglas Gregor23d23262009-02-14 20:49:29 +0000230static llvm::cl::opt<bool>
231Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000232 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000233 "freestanding environment"));
234
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000235static llvm::cl::opt<bool>
236MathErrno("fmath-errno",
Chris Lattner64239622009-02-17 00:30:31 +0000237 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner32e56892009-02-17 00:35:09 +0000238 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000239
Douglas Gregor23d23262009-02-14 20:49:29 +0000240//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000241// Language Options
242//===----------------------------------------------------------------------===//
243
244enum LangKind {
245 langkind_unspecified,
246 langkind_c,
247 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000248 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000249 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000250 langkind_cxx,
251 langkind_cxx_cpp,
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000252 langkind_cxx_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000253 langkind_objc,
254 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000255 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000256 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000257 langkind_objcxx_cpp,
258 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000259};
260
Chris Lattner4b009652007-07-25 00:24:17 +0000261static llvm::cl::opt<LangKind>
262BaseLang("x", llvm::cl::desc("Base language to compile"),
263 llvm::cl::init(langkind_unspecified),
264 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
265 clEnumValN(langkind_cxx, "c++", "C++"),
266 clEnumValN(langkind_objc, "objective-c", "Objective C"),
267 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000268 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000269 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000270 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
271 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000272 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000273 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000274 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
275 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000276 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000277 "Preprocessed Objective C++"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000278 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000279 "Precompiled C header"),
280 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000281 "Precompiled Objective-C header"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000282 clEnumValN(langkind_cxx_pch, "c++-header",
283 "Precompiled C++ header"),
Ted Kremenekceacc812009-01-09 00:38:08 +0000284 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
285 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000286 clEnumValEnd));
287
288static llvm::cl::opt<bool>
289LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
290 llvm::cl::Hidden);
291static llvm::cl::opt<bool>
292LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
293 llvm::cl::Hidden);
294
Ted Kremenek11ad8952007-12-05 23:49:08 +0000295/// InitializeBaseLanguage - Handle the -x foo options.
296static void InitializeBaseLanguage() {
297 if (LangObjC)
298 BaseLang = langkind_objc;
299 else if (LangObjCXX)
300 BaseLang = langkind_objcxx;
301}
302
303static LangKind GetLanguage(const std::string &Filename) {
304 if (BaseLang != langkind_unspecified)
305 return BaseLang;
306
307 std::string::size_type DotPos = Filename.rfind('.');
308
309 if (DotPos == std::string::npos) {
310 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000311 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000312 }
313
Ted Kremenek11ad8952007-12-05 23:49:08 +0000314 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
315 // C header: .h
316 // C++ header: .hh or .H;
317 // assembler no preprocessing: .s
318 // assembler: .S
319 if (Ext == "c")
320 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000321 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000322 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000323 else if (Ext == "i")
324 return langkind_c_cpp;
325 else if (Ext == "ii")
326 return langkind_cxx_cpp;
327 else if (Ext == "m")
328 return langkind_objc;
329 else if (Ext == "mi")
330 return langkind_objc_cpp;
331 else if (Ext == "mm" || Ext == "M")
332 return langkind_objcxx;
333 else if (Ext == "mii")
334 return langkind_objcxx_cpp;
335 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
336 Ext == "c++" || Ext == "cp" || Ext == "cxx")
337 return langkind_cxx;
338 else
339 return langkind_c;
340}
341
342
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000343static void InitializeCOptions(LangOptions &Options) {
344 // Do nothing.
345}
346
347static void InitializeObjCOptions(LangOptions &Options) {
348 Options.ObjC1 = Options.ObjC2 = 1;
349}
350
351
352static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000353 // FIXME: implement -fpreprocessed mode.
354 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000355 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000356
357 // Test for 'PCH'.
358 switch (LK) {
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000359 default:
360 break;
361 case langkind_c_pch:
362 LK = langkind_c;
363 PCH = true;
364 break;
365 case langkind_objc_pch:
366 LK = langkind_objc;
367 PCH = true;
368 break;
369 case langkind_cxx_pch:
370 LK = langkind_cxx;
371 PCH = true;
372 break;
373 case langkind_objcxx_pch:
374 LK = langkind_objcxx;
375 PCH = true;
376 break;
Ted Kremenekceacc812009-01-09 00:38:08 +0000377 }
Chris Lattner4b009652007-07-25 00:24:17 +0000378
Ted Kremenek11ad8952007-12-05 23:49:08 +0000379 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000380 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000381 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000382 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000383 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000384 case langkind_c_cpp:
385 NoPreprocess = true;
386 // FALLTHROUGH
387 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000388 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000389 break;
390 case langkind_cxx_cpp:
391 NoPreprocess = true;
392 // FALLTHROUGH
393 case langkind_cxx:
394 Options.CPlusPlus = 1;
395 break;
396 case langkind_objc_cpp:
397 NoPreprocess = true;
398 // FALLTHROUGH
399 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000400 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000401 break;
402 case langkind_objcxx_cpp:
403 NoPreprocess = true;
404 // FALLTHROUGH
405 case langkind_objcxx:
406 Options.ObjC1 = Options.ObjC2 = 1;
407 Options.CPlusPlus = 1;
408 break;
409 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000410
411 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000412}
413
414/// LangStds - Language standards we support.
415enum LangStds {
416 lang_unspecified,
417 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000418 lang_gnu_START,
419 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000420 lang_cxx98, lang_gnucxx98,
421 lang_cxx0x, lang_gnucxx0x
422};
423
424static llvm::cl::opt<LangStds>
425LangStd("std", llvm::cl::desc("Language standard to compile for"),
426 llvm::cl::init(lang_unspecified),
427 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
428 clEnumValN(lang_c89, "c90", "ISO C 1990"),
429 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
430 clEnumValN(lang_c94, "iso9899:199409",
431 "ISO C 1990 with amendment 1"),
432 clEnumValN(lang_c99, "c99", "ISO C 1999"),
433// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
434 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
435// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
436 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000437 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000438 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000439 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000440 clEnumValN(lang_gnu99, "gnu9x",
441 "ISO C 1999 with GNU extensions"),
442 clEnumValN(lang_cxx98, "c++98",
443 "ISO C++ 1998 with amendments"),
444 clEnumValN(lang_gnucxx98, "gnu++98",
445 "ISO C++ 1998 with amendments and GNU "
446 "extensions (default for C++)"),
447 clEnumValN(lang_cxx0x, "c++0x",
448 "Upcoming ISO C++ 200x with amendments"),
449 clEnumValN(lang_gnucxx0x, "gnu++0x",
450 "Upcoming ISO C++ 200x with amendments and GNU "
451 "extensions (default for C++)"),
452 clEnumValEnd));
453
454static llvm::cl::opt<bool>
455NoOperatorNames("fno-operator-names",
456 llvm::cl::desc("Do not treat C++ operator name keywords as "
457 "synonyms for operators"));
458
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000459static llvm::cl::opt<bool>
460PascalStrings("fpascal-strings",
461 llvm::cl::desc("Recognize and construct Pascal-style "
462 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000463
464static llvm::cl::opt<bool>
465MSExtensions("fms-extensions",
466 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000467 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000468
469static llvm::cl::opt<bool>
470WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000471 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000472
473static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000474NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000475 llvm::cl::desc("Disallow implicit conversions between "
476 "vectors with a different number of "
477 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000478
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000479static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000480EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
481 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
482 llvm::cl::ZeroOrMore);
483
484static llvm::cl::opt<bool>
485ObjCNonFragileABI("fobjc-nonfragile-abi",
486 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000487
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000488static llvm::cl::opt<bool>
489EmitAllDecls("femit-all-decls",
490 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000491
Daniel Dunbar91692d92008-08-11 17:36:14 +0000492// FIXME: This (and all GCC -f options) really come in -f... and
493// -fno-... forms, and additionally support automagic behavior when
494// they are not defined. For example, -fexceptions defaults to on or
495// off depending on the language. We should support this behavior in
496// some form (perhaps just add a facility for distinguishing when an
497// has its default value from when it has been set to its default
498// value).
499static llvm::cl::opt<bool>
500Exceptions("fexceptions",
501 llvm::cl::desc("Enable support for exception handling."));
502
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000503static llvm::cl::opt<bool>
504GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000505 llvm::cl::desc("Generate output compatible with the standard GNU "
506 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000507
508static llvm::cl::opt<bool>
509NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000510 llvm::cl::desc("Generate output compatible with the NeXT "
511 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000512
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000513
514
515static llvm::cl::opt<bool>
516Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
517
518static llvm::cl::opt<bool>
519Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
520
Chris Lattner738d3f62009-03-02 22:11:07 +0000521static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000522TargetFeatures("mattr", llvm::cl::CommaSeparated,
523 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
524
Chris Lattner738d3f62009-03-02 22:11:07 +0000525
526
Chris Lattner4b009652007-07-25 00:24:17 +0000527// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000528// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000529static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
530 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000531 // Allow the target to set the default the langauge options as it sees fit.
532 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000533
Chris Lattnerf6790a82009-03-03 19:56:18 +0000534 // If there are any -mattr options, pass them to the target for validation and
535 // processing. The driver should have already consolidated all the
536 // target-feature settings and passed them to us in the -mattr list. The
537 // -mattr list is treated by the code generator as a diff against the -mcpu
538 // setting, but the driver should pass all enabled options as "+" settings.
539 // This means that the target should only look at + settings.
540 if (!TargetFeatures.empty()
541 // FIXME: The driver is not quite yet ready for this.
542 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000543 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000544 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
545 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000546 if (Opt != -1) {
547 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000548 fprintf(stderr, "invalid feature '%s'\n",
549 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000550 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000551 fprintf(stderr, "feature '%s': %s\n",
552 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000553 exit(1);
554 }
555 }
556
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000557 if (Ansi) // "The -ansi option is equivalent to -std=c89."
558 LangStd = lang_c89;
559
Chris Lattner4b009652007-07-25 00:24:17 +0000560 if (LangStd == lang_unspecified) {
561 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000562 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000563 default: assert(0 && "Unknown base language");
564 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000565 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000566 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000567 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000568 case langkind_objc:
569 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000570 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000571 LangStd = lang_gnu99;
572 break;
573 case langkind_cxx:
574 case langkind_cxx_cpp:
575 case langkind_objcxx:
576 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000577 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000578 LangStd = lang_gnucxx98;
579 break;
580 }
581 }
582
583 switch (LangStd) {
584 default: assert(0 && "Unknown language standard!");
585
586 // Fall through from newer standards to older ones. This isn't really right.
587 // FIXME: Enable specifically the right features based on the language stds.
588 case lang_gnucxx0x:
589 case lang_cxx0x:
590 Options.CPlusPlus0x = 1;
591 // FALL THROUGH
592 case lang_gnucxx98:
593 case lang_cxx98:
594 Options.CPlusPlus = 1;
595 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000596 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000597 // FALL THROUGH.
598 case lang_gnu99:
599 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000600 Options.C99 = 1;
601 Options.HexFloats = 1;
602 // FALL THROUGH.
603 case lang_gnu89:
604 Options.BCPLComment = 1; // Only for C99/C++.
605 // FALL THROUGH.
606 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000607 Options.Digraphs = 1; // C94, C99, C++.
608 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000609 case lang_c89:
610 break;
611 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000612
613 if (Options.CPlusPlus) {
614 Options.C99 = 0;
615 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
616 }
Chris Lattner4b009652007-07-25 00:24:17 +0000617
Chris Lattner6ab935b2008-04-05 06:32:51 +0000618 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
619 Options.ImplicitInt = 1;
620 else
621 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000622
623 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
624 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000625 Options.Trigraphs = LangStd < lang_gnu_START;
626 if (Trigraphs.getPosition())
627 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000628
Chris Lattner58d5ba52008-12-05 00:10:44 +0000629 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
630 // even if they are normally on for the target. In GNU modes (e.g.
631 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000632 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
633 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000634 Options.Blocks = 0;
635
Chris Lattner4b009652007-07-25 00:24:17 +0000636 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000637 if (PascalStrings.getPosition())
638 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000639 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000640 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000641 if (NoLaxVectorConversions.getPosition())
642 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000643 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000644 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000645 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000646
Douglas Gregor23d23262009-02-14 20:49:29 +0000647 if (Freestanding)
648 Options.Freestanding = 1;
649
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000650 Options.MathErrno = MathErrno;
651
Chris Lattnerddae7102008-12-04 22:54:33 +0000652 // Override the default runtime if the user requested it.
653 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000654 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000655 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000656 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000657
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000658 if (ObjCNonFragileABI)
659 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000660
661 if (EmitAllDecls)
662 Options.EmitAllDecls = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000663}
664
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000665static llvm::cl::opt<bool>
666ObjCExclusiveGC("fobjc-gc-only",
667 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000668 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000669
670static llvm::cl::opt<bool>
671ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000672 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000673
674void InitializeGCMode(LangOptions &Options) {
675 if (ObjCExclusiveGC)
676 Options.setGCMode(LangOptions::GCOnly);
677 else if (ObjCEnableGC)
678 Options.setGCMode(LangOptions::HybridGC);
679}
680
Chris Lattner4b009652007-07-25 00:24:17 +0000681//===----------------------------------------------------------------------===//
682// Our DiagnosticClient implementation
683//===----------------------------------------------------------------------===//
684
685// FIXME: Werror should take a list of things, -Werror=foo,bar
686static llvm::cl::opt<bool>
687WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
688
689static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000690SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
691
692static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000693WarnOnExtensions("pedantic", llvm::cl::init(false),
694 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
695
696static llvm::cl::opt<bool>
697ErrorOnExtensions("pedantic-errors",
698 llvm::cl::desc("Issue an error on uses of GCC extensions"));
699
700static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000701SuppressSystemWarnings("suppress-system-warnings",
Chris Lattner71af6d62009-02-06 04:16:41 +0000702 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000703 llvm::cl::init(true));
704
705static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000706WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000707 llvm::cl::desc("Warn for unused macros in the main translation unit"));
708
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000709static llvm::cl::opt<bool>
710WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000711 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000712
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000713static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000714WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
715 llvm::cl::desc("Warn about readonly properties with writable attributes"));
716
717static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000718WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000719 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000720
Chris Lattnera616ee32008-01-23 17:19:46 +0000721static llvm::cl::opt<bool>
722WarnUndefMacros("Wundef",
723 llvm::cl::desc("Warn on use of undefined macros in #if's"));
724
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000725static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000726WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
727 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000728
Steve Naroffb91afca2008-10-21 10:37:50 +0000729static llvm::cl::opt<bool>
730WarnNoStrictSelectorMatch("Wno-strict-selector-match",
Chris Lattner71af6d62009-02-06 04:16:41 +0000731 llvm::cl::desc("Do not warn about duplicate methods that have the same size"
732 " and alignment"),
Steve Naroffb91afca2008-10-21 10:37:50 +0000733 llvm::cl::init(true));
734
Chris Lattner4b009652007-07-25 00:24:17 +0000735/// InitializeDiagnostics - Initialize the diagnostic object, based on the
736/// current command line option settings.
737static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000738 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000739 Diags.setWarningsAsErrors(WarningsAsErrors);
740 Diags.setWarnOnExtensions(WarnOnExtensions);
741 Diags.setErrorOnExtensions(ErrorOnExtensions);
742
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000743 // Suppress warnings in system headers unless requested not to.
744 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
745
Chris Lattner4b009652007-07-25 00:24:17 +0000746 // Silence the "macro is not used" warning unless requested.
747 if (!WarnUnusedMacros)
748 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000749
750 // Silence "floating point comparison" warnings unless requested.
751 if (!WarnFloatEqual)
752 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000753
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000754 if (!WarnPropertyReadonlyAttrs)
755 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
756 diag::MAP_IGNORE);
757
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000758 // Silence "format string is not a string literal" warnings if requested
759 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000760 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
761 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000762 if (!WarnUndefMacros)
763 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000764
Chris Lattner86a24842009-01-29 06:55:46 +0000765 if (WarnImplicitFunctionDeclaration)
766 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
767 diag::MAP_WARNING);
768 else
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000769 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
770 diag::MAP_IGNORE);
Chris Lattner71af6d62009-02-06 04:16:41 +0000771
772
773 Diags.setDiagnosticMapping(diag::err_pp_file_not_found, diag::MAP_FATAL);
Chris Lattner4b009652007-07-25 00:24:17 +0000774}
775
776//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000777// Target Triple Processing.
778//===----------------------------------------------------------------------===//
779
780static llvm::cl::opt<std::string>
781TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000782 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000783
Chris Lattnerfc457002008-03-05 01:18:20 +0000784static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000785Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000786
Chris Lattner2b168e02008-09-30 01:13:12 +0000787static llvm::cl::opt<std::string>
788MacOSVersionMin("mmacosx-version-min",
789 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
790
Chris Lattner01de9c82008-09-30 20:16:56 +0000791// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
792// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
793static void HandleMacOSVersionMin(std::string &Triple) {
794 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
795 if (DarwinDashIdx == std::string::npos) {
796 fprintf(stderr,
797 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
798 exit(1);
799 }
800 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
801
Chris Lattner01de9c82008-09-30 20:16:56 +0000802 // Remove the number.
803 Triple.resize(DarwinNumIdx);
804
805 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
806 bool MacOSVersionMinIsInvalid = false;
807 int VersionNum = 0;
808 if (MacOSVersionMin.size() < 4 ||
809 MacOSVersionMin.substr(0, 3) != "10." ||
810 !isdigit(MacOSVersionMin[3])) {
811 MacOSVersionMinIsInvalid = true;
812 } else {
813 const char *Start = MacOSVersionMin.c_str()+3;
814 char *End = 0;
815 VersionNum = (int)strtol(Start, &End, 10);
816
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000817 // The version number must be in the range 0-9.
818 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
819
Chris Lattner01de9c82008-09-30 20:16:56 +0000820 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
821 Triple += llvm::itostr(VersionNum+4);
822
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000823 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
824 // Add the period piece (.7) to the end of the triple. This gives us
825 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000826 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000827 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
828 MacOSVersionMinIsInvalid = true;
829 }
830 }
831
832 if (MacOSVersionMinIsInvalid) {
833 fprintf(stderr,
834 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
835 MacOSVersionMin.c_str());
836 exit(1);
837 }
838}
839
840/// CreateTargetTriple - Process the various options that affect the target
841/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000842static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000843 // Initialize base triple. If a -triple option has been specified, use
844 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000845 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000846 if (Triple.empty()) {
847 Triple = LLVM_HOSTTRIPLE;
848
Daniel Dunbar81caece2008-12-12 18:34:35 +0000849 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
850 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
851 Triple[2] == '8' && Triple[3] == '6')
852 Triple[1] = '3';
853
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000854 // On darwin, we want to update the version to match that of the
855 // host.
856 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
857 if (DarwinDashIdx != std::string::npos) {
858 Triple.resize(DarwinDashIdx + strlen("-darwin"));
859
Daniel Dunbar81caece2008-12-12 18:34:35 +0000860 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000861 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000862 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000863 }
864 }
Ted Kremenek40499482007-12-03 22:06:55 +0000865
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000866 // If -arch foo was specified, remove the architecture from the triple we have
867 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000868 if (!Arch.empty()) {
869 // Decompose the base triple into "arch" and suffix.
870 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000871
Chris Lattner2b168e02008-09-30 01:13:12 +0000872 if (FirstDashIdx == std::string::npos) {
873 fprintf(stderr,
874 "Malformed target triple: \"%s\" ('-' could not be found).\n",
875 Triple.c_str());
876 exit(1);
877 }
Ted Kremenek40499482007-12-03 22:06:55 +0000878
Chris Lattner2b168e02008-09-30 01:13:12 +0000879 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
880 }
881
882 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
883 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000884 if (!MacOSVersionMin.empty())
885 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000886
Chris Lattner2b168e02008-09-30 01:13:12 +0000887 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000888}
889
890//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000891// Preprocessor Initialization
892//===----------------------------------------------------------------------===//
893
894// FIXME: Preprocessor builtins to support.
895// -A... - Play with #assertions
896// -undef - Undefine all predefined macros
897
898static llvm::cl::list<std::string>
899D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
900 llvm::cl::desc("Predefine the specified macro"));
901static llvm::cl::list<std::string>
902U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
903 llvm::cl::desc("Undefine the specified macro"));
904
Chris Lattner008da782008-01-10 01:53:41 +0000905static llvm::cl::list<std::string>
906ImplicitIncludes("include", llvm::cl::value_desc("file"),
907 llvm::cl::desc("Include file before parsing"));
908
909
Chris Lattner4b009652007-07-25 00:24:17 +0000910// Append a #define line to Buf for Macro. Macro should be of the form XXX,
911// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
912// "#define XXX Y z W". To get a #define with no value, use "XXX=".
913static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
914 const char *Command = "#define ") {
915 Buf.insert(Buf.end(), Command, Command+strlen(Command));
916 if (const char *Equal = strchr(Macro, '=')) {
917 // Turn the = into ' '.
918 Buf.insert(Buf.end(), Macro, Equal);
919 Buf.push_back(' ');
920 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
921 } else {
922 // Push "macroname 1".
923 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
924 Buf.push_back(' ');
925 Buf.push_back('1');
926 }
927 Buf.push_back('\n');
928}
929
Chris Lattner008da782008-01-10 01:53:41 +0000930/// AddImplicitInclude - Add an implicit #include of the specified file to the
931/// predefines buffer.
932static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
933 const char *Inc = "#include \"";
934 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
935 Buf.insert(Buf.end(), File.begin(), File.end());
936 Buf.push_back('"');
937 Buf.push_back('\n');
938}
939
Chris Lattner4b009652007-07-25 00:24:17 +0000940
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000941/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000942/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000943///
Chris Lattner9d818a22008-04-19 23:25:44 +0000944static bool InitializePreprocessor(Preprocessor &PP,
945 bool InitializeSourceMgr,
946 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000947 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000948
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000949 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000950 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000951
952 if (InitializeSourceMgr) {
953 if (InFile != "-") {
954 const FileEntry *File = FileMgr.getFile(InFile);
955 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000956 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000957 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000958 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000959 }
960 } else {
961 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
962 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000963 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000964 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000965 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000966 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000967 }
Chris Lattner4b009652007-07-25 00:24:17 +0000968 }
Sam Bishop61a20782008-04-14 14:41:57 +0000969
Chris Lattner47b6a162008-04-19 23:09:31 +0000970 std::vector<char> PredefineBuffer;
971
Chris Lattner4b009652007-07-25 00:24:17 +0000972 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000973 unsigned d = 0, D = D_macros.size();
974 unsigned u = 0, U = U_macros.size();
975 while (d < D || u < U) {
976 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
977 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
978 else
979 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
980 }
981
Chris Lattner008da782008-01-10 01:53:41 +0000982 // FIXME: Read any files specified by -imacros.
983
984 // Add implicit #includes from -include.
985 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
986 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000987
Chris Lattner47b6a162008-04-19 23:09:31 +0000988 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000989 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000990 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000991
992 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000993 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000994}
995
996//===----------------------------------------------------------------------===//
997// Preprocessor include path information.
998//===----------------------------------------------------------------------===//
999
1000// This tool exports a large number of command line options to control how the
1001// preprocessor searches for header files. At root, however, the Preprocessor
1002// object takes a very simple interface: a list of directories to search for
1003//
1004// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001005// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001006//
Chris Lattner008da782008-01-10 01:53:41 +00001007// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +00001008
1009static llvm::cl::opt<bool>
1010nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1011
1012// Various command line options. These four add directories to each chain.
1013static llvm::cl::list<std::string>
1014F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1015 llvm::cl::desc("Add directory to framework include search path"));
1016static llvm::cl::list<std::string>
1017I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1018 llvm::cl::desc("Add directory to include search path"));
1019static llvm::cl::list<std::string>
1020idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1021 llvm::cl::desc("Add directory to AFTER include search path"));
1022static llvm::cl::list<std::string>
1023iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1024 llvm::cl::desc("Add directory to QUOTE include search path"));
1025static llvm::cl::list<std::string>
1026isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1027 llvm::cl::desc("Add directory to SYSTEM include search path"));
1028
1029// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1030static llvm::cl::list<std::string>
1031iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1032 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1033static llvm::cl::list<std::string>
1034iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1035 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1036static llvm::cl::list<std::string>
1037iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1038 llvm::cl::Prefix,
1039 llvm::cl::desc("Set directory to include search path with prefix"));
1040
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001041static llvm::cl::opt<std::string>
1042isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1043 llvm::cl::desc("Set the system root directory (usually /)"));
1044
Chris Lattner4b009652007-07-25 00:24:17 +00001045// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001046
Chris Lattner4b009652007-07-25 00:24:17 +00001047/// InitializeIncludePaths - Process the -I options and set them in the
1048/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001049void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1050 FileManager &FM, const LangOptions &Lang) {
1051 InitHeaderSearch Init(Headers, Verbose, isysroot);
1052
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001053 // Handle -I... and -F... options, walking the lists in parallel.
1054 unsigned Iidx = 0, Fidx = 0;
1055 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1056 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001057 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001058 ++Iidx;
1059 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001060 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001061 ++Fidx;
1062 }
1063 }
Chris Lattner4b009652007-07-25 00:24:17 +00001064
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001065 // Consume what's left from whatever list was longer.
1066 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001067 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001068 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001069 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001070
1071 // Handle -idirafter... options.
1072 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001073 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1074 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001075
1076 // Handle -iquote... options.
1077 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001078 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001079
1080 // Handle -isystem... options.
1081 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001082 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001083
1084 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1085 // parallel, processing the values in order of occurance to get the right
1086 // prefixes.
1087 {
1088 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1089 unsigned iprefix_idx = 0;
1090 unsigned iwithprefix_idx = 0;
1091 unsigned iwithprefixbefore_idx = 0;
1092 bool iprefix_done = iprefix_vals.empty();
1093 bool iwithprefix_done = iwithprefix_vals.empty();
1094 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1095 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1096 if (!iprefix_done &&
1097 (iwithprefix_done ||
1098 iprefix_vals.getPosition(iprefix_idx) <
1099 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1100 (iwithprefixbefore_done ||
1101 iprefix_vals.getPosition(iprefix_idx) <
1102 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1103 Prefix = iprefix_vals[iprefix_idx];
1104 ++iprefix_idx;
1105 iprefix_done = iprefix_idx == iprefix_vals.size();
1106 } else if (!iwithprefix_done &&
1107 (iwithprefixbefore_done ||
1108 iwithprefix_vals.getPosition(iwithprefix_idx) <
1109 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001110 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1111 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001112 ++iwithprefix_idx;
1113 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1114 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001115 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1116 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001117 ++iwithprefixbefore_idx;
1118 iwithprefixbefore_done =
1119 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1120 }
1121 }
1122 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001123
Nico Weber770e3882008-08-22 09:25:22 +00001124 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001125
Daniel Dunbar4e604292009-02-21 20:52:41 +00001126 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001127 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001128 llvm::sys::Path::GetMainExecutable(Argv0,
1129 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001130 if (!MainExecutablePath.isEmpty()) {
1131 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1132 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001133
1134 // Get foo/lib/clang/1.0/include
1135 //
1136 // FIXME: Don't embed version here.
1137 MainExecutablePath.appendComponent("lib");
1138 MainExecutablePath.appendComponent("clang");
1139 MainExecutablePath.appendComponent("1.0");
1140 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001141
1142 // We pass true to ignore sysroot so that we *always* look for clang headers
1143 // relative to our executable, never relative to -isysroot.
1144 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1145 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001146 }
1147
Nico Weber770e3882008-08-22 09:25:22 +00001148 if (!nostdinc)
1149 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001150
1151 // Now that we have collected all of the include paths, merge them all
1152 // together and tell the preprocessor about them.
1153
Nico Weber770e3882008-08-22 09:25:22 +00001154 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001155}
1156
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001157//===----------------------------------------------------------------------===//
1158// Driver PreprocessorFactory - For lazily generating preprocessors ...
1159//===----------------------------------------------------------------------===//
1160
1161namespace {
1162class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001163 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001164 Diagnostic &Diags;
1165 const LangOptions &LangInfo;
1166 TargetInfo &Target;
1167 SourceManager &SourceMgr;
1168 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001169 bool InitializeSourceMgr;
1170
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001171public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001172 DriverPreprocessorFactory(const std::string &infile,
1173 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001174 TargetInfo &target, SourceManager &SM,
1175 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001176 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1177 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1178
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001179
1180 virtual ~DriverPreprocessorFactory() {}
1181
1182 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001183 llvm::OwningPtr<PTHManager> PTHMgr;
1184
1185 // Use PTH?
1186 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001187 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001188
1189 // Create the Preprocessor.
1190 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1191 SourceMgr, HeaderInfo,
1192 PTHMgr.get()));
1193
1194 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1195 // That argument is used as the IdentifierInfoLookup argument to
1196 // IdentifierTable's ctor.
1197 if (PTHMgr) {
1198 PTHMgr->setPreprocessor(PP.get());
1199 PP->setPTHManager(PTHMgr.take());
1200 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001201
Chris Lattner9d818a22008-04-19 23:25:44 +00001202 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001203 return NULL;
1204 }
1205
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001206 /// FIXME: PP can only handle one callback
1207 if (ProgAction != PrintPreprocessedInput) {
1208 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001209 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001210 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001211 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001212 return NULL;
1213 }
1214 }
1215
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001216 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001217 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001218 }
1219};
1220}
Chris Lattner4b009652007-07-25 00:24:17 +00001221
Chris Lattner4b009652007-07-25 00:24:17 +00001222//===----------------------------------------------------------------------===//
1223// Basic Parser driver
1224//===----------------------------------------------------------------------===//
1225
Chris Lattner9d818a22008-04-19 23:25:44 +00001226static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001227 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001228 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001229
1230 // Parsing the specified input file.
1231 P.ParseTranslationUnit();
1232 delete PA;
1233}
1234
1235//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001236// Code generation options
1237//===----------------------------------------------------------------------===//
1238
1239static llvm::cl::opt<bool>
Daniel Dunbarfd46ea22009-02-16 22:43:43 +00001240OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001241
1242// It might be nice to add bounds to the CommandLine library directly.
1243struct OptLevelParser : public llvm::cl::parser<unsigned> {
1244 bool parse(llvm::cl::Option &O, const char *ArgName,
1245 const std::string &Arg, unsigned &Val) {
1246 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1247 return true;
1248 // FIXME: Support -O4.
1249 if (Val > 3)
1250 return O.error(": '" + Arg + "' invalid optimization level!");
1251 return false;
1252 }
1253};
1254static llvm::cl::opt<unsigned, false, OptLevelParser>
1255OptLevel("O", llvm::cl::Prefix,
1256 llvm::cl::desc("Optimization level"),
1257 llvm::cl::init(0));
1258
Daniel Dunbar9101a632009-02-17 19:47:34 +00001259static llvm::cl::opt<std::string>
1260TargetCPU("mcpu",
1261 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1262
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001263static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001264 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001265 if (OptSize) {
1266 // -Os implies -O2
1267 // FIXME: Diagnose conflicting options.
1268 Opts.OptimizationLevel = 2;
1269 } else {
1270 Opts.OptimizationLevel = OptLevel;
1271 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001272
1273 // FIXME: There are llvm-gcc options to control these selectively.
1274 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1275 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Daniel Dunbar6670e332009-02-15 20:00:15 +00001276 Opts.SimplifyLibCalls = !Freestanding;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001277
1278#ifdef NDEBUG
1279 Opts.VerifyModule = 0;
1280#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001281
1282 Opts.CPU = TargetCPU;
1283 Opts.Features.insert(Opts.Features.end(),
1284 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001285
1286 // Handle -ftime-report.
1287 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001288}
1289
1290//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001291// Main driver
1292//===----------------------------------------------------------------------===//
1293
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001294/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1295/// action. These consumers can operate on both ASTs that are freshly
1296/// parsed from source files as well as those deserialized from Bitcode.
Chris Lattner7f902922009-02-18 01:20:05 +00001297static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001298 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001299 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001300 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001301 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001302 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001303 default:
1304 return NULL;
1305
1306 case ASTPrint:
1307 return CreateASTPrinter();
1308
1309 case ASTDump:
1310 return CreateASTDumper();
1311
1312 case ASTView:
1313 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001314
Chris Lattner7f902922009-02-18 01:20:05 +00001315 case PrintDeclContext:
1316 return CreateDeclContextPrinter();
1317
1318 case EmitHTML:
1319 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001320
Chris Lattner7f902922009-02-18 01:20:05 +00001321 case InheritanceView:
1322 return CreateInheritanceViewer(InheritanceViewCls);
1323
1324 case TestSerialization:
1325 return CreateSerializationTest(Diag, FileMgr);
1326
1327 case EmitAssembly:
1328 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001329 case EmitBC:
1330 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001331 BackendAction Act;
1332 if (ProgAction == EmitAssembly)
1333 Act = Backend_EmitAssembly;
1334 else if (ProgAction == EmitLLVM)
1335 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001336 else if (ProgAction == EmitLLVMOnly)
1337 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001338 else
1339 Act = Backend_EmitBC;
1340
1341 CompileOptions Opts;
1342 InitializeCompileOptions(Opts);
1343 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
1344 InFile, OutputFile, GenerateDebugInfo);
1345 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001346
Chris Lattner7f902922009-02-18 01:20:05 +00001347 case SerializeAST:
1348 // FIXME: Allow user to tailor where the file is written.
1349 return CreateASTSerializer(InFile, OutputFile, Diag);
1350
1351 case RewriteObjC:
1352 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001353
Chris Lattner7f902922009-02-18 01:20:05 +00001354 case RewriteBlocks:
1355 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1356
1357 case RunAnalysis:
1358 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001359 }
1360}
1361
Chris Lattner4b009652007-07-25 00:24:17 +00001362/// ProcessInputFile - Process a single input file with the specified state.
1363///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001364static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001365 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001366 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001367 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001368
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001369 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001370 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001371 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1372 PP.getFileManager(), PP.getLangOptions(),
1373 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001374
1375 if (!Consumer) {
1376 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001377 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001378 return;
1379 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001380
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001381 break;
1382
Chris Lattneraf669fb2008-10-12 05:03:36 +00001383 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001384 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001385 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001386 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001387 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001388 RawLex.SetKeepWhitespaceMode(true);
1389
1390 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001391 RawLex.LexFromRawLexer(RawTok);
1392 while (RawTok.isNot(tok::eof)) {
1393 PP.DumpToken(RawTok, true);
1394 fprintf(stderr, "\n");
1395 RawLex.LexFromRawLexer(RawTok);
1396 }
1397 ClearSourceMgr = true;
1398 break;
1399 }
Chris Lattner4b009652007-07-25 00:24:17 +00001400 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001401 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001402 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001403 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001404 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001405 do {
1406 PP.Lex(Tok);
1407 PP.DumpToken(Tok, true);
1408 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001409 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001410 ClearSourceMgr = true;
1411 break;
1412 }
1413 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001414 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001415 Token Tok;
1416 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001417 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001418 do {
1419 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001420 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001421 ClearSourceMgr = true;
1422 break;
1423 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001424
1425 case GeneratePCH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001426 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001427 CacheTokens(PP, OutputFile);
1428 ClearSourceMgr = true;
1429 break;
1430 }
Chris Lattner4b009652007-07-25 00:24:17 +00001431
Chris Lattnerefe33382009-02-18 01:51:21 +00001432 case PrintPreprocessedInput: { // -E mode.
1433 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001434 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001435 ClearSourceMgr = true;
1436 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001437 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001438
Chris Lattnerefe33382009-02-18 01:51:21 +00001439 case ParseNoop: { // -parse-noop
1440 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001441 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001442 ClearSourceMgr = true;
1443 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001444 }
Chris Lattner4b009652007-07-25 00:24:17 +00001445
Chris Lattnerefe33382009-02-18 01:51:21 +00001446 case ParsePrintCallbacks: {
1447 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001448 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001449 ClearSourceMgr = true;
1450 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001451 }
1452
1453 case ParseSyntaxOnly: { // -fsyntax-only
1454 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001455 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001456 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001457 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001458
1459 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001460 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001461 ClearSourceMgr = true;
1462 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001463
Chris Lattnerefe33382009-02-18 01:51:21 +00001464 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001465 DoRewriteTest(PP, InFile, OutputFile);
1466 ClearSourceMgr = true;
1467 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001468 }
Chris Lattnerefe33382009-02-18 01:51:21 +00001469 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001470
1471 if (Consumer) {
1472 TranslationUnit *TU = 0;
1473 if (DisableFree) {
1474 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1475 PP.getSourceManager(),
1476 PP.getTargetInfo(),
1477 PP.getIdentifierTable(),
1478 PP.getSelectorTable(),
1479 /* FreeMemory = */ false);
1480 TU = new TranslationUnit(*Context);
1481 }
1482 ParseAST(PP, Consumer.get(), TU, Stats);
1483 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001484
1485 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001486 if (CheckDiagnostics(PP))
1487 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001488
Chris Lattner4b009652007-07-25 00:24:17 +00001489 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001490 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001491 PP.PrintStats();
1492 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001493 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001494 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001495 fprintf(stderr, "\n");
1496 }
1497
1498 // For a multi-file compilation, some things are ok with nuking the source
1499 // manager tables, other require stable fileid/macroid's across multiple
1500 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001501 if (ClearSourceMgr)
1502 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001503
1504 if (DisableFree)
1505 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001506}
1507
Ted Kremenek80d53372007-12-12 23:41:08 +00001508static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1509 FileManager& FileMgr) {
1510
1511 if (VerifyDiagnostics) {
1512 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1513 exit (1);
1514 }
1515
1516 llvm::sys::Path Filename(InFile);
1517
1518 if (!Filename.isValid()) {
1519 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1520 exit (1);
1521 }
1522
Ted Kremenek863b01f2008-04-23 16:25:39 +00001523 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001524
1525 if (!TU) {
1526 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1527 InFile.c_str());
1528 exit (1);
1529 }
1530
Ted Kremenekab749372007-12-19 19:27:38 +00001531 // Observe that we use the source file name stored in the deserialized
1532 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001533 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001534 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001535 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001536
Ted Kremenek80d53372007-12-12 23:41:08 +00001537 if (!Consumer) {
1538 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1539 exit (1);
1540 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001541
Ted Kremenek863b01f2008-04-23 16:25:39 +00001542 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001543
Chris Lattner8d72ee02008-02-06 01:42:25 +00001544 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001545 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1546 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001547}
1548
1549
Chris Lattner4b009652007-07-25 00:24:17 +00001550static llvm::cl::list<std::string>
1551InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1552
Ted Kremenek80d53372007-12-12 23:41:08 +00001553static bool isSerializedFile(const std::string& InFile) {
1554 if (InFile.size() < 4)
1555 return false;
1556
1557 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001558 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001559}
1560
Chris Lattner4b009652007-07-25 00:24:17 +00001561
1562int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001563 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001564 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001565 llvm::cl::ParseCommandLineOptions(argc, argv,
1566 "LLVM 'Clang' frontend: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001567
Chris Lattnerefe33382009-02-18 01:51:21 +00001568 if (TimeReport)
1569 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1570
Chris Lattner4b009652007-07-25 00:24:17 +00001571 // If no input was specified, read from stdin.
1572 if (InputFilenames.empty())
1573 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001574
Chris Lattner4b009652007-07-25 00:24:17 +00001575 // Create a file manager object to provide access to and cache the filesystem.
1576 FileManager FileMgr;
1577
Ted Kremenekb240e822007-12-11 23:28:38 +00001578 // Create the diagnostic client for reporting errors or for
1579 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001580 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001581
Ted Kremenek5c341732008-08-07 17:49:57 +00001582 if (!VerifyDiagnostics) {
1583 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001584 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1585 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001586 !NoCaretDiagnostics,
1587 !NoShowLocation);
Ted Kremenek5c341732008-08-07 17:49:57 +00001588 } else {
1589 // When checking diagnostics, just buffer them up.
1590 TextDiagClient = new TextDiagnosticBuffer();
1591
1592 if (InputFilenames.size() != 1) {
1593 fprintf(stderr,
1594 "-verify only works on single input files for now.\n");
1595 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001596 }
1597 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001598
Chris Lattner4b009652007-07-25 00:24:17 +00001599 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001600 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1601 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001602 InitializeDiagnostics(Diags);
1603
Chris Lattner45a56e02007-12-05 23:24:17 +00001604 // -I- is a deprecated GCC feature, scan for it and reject it.
1605 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1606 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001607 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001608 I_dirs.erase(I_dirs.begin()+i);
1609 --i;
1610 }
1611 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001612
1613 // Get information about the target being compiled for.
1614 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001615 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1616
Chris Lattner2c77d852008-03-14 06:12:05 +00001617 if (Target == 0) {
1618 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1619 Triple.c_str());
1620 fprintf(stderr, "Please use -triple or -arch.\n");
1621 exit(1);
1622 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001623
Daniel Dunbar9c321102009-01-20 23:17:32 +00001624 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001625 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001626
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001627 llvm::OwningPtr<SourceManager> SourceMgr;
1628
Chris Lattner4b009652007-07-25 00:24:17 +00001629 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001630 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001631
Ted Kremenek5c341732008-08-07 17:49:57 +00001632 if (isSerializedFile(InFile)) {
1633 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001634 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001635 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001636 }
Chris Lattner2b989562009-03-04 21:40:56 +00001637
1638 /// Create a SourceManager object. This tracks and owns all the file
1639 /// buffers allocated to a translation unit.
1640 if (!SourceMgr)
1641 SourceMgr.reset(new SourceManager());
1642 else
1643 SourceMgr->clearIDTables();
1644
1645 // Initialize language options, inferring file types from input filenames.
1646 LangOptions LangInfo;
1647 InitializeBaseLanguage();
1648 LangKind LK = GetLanguage(InFile);
1649 bool PCH = InitializeLangOptions(LangInfo, LK);
1650 InitializeGCMode(LangInfo);
1651 InitializeLanguageStandard(LangInfo, LK, Target.get());
1652
1653 // Process the -I options and set them in the HeaderInfo.
1654 HeaderSearch HeaderInfo(FileMgr);
1655
1656 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1657
1658 // Set up the preprocessor with these options.
1659 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1660 *SourceMgr.get(), HeaderInfo);
1661
1662 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1663
1664 if (!PP)
1665 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001666
Chris Lattner2b989562009-03-04 21:40:56 +00001667 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1668 // always reset to using TextDiagClient.
1669 llvm::OwningPtr<DiagnosticClient> TmpClient;
1670
1671 if (!HTMLDiag.empty()) {
1672 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1673 &PPFactory));
1674 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001675 }
Chris Lattner2b989562009-03-04 21:40:56 +00001676 else
1677 Diags.setClient(TextDiagClient);
1678
1679 // Process the source file.
1680 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1681
1682 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001683 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001684
Mike Stump91d01352009-01-28 02:43:35 +00001685 if (Verbose)
1686 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1687 " hosted on " LLVM_HOSTTRIPLE "\n");
1688
Ted Kremenekec6c5252008-08-07 18:13:12 +00001689 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001690 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1691 (NumDiagnostics == 1 ? "" : "s"));
1692
1693 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001694 FileMgr.PrintStats();
1695 fprintf(stderr, "\n");
1696 }
1697
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001698 // If verifying diagnostics and we reached here, all is well.
1699 if (VerifyDiagnostics)
1700 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001701
1702 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001703
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001704 // Managed static deconstruction. Useful for making things like
1705 // -time-passes usable.
1706 llvm::llvm_shutdown();
1707
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001708 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001709}