blob: ba891c7e56b9a6c32ce5abd168604e3b797d8e6d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenekc2542b62009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000031#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000032#include "clang/Frontend/TextDiagnosticBuffer.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000039#include "clang/AST/ASTContext.h"
40#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000041#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "clang/Parse/Parser.h"
43#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000044#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045#include "clang/Basic/FileManager.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000048#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000049#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000050#include "llvm/ADT/StringExtras.h"
51#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000053#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000055#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000056#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000057#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000058#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000059#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000060#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000061using namespace clang;
62
63//===----------------------------------------------------------------------===//
64// Global options.
65//===----------------------------------------------------------------------===//
66
Chris Lattner47099742009-02-18 01:51:21 +000067/// ClangFrontendTimer - The front-end activities should charge time to it with
68/// TimeRegion. The -ftime-report option controls whether this will do
69/// anything.
70llvm::Timer *ClangFrontendTimer = 0;
71
Daniel Dunbard3db4012008-10-16 16:54:18 +000072static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000073
Reid Spencer5f016e22007-07-11 17:01:13 +000074static llvm::cl::opt<bool>
75Verbose("v", llvm::cl::desc("Enable verbose output"));
76static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000077Stats("print-stats",
78 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000079static llvm::cl::opt<bool>
80DisableFree("disable-free",
81 llvm::cl::desc("Disable freeing of memory on exit"),
82 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000083
84enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000085 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000086 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000087 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000088 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +000089 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +000090 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000091 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000092 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000093 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +000094 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000095 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000096 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000097 ASTPrint, // Parse ASTs and print them.
98 ASTDump, // Parse ASTs and dump them.
99 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000100 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000101 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 ParsePrintCallbacks, // Parse and print each callback.
103 ParseSyntaxOnly, // Parse and perform semantic analysis.
104 ParseNoop, // Parse with noop callbacks.
105 RunPreprocessorOnly, // Just lex, no output.
106 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000107 DumpTokens, // Dump out preprocessed tokens.
108 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000109 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000110 GeneratePCH, // Generate precompiled header.
111 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000112};
113
114static llvm::cl::opt<ProgActions>
115ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
116 llvm::cl::init(ParseSyntaxOnly),
117 llvm::cl::values(
118 clEnumValN(RunPreprocessorOnly, "Eonly",
119 "Just run preprocessor, no output (for timings)"),
120 clEnumValN(PrintPreprocessedInput, "E",
121 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000122 clEnumValN(DumpRawTokens, "dump-raw-tokens",
123 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000124 clEnumValN(RunAnalysis, "analyze",
125 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000126 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 "Run preprocessor, dump internal rep of tokens"),
128 clEnumValN(ParseNoop, "parse-noop",
129 "Run parser with noop callbacks (for timings)"),
130 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
131 "Run parser and perform semantic analysis"),
132 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
133 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000134 clEnumValN(EmitHTML, "emit-html",
135 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 clEnumValN(ASTPrint, "ast-print",
137 "Build ASTs and then pretty-print them"),
138 clEnumValN(ASTDump, "ast-dump",
139 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000140 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000141 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000142 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000143 "Print DeclContexts and their Decls"),
144 clEnumValN(GeneratePCH, "emit-pth",
145 "Generate pre-tokenized header file"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000146 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000147 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000148 clEnumValN(EmitAssembly, "S",
149 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000151 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000152 clEnumValN(EmitBC, "emit-llvm-bc",
153 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000154 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
155 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000156 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000157 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000158 clEnumValN(RewriteTest, "rewrite-test",
159 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000160 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000161 "Rewrite ObjC into C (code rewriter example)"),
162 clEnumValN(RewriteMacros, "rewrite-macros",
163 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000164 clEnumValN(RewriteBlocks, "rewrite-blocks",
165 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000166 clEnumValN(FixIt, "fixit",
167 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 clEnumValEnd));
169
Ted Kremenekccc76472007-12-19 19:47:59 +0000170
171static llvm::cl::opt<std::string>
172OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000173 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000174 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000175
Ted Kremenekc2e72992008-12-02 19:57:31 +0000176
177//===----------------------------------------------------------------------===//
178// PTH.
179//===----------------------------------------------------------------------===//
180
181static llvm::cl::opt<std::string>
182TokenCache("token-cache", llvm::cl::value_desc("path"),
183 llvm::cl::desc("Use specified token cache file"));
184
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000185//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000186// Diagnostic Options
187//===----------------------------------------------------------------------===//
188
Ted Kremenek41193e42007-09-26 19:42:19 +0000189static llvm::cl::opt<bool>
190VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000191 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000192
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000193static llvm::cl::opt<std::string>
194HTMLDiag("html-diags",
195 llvm::cl::desc("Generate HTML to report diagnostics"),
196 llvm::cl::value_desc("HTML directory"));
197
Nico Weberfd54ebc2008-08-05 23:33:20 +0000198static llvm::cl::opt<bool>
199NoShowColumn("fno-show-column",
200 llvm::cl::desc("Do not include column number on diagnostics"));
201
202static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000203NoShowLocation("fno-show-source-location",
204 llvm::cl::desc("Do not include source location information with"
205 " diagnostics"));
206
207static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000208NoCaretDiagnostics("fno-caret-diagnostics",
209 llvm::cl::desc("Do not include source line and caret with"
210 " diagnostics"));
211
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000212static llvm::cl::opt<bool>
213PrintSourceRangeInfo("fprint-source-range-info",
214 llvm::cl::desc("Print source range spans in numeric form"));
215
Nico Weberfd54ebc2008-08-05 23:33:20 +0000216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000218// C++ Visualization.
219//===----------------------------------------------------------------------===//
220
221static llvm::cl::opt<std::string>
222InheritanceViewCls("cxx-inheritance-view",
223 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000224 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000225
226//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000227// Builtin Options
228//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000229
230static llvm::cl::opt<bool>
231TimeReport("ftime-report",
232 llvm::cl::desc("Print the amount of time each "
233 "phase of compilation takes"));
234
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000235static llvm::cl::opt<bool>
236Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000237 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000238 "freestanding environment"));
239
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000240static llvm::cl::opt<bool>
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000241AllowBuiltins("fbuiltin",
242 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
243 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner7644f072009-03-13 22:38:49 +0000244
245
246static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000247MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000248 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000249 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000250
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000251//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000252// Language Options
253//===----------------------------------------------------------------------===//
254
255enum LangKind {
256 langkind_unspecified,
257 langkind_c,
258 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000259 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 langkind_cxx,
261 langkind_cxx_cpp,
262 langkind_objc,
263 langkind_objc_cpp,
264 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000265 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000266};
267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268static llvm::cl::opt<LangKind>
269BaseLang("x", llvm::cl::desc("Base language to compile"),
270 llvm::cl::init(langkind_unspecified),
271 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
272 clEnumValN(langkind_cxx, "c++", "C++"),
273 clEnumValN(langkind_objc, "objective-c", "Objective C"),
274 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000275 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000277 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
278 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000280 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
282 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000283 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000285 clEnumValN(langkind_c, "c-header",
286 "C header"),
287 clEnumValN(langkind_objc, "objective-c-header",
288 "Objective-C header"),
289 clEnumValN(langkind_cxx, "c++-header",
290 "C++ header"),
291 clEnumValN(langkind_objcxx, "objective-c++-header",
292 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 clEnumValEnd));
294
295static llvm::cl::opt<bool>
296LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
297 llvm::cl::Hidden);
298static llvm::cl::opt<bool>
299LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
300 llvm::cl::Hidden);
301
Ted Kremenek8904f152007-12-05 23:49:08 +0000302/// InitializeBaseLanguage - Handle the -x foo options.
303static void InitializeBaseLanguage() {
304 if (LangObjC)
305 BaseLang = langkind_objc;
306 else if (LangObjCXX)
307 BaseLang = langkind_objcxx;
308}
309
310static LangKind GetLanguage(const std::string &Filename) {
311 if (BaseLang != langkind_unspecified)
312 return BaseLang;
313
314 std::string::size_type DotPos = Filename.rfind('.');
315
316 if (DotPos == std::string::npos) {
317 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000318 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 }
320
Ted Kremenek8904f152007-12-05 23:49:08 +0000321 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
322 // C header: .h
323 // C++ header: .hh or .H;
324 // assembler no preprocessing: .s
325 // assembler: .S
326 if (Ext == "c")
327 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000328 else if (Ext == "S" ||
329 // If the compiler is run on a .s file, preprocess it as .S
330 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000331 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000332 else if (Ext == "i")
333 return langkind_c_cpp;
334 else if (Ext == "ii")
335 return langkind_cxx_cpp;
336 else if (Ext == "m")
337 return langkind_objc;
338 else if (Ext == "mi")
339 return langkind_objc_cpp;
340 else if (Ext == "mm" || Ext == "M")
341 return langkind_objcxx;
342 else if (Ext == "mii")
343 return langkind_objcxx_cpp;
344 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
345 Ext == "c++" || Ext == "cp" || Ext == "cxx")
346 return langkind_cxx;
347 else
348 return langkind_c;
349}
350
351
Ted Kremenek85888962008-10-21 00:54:44 +0000352static void InitializeCOptions(LangOptions &Options) {
353 // Do nothing.
354}
355
356static void InitializeObjCOptions(LangOptions &Options) {
357 Options.ObjC1 = Options.ObjC2 = 1;
358}
359
360
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000361static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // FIXME: implement -fpreprocessed mode.
363 bool NoPreprocess = false;
364
Ted Kremenek8904f152007-12-05 23:49:08 +0000365 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000367 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000368 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000369 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 case langkind_c_cpp:
371 NoPreprocess = true;
372 // FALLTHROUGH
373 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000374 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 break;
376 case langkind_cxx_cpp:
377 NoPreprocess = true;
378 // FALLTHROUGH
379 case langkind_cxx:
380 Options.CPlusPlus = 1;
381 break;
382 case langkind_objc_cpp:
383 NoPreprocess = true;
384 // FALLTHROUGH
385 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000386 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 break;
388 case langkind_objcxx_cpp:
389 NoPreprocess = true;
390 // FALLTHROUGH
391 case langkind_objcxx:
392 Options.ObjC1 = Options.ObjC2 = 1;
393 Options.CPlusPlus = 1;
394 break;
395 }
396}
397
398/// LangStds - Language standards we support.
399enum LangStds {
400 lang_unspecified,
401 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000402 lang_gnu_START,
403 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000404 lang_cxx98, lang_gnucxx98,
405 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000406};
407
408static llvm::cl::opt<LangStds>
409LangStd("std", llvm::cl::desc("Language standard to compile for"),
410 llvm::cl::init(lang_unspecified),
411 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
412 clEnumValN(lang_c89, "c90", "ISO C 1990"),
413 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
414 clEnumValN(lang_c94, "iso9899:199409",
415 "ISO C 1990 with amendment 1"),
416 clEnumValN(lang_c99, "c99", "ISO C 1999"),
417// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
418 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
419// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
420 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000421 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000423 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 clEnumValN(lang_gnu99, "gnu9x",
425 "ISO C 1999 with GNU extensions"),
426 clEnumValN(lang_cxx98, "c++98",
427 "ISO C++ 1998 with amendments"),
428 clEnumValN(lang_gnucxx98, "gnu++98",
429 "ISO C++ 1998 with amendments and GNU "
430 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000431 clEnumValN(lang_cxx0x, "c++0x",
432 "Upcoming ISO C++ 200x with amendments"),
433 clEnumValN(lang_gnucxx0x, "gnu++0x",
434 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000435 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 clEnumValEnd));
437
438static llvm::cl::opt<bool>
439NoOperatorNames("fno-operator-names",
440 llvm::cl::desc("Do not treat C++ operator name keywords as "
441 "synonyms for operators"));
442
Anders Carlssonee98ac52007-10-15 02:50:23 +0000443static llvm::cl::opt<bool>
444PascalStrings("fpascal-strings",
445 llvm::cl::desc("Recognize and construct Pascal-style "
446 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000447
448static llvm::cl::opt<bool>
449MSExtensions("fms-extensions",
450 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000451 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000452
453static llvm::cl::opt<bool>
454WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000455 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000456
457static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000458NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000459 llvm::cl::desc("Disallow implicit conversions between "
460 "vectors with a different number of "
461 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000462
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000463static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000464EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
465 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
466 llvm::cl::ZeroOrMore);
467
468static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000469EnableHeinousExtensions("fheinous-gnu-extensions",
470 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
471 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
472
473static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000474ObjCNonFragileABI("fobjc-nonfragile-abi",
475 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000476
Daniel Dunbard604c402009-02-04 21:19:06 +0000477static llvm::cl::opt<bool>
478EmitAllDecls("femit-all-decls",
479 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000480
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000481// FIXME: This (and all GCC -f options) really come in -f... and
482// -fno-... forms, and additionally support automagic behavior when
483// they are not defined. For example, -fexceptions defaults to on or
484// off depending on the language. We should support this behavior in
485// some form (perhaps just add a facility for distinguishing when an
486// has its default value from when it has been set to its default
487// value).
488static llvm::cl::opt<bool>
489Exceptions("fexceptions",
490 llvm::cl::desc("Enable support for exception handling."));
491
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000492static llvm::cl::opt<bool>
493GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000494 llvm::cl::desc("Generate output compatible with the standard GNU "
495 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000496
497static llvm::cl::opt<bool>
498NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000499 llvm::cl::desc("Generate output compatible with the NeXT "
500 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000501
Ted Kremenekea644d82008-09-03 21:22:16 +0000502
503
504static llvm::cl::opt<bool>
505Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
506
507static llvm::cl::opt<bool>
508Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
509
Chris Lattner16167a62009-03-02 22:11:07 +0000510static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000511TargetFeatures("mattr", llvm::cl::CommaSeparated,
512 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
513
Douglas Gregor26dce442009-03-10 00:06:19 +0000514static llvm::cl::opt<unsigned>
515TemplateDepth("ftemplate-depth", llvm::cl::init(99),
516 llvm::cl::desc("Maximum depth of recursive template "
517 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000518
Reid Spencer5f016e22007-07-11 17:01:13 +0000519// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000520// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000521static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
522 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000523 // Allow the target to set the default the langauge options as it sees fit.
524 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000525
Chris Lattner6328cc32009-03-03 19:56:18 +0000526 // If there are any -mattr options, pass them to the target for validation and
527 // processing. The driver should have already consolidated all the
528 // target-feature settings and passed them to us in the -mattr list. The
529 // -mattr list is treated by the code generator as a diff against the -mcpu
530 // setting, but the driver should pass all enabled options as "+" settings.
531 // This means that the target should only look at + settings.
532 if (!TargetFeatures.empty()
533 // FIXME: The driver is not quite yet ready for this.
534 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000535 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000536 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
537 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000538 if (Opt != -1) {
539 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000540 fprintf(stderr, "invalid feature '%s'\n",
541 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000542 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000543 fprintf(stderr, "feature '%s': %s\n",
544 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000545 exit(1);
546 }
547 }
548
Ted Kremenekea644d82008-09-03 21:22:16 +0000549 if (Ansi) // "The -ansi option is equivalent to -std=c89."
550 LangStd = lang_c89;
551
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 if (LangStd == lang_unspecified) {
553 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000554 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000555 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000557 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 case langkind_c_cpp:
559 case langkind_objc:
560 case langkind_objc_cpp:
561 LangStd = lang_gnu99;
562 break;
563 case langkind_cxx:
564 case langkind_cxx_cpp:
565 case langkind_objcxx:
566 case langkind_objcxx_cpp:
567 LangStd = lang_gnucxx98;
568 break;
569 }
570 }
571
572 switch (LangStd) {
573 default: assert(0 && "Unknown language standard!");
574
575 // Fall through from newer standards to older ones. This isn't really right.
576 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000577 case lang_gnucxx0x:
578 case lang_cxx0x:
579 Options.CPlusPlus0x = 1;
580 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 case lang_gnucxx98:
582 case lang_cxx98:
583 Options.CPlusPlus = 1;
584 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000585 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // FALL THROUGH.
587 case lang_gnu99:
588 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 Options.C99 = 1;
590 Options.HexFloats = 1;
591 // FALL THROUGH.
592 case lang_gnu89:
593 Options.BCPLComment = 1; // Only for C99/C++.
594 // FALL THROUGH.
595 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000596 Options.Digraphs = 1; // C94, C99, C++.
597 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 case lang_c89:
599 break;
600 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000601
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000602 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
603 Options.GNUMode = LangStd >= lang_gnu_START;
604
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000605 if (Options.CPlusPlus) {
606 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000607 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000608 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000609
Chris Lattnerd658b562008-04-05 06:32:51 +0000610 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
611 Options.ImplicitInt = 1;
612 else
613 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000614
615 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
616 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000617 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000618 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000619 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000620
Chris Lattner802db9b2008-12-05 00:10:44 +0000621 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
622 // even if they are normally on for the target. In GNU modes (e.g.
623 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000624 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000625 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000626 Options.Blocks = 0;
627
Daniel Dunbar85c49102009-03-15 00:11:28 +0000628 // Never accept '$' in identifiers when preprocessing assembler.
629 if (LK != langkind_asm_cpp)
630 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000631 if (PascalStrings.getPosition())
632 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000633 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000634 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000635 if (NoLaxVectorConversions.getPosition())
636 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000637 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000638 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000639 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000640
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000641 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000642 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000643 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000644 Options.Freestanding = Options.NoBuiltin = 1;
645
Chris Lattner810f6d52009-03-13 17:38:01 +0000646 if (EnableHeinousExtensions)
647 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000648
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000649 Options.MathErrno = MathErrno;
650
Douglas Gregor26dce442009-03-10 00:06:19 +0000651 Options.InstantiationDepth = TemplateDepth;
652
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000653 // Override the default runtime if the user requested it.
654 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000655 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000656 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000657 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000658
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000659 if (ObjCNonFragileABI)
660 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000661
662 if (EmitAllDecls)
663 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000664}
665
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000666static llvm::cl::opt<bool>
667ObjCExclusiveGC("fobjc-gc-only",
668 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000669 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000670
671static llvm::cl::opt<bool>
672ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000673 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000674
675void InitializeGCMode(LangOptions &Options) {
676 if (ObjCExclusiveGC)
677 Options.setGCMode(LangOptions::GCOnly);
678 else if (ObjCEnableGC)
679 Options.setGCMode(LangOptions::HybridGC);
680}
681
Mike Stump2add4732009-04-01 20:28:16 +0000682static llvm::cl::opt<bool>
Mike Stump5d8b2cf2009-04-02 01:03:55 +0000683UnsignedOverflowChecking("ftrapu",
684 llvm::cl::desc("Trap on unsigned and signed integer overflow"),
685 llvm::cl::init(false));
686
687static llvm::cl::opt<bool>
Mike Stump2add4732009-04-01 20:28:16 +0000688OverflowChecking("ftrapv",
Mike Stump5d8b2cf2009-04-02 01:03:55 +0000689 llvm::cl::desc("Trap on signed integer overflow"),
Mike Stump2add4732009-04-01 20:28:16 +0000690 llvm::cl::init(false));
691
692void InitializeOverflowChecking(LangOptions &Options) {
Mike Stump5d8b2cf2009-04-02 01:03:55 +0000693 Options.OverflowChecking = OverflowChecking | UnsignedOverflowChecking;
694 Options.UnsignedOverflowChecking = UnsignedOverflowChecking;
Mike Stump2add4732009-04-01 20:28:16 +0000695}
Reid Spencer5f016e22007-07-11 17:01:13 +0000696//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000697// Target Triple Processing.
698//===----------------------------------------------------------------------===//
699
700static llvm::cl::opt<std::string>
701TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000702 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000703
Chris Lattner42e67372008-03-05 01:18:20 +0000704static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000705Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000706
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000707static llvm::cl::opt<std::string>
708MacOSVersionMin("mmacosx-version-min",
709 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
710
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000711// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
712// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000713
714// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000715static void HandleMacOSVersionMin(std::string &Triple) {
716 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
717 if (DarwinDashIdx == std::string::npos) {
718 fprintf(stderr,
719 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
720 exit(1);
721 }
722 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
723
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000724 // Remove the number.
725 Triple.resize(DarwinNumIdx);
726
727 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
728 bool MacOSVersionMinIsInvalid = false;
729 int VersionNum = 0;
730 if (MacOSVersionMin.size() < 4 ||
731 MacOSVersionMin.substr(0, 3) != "10." ||
732 !isdigit(MacOSVersionMin[3])) {
733 MacOSVersionMinIsInvalid = true;
734 } else {
735 const char *Start = MacOSVersionMin.c_str()+3;
736 char *End = 0;
737 VersionNum = (int)strtol(Start, &End, 10);
738
Chris Lattner079f2c462008-09-30 20:30:12 +0000739 // The version number must be in the range 0-9.
740 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
741
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000742 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
743 Triple += llvm::itostr(VersionNum+4);
744
Chris Lattner079f2c462008-09-30 20:30:12 +0000745 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
746 // Add the period piece (.7) to the end of the triple. This gives us
747 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000748 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000749 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
750 MacOSVersionMinIsInvalid = true;
751 }
752 }
753
754 if (MacOSVersionMinIsInvalid) {
755 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000756 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000757 MacOSVersionMin.c_str());
758 exit(1);
759 }
760}
761
762/// CreateTargetTriple - Process the various options that affect the target
763/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000764static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000765 // Initialize base triple. If a -triple option has been specified, use
766 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000767 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000768 if (Triple.empty())
769 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000770
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000771 // If -arch foo was specified, remove the architecture from the triple we have
772 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000773
774 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000775 if (!Arch.empty()) {
776 // Decompose the base triple into "arch" and suffix.
777 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000778
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000779 if (FirstDashIdx == std::string::npos) {
780 fprintf(stderr,
781 "Malformed target triple: \"%s\" ('-' could not be found).\n",
782 Triple.c_str());
783 exit(1);
784 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000785
786 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
787 if (Arch == "ppc")
788 Arch = "powerpc";
789 else if (Arch == "ppc64")
790 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000791
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000792 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
793 }
794
795 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
796 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000797 if (!MacOSVersionMin.empty())
798 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000799
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000800 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000801}
802
803//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000804// Preprocessor Initialization
805//===----------------------------------------------------------------------===//
806
807// FIXME: Preprocessor builtins to support.
808// -A... - Play with #assertions
809// -undef - Undefine all predefined macros
810
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000811// FIXME: -imacros
812
Reid Spencer5f016e22007-07-11 17:01:13 +0000813static llvm::cl::list<std::string>
814D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
815 llvm::cl::desc("Predefine the specified macro"));
816static llvm::cl::list<std::string>
817U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
818 llvm::cl::desc("Undefine the specified macro"));
819
Chris Lattner64299f82008-01-10 01:53:41 +0000820static llvm::cl::list<std::string>
821ImplicitIncludes("include", llvm::cl::value_desc("file"),
822 llvm::cl::desc("Include file before parsing"));
823
Ted Kremenek748d5d62009-03-20 00:26:38 +0000824static llvm::cl::opt<std::string>
825ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
826 llvm::cl::desc("Include file before parsing"));
827
Reid Spencer5f016e22007-07-11 17:01:13 +0000828// Append a #define line to Buf for Macro. Macro should be of the form XXX,
829// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
830// "#define XXX Y z W". To get a #define with no value, use "XXX=".
831static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
832 const char *Command = "#define ") {
833 Buf.insert(Buf.end(), Command, Command+strlen(Command));
834 if (const char *Equal = strchr(Macro, '=')) {
835 // Turn the = into ' '.
836 Buf.insert(Buf.end(), Macro, Equal);
837 Buf.push_back(' ');
838 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
839 } else {
840 // Push "macroname 1".
841 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
842 Buf.push_back(' ');
843 Buf.push_back('1');
844 }
845 Buf.push_back('\n');
846}
847
Chris Lattner64299f82008-01-10 01:53:41 +0000848/// AddImplicitInclude - Add an implicit #include of the specified file to the
849/// predefines buffer.
850static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
851 const char *Inc = "#include \"";
852 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
853 Buf.insert(Buf.end(), File.begin(), File.end());
854 Buf.push_back('"');
855 Buf.push_back('\n');
856}
857
Ted Kremenek748d5d62009-03-20 00:26:38 +0000858/// AddImplicitIncludePTH - Add an implicit #include using the original file
859/// used to generate a PTH cache.
860static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
861 PTHManager *P = PP.getPTHManager();
862 assert(P && "No PTHManager.");
863 const char *OriginalFile = P->getOriginalSourceFile();
864
865 if (!OriginalFile) {
866 assert(!ImplicitIncludePTH.empty());
867 fprintf(stderr, "error: PTH file '%s' does not designate an original "
868 "source header file for -include-pth\n",
869 ImplicitIncludePTH.c_str());
870 exit (1);
871 }
872
873 AddImplicitInclude(Buf, OriginalFile);
874}
Reid Spencer5f016e22007-07-11 17:01:13 +0000875
Chris Lattner53b0dab2007-10-09 22:10:18 +0000876/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000877/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000878///
Chris Lattner51574ea2008-04-19 23:25:44 +0000879static bool InitializePreprocessor(Preprocessor &PP,
880 bool InitializeSourceMgr,
881 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000882 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000883
Chris Lattner53b0dab2007-10-09 22:10:18 +0000884 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000885 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000886
887 if (InitializeSourceMgr) {
888 if (InFile != "-") {
889 const FileEntry *File = FileMgr.getFile(InFile);
890 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000891 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000892 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
893 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +0000894 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000895 }
896 } else {
897 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +0000898
899 // If stdin was empty, SB is null. Cons up an empty memory
900 // buffer now.
901 if (!SB) {
902 const char *EmptyStr = "";
903 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
904 }
905
906 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000907 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000908 PP.getDiagnostics().Report(FullSourceLoc(),
909 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +0000910 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000911 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000912 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000914
Chris Lattneraa391972008-04-19 23:09:31 +0000915 std::vector<char> PredefineBuffer;
916
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000918 unsigned d = 0, D = D_macros.size();
919 unsigned u = 0, U = U_macros.size();
920 while (d < D || u < U) {
921 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
922 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
923 else
924 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
925 }
926
Chris Lattner64299f82008-01-10 01:53:41 +0000927 // FIXME: Read any files specified by -imacros.
928
Ted Kremenek748d5d62009-03-20 00:26:38 +0000929 // Add implicit #includes from -include and -include-pth.
930 bool handledPTH = ImplicitIncludePTH.empty();
931 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +0000932 if (!handledPTH &&
933 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +0000934 AddImplicitIncludePTH(PredefineBuffer, PP);
935 handledPTH = true;
936 }
937
Chris Lattner64299f82008-01-10 01:53:41 +0000938 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +0000939 }
940 if (!handledPTH && !ImplicitIncludePTH.empty())
941 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000942
Chris Lattneraa391972008-04-19 23:09:31 +0000943 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000944 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000945 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000946
947 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000948 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000949}
950
951//===----------------------------------------------------------------------===//
952// Preprocessor include path information.
953//===----------------------------------------------------------------------===//
954
955// This tool exports a large number of command line options to control how the
956// preprocessor searches for header files. At root, however, the Preprocessor
957// object takes a very simple interface: a list of directories to search for
958//
959// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000960// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000961//
Reid Spencer5f016e22007-07-11 17:01:13 +0000962
963static llvm::cl::opt<bool>
964nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
965
966// Various command line options. These four add directories to each chain.
967static llvm::cl::list<std::string>
968F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
969 llvm::cl::desc("Add directory to framework include search path"));
970static llvm::cl::list<std::string>
971I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
972 llvm::cl::desc("Add directory to include search path"));
973static llvm::cl::list<std::string>
974idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
975 llvm::cl::desc("Add directory to AFTER include search path"));
976static llvm::cl::list<std::string>
977iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
978 llvm::cl::desc("Add directory to QUOTE include search path"));
979static llvm::cl::list<std::string>
980isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
981 llvm::cl::desc("Add directory to SYSTEM include search path"));
982
983// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
984static llvm::cl::list<std::string>
985iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
986 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
987static llvm::cl::list<std::string>
988iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
989 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
990static llvm::cl::list<std::string>
991iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
992 llvm::cl::Prefix,
993 llvm::cl::desc("Set directory to include search path with prefix"));
994
Chris Lattner0c946412007-08-26 17:47:35 +0000995static llvm::cl::opt<std::string>
996isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
997 llvm::cl::desc("Set the system root directory (usually /)"));
998
Reid Spencer5f016e22007-07-11 17:01:13 +0000999// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001000
Reid Spencer5f016e22007-07-11 17:01:13 +00001001/// InitializeIncludePaths - Process the -I options and set them in the
1002/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001003void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1004 FileManager &FM, const LangOptions &Lang) {
1005 InitHeaderSearch Init(Headers, Verbose, isysroot);
1006
Ted Kremenekf3721112008-05-31 00:27:00 +00001007 // Handle -I... and -F... options, walking the lists in parallel.
1008 unsigned Iidx = 0, Fidx = 0;
1009 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1010 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001011 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001012 ++Iidx;
1013 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001014 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001015 ++Fidx;
1016 }
1017 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001018
Ted Kremenekf3721112008-05-31 00:27:00 +00001019 // Consume what's left from whatever list was longer.
1020 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001021 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001022 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001023 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001024
1025 // Handle -idirafter... options.
1026 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001027 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1028 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001029
1030 // Handle -iquote... options.
1031 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001032 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001033
1034 // Handle -isystem... options.
1035 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001036 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001037
1038 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1039 // parallel, processing the values in order of occurance to get the right
1040 // prefixes.
1041 {
1042 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1043 unsigned iprefix_idx = 0;
1044 unsigned iwithprefix_idx = 0;
1045 unsigned iwithprefixbefore_idx = 0;
1046 bool iprefix_done = iprefix_vals.empty();
1047 bool iwithprefix_done = iwithprefix_vals.empty();
1048 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1049 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1050 if (!iprefix_done &&
1051 (iwithprefix_done ||
1052 iprefix_vals.getPosition(iprefix_idx) <
1053 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1054 (iwithprefixbefore_done ||
1055 iprefix_vals.getPosition(iprefix_idx) <
1056 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1057 Prefix = iprefix_vals[iprefix_idx];
1058 ++iprefix_idx;
1059 iprefix_done = iprefix_idx == iprefix_vals.size();
1060 } else if (!iwithprefix_done &&
1061 (iwithprefixbefore_done ||
1062 iwithprefix_vals.getPosition(iwithprefix_idx) <
1063 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001064 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1065 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001066 ++iwithprefix_idx;
1067 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1068 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001069 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1070 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 ++iwithprefixbefore_idx;
1072 iwithprefixbefore_done =
1073 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1074 }
1075 }
1076 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001077
Nico Weber0fca0222008-08-22 09:25:22 +00001078 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001079
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001080 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001081 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001082 llvm::sys::Path::GetMainExecutable(Argv0,
1083 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001084 if (!MainExecutablePath.isEmpty()) {
1085 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1086 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001087
1088 // Get foo/lib/clang/1.0/include
1089 //
1090 // FIXME: Don't embed version here.
1091 MainExecutablePath.appendComponent("lib");
1092 MainExecutablePath.appendComponent("clang");
1093 MainExecutablePath.appendComponent("1.0");
1094 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001095
1096 // We pass true to ignore sysroot so that we *always* look for clang headers
1097 // relative to our executable, never relative to -isysroot.
1098 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1099 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001100 }
1101
Nico Weber0fca0222008-08-22 09:25:22 +00001102 if (!nostdinc)
1103 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001104
1105 // Now that we have collected all of the include paths, merge them all
1106 // together and tell the preprocessor about them.
1107
Nico Weber0fca0222008-08-22 09:25:22 +00001108 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001109}
1110
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001111//===----------------------------------------------------------------------===//
1112// Driver PreprocessorFactory - For lazily generating preprocessors ...
1113//===----------------------------------------------------------------------===//
1114
1115namespace {
1116class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001117 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001118 Diagnostic &Diags;
1119 const LangOptions &LangInfo;
1120 TargetInfo &Target;
1121 SourceManager &SourceMgr;
1122 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001123 bool InitializeSourceMgr;
1124
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001125public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001126 DriverPreprocessorFactory(const std::string &infile,
1127 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001128 TargetInfo &target, SourceManager &SM,
1129 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001130 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1131 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1132
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001133
1134 virtual ~DriverPreprocessorFactory() {}
1135
1136 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001137 llvm::OwningPtr<PTHManager> PTHMgr;
1138
Ted Kremenek748d5d62009-03-20 00:26:38 +00001139 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1140 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1141 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001142 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001143 }
1144
Ted Kremenek72b1b152009-01-15 18:47:46 +00001145 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001146 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1147 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001148 PTHMgr.reset(PTHManager::Create(x, &Diags,
1149 TokenCache.empty() ? Diagnostic::Error
1150 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001151 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001152
Ted Kremenek22f0d092009-03-22 06:42:39 +00001153 if (Diags.hasErrorOccurred())
1154 exit(1);
1155
Ted Kremenek72b1b152009-01-15 18:47:46 +00001156 // Create the Preprocessor.
1157 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1158 SourceMgr, HeaderInfo,
1159 PTHMgr.get()));
1160
1161 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1162 // That argument is used as the IdentifierInfoLookup argument to
1163 // IdentifierTable's ctor.
1164 if (PTHMgr) {
1165 PTHMgr->setPreprocessor(PP.get());
1166 PP->setPTHManager(PTHMgr.take());
1167 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001168
Chris Lattner51574ea2008-04-19 23:25:44 +00001169 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001170 return NULL;
1171 }
1172
Daniel Dunbar750c3582008-10-24 22:12:41 +00001173 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001174 if (ProgAction != PrintPreprocessedInput) {
1175 std::string ErrStr;
1176 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1177 if (!DFG && !ErrStr.empty()) {
1178 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001179 return NULL;
1180 }
1181 }
1182
Ted Kremenek339b9c22008-04-17 22:31:54 +00001183 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001184 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001185 }
1186};
1187}
Reid Spencer5f016e22007-07-11 17:01:13 +00001188
Reid Spencer5f016e22007-07-11 17:01:13 +00001189//===----------------------------------------------------------------------===//
1190// Basic Parser driver
1191//===----------------------------------------------------------------------===//
1192
Chris Lattner51574ea2008-04-19 23:25:44 +00001193static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001195 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001196
1197 // Parsing the specified input file.
1198 P.ParseTranslationUnit();
1199 delete PA;
1200}
1201
1202//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001203// Code generation options
1204//===----------------------------------------------------------------------===//
1205
1206static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001207GenerateDebugInfo("g",
1208 llvm::cl::desc("Generate source level debug information"));
1209
1210static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001211OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001212
Chris Lattnerbd360642009-03-26 05:00:52 +00001213static llvm::cl::opt<bool>
1214NoCommon("fno-common",
Mike Stump1c9b7422009-03-27 20:15:22 +00001215 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner925a7042009-03-28 02:12:08 +00001216 llvm::cl::ValueDisallowed);
Chris Lattnerbd360642009-03-26 05:00:52 +00001217
Daniel Dunbar70f92432008-10-23 05:50:47 +00001218// It might be nice to add bounds to the CommandLine library directly.
1219struct OptLevelParser : public llvm::cl::parser<unsigned> {
1220 bool parse(llvm::cl::Option &O, const char *ArgName,
1221 const std::string &Arg, unsigned &Val) {
1222 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1223 return true;
1224 // FIXME: Support -O4.
1225 if (Val > 3)
1226 return O.error(": '" + Arg + "' invalid optimization level!");
1227 return false;
1228 }
1229};
1230static llvm::cl::opt<unsigned, false, OptLevelParser>
1231OptLevel("O", llvm::cl::Prefix,
1232 llvm::cl::desc("Optimization level"),
1233 llvm::cl::init(0));
1234
Daniel Dunbara034ba82009-02-17 19:47:34 +00001235static llvm::cl::opt<std::string>
1236TargetCPU("mcpu",
1237 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1238
Chris Lattner7afae712009-03-16 18:41:18 +00001239static void InitializeCompileOptions(CompileOptions &Opts,
1240 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001241 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001242 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001243 if (OptSize) {
1244 // -Os implies -O2
1245 // FIXME: Diagnose conflicting options.
1246 Opts.OptimizationLevel = 2;
1247 } else {
1248 Opts.OptimizationLevel = OptLevel;
1249 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001250
1251 // FIXME: There are llvm-gcc options to control these selectively.
1252 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1253 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001254 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001255
1256#ifdef NDEBUG
1257 Opts.VerifyModule = 0;
1258#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001259
1260 Opts.CPU = TargetCPU;
1261 Opts.Features.insert(Opts.Features.end(),
1262 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001263
Chris Lattnerbd360642009-03-26 05:00:52 +00001264 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1265
Chris Lattner44502662009-02-18 01:23:44 +00001266 // Handle -ftime-report.
1267 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001268}
1269
1270//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001271// Main driver
1272//===----------------------------------------------------------------------===//
1273
Ted Kremenekdb094a22007-12-05 18:27:04 +00001274/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001275/// action. These consumers can operate on both ASTs that are freshly
1276/// parsed from source files as well as those deserialized from Bitcode.
1277/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001278static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001279 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001280 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001281 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001282 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001283 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001284 default:
1285 return NULL;
1286
1287 case ASTPrint:
1288 return CreateASTPrinter();
1289
1290 case ASTDump:
1291 return CreateASTDumper();
1292
1293 case ASTView:
1294 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001295
Chris Lattner8a5c8092009-02-18 01:20:05 +00001296 case PrintDeclContext:
1297 return CreateDeclContextPrinter();
1298
1299 case EmitHTML:
1300 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001301
Chris Lattner8a5c8092009-02-18 01:20:05 +00001302 case InheritanceView:
1303 return CreateInheritanceViewer(InheritanceViewCls);
1304
1305 case TestSerialization:
1306 return CreateSerializationTest(Diag, FileMgr);
1307
1308 case EmitAssembly:
1309 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001310 case EmitBC:
1311 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001312 BackendAction Act;
1313 if (ProgAction == EmitAssembly)
1314 Act = Backend_EmitAssembly;
1315 else if (ProgAction == EmitLLVM)
1316 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001317 else if (ProgAction == EmitLLVMOnly)
1318 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001319 else
1320 Act = Backend_EmitBC;
1321
1322 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001323 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001324 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001325 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001326 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001327
Chris Lattner8a5c8092009-02-18 01:20:05 +00001328 case SerializeAST:
1329 // FIXME: Allow user to tailor where the file is written.
1330 return CreateASTSerializer(InFile, OutputFile, Diag);
1331
1332 case RewriteObjC:
1333 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001334
Chris Lattner8a5c8092009-02-18 01:20:05 +00001335 case RewriteBlocks:
1336 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1337
1338 case RunAnalysis:
1339 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001340 }
1341}
1342
Reid Spencer5f016e22007-07-11 17:01:13 +00001343/// ProcessInputFile - Process a single input file with the specified state.
1344///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001345static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001346 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001347 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001348 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001349 FixItRewriter *FixItRewrite = 0;
1350
Ted Kremenek85888962008-10-21 00:54:44 +00001351 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001353 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1354 PP.getFileManager(), PP.getLangOptions(),
1355 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001356
1357 if (!Consumer) {
1358 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001359 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001360 return;
1361 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001362
Ted Kremenekdb094a22007-12-05 18:27:04 +00001363 break;
1364
Chris Lattnerc106c102008-10-12 05:03:36 +00001365 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001366 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001367 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001368 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001369 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001370 RawLex.SetKeepWhitespaceMode(true);
1371
1372 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001373 RawLex.LexFromRawLexer(RawTok);
1374 while (RawTok.isNot(tok::eof)) {
1375 PP.DumpToken(RawTok, true);
1376 fprintf(stderr, "\n");
1377 RawLex.LexFromRawLexer(RawTok);
1378 }
1379 ClearSourceMgr = true;
1380 break;
1381 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001383 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001384 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001385 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001386 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 do {
1388 PP.Lex(Tok);
1389 PP.DumpToken(Tok, true);
1390 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001391 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001392 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 break;
1394 }
1395 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001396 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001397 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001399 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 do {
1401 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001402 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001403 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 break;
1405 }
Ted Kremenek85888962008-10-21 00:54:44 +00001406
1407 case GeneratePCH: {
Chris Lattner47099742009-02-18 01:51:21 +00001408 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001409 CacheTokens(PP, OutputFile);
1410 ClearSourceMgr = true;
1411 break;
1412 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001413
Chris Lattner47099742009-02-18 01:51:21 +00001414 case PrintPreprocessedInput: { // -E mode.
1415 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001416 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001417 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 break;
Chris Lattner47099742009-02-18 01:51:21 +00001419 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001420
Chris Lattner47099742009-02-18 01:51:21 +00001421 case ParseNoop: { // -parse-noop
1422 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001423 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001424 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 break;
Chris Lattner47099742009-02-18 01:51:21 +00001426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001427
Chris Lattner47099742009-02-18 01:51:21 +00001428 case ParsePrintCallbacks: {
1429 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001430 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001431 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 break;
Chris Lattner47099742009-02-18 01:51:21 +00001433 }
1434
1435 case ParseSyntaxOnly: { // -fsyntax-only
1436 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001437 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001438 break;
Chris Lattner47099742009-02-18 01:51:21 +00001439 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001440
1441 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001442 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001443 ClearSourceMgr = true;
1444 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001445
Chris Lattner47099742009-02-18 01:51:21 +00001446 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001447 DoRewriteTest(PP, InFile, OutputFile);
1448 ClearSourceMgr = true;
1449 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001450 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001451
1452 case FixIt:
1453 llvm::TimeRegion Timer(ClangFrontendTimer);
1454 Consumer.reset(new ASTConsumer());
1455 FixItRewrite = new FixItRewriter(PP.getDiagnostics().getClient(),
1456 PP.getSourceManager());
1457 PP.getDiagnostics().setClient(FixItRewrite);
1458 break;
Chris Lattner47099742009-02-18 01:51:21 +00001459 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001460
1461 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001462 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001463
1464 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1465 PP.getSourceManager(),
1466 PP.getTargetInfo(),
1467 PP.getIdentifierTable(),
1468 PP.getSelectorTable(),
1469 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001470
1471
Chris Lattner3599dbe2009-03-28 04:13:34 +00001472 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001473
Douglas Gregor558cb562009-04-02 01:08:08 +00001474 if (FixItRewrite)
1475 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1476
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001477 // If in -disable-free mode, don't deallocate these when they go out of
1478 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001479 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001480 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001481 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001482
1483 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001484 if (CheckDiagnostics(PP))
1485 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001486
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001488 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 PP.PrintStats();
1490 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001491 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001492 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 fprintf(stderr, "\n");
1494 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001495
1496 // For a multi-file compilation, some things are ok with nuking the source
1497 // manager tables, other require stable fileid/macroid's across multiple
1498 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001499 if (ClearSourceMgr)
1500 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001501
1502 if (DisableFree)
1503 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001504}
1505
Ted Kremenek20e97482007-12-12 23:41:08 +00001506static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1507 FileManager& FileMgr) {
1508
1509 if (VerifyDiagnostics) {
1510 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1511 exit (1);
1512 }
1513
1514 llvm::sys::Path Filename(InFile);
1515
1516 if (!Filename.isValid()) {
1517 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1518 exit (1);
1519 }
1520
Chris Lattner557c5b12009-03-28 04:27:18 +00001521 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001522
1523 // Create the memory buffer that contains the contents of the file.
1524 llvm::OwningPtr<llvm::MemoryBuffer>
1525 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1526
1527 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001528 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001529
Chris Lattner557c5b12009-03-28 04:27:18 +00001530 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001531 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1532 InFile.c_str());
1533 exit (1);
1534 }
1535
Ted Kremenek63ea8632007-12-19 19:27:38 +00001536 // Observe that we use the source file name stored in the deserialized
1537 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001538 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001539 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001540 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001541
Ted Kremenek20e97482007-12-12 23:41:08 +00001542 if (!Consumer) {
1543 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1544 exit (1);
1545 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001546
Chris Lattner557c5b12009-03-28 04:27:18 +00001547 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001548
Chris Lattnere66b65c2008-02-06 01:42:25 +00001549 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001550 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1551 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1552 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001553 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001554}
1555
1556
Reid Spencer5f016e22007-07-11 17:01:13 +00001557static llvm::cl::list<std::string>
1558InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1559
Ted Kremenek20e97482007-12-12 23:41:08 +00001560static bool isSerializedFile(const std::string& InFile) {
1561 if (InFile.size() < 4)
1562 return false;
1563
1564 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001565 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001566}
1567
Reid Spencer5f016e22007-07-11 17:01:13 +00001568
1569int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001571 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001572 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001573 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001574
Chris Lattner47099742009-02-18 01:51:21 +00001575 if (TimeReport)
1576 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1577
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 // If no input was specified, read from stdin.
1579 if (InputFilenames.empty())
1580 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 // Create a file manager object to provide access to and cache the filesystem.
1583 FileManager FileMgr;
1584
Ted Kremenek31e703b2007-12-11 23:28:38 +00001585 // Create the diagnostic client for reporting errors or for
1586 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001587 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001588
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001589 if (!VerifyDiagnostics) {
1590 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001591 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1592 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001593 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001594 !NoShowLocation,
1595 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001596 } else {
1597 // When checking diagnostics, just buffer them up.
1598 TextDiagClient = new TextDiagnosticBuffer();
1599
1600 if (InputFilenames.size() != 1) {
1601 fprintf(stderr,
1602 "-verify only works on single input files for now.\n");
1603 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 }
1605 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001608 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1609 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001610 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001611 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001612
Chris Lattner4f037832007-12-05 23:24:17 +00001613 // -I- is a deprecated GCC feature, scan for it and reject it.
1614 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1615 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001616 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001617 I_dirs.erase(I_dirs.begin()+i);
1618 --i;
1619 }
1620 }
Chris Lattner11215192008-03-14 06:12:05 +00001621
1622 // Get information about the target being compiled for.
1623 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001624 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1625
Chris Lattner11215192008-03-14 06:12:05 +00001626 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001627 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1628 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001629 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001630 }
Chris Lattner4f037832007-12-05 23:24:17 +00001631
Daniel Dunbard4270232009-01-20 23:17:32 +00001632 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001633 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001634
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001635 llvm::OwningPtr<SourceManager> SourceMgr;
1636
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001638 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001639
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001640 if (isSerializedFile(InFile)) {
1641 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001642 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001643 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001644 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001645
1646 /// Create a SourceManager object. This tracks and owns all the file
1647 /// buffers allocated to a translation unit.
1648 if (!SourceMgr)
1649 SourceMgr.reset(new SourceManager());
1650 else
1651 SourceMgr->clearIDTables();
1652
1653 // Initialize language options, inferring file types from input filenames.
1654 LangOptions LangInfo;
1655 InitializeBaseLanguage();
1656 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001657 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001658 InitializeGCMode(LangInfo);
Mike Stump2add4732009-04-01 20:28:16 +00001659 InitializeOverflowChecking(LangInfo);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001660 InitializeLanguageStandard(LangInfo, LK, Target.get());
1661
1662 // Process the -I options and set them in the HeaderInfo.
1663 HeaderSearch HeaderInfo(FileMgr);
1664
1665 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1666
1667 // Set up the preprocessor with these options.
1668 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1669 *SourceMgr.get(), HeaderInfo);
1670
1671 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1672
1673 if (!PP)
1674 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001675
Chris Lattnerf63aea32009-03-04 21:40:56 +00001676 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1677 // always reset to using TextDiagClient.
1678 llvm::OwningPtr<DiagnosticClient> TmpClient;
1679
1680 if (!HTMLDiag.empty()) {
1681 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1682 &PPFactory));
1683 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001684 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001685 else
1686 Diags.setClient(TextDiagClient);
1687
1688 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001689 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001690
1691 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 }
Chris Lattner11215192008-03-14 06:12:05 +00001693
Mike Stump007f2a92009-01-28 02:43:35 +00001694 if (Verbose)
1695 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1696 " hosted on " LLVM_HOSTTRIPLE "\n");
1697
Ted Kremenek7a08e282008-08-07 18:13:12 +00001698 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1700 (NumDiagnostics == 1 ? "" : "s"));
1701
1702 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 FileMgr.PrintStats();
1704 fprintf(stderr, "\n");
1705 }
1706
Daniel Dunbar276373d2008-10-27 22:10:13 +00001707 // If verifying diagnostics and we reached here, all is well.
1708 if (VerifyDiagnostics)
1709 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001710
1711 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001712
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001713 // Managed static deconstruction. Useful for making things like
1714 // -time-passes usable.
1715 llvm::llvm_shutdown();
1716
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001717 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001718}