blob: 7541f80883fd9e801a61d3cc6ff7b12ea98cf50b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000029#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000030#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000031#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000033#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000034#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000035#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000036#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000037#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000038#include "clang/AST/ASTContext.h"
39#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000040#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "clang/Parse/Parser.h"
42#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000043#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044#include "clang/Basic/FileManager.h"
45#include "clang/Basic/SourceManager.h"
46#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000048#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000051#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000052#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000053#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000054#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000055#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000056#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000057#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000058#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// Global options.
64//===----------------------------------------------------------------------===//
65
Chris Lattner47099742009-02-18 01:51:21 +000066/// ClangFrontendTimer - The front-end activities should charge time to it with
67/// TimeRegion. The -ftime-report option controls whether this will do
68/// anything.
69llvm::Timer *ClangFrontendTimer = 0;
70
Daniel Dunbard3db4012008-10-16 16:54:18 +000071static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000072
Reid Spencer5f016e22007-07-11 17:01:13 +000073static llvm::cl::opt<bool>
74Verbose("v", llvm::cl::desc("Enable verbose output"));
75static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000076Stats("print-stats",
77 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000078static llvm::cl::opt<bool>
79DisableFree("disable-free",
80 llvm::cl::desc("Disable freeing of memory on exit"),
81 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000082
83enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000084 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000085 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000086 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000087 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000088 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000089 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000090 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000091 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +000092 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000093 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000094 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000095 ASTPrint, // Parse ASTs and print them.
96 ASTDump, // Parse ASTs and dump them.
97 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +000098 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000099 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 ParsePrintCallbacks, // Parse and print each callback.
101 ParseSyntaxOnly, // Parse and perform semantic analysis.
102 ParseNoop, // Parse with noop callbacks.
103 RunPreprocessorOnly, // Just lex, no output.
104 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000105 DumpTokens, // Dump out preprocessed tokens.
106 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000107 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000108 GeneratePCH, // Generate precompiled header.
109 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000110};
111
112static llvm::cl::opt<ProgActions>
113ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
114 llvm::cl::init(ParseSyntaxOnly),
115 llvm::cl::values(
116 clEnumValN(RunPreprocessorOnly, "Eonly",
117 "Just run preprocessor, no output (for timings)"),
118 clEnumValN(PrintPreprocessedInput, "E",
119 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000120 clEnumValN(DumpRawTokens, "dump-raw-tokens",
121 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000122 clEnumValN(RunAnalysis, "analyze",
123 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000124 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 "Run preprocessor, dump internal rep of tokens"),
126 clEnumValN(ParseNoop, "parse-noop",
127 "Run parser with noop callbacks (for timings)"),
128 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
129 "Run parser and perform semantic analysis"),
130 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
131 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000132 clEnumValN(EmitHTML, "emit-html",
133 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 clEnumValN(ASTPrint, "ast-print",
135 "Build ASTs and then pretty-print them"),
136 clEnumValN(ASTDump, "ast-dump",
137 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000138 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000139 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000140 clEnumValN(PrintDeclContext, "print-decl-contexts",
141 "Print DeclContexts and their Decls."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000142 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000143 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000144 clEnumValN(EmitAssembly, "S",
145 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000147 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000148 clEnumValN(EmitBC, "emit-llvm-bc",
149 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000150 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
151 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000152 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000153 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000154 clEnumValN(RewriteTest, "rewrite-test",
155 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000156 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000157 "Rewrite ObjC into C (code rewriter example)"),
158 clEnumValN(RewriteMacros, "rewrite-macros",
159 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000160 clEnumValN(RewriteBlocks, "rewrite-blocks",
161 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 clEnumValEnd));
163
Ted Kremenekccc76472007-12-19 19:47:59 +0000164
165static llvm::cl::opt<std::string>
166OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000167 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000168 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000169
Ted Kremenekc2e72992008-12-02 19:57:31 +0000170
171//===----------------------------------------------------------------------===//
172// PTH.
173//===----------------------------------------------------------------------===//
174
175static llvm::cl::opt<std::string>
176TokenCache("token-cache", llvm::cl::value_desc("path"),
177 llvm::cl::desc("Use specified token cache file"));
178
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000179//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000180// Diagnostic Options
181//===----------------------------------------------------------------------===//
182
Ted Kremenek41193e42007-09-26 19:42:19 +0000183static llvm::cl::opt<bool>
184VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000185 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000186
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000187static llvm::cl::opt<std::string>
188HTMLDiag("html-diags",
189 llvm::cl::desc("Generate HTML to report diagnostics"),
190 llvm::cl::value_desc("HTML directory"));
191
Nico Weberfd54ebc2008-08-05 23:33:20 +0000192static llvm::cl::opt<bool>
193NoShowColumn("fno-show-column",
194 llvm::cl::desc("Do not include column number on diagnostics"));
195
196static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000197NoShowLocation("fno-show-source-location",
198 llvm::cl::desc("Do not include source location information with"
199 " diagnostics"));
200
201static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000202NoCaretDiagnostics("fno-caret-diagnostics",
203 llvm::cl::desc("Do not include source line and caret with"
204 " diagnostics"));
205
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000206static llvm::cl::opt<bool>
207PrintSourceRangeInfo("fprint-source-range-info",
208 llvm::cl::desc("Print source range spans in numeric form"));
209
Nico Weberfd54ebc2008-08-05 23:33:20 +0000210
Reid Spencer5f016e22007-07-11 17:01:13 +0000211//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000212// C++ Visualization.
213//===----------------------------------------------------------------------===//
214
215static llvm::cl::opt<std::string>
216InheritanceViewCls("cxx-inheritance-view",
217 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000218 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000219
220//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000221// Builtin Options
222//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000223
224static llvm::cl::opt<bool>
225TimeReport("ftime-report",
226 llvm::cl::desc("Print the amount of time each "
227 "phase of compilation takes"));
228
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000229static llvm::cl::opt<bool>
230Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000231 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000232 "freestanding environment"));
233
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000234static llvm::cl::opt<bool>
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000235AllowBuiltins("fbuiltin",
236 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
237 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner7644f072009-03-13 22:38:49 +0000238
239
240static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000241MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000242 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000243 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000244
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000245//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000246// Language Options
247//===----------------------------------------------------------------------===//
248
249enum LangKind {
250 langkind_unspecified,
251 langkind_c,
252 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000253 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000254 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 langkind_cxx,
256 langkind_cxx_cpp,
Chris Lattnerc76d8072009-02-06 06:19:20 +0000257 langkind_cxx_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 langkind_objc,
259 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000260 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000261 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000262 langkind_objcxx_cpp,
263 langkind_objcxx_pch
Reid Spencer5f016e22007-07-11 17:01:13 +0000264};
265
Reid Spencer5f016e22007-07-11 17:01:13 +0000266static llvm::cl::opt<LangKind>
267BaseLang("x", llvm::cl::desc("Base language to compile"),
268 llvm::cl::init(langkind_unspecified),
269 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
270 clEnumValN(langkind_cxx, "c++", "C++"),
271 clEnumValN(langkind_objc, "objective-c", "Objective C"),
272 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000273 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000275 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
276 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000278 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
280 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000281 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 "Preprocessed Objective C++"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000283 clEnumValN(langkind_c_pch, "c-header",
Ted Kremenek85888962008-10-21 00:54:44 +0000284 "Precompiled C header"),
285 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000286 "Precompiled Objective-C header"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000287 clEnumValN(langkind_cxx_pch, "c++-header",
288 "Precompiled C++ header"),
Ted Kremenekf8901912009-01-09 00:38:08 +0000289 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
290 "Precompiled Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 clEnumValEnd));
292
293static llvm::cl::opt<bool>
294LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
295 llvm::cl::Hidden);
296static llvm::cl::opt<bool>
297LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
298 llvm::cl::Hidden);
299
Ted Kremenek8904f152007-12-05 23:49:08 +0000300/// InitializeBaseLanguage - Handle the -x foo options.
301static void InitializeBaseLanguage() {
302 if (LangObjC)
303 BaseLang = langkind_objc;
304 else if (LangObjCXX)
305 BaseLang = langkind_objcxx;
306}
307
308static LangKind GetLanguage(const std::string &Filename) {
309 if (BaseLang != langkind_unspecified)
310 return BaseLang;
311
312 std::string::size_type DotPos = Filename.rfind('.');
313
314 if (DotPos == std::string::npos) {
315 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000316 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 }
318
Ted Kremenek8904f152007-12-05 23:49:08 +0000319 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
320 // C header: .h
321 // C++ header: .hh or .H;
322 // assembler no preprocessing: .s
323 // assembler: .S
324 if (Ext == "c")
325 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000326 else if (Ext == "S" ||
327 // If the compiler is run on a .s file, preprocess it as .S
328 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000329 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000330 else if (Ext == "i")
331 return langkind_c_cpp;
332 else if (Ext == "ii")
333 return langkind_cxx_cpp;
334 else if (Ext == "m")
335 return langkind_objc;
336 else if (Ext == "mi")
337 return langkind_objc_cpp;
338 else if (Ext == "mm" || Ext == "M")
339 return langkind_objcxx;
340 else if (Ext == "mii")
341 return langkind_objcxx_cpp;
342 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
343 Ext == "c++" || Ext == "cp" || Ext == "cxx")
344 return langkind_cxx;
345 else
346 return langkind_c;
347}
348
349
Ted Kremenek85888962008-10-21 00:54:44 +0000350static void InitializeCOptions(LangOptions &Options) {
351 // Do nothing.
352}
353
354static void InitializeObjCOptions(LangOptions &Options) {
355 Options.ObjC1 = Options.ObjC2 = 1;
356}
357
358
359static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // FIXME: implement -fpreprocessed mode.
361 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000362 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000363
364 // Test for 'PCH'.
365 switch (LK) {
Chris Lattnerc76d8072009-02-06 06:19:20 +0000366 default:
367 break;
368 case langkind_c_pch:
369 LK = langkind_c;
370 PCH = true;
371 break;
372 case langkind_objc_pch:
373 LK = langkind_objc;
374 PCH = true;
375 break;
376 case langkind_cxx_pch:
377 LK = langkind_cxx;
378 PCH = true;
379 break;
380 case langkind_objcxx_pch:
381 LK = langkind_objcxx;
382 PCH = true;
383 break;
Ted Kremenekf8901912009-01-09 00:38:08 +0000384 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000385
Ted Kremenek8904f152007-12-05 23:49:08 +0000386 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000388 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000389 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000390 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 case langkind_c_cpp:
392 NoPreprocess = true;
393 // FALLTHROUGH
394 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000395 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 break;
397 case langkind_cxx_cpp:
398 NoPreprocess = true;
399 // FALLTHROUGH
400 case langkind_cxx:
401 Options.CPlusPlus = 1;
402 break;
403 case langkind_objc_cpp:
404 NoPreprocess = true;
405 // FALLTHROUGH
406 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000407 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 break;
409 case langkind_objcxx_cpp:
410 NoPreprocess = true;
411 // FALLTHROUGH
412 case langkind_objcxx:
413 Options.ObjC1 = Options.ObjC2 = 1;
414 Options.CPlusPlus = 1;
415 break;
416 }
Ted Kremenek85888962008-10-21 00:54:44 +0000417
418 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000419}
420
421/// LangStds - Language standards we support.
422enum LangStds {
423 lang_unspecified,
424 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000425 lang_gnu_START,
426 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000427 lang_cxx98, lang_gnucxx98,
428 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000429};
430
431static llvm::cl::opt<LangStds>
432LangStd("std", llvm::cl::desc("Language standard to compile for"),
433 llvm::cl::init(lang_unspecified),
434 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
435 clEnumValN(lang_c89, "c90", "ISO C 1990"),
436 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
437 clEnumValN(lang_c94, "iso9899:199409",
438 "ISO C 1990 with amendment 1"),
439 clEnumValN(lang_c99, "c99", "ISO C 1999"),
440// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
441 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
442// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
443 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000444 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000446 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 clEnumValN(lang_gnu99, "gnu9x",
448 "ISO C 1999 with GNU extensions"),
449 clEnumValN(lang_cxx98, "c++98",
450 "ISO C++ 1998 with amendments"),
451 clEnumValN(lang_gnucxx98, "gnu++98",
452 "ISO C++ 1998 with amendments and GNU "
453 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000454 clEnumValN(lang_cxx0x, "c++0x",
455 "Upcoming ISO C++ 200x with amendments"),
456 clEnumValN(lang_gnucxx0x, "gnu++0x",
457 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000458 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 clEnumValEnd));
460
461static llvm::cl::opt<bool>
462NoOperatorNames("fno-operator-names",
463 llvm::cl::desc("Do not treat C++ operator name keywords as "
464 "synonyms for operators"));
465
Anders Carlssonee98ac52007-10-15 02:50:23 +0000466static llvm::cl::opt<bool>
467PascalStrings("fpascal-strings",
468 llvm::cl::desc("Recognize and construct Pascal-style "
469 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000470
471static llvm::cl::opt<bool>
472MSExtensions("fms-extensions",
473 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000474 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000475
476static llvm::cl::opt<bool>
477WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000478 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000479
480static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000481NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000482 llvm::cl::desc("Disallow implicit conversions between "
483 "vectors with a different number of "
484 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000485
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000486static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000487EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
488 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
489 llvm::cl::ZeroOrMore);
490
491static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000492EnableHeinousExtensions("fheinous-gnu-extensions",
493 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
494 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
495
496static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000497ObjCNonFragileABI("fobjc-nonfragile-abi",
498 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000499
Daniel Dunbard604c402009-02-04 21:19:06 +0000500static llvm::cl::opt<bool>
501EmitAllDecls("femit-all-decls",
502 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000503
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000504// FIXME: This (and all GCC -f options) really come in -f... and
505// -fno-... forms, and additionally support automagic behavior when
506// they are not defined. For example, -fexceptions defaults to on or
507// off depending on the language. We should support this behavior in
508// some form (perhaps just add a facility for distinguishing when an
509// has its default value from when it has been set to its default
510// value).
511static llvm::cl::opt<bool>
512Exceptions("fexceptions",
513 llvm::cl::desc("Enable support for exception handling."));
514
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000515static llvm::cl::opt<bool>
516GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000517 llvm::cl::desc("Generate output compatible with the standard GNU "
518 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000519
520static llvm::cl::opt<bool>
521NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000522 llvm::cl::desc("Generate output compatible with the NeXT "
523 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000524
Ted Kremenekea644d82008-09-03 21:22:16 +0000525
526
527static llvm::cl::opt<bool>
528Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
529
530static llvm::cl::opt<bool>
531Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
532
Chris Lattner16167a62009-03-02 22:11:07 +0000533static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000534TargetFeatures("mattr", llvm::cl::CommaSeparated,
535 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
536
Douglas Gregor26dce442009-03-10 00:06:19 +0000537static llvm::cl::opt<unsigned>
538TemplateDepth("ftemplate-depth", llvm::cl::init(99),
539 llvm::cl::desc("Maximum depth of recursive template "
540 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000541
Reid Spencer5f016e22007-07-11 17:01:13 +0000542// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000543// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000544static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
545 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000546 // Allow the target to set the default the langauge options as it sees fit.
547 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000548
Chris Lattner6328cc32009-03-03 19:56:18 +0000549 // If there are any -mattr options, pass them to the target for validation and
550 // processing. The driver should have already consolidated all the
551 // target-feature settings and passed them to us in the -mattr list. The
552 // -mattr list is treated by the code generator as a diff against the -mcpu
553 // setting, but the driver should pass all enabled options as "+" settings.
554 // This means that the target should only look at + settings.
555 if (!TargetFeatures.empty()
556 // FIXME: The driver is not quite yet ready for this.
557 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000558 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000559 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
560 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000561 if (Opt != -1) {
562 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000563 fprintf(stderr, "invalid feature '%s'\n",
564 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000565 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000566 fprintf(stderr, "feature '%s': %s\n",
567 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000568 exit(1);
569 }
570 }
571
Ted Kremenekea644d82008-09-03 21:22:16 +0000572 if (Ansi) // "The -ansi option is equivalent to -std=c89."
573 LangStd = lang_c89;
574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 if (LangStd == lang_unspecified) {
576 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000577 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000578 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000580 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000582 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 case langkind_objc:
584 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000585 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 LangStd = lang_gnu99;
587 break;
588 case langkind_cxx:
589 case langkind_cxx_cpp:
Ted Kremenekab56c5d2009-03-19 18:21:42 +0000590 case langkind_cxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 case langkind_objcxx:
592 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000593 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 LangStd = lang_gnucxx98;
595 break;
596 }
597 }
598
599 switch (LangStd) {
600 default: assert(0 && "Unknown language standard!");
601
602 // Fall through from newer standards to older ones. This isn't really right.
603 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000604 case lang_gnucxx0x:
605 case lang_cxx0x:
606 Options.CPlusPlus0x = 1;
607 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 case lang_gnucxx98:
609 case lang_cxx98:
610 Options.CPlusPlus = 1;
611 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000612 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 // FALL THROUGH.
614 case lang_gnu99:
615 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 Options.C99 = 1;
617 Options.HexFloats = 1;
618 // FALL THROUGH.
619 case lang_gnu89:
620 Options.BCPLComment = 1; // Only for C99/C++.
621 // FALL THROUGH.
622 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000623 Options.Digraphs = 1; // C94, C99, C++.
624 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 case lang_c89:
626 break;
627 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000628
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000629 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
630 Options.GNUMode = LangStd >= lang_gnu_START;
631
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000632 if (Options.CPlusPlus) {
633 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000634 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000635 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000636
Chris Lattnerd658b562008-04-05 06:32:51 +0000637 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
638 Options.ImplicitInt = 1;
639 else
640 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000641
642 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
643 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000644 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000645 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000646 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000647
Chris Lattner802db9b2008-12-05 00:10:44 +0000648 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
649 // even if they are normally on for the target. In GNU modes (e.g.
650 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000651 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000652 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000653 Options.Blocks = 0;
654
Daniel Dunbar85c49102009-03-15 00:11:28 +0000655 // Never accept '$' in identifiers when preprocessing assembler.
656 if (LK != langkind_asm_cpp)
657 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000658 if (PascalStrings.getPosition())
659 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000660 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000661 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000662 if (NoLaxVectorConversions.getPosition())
663 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000664 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000665 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000666 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000667
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000668 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000669 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000670 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000671 Options.Freestanding = Options.NoBuiltin = 1;
672
Chris Lattner810f6d52009-03-13 17:38:01 +0000673 if (EnableHeinousExtensions)
674 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000675
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000676 Options.MathErrno = MathErrno;
677
Douglas Gregor26dce442009-03-10 00:06:19 +0000678 Options.InstantiationDepth = TemplateDepth;
679
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000680 // Override the default runtime if the user requested it.
681 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000682 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000683 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000684 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000685
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000686 if (ObjCNonFragileABI)
687 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000688
689 if (EmitAllDecls)
690 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000691}
692
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000693static llvm::cl::opt<bool>
694ObjCExclusiveGC("fobjc-gc-only",
695 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000696 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000697
698static llvm::cl::opt<bool>
699ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000700 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000701
702void InitializeGCMode(LangOptions &Options) {
703 if (ObjCExclusiveGC)
704 Options.setGCMode(LangOptions::GCOnly);
705 else if (ObjCEnableGC)
706 Options.setGCMode(LangOptions::HybridGC);
707}
708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000710// Target Triple Processing.
711//===----------------------------------------------------------------------===//
712
713static llvm::cl::opt<std::string>
714TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000715 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000716
Chris Lattner42e67372008-03-05 01:18:20 +0000717static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000718Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000719
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000720static llvm::cl::opt<std::string>
721MacOSVersionMin("mmacosx-version-min",
722 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
723
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000724// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
725// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
726static void HandleMacOSVersionMin(std::string &Triple) {
727 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
728 if (DarwinDashIdx == std::string::npos) {
729 fprintf(stderr,
730 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
731 exit(1);
732 }
733 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
734
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000735 // Remove the number.
736 Triple.resize(DarwinNumIdx);
737
738 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
739 bool MacOSVersionMinIsInvalid = false;
740 int VersionNum = 0;
741 if (MacOSVersionMin.size() < 4 ||
742 MacOSVersionMin.substr(0, 3) != "10." ||
743 !isdigit(MacOSVersionMin[3])) {
744 MacOSVersionMinIsInvalid = true;
745 } else {
746 const char *Start = MacOSVersionMin.c_str()+3;
747 char *End = 0;
748 VersionNum = (int)strtol(Start, &End, 10);
749
Chris Lattner079f2c462008-09-30 20:30:12 +0000750 // The version number must be in the range 0-9.
751 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
752
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000753 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
754 Triple += llvm::itostr(VersionNum+4);
755
Chris Lattner079f2c462008-09-30 20:30:12 +0000756 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
757 // Add the period piece (.7) to the end of the triple. This gives us
758 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000759 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000760 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
761 MacOSVersionMinIsInvalid = true;
762 }
763 }
764
765 if (MacOSVersionMinIsInvalid) {
766 fprintf(stderr,
767 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
768 MacOSVersionMin.c_str());
769 exit(1);
770 }
771}
772
773/// CreateTargetTriple - Process the various options that affect the target
774/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000775static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000776 // Initialize base triple. If a -triple option has been specified, use
777 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000778 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000779 if (Triple.empty()) {
780 Triple = LLVM_HOSTTRIPLE;
781
Daniel Dunbara6291902008-12-12 18:34:35 +0000782 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
783 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
784 Triple[2] == '8' && Triple[3] == '6')
785 Triple[1] = '3';
786
Daniel Dunbare553a722008-10-02 01:21:33 +0000787 // On darwin, we want to update the version to match that of the
788 // host.
789 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
790 if (DarwinDashIdx != std::string::npos) {
791 Triple.resize(DarwinDashIdx + strlen("-darwin"));
792
Daniel Dunbara6291902008-12-12 18:34:35 +0000793 // Only add the major part of the os version.
Chris Lattnera05ff452009-01-22 20:57:52 +0000794 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbara6291902008-12-12 18:34:35 +0000795 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000796 }
797 }
Ted Kremenekae360762007-12-03 22:06:55 +0000798
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000799 // If -arch foo was specified, remove the architecture from the triple we have
800 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000801 if (!Arch.empty()) {
802 // Decompose the base triple into "arch" and suffix.
803 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000804
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000805 if (FirstDashIdx == std::string::npos) {
806 fprintf(stderr,
807 "Malformed target triple: \"%s\" ('-' could not be found).\n",
808 Triple.c_str());
809 exit(1);
810 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000811
812 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
813 if (Arch == "ppc")
814 Arch = "powerpc";
815 else if (Arch == "ppc64")
816 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000817
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000818 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
819 }
820
821 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
822 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000823 if (!MacOSVersionMin.empty())
824 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000825
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000826 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000827}
828
829//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000830// Preprocessor Initialization
831//===----------------------------------------------------------------------===//
832
833// FIXME: Preprocessor builtins to support.
834// -A... - Play with #assertions
835// -undef - Undefine all predefined macros
836
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000837// FIXME: -imacros
838
Reid Spencer5f016e22007-07-11 17:01:13 +0000839static llvm::cl::list<std::string>
840D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
841 llvm::cl::desc("Predefine the specified macro"));
842static llvm::cl::list<std::string>
843U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
844 llvm::cl::desc("Undefine the specified macro"));
845
Chris Lattner64299f82008-01-10 01:53:41 +0000846static llvm::cl::list<std::string>
847ImplicitIncludes("include", llvm::cl::value_desc("file"),
848 llvm::cl::desc("Include file before parsing"));
849
Ted Kremenek748d5d62009-03-20 00:26:38 +0000850static llvm::cl::opt<std::string>
851ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
852 llvm::cl::desc("Include file before parsing"));
853
Reid Spencer5f016e22007-07-11 17:01:13 +0000854// Append a #define line to Buf for Macro. Macro should be of the form XXX,
855// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
856// "#define XXX Y z W". To get a #define with no value, use "XXX=".
857static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
858 const char *Command = "#define ") {
859 Buf.insert(Buf.end(), Command, Command+strlen(Command));
860 if (const char *Equal = strchr(Macro, '=')) {
861 // Turn the = into ' '.
862 Buf.insert(Buf.end(), Macro, Equal);
863 Buf.push_back(' ');
864 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
865 } else {
866 // Push "macroname 1".
867 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
868 Buf.push_back(' ');
869 Buf.push_back('1');
870 }
871 Buf.push_back('\n');
872}
873
Chris Lattner64299f82008-01-10 01:53:41 +0000874/// AddImplicitInclude - Add an implicit #include of the specified file to the
875/// predefines buffer.
876static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
877 const char *Inc = "#include \"";
878 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
879 Buf.insert(Buf.end(), File.begin(), File.end());
880 Buf.push_back('"');
881 Buf.push_back('\n');
882}
883
Ted Kremenek748d5d62009-03-20 00:26:38 +0000884/// AddImplicitIncludePTH - Add an implicit #include using the original file
885/// used to generate a PTH cache.
886static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
887 PTHManager *P = PP.getPTHManager();
888 assert(P && "No PTHManager.");
889 const char *OriginalFile = P->getOriginalSourceFile();
890
891 if (!OriginalFile) {
892 assert(!ImplicitIncludePTH.empty());
893 fprintf(stderr, "error: PTH file '%s' does not designate an original "
894 "source header file for -include-pth\n",
895 ImplicitIncludePTH.c_str());
896 exit (1);
897 }
898
899 AddImplicitInclude(Buf, OriginalFile);
900}
Reid Spencer5f016e22007-07-11 17:01:13 +0000901
Chris Lattner53b0dab2007-10-09 22:10:18 +0000902/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000903/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000904///
Chris Lattner51574ea2008-04-19 23:25:44 +0000905static bool InitializePreprocessor(Preprocessor &PP,
906 bool InitializeSourceMgr,
907 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000908 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000909
Chris Lattner53b0dab2007-10-09 22:10:18 +0000910 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000911 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000912
913 if (InitializeSourceMgr) {
914 if (InFile != "-") {
915 const FileEntry *File = FileMgr.getFile(InFile);
916 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000917 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000918 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
919 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +0000920 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000921 }
922 } else {
923 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +0000924
925 // If stdin was empty, SB is null. Cons up an empty memory
926 // buffer now.
927 if (!SB) {
928 const char *EmptyStr = "";
929 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
930 }
931
932 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000933 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000934 PP.getDiagnostics().Report(FullSourceLoc(),
935 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +0000936 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000937 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000938 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000940
Chris Lattneraa391972008-04-19 23:09:31 +0000941 std::vector<char> PredefineBuffer;
942
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000944 unsigned d = 0, D = D_macros.size();
945 unsigned u = 0, U = U_macros.size();
946 while (d < D || u < U) {
947 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
948 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
949 else
950 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
951 }
952
Chris Lattner64299f82008-01-10 01:53:41 +0000953 // FIXME: Read any files specified by -imacros.
954
Ted Kremenek748d5d62009-03-20 00:26:38 +0000955 // Add implicit #includes from -include and -include-pth.
956 bool handledPTH = ImplicitIncludePTH.empty();
957 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +0000958 if (!handledPTH &&
959 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +0000960 AddImplicitIncludePTH(PredefineBuffer, PP);
961 handledPTH = true;
962 }
963
Chris Lattner64299f82008-01-10 01:53:41 +0000964 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +0000965 }
966 if (!handledPTH && !ImplicitIncludePTH.empty())
967 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000968
Chris Lattneraa391972008-04-19 23:09:31 +0000969 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000970 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000971 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000972
973 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000974 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000975}
976
977//===----------------------------------------------------------------------===//
978// Preprocessor include path information.
979//===----------------------------------------------------------------------===//
980
981// This tool exports a large number of command line options to control how the
982// preprocessor searches for header files. At root, however, the Preprocessor
983// object takes a very simple interface: a list of directories to search for
984//
985// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000986// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000987//
Reid Spencer5f016e22007-07-11 17:01:13 +0000988
989static llvm::cl::opt<bool>
990nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
991
992// Various command line options. These four add directories to each chain.
993static llvm::cl::list<std::string>
994F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
995 llvm::cl::desc("Add directory to framework include search path"));
996static llvm::cl::list<std::string>
997I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
998 llvm::cl::desc("Add directory to include search path"));
999static llvm::cl::list<std::string>
1000idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1001 llvm::cl::desc("Add directory to AFTER include search path"));
1002static llvm::cl::list<std::string>
1003iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1004 llvm::cl::desc("Add directory to QUOTE include search path"));
1005static llvm::cl::list<std::string>
1006isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1007 llvm::cl::desc("Add directory to SYSTEM include search path"));
1008
1009// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1010static llvm::cl::list<std::string>
1011iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1012 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1013static llvm::cl::list<std::string>
1014iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1015 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1016static llvm::cl::list<std::string>
1017iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1018 llvm::cl::Prefix,
1019 llvm::cl::desc("Set directory to include search path with prefix"));
1020
Chris Lattner0c946412007-08-26 17:47:35 +00001021static llvm::cl::opt<std::string>
1022isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1023 llvm::cl::desc("Set the system root directory (usually /)"));
1024
Reid Spencer5f016e22007-07-11 17:01:13 +00001025// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001026
Reid Spencer5f016e22007-07-11 17:01:13 +00001027/// InitializeIncludePaths - Process the -I options and set them in the
1028/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001029void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1030 FileManager &FM, const LangOptions &Lang) {
1031 InitHeaderSearch Init(Headers, Verbose, isysroot);
1032
Ted Kremenekf3721112008-05-31 00:27:00 +00001033 // Handle -I... and -F... options, walking the lists in parallel.
1034 unsigned Iidx = 0, Fidx = 0;
1035 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1036 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001037 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001038 ++Iidx;
1039 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001040 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001041 ++Fidx;
1042 }
1043 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001044
Ted Kremenekf3721112008-05-31 00:27:00 +00001045 // Consume what's left from whatever list was longer.
1046 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001047 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001048 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001049 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001050
1051 // Handle -idirafter... options.
1052 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001053 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1054 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001055
1056 // Handle -iquote... options.
1057 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001058 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001059
1060 // Handle -isystem... options.
1061 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001062 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001063
1064 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1065 // parallel, processing the values in order of occurance to get the right
1066 // prefixes.
1067 {
1068 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1069 unsigned iprefix_idx = 0;
1070 unsigned iwithprefix_idx = 0;
1071 unsigned iwithprefixbefore_idx = 0;
1072 bool iprefix_done = iprefix_vals.empty();
1073 bool iwithprefix_done = iwithprefix_vals.empty();
1074 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1075 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1076 if (!iprefix_done &&
1077 (iwithprefix_done ||
1078 iprefix_vals.getPosition(iprefix_idx) <
1079 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1080 (iwithprefixbefore_done ||
1081 iprefix_vals.getPosition(iprefix_idx) <
1082 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1083 Prefix = iprefix_vals[iprefix_idx];
1084 ++iprefix_idx;
1085 iprefix_done = iprefix_idx == iprefix_vals.size();
1086 } else if (!iwithprefix_done &&
1087 (iwithprefixbefore_done ||
1088 iwithprefix_vals.getPosition(iwithprefix_idx) <
1089 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001090 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1091 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 ++iwithprefix_idx;
1093 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1094 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001095 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1096 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 ++iwithprefixbefore_idx;
1098 iwithprefixbefore_done =
1099 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1100 }
1101 }
1102 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001103
Nico Weber0fca0222008-08-22 09:25:22 +00001104 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001105
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001106 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001107 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001108 llvm::sys::Path::GetMainExecutable(Argv0,
1109 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001110 if (!MainExecutablePath.isEmpty()) {
1111 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1112 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001113
1114 // Get foo/lib/clang/1.0/include
1115 //
1116 // FIXME: Don't embed version here.
1117 MainExecutablePath.appendComponent("lib");
1118 MainExecutablePath.appendComponent("clang");
1119 MainExecutablePath.appendComponent("1.0");
1120 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001121
1122 // We pass true to ignore sysroot so that we *always* look for clang headers
1123 // relative to our executable, never relative to -isysroot.
1124 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1125 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001126 }
1127
Nico Weber0fca0222008-08-22 09:25:22 +00001128 if (!nostdinc)
1129 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001130
1131 // Now that we have collected all of the include paths, merge them all
1132 // together and tell the preprocessor about them.
1133
Nico Weber0fca0222008-08-22 09:25:22 +00001134 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001135}
1136
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001137//===----------------------------------------------------------------------===//
1138// Driver PreprocessorFactory - For lazily generating preprocessors ...
1139//===----------------------------------------------------------------------===//
1140
1141namespace {
1142class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001143 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001144 Diagnostic &Diags;
1145 const LangOptions &LangInfo;
1146 TargetInfo &Target;
1147 SourceManager &SourceMgr;
1148 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001149 bool InitializeSourceMgr;
1150
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001151public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001152 DriverPreprocessorFactory(const std::string &infile,
1153 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001154 TargetInfo &target, SourceManager &SM,
1155 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001156 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1157 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1158
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001159
1160 virtual ~DriverPreprocessorFactory() {}
1161
1162 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001163 llvm::OwningPtr<PTHManager> PTHMgr;
1164
Ted Kremenek748d5d62009-03-20 00:26:38 +00001165 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1166 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1167 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001168 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001169 }
1170
Ted Kremenek72b1b152009-01-15 18:47:46 +00001171 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001172 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1173 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001174 PTHMgr.reset(PTHManager::Create(x, &Diags,
1175 TokenCache.empty() ? Diagnostic::Error
1176 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001177 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001178
Ted Kremenek22f0d092009-03-22 06:42:39 +00001179 if (Diags.hasErrorOccurred())
1180 exit(1);
1181
Ted Kremenek72b1b152009-01-15 18:47:46 +00001182 // Create the Preprocessor.
1183 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1184 SourceMgr, HeaderInfo,
1185 PTHMgr.get()));
1186
1187 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1188 // That argument is used as the IdentifierInfoLookup argument to
1189 // IdentifierTable's ctor.
1190 if (PTHMgr) {
1191 PTHMgr->setPreprocessor(PP.get());
1192 PP->setPTHManager(PTHMgr.take());
1193 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001194
Chris Lattner51574ea2008-04-19 23:25:44 +00001195 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001196 return NULL;
1197 }
1198
Daniel Dunbar750c3582008-10-24 22:12:41 +00001199 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001200 if (ProgAction != PrintPreprocessedInput) {
1201 std::string ErrStr;
1202 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1203 if (!DFG && !ErrStr.empty()) {
1204 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001205 return NULL;
1206 }
1207 }
1208
Ted Kremenek339b9c22008-04-17 22:31:54 +00001209 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001210 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001211 }
1212};
1213}
Reid Spencer5f016e22007-07-11 17:01:13 +00001214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215//===----------------------------------------------------------------------===//
1216// Basic Parser driver
1217//===----------------------------------------------------------------------===//
1218
Chris Lattner51574ea2008-04-19 23:25:44 +00001219static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001221 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001222
1223 // Parsing the specified input file.
1224 P.ParseTranslationUnit();
1225 delete PA;
1226}
1227
1228//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001229// Code generation options
1230//===----------------------------------------------------------------------===//
1231
1232static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001233GenerateDebugInfo("g",
1234 llvm::cl::desc("Generate source level debug information"));
1235
1236static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001237OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001238
Chris Lattnerbd360642009-03-26 05:00:52 +00001239static llvm::cl::opt<bool>
1240NoCommon("fno-common",
Mike Stump1c9b7422009-03-27 20:15:22 +00001241 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner925a7042009-03-28 02:12:08 +00001242 llvm::cl::ValueDisallowed);
Chris Lattnerbd360642009-03-26 05:00:52 +00001243
Daniel Dunbar70f92432008-10-23 05:50:47 +00001244// It might be nice to add bounds to the CommandLine library directly.
1245struct OptLevelParser : public llvm::cl::parser<unsigned> {
1246 bool parse(llvm::cl::Option &O, const char *ArgName,
1247 const std::string &Arg, unsigned &Val) {
1248 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1249 return true;
1250 // FIXME: Support -O4.
1251 if (Val > 3)
1252 return O.error(": '" + Arg + "' invalid optimization level!");
1253 return false;
1254 }
1255};
1256static llvm::cl::opt<unsigned, false, OptLevelParser>
1257OptLevel("O", llvm::cl::Prefix,
1258 llvm::cl::desc("Optimization level"),
1259 llvm::cl::init(0));
1260
Daniel Dunbara034ba82009-02-17 19:47:34 +00001261static llvm::cl::opt<std::string>
1262TargetCPU("mcpu",
1263 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1264
Chris Lattner7afae712009-03-16 18:41:18 +00001265static void InitializeCompileOptions(CompileOptions &Opts,
1266 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001267 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001268 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001269 if (OptSize) {
1270 // -Os implies -O2
1271 // FIXME: Diagnose conflicting options.
1272 Opts.OptimizationLevel = 2;
1273 } else {
1274 Opts.OptimizationLevel = OptLevel;
1275 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001276
1277 // FIXME: There are llvm-gcc options to control these selectively.
1278 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1279 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001280 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001281
1282#ifdef NDEBUG
1283 Opts.VerifyModule = 0;
1284#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001285
1286 Opts.CPU = TargetCPU;
1287 Opts.Features.insert(Opts.Features.end(),
1288 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001289
Chris Lattnerbd360642009-03-26 05:00:52 +00001290 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1291
Chris Lattner44502662009-02-18 01:23:44 +00001292 // Handle -ftime-report.
1293 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001294}
1295
1296//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001297// Main driver
1298//===----------------------------------------------------------------------===//
1299
Ted Kremenekdb094a22007-12-05 18:27:04 +00001300/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001301/// action. These consumers can operate on both ASTs that are freshly
1302/// parsed from source files as well as those deserialized from Bitcode.
1303/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001304static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001305 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001306 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001307 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001308 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001309 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001310 default:
1311 return NULL;
1312
1313 case ASTPrint:
1314 return CreateASTPrinter();
1315
1316 case ASTDump:
1317 return CreateASTDumper();
1318
1319 case ASTView:
1320 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001321
Chris Lattner8a5c8092009-02-18 01:20:05 +00001322 case PrintDeclContext:
1323 return CreateDeclContextPrinter();
1324
1325 case EmitHTML:
1326 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001327
Chris Lattner8a5c8092009-02-18 01:20:05 +00001328 case InheritanceView:
1329 return CreateInheritanceViewer(InheritanceViewCls);
1330
1331 case TestSerialization:
1332 return CreateSerializationTest(Diag, FileMgr);
1333
1334 case EmitAssembly:
1335 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001336 case EmitBC:
1337 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001338 BackendAction Act;
1339 if (ProgAction == EmitAssembly)
1340 Act = Backend_EmitAssembly;
1341 else if (ProgAction == EmitLLVM)
1342 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001343 else if (ProgAction == EmitLLVMOnly)
1344 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001345 else
1346 Act = Backend_EmitBC;
1347
1348 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001349 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001350 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001351 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001352 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001353
Chris Lattner8a5c8092009-02-18 01:20:05 +00001354 case SerializeAST:
1355 // FIXME: Allow user to tailor where the file is written.
1356 return CreateASTSerializer(InFile, OutputFile, Diag);
1357
1358 case RewriteObjC:
1359 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001360
Chris Lattner8a5c8092009-02-18 01:20:05 +00001361 case RewriteBlocks:
1362 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1363
1364 case RunAnalysis:
1365 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001366 }
1367}
1368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369/// ProcessInputFile - Process a single input file with the specified state.
1370///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001371static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001372 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001373 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001374 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001375
Ted Kremenek85888962008-10-21 00:54:44 +00001376 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001378 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1379 PP.getFileManager(), PP.getLangOptions(),
1380 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001381
1382 if (!Consumer) {
1383 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001384 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001385 return;
1386 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001387
Ted Kremenekdb094a22007-12-05 18:27:04 +00001388 break;
1389
Chris Lattnerc106c102008-10-12 05:03:36 +00001390 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001391 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001392 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001393 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001394 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001395 RawLex.SetKeepWhitespaceMode(true);
1396
1397 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001398 RawLex.LexFromRawLexer(RawTok);
1399 while (RawTok.isNot(tok::eof)) {
1400 PP.DumpToken(RawTok, true);
1401 fprintf(stderr, "\n");
1402 RawLex.LexFromRawLexer(RawTok);
1403 }
1404 ClearSourceMgr = true;
1405 break;
1406 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001408 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001409 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001410 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001411 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 do {
1413 PP.Lex(Tok);
1414 PP.DumpToken(Tok, true);
1415 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001416 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001417 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 break;
1419 }
1420 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001421 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001422 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001424 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 do {
1426 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001427 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001428 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 break;
1430 }
Ted Kremenek85888962008-10-21 00:54:44 +00001431
1432 case GeneratePCH: {
Chris Lattner47099742009-02-18 01:51:21 +00001433 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001434 CacheTokens(PP, OutputFile);
1435 ClearSourceMgr = true;
1436 break;
1437 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001438
Chris Lattner47099742009-02-18 01:51:21 +00001439 case PrintPreprocessedInput: { // -E mode.
1440 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001441 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001442 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001443 break;
Chris Lattner47099742009-02-18 01:51:21 +00001444 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001445
Chris Lattner47099742009-02-18 01:51:21 +00001446 case ParseNoop: { // -parse-noop
1447 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001448 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001449 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 break;
Chris Lattner47099742009-02-18 01:51:21 +00001451 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001452
Chris Lattner47099742009-02-18 01:51:21 +00001453 case ParsePrintCallbacks: {
1454 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001455 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001456 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 break;
Chris Lattner47099742009-02-18 01:51:21 +00001458 }
1459
1460 case ParseSyntaxOnly: { // -fsyntax-only
1461 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001462 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001463 break;
Chris Lattner47099742009-02-18 01:51:21 +00001464 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001465
1466 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001467 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001468 ClearSourceMgr = true;
1469 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001470
Chris Lattner47099742009-02-18 01:51:21 +00001471 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001472 DoRewriteTest(PP, InFile, OutputFile);
1473 ClearSourceMgr = true;
1474 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001475 }
Chris Lattner47099742009-02-18 01:51:21 +00001476 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001477
1478 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001479 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001480
1481 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1482 PP.getSourceManager(),
1483 PP.getTargetInfo(),
1484 PP.getIdentifierTable(),
1485 PP.getSelectorTable(),
1486 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001487
1488
Chris Lattner3599dbe2009-03-28 04:13:34 +00001489 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001490
1491 // If in -disable-free mode, don't deallocate these when they go out of
1492 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001493 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001494 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001495 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001496
1497 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001498 if (CheckDiagnostics(PP))
1499 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001500
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001502 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 PP.PrintStats();
1504 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001505 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001506 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 fprintf(stderr, "\n");
1508 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001509
1510 // For a multi-file compilation, some things are ok with nuking the source
1511 // manager tables, other require stable fileid/macroid's across multiple
1512 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001513 if (ClearSourceMgr)
1514 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001515
1516 if (DisableFree)
1517 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001518}
1519
Ted Kremenek20e97482007-12-12 23:41:08 +00001520static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1521 FileManager& FileMgr) {
1522
1523 if (VerifyDiagnostics) {
1524 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1525 exit (1);
1526 }
1527
1528 llvm::sys::Path Filename(InFile);
1529
1530 if (!Filename.isValid()) {
1531 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1532 exit (1);
1533 }
1534
Chris Lattner557c5b12009-03-28 04:27:18 +00001535 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001536
1537 // Create the memory buffer that contains the contents of the file.
1538 llvm::OwningPtr<llvm::MemoryBuffer>
1539 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1540
1541 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001542 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001543
Chris Lattner557c5b12009-03-28 04:27:18 +00001544 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001545 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1546 InFile.c_str());
1547 exit (1);
1548 }
1549
Ted Kremenek63ea8632007-12-19 19:27:38 +00001550 // Observe that we use the source file name stored in the deserialized
1551 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001552 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001553 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001554 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001555
Ted Kremenek20e97482007-12-12 23:41:08 +00001556 if (!Consumer) {
1557 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1558 exit (1);
1559 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001560
Chris Lattner557c5b12009-03-28 04:27:18 +00001561 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001562
Chris Lattnere66b65c2008-02-06 01:42:25 +00001563 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001564 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1565 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1566 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001567 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001568}
1569
1570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571static llvm::cl::list<std::string>
1572InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1573
Ted Kremenek20e97482007-12-12 23:41:08 +00001574static bool isSerializedFile(const std::string& InFile) {
1575 if (InFile.size() < 4)
1576 return false;
1577
1578 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001579 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001580}
1581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582
1583int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001585 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001586 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001587 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001588
Chris Lattner47099742009-02-18 01:51:21 +00001589 if (TimeReport)
1590 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1591
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 // If no input was specified, read from stdin.
1593 if (InputFilenames.empty())
1594 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001595
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 // Create a file manager object to provide access to and cache the filesystem.
1597 FileManager FileMgr;
1598
Ted Kremenek31e703b2007-12-11 23:28:38 +00001599 // Create the diagnostic client for reporting errors or for
1600 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001601 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001602
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001603 if (!VerifyDiagnostics) {
1604 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001605 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1606 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001607 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001608 !NoShowLocation,
1609 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001610 } else {
1611 // When checking diagnostics, just buffer them up.
1612 TextDiagClient = new TextDiagnosticBuffer();
1613
1614 if (InputFilenames.size() != 1) {
1615 fprintf(stderr,
1616 "-verify only works on single input files for now.\n");
1617 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 }
1619 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001620
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001622 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1623 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001624 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001625 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001626
Chris Lattner4f037832007-12-05 23:24:17 +00001627 // -I- is a deprecated GCC feature, scan for it and reject it.
1628 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1629 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001630 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001631 I_dirs.erase(I_dirs.begin()+i);
1632 --i;
1633 }
1634 }
Chris Lattner11215192008-03-14 06:12:05 +00001635
1636 // Get information about the target being compiled for.
1637 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001638 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1639
Chris Lattner11215192008-03-14 06:12:05 +00001640 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001641 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1642 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001643 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001644 }
Chris Lattner4f037832007-12-05 23:24:17 +00001645
Daniel Dunbard4270232009-01-20 23:17:32 +00001646 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001647 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001648
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001649 llvm::OwningPtr<SourceManager> SourceMgr;
1650
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001652 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001653
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001654 if (isSerializedFile(InFile)) {
1655 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001656 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001657 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001658 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001659
1660 /// Create a SourceManager object. This tracks and owns all the file
1661 /// buffers allocated to a translation unit.
1662 if (!SourceMgr)
1663 SourceMgr.reset(new SourceManager());
1664 else
1665 SourceMgr->clearIDTables();
1666
1667 // Initialize language options, inferring file types from input filenames.
1668 LangOptions LangInfo;
1669 InitializeBaseLanguage();
1670 LangKind LK = GetLanguage(InFile);
1671 bool PCH = InitializeLangOptions(LangInfo, LK);
1672 InitializeGCMode(LangInfo);
1673 InitializeLanguageStandard(LangInfo, LK, Target.get());
1674
1675 // Process the -I options and set them in the HeaderInfo.
1676 HeaderSearch HeaderInfo(FileMgr);
1677
1678 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1679
1680 // Set up the preprocessor with these options.
1681 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1682 *SourceMgr.get(), HeaderInfo);
1683
1684 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1685
1686 if (!PP)
1687 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001688
Chris Lattnerf63aea32009-03-04 21:40:56 +00001689 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1690 // always reset to using TextDiagClient.
1691 llvm::OwningPtr<DiagnosticClient> TmpClient;
1692
1693 if (!HTMLDiag.empty()) {
1694 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1695 &PPFactory));
1696 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001697 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001698 else
1699 Diags.setClient(TextDiagClient);
1700
1701 // Process the source file.
1702 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1703
1704 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 }
Chris Lattner11215192008-03-14 06:12:05 +00001706
Mike Stump007f2a92009-01-28 02:43:35 +00001707 if (Verbose)
1708 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1709 " hosted on " LLVM_HOSTTRIPLE "\n");
1710
Ted Kremenek7a08e282008-08-07 18:13:12 +00001711 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1713 (NumDiagnostics == 1 ? "" : "s"));
1714
1715 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 FileMgr.PrintStats();
1717 fprintf(stderr, "\n");
1718 }
1719
Daniel Dunbar276373d2008-10-27 22:10:13 +00001720 // If verifying diagnostics and we reached here, all is well.
1721 if (VerifyDiagnostics)
1722 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001723
1724 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001725
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001726 // Managed static deconstruction. Useful for making things like
1727 // -time-passes usable.
1728 llvm::llvm_shutdown();
1729
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001730 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001731}