blob: d5c44cd078edba71f6bb79e348afef4da8677f79 [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"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000051#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000053#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000054#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000055#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000056#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000057#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000058#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000059#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000060#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000061#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000062#include <cstdlib>
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064using namespace clang;
65
66//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000067// Source Location Parser
68//===----------------------------------------------------------------------===//
69
70/// \brief A source location that has been parsed on the command line.
71struct ParsedSourceLocation {
72 std::string FileName;
73 unsigned Line;
74 unsigned Column;
75
76 /// \brief Try to resolve the file name of a parsed source location.
77 ///
78 /// \returns true if there was an error, false otherwise.
79 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
80};
81
82bool
83ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
84 RequestedSourceLocation &Result) {
85 const FileEntry *File = FileMgr.getFile(FileName);
86 if (!File)
87 return true;
88
89 Result.File = File;
90 Result.Line = Line;
91 Result.Column = Column;
92 return false;
93}
94
95namespace llvm {
96 namespace cl {
97 /// \brief Command-line option parser that parses source locations.
98 ///
99 /// Source locations are of the form filename:line:column.
100 template<>
101 class parser<ParsedSourceLocation>
102 : public basic_parser<ParsedSourceLocation> {
103 public:
104 bool parse(Option &O, const char *ArgName,
105 const std::string &ArgValue,
106 ParsedSourceLocation &Val);
107 };
108
109 bool
110 parser<ParsedSourceLocation>::
111 parse(Option &O, const char *ArgName, const std::string &ArgValue,
112 ParsedSourceLocation &Val) {
113 using namespace clang;
114
115 const char *ExpectedFormat
116 = "source location must be of the form filename:line:column";
117 std::string::size_type SecondColon = ArgValue.rfind(':');
118 if (SecondColon == std::string::npos) {
119 std::fprintf(stderr, "%s\n", ExpectedFormat);
120 return true;
121 }
122 char *EndPtr;
123 long Column
124 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
125 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
126 std::fprintf(stderr, "%s\n", ExpectedFormat);
127 return true;
128 }
129
130 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
131 if (SecondColon == std::string::npos) {
132 std::fprintf(stderr, "%s\n", ExpectedFormat);
133 return true;
134 }
135 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
136 if (EndPtr != ArgValue.c_str() + SecondColon) {
137 std::fprintf(stderr, "%s\n", ExpectedFormat);
138 return true;
139 }
140
141 Val.FileName = ArgValue.substr(0, FirstColon);
142 Val.Line = Line;
143 Val.Column = Column;
144 return false;
145 }
146 }
147}
148
149//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000150// Global options.
151//===----------------------------------------------------------------------===//
152
Chris Lattner47099742009-02-18 01:51:21 +0000153/// ClangFrontendTimer - The front-end activities should charge time to it with
154/// TimeRegion. The -ftime-report option controls whether this will do
155/// anything.
156llvm::Timer *ClangFrontendTimer = 0;
157
Daniel Dunbard3db4012008-10-16 16:54:18 +0000158static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000159
Reid Spencer5f016e22007-07-11 17:01:13 +0000160static llvm::cl::opt<bool>
161Verbose("v", llvm::cl::desc("Enable verbose output"));
162static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000163Stats("print-stats",
164 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000165static llvm::cl::opt<bool>
166DisableFree("disable-free",
167 llvm::cl::desc("Disable freeing of memory on exit"),
168 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +0000169
170enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000171 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000172 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000173 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000174 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000175 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000176 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000177 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000179 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000180 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000181 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +0000182 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000183 ASTPrint, // Parse ASTs and print them.
184 ASTDump, // Parse ASTs and dump them.
185 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000186 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000187 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 ParsePrintCallbacks, // Parse and print each callback.
189 ParseSyntaxOnly, // Parse and perform semantic analysis.
190 ParseNoop, // Parse with noop callbacks.
191 RunPreprocessorOnly, // Just lex, no output.
192 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000193 DumpTokens, // Dump out preprocessed tokens.
194 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000195 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000196 GeneratePTH, // Generate pre-tokenized header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000197 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000198};
199
200static llvm::cl::opt<ProgActions>
201ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
202 llvm::cl::init(ParseSyntaxOnly),
203 llvm::cl::values(
204 clEnumValN(RunPreprocessorOnly, "Eonly",
205 "Just run preprocessor, no output (for timings)"),
206 clEnumValN(PrintPreprocessedInput, "E",
207 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000208 clEnumValN(DumpRawTokens, "dump-raw-tokens",
209 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000210 clEnumValN(RunAnalysis, "analyze",
211 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000212 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 "Run preprocessor, dump internal rep of tokens"),
214 clEnumValN(ParseNoop, "parse-noop",
215 "Run parser with noop callbacks (for timings)"),
216 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
217 "Run parser and perform semantic analysis"),
218 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
219 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000220 clEnumValN(EmitHTML, "emit-html",
221 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000222 clEnumValN(ASTPrint, "ast-print",
223 "Build ASTs and then pretty-print them"),
224 clEnumValN(ASTDump, "ast-dump",
225 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000226 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000227 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000228 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000229 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000230 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000231 "Generate pre-tokenized header file"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000232 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000233 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000234 clEnumValN(EmitAssembly, "S",
235 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000237 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000238 clEnumValN(EmitBC, "emit-llvm-bc",
239 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000240 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
241 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000242 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000243 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000244 clEnumValN(RewriteTest, "rewrite-test",
245 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000246 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000247 "Rewrite ObjC into C (code rewriter example)"),
248 clEnumValN(RewriteMacros, "rewrite-macros",
249 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000250 clEnumValN(RewriteBlocks, "rewrite-blocks",
251 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000252 clEnumValN(FixIt, "fixit",
253 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 clEnumValEnd));
255
Ted Kremenekccc76472007-12-19 19:47:59 +0000256
257static llvm::cl::opt<std::string>
258OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000259 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000260 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000261
Ted Kremenekc2e72992008-12-02 19:57:31 +0000262
263//===----------------------------------------------------------------------===//
264// PTH.
265//===----------------------------------------------------------------------===//
266
267static llvm::cl::opt<std::string>
268TokenCache("token-cache", llvm::cl::value_desc("path"),
269 llvm::cl::desc("Use specified token cache file"));
270
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000271//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000272// Diagnostic Options
273//===----------------------------------------------------------------------===//
274
Ted Kremenek41193e42007-09-26 19:42:19 +0000275static llvm::cl::opt<bool>
276VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000277 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000278
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000279static llvm::cl::opt<std::string>
280HTMLDiag("html-diags",
281 llvm::cl::desc("Generate HTML to report diagnostics"),
282 llvm::cl::value_desc("HTML directory"));
283
Nico Weberfd54ebc2008-08-05 23:33:20 +0000284static llvm::cl::opt<bool>
285NoShowColumn("fno-show-column",
286 llvm::cl::desc("Do not include column number on diagnostics"));
287
288static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000289NoShowLocation("fno-show-source-location",
290 llvm::cl::desc("Do not include source location information with"
291 " diagnostics"));
292
293static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000294NoCaretDiagnostics("fno-caret-diagnostics",
295 llvm::cl::desc("Do not include source line and caret with"
296 " diagnostics"));
297
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000298static llvm::cl::opt<bool>
299PrintSourceRangeInfo("fprint-source-range-info",
300 llvm::cl::desc("Print source range spans in numeric form"));
301
Nico Weberfd54ebc2008-08-05 23:33:20 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000304// C++ Visualization.
305//===----------------------------------------------------------------------===//
306
307static llvm::cl::opt<std::string>
308InheritanceViewCls("cxx-inheritance-view",
309 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000310 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000311
312//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000313// Builtin Options
314//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000315
316static llvm::cl::opt<bool>
317TimeReport("ftime-report",
318 llvm::cl::desc("Print the amount of time each "
319 "phase of compilation takes"));
320
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000321static llvm::cl::opt<bool>
322Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000323 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000324 "freestanding environment"));
325
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000326static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000327AllowBuiltins("fbuiltin", llvm::cl::init(true),
328 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000329
330
331static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000332MathErrno("fmath-errno", llvm::cl::init(true),
333 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000334
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000335//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000336// Language Options
337//===----------------------------------------------------------------------===//
338
339enum LangKind {
340 langkind_unspecified,
341 langkind_c,
342 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000343 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 langkind_cxx,
345 langkind_cxx_cpp,
346 langkind_objc,
347 langkind_objc_cpp,
348 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000349 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000350};
351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352static llvm::cl::opt<LangKind>
353BaseLang("x", llvm::cl::desc("Base language to compile"),
354 llvm::cl::init(langkind_unspecified),
355 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
356 clEnumValN(langkind_cxx, "c++", "C++"),
357 clEnumValN(langkind_objc, "objective-c", "Objective C"),
358 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000359 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000361 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
362 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000364 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
366 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000367 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000369 clEnumValN(langkind_c, "c-header",
370 "C header"),
371 clEnumValN(langkind_objc, "objective-c-header",
372 "Objective-C header"),
373 clEnumValN(langkind_cxx, "c++-header",
374 "C++ header"),
375 clEnumValN(langkind_objcxx, "objective-c++-header",
376 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 clEnumValEnd));
378
379static llvm::cl::opt<bool>
380LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
381 llvm::cl::Hidden);
382static llvm::cl::opt<bool>
383LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
384 llvm::cl::Hidden);
385
Ted Kremenek8904f152007-12-05 23:49:08 +0000386/// InitializeBaseLanguage - Handle the -x foo options.
387static void InitializeBaseLanguage() {
388 if (LangObjC)
389 BaseLang = langkind_objc;
390 else if (LangObjCXX)
391 BaseLang = langkind_objcxx;
392}
393
394static LangKind GetLanguage(const std::string &Filename) {
395 if (BaseLang != langkind_unspecified)
396 return BaseLang;
397
398 std::string::size_type DotPos = Filename.rfind('.');
399
400 if (DotPos == std::string::npos) {
401 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000402 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 }
404
Ted Kremenek8904f152007-12-05 23:49:08 +0000405 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
406 // C header: .h
407 // C++ header: .hh or .H;
408 // assembler no preprocessing: .s
409 // assembler: .S
410 if (Ext == "c")
411 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000412 else if (Ext == "S" ||
413 // If the compiler is run on a .s file, preprocess it as .S
414 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000415 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000416 else if (Ext == "i")
417 return langkind_c_cpp;
418 else if (Ext == "ii")
419 return langkind_cxx_cpp;
420 else if (Ext == "m")
421 return langkind_objc;
422 else if (Ext == "mi")
423 return langkind_objc_cpp;
424 else if (Ext == "mm" || Ext == "M")
425 return langkind_objcxx;
426 else if (Ext == "mii")
427 return langkind_objcxx_cpp;
428 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
429 Ext == "c++" || Ext == "cp" || Ext == "cxx")
430 return langkind_cxx;
431 else
432 return langkind_c;
433}
434
435
Ted Kremenek85888962008-10-21 00:54:44 +0000436static void InitializeCOptions(LangOptions &Options) {
437 // Do nothing.
438}
439
440static void InitializeObjCOptions(LangOptions &Options) {
441 Options.ObjC1 = Options.ObjC2 = 1;
442}
443
444
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000445static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // FIXME: implement -fpreprocessed mode.
447 bool NoPreprocess = false;
448
Ted Kremenek8904f152007-12-05 23:49:08 +0000449 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000451 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000452 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000453 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 case langkind_c_cpp:
455 NoPreprocess = true;
456 // FALLTHROUGH
457 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000458 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 break;
460 case langkind_cxx_cpp:
461 NoPreprocess = true;
462 // FALLTHROUGH
463 case langkind_cxx:
464 Options.CPlusPlus = 1;
465 break;
466 case langkind_objc_cpp:
467 NoPreprocess = true;
468 // FALLTHROUGH
469 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000470 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 break;
472 case langkind_objcxx_cpp:
473 NoPreprocess = true;
474 // FALLTHROUGH
475 case langkind_objcxx:
476 Options.ObjC1 = Options.ObjC2 = 1;
477 Options.CPlusPlus = 1;
478 break;
479 }
480}
481
482/// LangStds - Language standards we support.
483enum LangStds {
484 lang_unspecified,
485 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000486 lang_gnu_START,
487 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000488 lang_cxx98, lang_gnucxx98,
489 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000490};
491
492static llvm::cl::opt<LangStds>
493LangStd("std", llvm::cl::desc("Language standard to compile for"),
494 llvm::cl::init(lang_unspecified),
495 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
496 clEnumValN(lang_c89, "c90", "ISO C 1990"),
497 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
498 clEnumValN(lang_c94, "iso9899:199409",
499 "ISO C 1990 with amendment 1"),
500 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000501 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000503 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000505 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000507 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 clEnumValN(lang_gnu99, "gnu9x",
509 "ISO C 1999 with GNU extensions"),
510 clEnumValN(lang_cxx98, "c++98",
511 "ISO C++ 1998 with amendments"),
512 clEnumValN(lang_gnucxx98, "gnu++98",
513 "ISO C++ 1998 with amendments and GNU "
514 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000515 clEnumValN(lang_cxx0x, "c++0x",
516 "Upcoming ISO C++ 200x with amendments"),
517 clEnumValN(lang_gnucxx0x, "gnu++0x",
518 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000519 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 clEnumValEnd));
521
522static llvm::cl::opt<bool>
523NoOperatorNames("fno-operator-names",
524 llvm::cl::desc("Do not treat C++ operator name keywords as "
525 "synonyms for operators"));
526
Anders Carlssonee98ac52007-10-15 02:50:23 +0000527static llvm::cl::opt<bool>
528PascalStrings("fpascal-strings",
529 llvm::cl::desc("Recognize and construct Pascal-style "
530 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000531
532static llvm::cl::opt<bool>
533MSExtensions("fms-extensions",
534 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000535 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000536
537static llvm::cl::opt<bool>
538WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000539 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000540
541static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000542NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000543 llvm::cl::desc("Disallow implicit conversions between "
544 "vectors with a different number of "
545 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000546
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000547static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000548EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000549
550static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000551EnableHeinousExtensions("fheinous-gnu-extensions",
552 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
553 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
554
555static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000556ObjCNonFragileABI("fobjc-nonfragile-abi",
557 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000558
Daniel Dunbard604c402009-02-04 21:19:06 +0000559static llvm::cl::opt<bool>
560EmitAllDecls("femit-all-decls",
561 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000562
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000563// FIXME: This (and all GCC -f options) really come in -f... and
564// -fno-... forms, and additionally support automagic behavior when
565// they are not defined. For example, -fexceptions defaults to on or
566// off depending on the language. We should support this behavior in
567// some form (perhaps just add a facility for distinguishing when an
568// has its default value from when it has been set to its default
569// value).
570static llvm::cl::opt<bool>
571Exceptions("fexceptions",
572 llvm::cl::desc("Enable support for exception handling."));
573
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000574static llvm::cl::opt<bool>
575GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000576 llvm::cl::desc("Generate output compatible with the standard GNU "
577 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000578
579static llvm::cl::opt<bool>
580NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000581 llvm::cl::desc("Generate output compatible with the NeXT "
582 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000583
Ted Kremenekea644d82008-09-03 21:22:16 +0000584
585
586static llvm::cl::opt<bool>
587Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
588
Chris Lattner16167a62009-03-02 22:11:07 +0000589static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000590TargetFeatures("mattr", llvm::cl::CommaSeparated,
591 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
592
Douglas Gregor26dce442009-03-10 00:06:19 +0000593static llvm::cl::opt<unsigned>
594TemplateDepth("ftemplate-depth", llvm::cl::init(99),
595 llvm::cl::desc("Maximum depth of recursive template "
596 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000597
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000598
599static llvm::cl::opt<bool>
600OptSize("Os", llvm::cl::desc("Optimize for size"));
601
602static llvm::cl::opt<bool>
603NoCommon("fno-common",
604 llvm::cl::desc("Compile common globals like normal definitions"),
605 llvm::cl::ValueDisallowed);
606
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000607static llvm::cl::opt<std::string>
608MainFileName("main-file-name",
609 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000610
611// It might be nice to add bounds to the CommandLine library directly.
612struct OptLevelParser : public llvm::cl::parser<unsigned> {
613 bool parse(llvm::cl::Option &O, const char *ArgName,
614 const std::string &Arg, unsigned &Val) {
615 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
616 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000617 if (Val > 3)
618 return O.error(": '" + Arg + "' invalid optimization level!");
619 return false;
620 }
621};
622static llvm::cl::opt<unsigned, false, OptLevelParser>
623OptLevel("O", llvm::cl::Prefix,
624 llvm::cl::desc("Optimization level"),
625 llvm::cl::init(0));
626
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000627static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000628PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
629
630static llvm::cl::opt<bool>
631StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000632
Reid Spencer5f016e22007-07-11 17:01:13 +0000633// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000634// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000635static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
636 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000637 // Allow the target to set the default the langauge options as it sees fit.
638 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000639
Chris Lattner6328cc32009-03-03 19:56:18 +0000640 // If there are any -mattr options, pass them to the target for validation and
641 // processing. The driver should have already consolidated all the
642 // target-feature settings and passed them to us in the -mattr list. The
643 // -mattr list is treated by the code generator as a diff against the -mcpu
644 // setting, but the driver should pass all enabled options as "+" settings.
645 // This means that the target should only look at + settings.
646 if (!TargetFeatures.empty()
647 // FIXME: The driver is not quite yet ready for this.
648 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000649 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000650 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
651 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000652 if (Opt != -1) {
653 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000654 fprintf(stderr, "invalid feature '%s'\n",
655 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000656 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000657 fprintf(stderr, "feature '%s': %s\n",
658 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000659 exit(1);
660 }
661 }
662
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 if (LangStd == lang_unspecified) {
664 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000665 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000666 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000668 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 case langkind_c_cpp:
670 case langkind_objc:
671 case langkind_objc_cpp:
672 LangStd = lang_gnu99;
673 break;
674 case langkind_cxx:
675 case langkind_cxx_cpp:
676 case langkind_objcxx:
677 case langkind_objcxx_cpp:
678 LangStd = lang_gnucxx98;
679 break;
680 }
681 }
682
683 switch (LangStd) {
684 default: assert(0 && "Unknown language standard!");
685
686 // Fall through from newer standards to older ones. This isn't really right.
687 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000688 case lang_gnucxx0x:
689 case lang_cxx0x:
690 Options.CPlusPlus0x = 1;
691 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 case lang_gnucxx98:
693 case lang_cxx98:
694 Options.CPlusPlus = 1;
695 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000696 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 // FALL THROUGH.
698 case lang_gnu99:
699 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 Options.C99 = 1;
701 Options.HexFloats = 1;
702 // FALL THROUGH.
703 case lang_gnu89:
704 Options.BCPLComment = 1; // Only for C99/C++.
705 // FALL THROUGH.
706 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000707 Options.Digraphs = 1; // C94, C99, C++.
708 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 case lang_c89:
710 break;
711 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000712
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000713 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
714 Options.GNUMode = LangStd >= lang_gnu_START;
715
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000716 if (Options.CPlusPlus) {
717 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000718 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000719 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000720
Chris Lattnerd658b562008-04-05 06:32:51 +0000721 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
722 Options.ImplicitInt = 1;
723 else
724 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000725
Daniel Dunbard573d262009-04-07 22:13:21 +0000726 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
727 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000728 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000729 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000730 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000731
Chris Lattner802db9b2008-12-05 00:10:44 +0000732 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
733 // even if they are normally on for the target. In GNU modes (e.g.
734 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000735 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000736 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000737 Options.Blocks = 0;
738
Daniel Dunbar85c49102009-03-15 00:11:28 +0000739 // Never accept '$' in identifiers when preprocessing assembler.
740 if (LK != langkind_asm_cpp)
741 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000742 if (PascalStrings.getPosition())
743 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000744 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000745 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000746 if (NoLaxVectorConversions.getPosition())
747 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000748 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000749 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000750 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000751
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000752 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000753 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000754 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000755 Options.Freestanding = Options.NoBuiltin = 1;
756
Chris Lattner810f6d52009-03-13 17:38:01 +0000757 if (EnableHeinousExtensions)
758 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000759
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000760 Options.MathErrno = MathErrno;
761
Douglas Gregor26dce442009-03-10 00:06:19 +0000762 Options.InstantiationDepth = TemplateDepth;
763
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000764 // Override the default runtime if the user requested it.
765 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000766 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000767 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000768 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000769
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000770 if (ObjCNonFragileABI)
771 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000772
773 if (EmitAllDecls)
774 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000775
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000776 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
777 // support.
778 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000779
780 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000781 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000782 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000783
784 assert(PICLevel <= 2 && "Invalid value for -pic-level");
785 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000786
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000787 Options.GNUInline = !Options.C99;
788 // FIXME: This is affected by other options (-fno-inline).
789 Options.NoInline = !OptSize && !OptLevel;
790
791 Options.Static = StaticDefine;
792
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000793 if (MainFileName.getPosition())
794 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000795}
796
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000797static llvm::cl::opt<bool>
798ObjCExclusiveGC("fobjc-gc-only",
799 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000800 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000801
802static llvm::cl::opt<bool>
803ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000804 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000805
806void InitializeGCMode(LangOptions &Options) {
807 if (ObjCExclusiveGC)
808 Options.setGCMode(LangOptions::GCOnly);
809 else if (ObjCEnableGC)
810 Options.setGCMode(LangOptions::HybridGC);
811}
812
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000813static llvm::cl::opt<std::string>
814SymbolVisibility("fvisibility",
815 llvm::cl::desc("Set the default visibility to the specific option"));
816
817void InitializeSymbolVisibility(LangOptions &Options) {
818 if (SymbolVisibility.empty())
819 return;
820 std::string Visibility = SymbolVisibility;
821 const char *vkind = Visibility.c_str();
822 if (!strcmp(vkind, "default"))
823 Options.setVisibilityMode(LangOptions::DefaultVisibility);
824 else if (!strcmp(vkind, "protected"))
825 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
826 else if (!strcmp(vkind, "hidden"))
827 Options.setVisibilityMode(LangOptions::HiddenVisibility);
828 else if (!strcmp(vkind, "internal"))
829 Options.setVisibilityMode(LangOptions::InternalVisibility);
830 else
831 fprintf(stderr,
832 "-fvisibility only valid for default|protected|hidden|internal\n");
833}
834
Mike Stump2add4732009-04-01 20:28:16 +0000835static llvm::cl::opt<bool>
836OverflowChecking("ftrapv",
Mike Stump035cf892009-04-02 18:15:54 +0000837 llvm::cl::desc("Trap on integer overflow"),
Mike Stump2add4732009-04-01 20:28:16 +0000838 llvm::cl::init(false));
839
840void InitializeOverflowChecking(LangOptions &Options) {
Mike Stump035cf892009-04-02 18:15:54 +0000841 Options.OverflowChecking = OverflowChecking;
Mike Stump2add4732009-04-01 20:28:16 +0000842}
Reid Spencer5f016e22007-07-11 17:01:13 +0000843//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000844// Target Triple Processing.
845//===----------------------------------------------------------------------===//
846
847static llvm::cl::opt<std::string>
848TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000849 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000850
Chris Lattner42e67372008-03-05 01:18:20 +0000851static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000852Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000853
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000854static llvm::cl::opt<std::string>
855MacOSVersionMin("mmacosx-version-min",
856 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
857
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000858// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
859// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000860
861// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000862static void HandleMacOSVersionMin(std::string &Triple) {
863 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
864 if (DarwinDashIdx == std::string::npos) {
865 fprintf(stderr,
866 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
867 exit(1);
868 }
869 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
870
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000871 // Remove the number.
872 Triple.resize(DarwinNumIdx);
873
874 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
875 bool MacOSVersionMinIsInvalid = false;
876 int VersionNum = 0;
877 if (MacOSVersionMin.size() < 4 ||
878 MacOSVersionMin.substr(0, 3) != "10." ||
879 !isdigit(MacOSVersionMin[3])) {
880 MacOSVersionMinIsInvalid = true;
881 } else {
882 const char *Start = MacOSVersionMin.c_str()+3;
883 char *End = 0;
884 VersionNum = (int)strtol(Start, &End, 10);
885
Chris Lattner079f2c462008-09-30 20:30:12 +0000886 // The version number must be in the range 0-9.
887 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
888
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000889 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
890 Triple += llvm::itostr(VersionNum+4);
891
Chris Lattner079f2c462008-09-30 20:30:12 +0000892 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
893 // Add the period piece (.7) to the end of the triple. This gives us
894 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000895 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000896 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
897 MacOSVersionMinIsInvalid = true;
898 }
899 }
900
901 if (MacOSVersionMinIsInvalid) {
902 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000903 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000904 MacOSVersionMin.c_str());
905 exit(1);
906 }
907}
908
909/// CreateTargetTriple - Process the various options that affect the target
910/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000911static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000912 // Initialize base triple. If a -triple option has been specified, use
913 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000914 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000915 if (Triple.empty())
916 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000917
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000918 // If -arch foo was specified, remove the architecture from the triple we have
919 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000920
921 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000922 if (!Arch.empty()) {
923 // Decompose the base triple into "arch" and suffix.
924 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000925
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000926 if (FirstDashIdx == std::string::npos) {
927 fprintf(stderr,
928 "Malformed target triple: \"%s\" ('-' could not be found).\n",
929 Triple.c_str());
930 exit(1);
931 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000932
933 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
934 if (Arch == "ppc")
935 Arch = "powerpc";
936 else if (Arch == "ppc64")
937 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000938
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000939 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
940 }
941
942 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
943 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000944 if (!MacOSVersionMin.empty())
945 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000946
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000947 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000948}
949
950//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000951// Preprocessor Initialization
952//===----------------------------------------------------------------------===//
953
954// FIXME: Preprocessor builtins to support.
955// -A... - Play with #assertions
956// -undef - Undefine all predefined macros
957
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000958// FIXME: -imacros
959
Reid Spencer5f016e22007-07-11 17:01:13 +0000960static llvm::cl::list<std::string>
961D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
962 llvm::cl::desc("Predefine the specified macro"));
963static llvm::cl::list<std::string>
964U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
965 llvm::cl::desc("Undefine the specified macro"));
966
Chris Lattner64299f82008-01-10 01:53:41 +0000967static llvm::cl::list<std::string>
968ImplicitIncludes("include", llvm::cl::value_desc("file"),
969 llvm::cl::desc("Include file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000970static llvm::cl::list<std::string>
971ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
972 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner64299f82008-01-10 01:53:41 +0000973
Ted Kremenek748d5d62009-03-20 00:26:38 +0000974static llvm::cl::opt<std::string>
975ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
976 llvm::cl::desc("Include file before parsing"));
977
Reid Spencer5f016e22007-07-11 17:01:13 +0000978// Append a #define line to Buf for Macro. Macro should be of the form XXX,
979// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
980// "#define XXX Y z W". To get a #define with no value, use "XXX=".
981static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
982 const char *Command = "#define ") {
983 Buf.insert(Buf.end(), Command, Command+strlen(Command));
984 if (const char *Equal = strchr(Macro, '=')) {
985 // Turn the = into ' '.
986 Buf.insert(Buf.end(), Macro, Equal);
987 Buf.push_back(' ');
Chris Lattner0b514152009-04-07 06:02:44 +0000988
989 // Per GCC -D semantics, the macro ends at \n if it exists.
990 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner3eb2fc82009-04-07 18:18:09 +0000991 if (End) {
Chris Lattner56473d32009-04-08 03:36:03 +0000992 fprintf(stderr, "warning: macro '%s' contains embedded newline, text "
Chris Lattner3eb2fc82009-04-07 18:18:09 +0000993 "after the newline is ignored.\n",
994 std::string(Macro, Equal).c_str());
995 } else {
996 End = Equal+strlen(Equal);
997 }
Chris Lattner0b514152009-04-07 06:02:44 +0000998
999 Buf.insert(Buf.end(), Equal+1, End);
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 } else {
1001 // Push "macroname 1".
1002 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
1003 Buf.push_back(' ');
1004 Buf.push_back('1');
1005 }
1006 Buf.push_back('\n');
1007}
1008
Chris Lattner64299f82008-01-10 01:53:41 +00001009/// AddImplicitInclude - Add an implicit #include of the specified file to the
1010/// predefines buffer.
1011static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
1012 const char *Inc = "#include \"";
1013 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1014 Buf.insert(Buf.end(), File.begin(), File.end());
1015 Buf.push_back('"');
1016 Buf.push_back('\n');
1017}
1018
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001019static void AddImplicitIncludeMacros(std::vector<char> &Buf,
1020 const std::string &File) {
1021 const char *Inc = "#__include_macros \"";
1022 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1023 Buf.insert(Buf.end(), File.begin(), File.end());
1024 Buf.push_back('"');
1025 Buf.push_back('\n');
1026}
1027
Ted Kremenek748d5d62009-03-20 00:26:38 +00001028/// AddImplicitIncludePTH - Add an implicit #include using the original file
1029/// used to generate a PTH cache.
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001030static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor &PP) {
Ted Kremenek748d5d62009-03-20 00:26:38 +00001031 PTHManager *P = PP.getPTHManager();
1032 assert(P && "No PTHManager.");
1033 const char *OriginalFile = P->getOriginalSourceFile();
1034
1035 if (!OriginalFile) {
1036 assert(!ImplicitIncludePTH.empty());
1037 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1038 "source header file for -include-pth\n",
1039 ImplicitIncludePTH.c_str());
1040 exit (1);
1041 }
1042
1043 AddImplicitInclude(Buf, OriginalFile);
1044}
Reid Spencer5f016e22007-07-11 17:01:13 +00001045
Chris Lattner53b0dab2007-10-09 22:10:18 +00001046/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +00001047/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001048///
Chris Lattner51574ea2008-04-19 23:25:44 +00001049static bool InitializePreprocessor(Preprocessor &PP,
1050 bool InitializeSourceMgr,
1051 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +00001052 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +00001053
Chris Lattner53b0dab2007-10-09 22:10:18 +00001054 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +00001055 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +00001056
1057 if (InitializeSourceMgr) {
1058 if (InFile != "-") {
1059 const FileEntry *File = FileMgr.getFile(InFile);
1060 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +00001061 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001062 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1063 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +00001064 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001065 }
1066 } else {
1067 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +00001068
1069 // If stdin was empty, SB is null. Cons up an empty memory
1070 // buffer now.
1071 if (!SB) {
1072 const char *EmptyStr = "";
1073 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1074 }
1075
1076 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +00001077 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001078 PP.getDiagnostics().Report(FullSourceLoc(),
1079 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +00001080 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001081 }
Chris Lattner53b0dab2007-10-09 22:10:18 +00001082 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 }
Sam Bishop1102d6b2008-04-14 14:41:57 +00001084
Chris Lattneraa391972008-04-19 23:09:31 +00001085 std::vector<char> PredefineBuffer;
1086
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +00001088 unsigned d = 0, D = D_macros.size();
1089 unsigned u = 0, U = U_macros.size();
1090 while (d < D || u < U) {
1091 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1092 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1093 else
1094 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1095 }
1096
Chris Lattner64299f82008-01-10 01:53:41 +00001097 // FIXME: Read any files specified by -imacros.
1098
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001099 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1100 !ImplicitMacroIncludes.empty()) {
1101 // We want to add these paths to the predefines buffer in order, make a temporary
1102 // vector to sort by their occurrence.
1103 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1104
1105 if (!ImplicitIncludePTH.empty())
1106 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1107 &ImplicitIncludePTH));
1108 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1109 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1110 &ImplicitIncludes[i]));
1111 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1112 OrderedPaths.push_back(std::make_pair(ImplicitMacroIncludes
1113 .getPosition(i),
1114 &ImplicitMacroIncludes[i]));
1115 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1116
1117 // Now that they are ordered by position, add to the predefines buffer.
1118 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1119 std::string *Ptr = OrderedPaths[i].second;
1120 if (!ImplicitIncludes.empty() &&
1121 Ptr >= &ImplicitIncludes[0] &&
1122 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1123 AddImplicitInclude(PredefineBuffer, *Ptr);
1124 } else if (Ptr == &ImplicitIncludePTH) {
1125 AddImplicitIncludePTH(PredefineBuffer, PP);
1126 } else {
1127 assert(Ptr >= &ImplicitMacroIncludes[0] &&
1128 Ptr <= &ImplicitMacroIncludes[ImplicitMacroIncludes.size()-1] &&
1129 "String must have been in -imacros?");
1130 AddImplicitIncludeMacros(PredefineBuffer, *Ptr);
1131 }
1132 }
Ted Kremenek748d5d62009-03-20 00:26:38 +00001133 }
Chris Lattner53b0dab2007-10-09 22:10:18 +00001134
Chris Lattneraa391972008-04-19 23:09:31 +00001135 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001136 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +00001137 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001138
1139 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +00001140 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141}
1142
1143//===----------------------------------------------------------------------===//
1144// Preprocessor include path information.
1145//===----------------------------------------------------------------------===//
1146
1147// This tool exports a large number of command line options to control how the
1148// preprocessor searches for header files. At root, however, the Preprocessor
1149// object takes a very simple interface: a list of directories to search for
1150//
1151// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001152// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001153//
Reid Spencer5f016e22007-07-11 17:01:13 +00001154
1155static llvm::cl::opt<bool>
1156nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1157
1158// Various command line options. These four add directories to each chain.
1159static llvm::cl::list<std::string>
1160F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1161 llvm::cl::desc("Add directory to framework include search path"));
1162static llvm::cl::list<std::string>
1163I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1164 llvm::cl::desc("Add directory to include search path"));
1165static llvm::cl::list<std::string>
1166idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1167 llvm::cl::desc("Add directory to AFTER include search path"));
1168static llvm::cl::list<std::string>
1169iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1170 llvm::cl::desc("Add directory to QUOTE include search path"));
1171static llvm::cl::list<std::string>
1172isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1173 llvm::cl::desc("Add directory to SYSTEM include search path"));
1174
1175// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1176static llvm::cl::list<std::string>
1177iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1178 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1179static llvm::cl::list<std::string>
1180iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1181 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1182static llvm::cl::list<std::string>
1183iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1184 llvm::cl::Prefix,
1185 llvm::cl::desc("Set directory to include search path with prefix"));
1186
Chris Lattner0c946412007-08-26 17:47:35 +00001187static llvm::cl::opt<std::string>
1188isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1189 llvm::cl::desc("Set the system root directory (usually /)"));
1190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001192
Reid Spencer5f016e22007-07-11 17:01:13 +00001193/// InitializeIncludePaths - Process the -I options and set them in the
1194/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001195void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1196 FileManager &FM, const LangOptions &Lang) {
1197 InitHeaderSearch Init(Headers, Verbose, isysroot);
1198
Ted Kremenekf3721112008-05-31 00:27:00 +00001199 // Handle -I... and -F... options, walking the lists in parallel.
1200 unsigned Iidx = 0, Fidx = 0;
1201 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1202 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001203 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001204 ++Iidx;
1205 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001206 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001207 ++Fidx;
1208 }
1209 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001210
Ted Kremenekf3721112008-05-31 00:27:00 +00001211 // Consume what's left from whatever list was longer.
1212 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001213 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001214 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001215 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001216
1217 // Handle -idirafter... options.
1218 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001219 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1220 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221
1222 // Handle -iquote... options.
1223 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001224 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001225
1226 // Handle -isystem... options.
1227 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001228 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229
1230 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1231 // parallel, processing the values in order of occurance to get the right
1232 // prefixes.
1233 {
1234 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1235 unsigned iprefix_idx = 0;
1236 unsigned iwithprefix_idx = 0;
1237 unsigned iwithprefixbefore_idx = 0;
1238 bool iprefix_done = iprefix_vals.empty();
1239 bool iwithprefix_done = iwithprefix_vals.empty();
1240 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1241 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1242 if (!iprefix_done &&
1243 (iwithprefix_done ||
1244 iprefix_vals.getPosition(iprefix_idx) <
1245 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1246 (iwithprefixbefore_done ||
1247 iprefix_vals.getPosition(iprefix_idx) <
1248 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1249 Prefix = iprefix_vals[iprefix_idx];
1250 ++iprefix_idx;
1251 iprefix_done = iprefix_idx == iprefix_vals.size();
1252 } else if (!iwithprefix_done &&
1253 (iwithprefixbefore_done ||
1254 iwithprefix_vals.getPosition(iwithprefix_idx) <
1255 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001256 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1257 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 ++iwithprefix_idx;
1259 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1260 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001261 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1262 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 ++iwithprefixbefore_idx;
1264 iwithprefixbefore_done =
1265 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1266 }
1267 }
1268 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001269
Nico Weber0fca0222008-08-22 09:25:22 +00001270 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001271
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001272 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001273 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001274 llvm::sys::Path::GetMainExecutable(Argv0,
1275 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001276 if (!MainExecutablePath.isEmpty()) {
1277 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1278 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001279
1280 // Get foo/lib/clang/1.0/include
1281 //
1282 // FIXME: Don't embed version here.
1283 MainExecutablePath.appendComponent("lib");
1284 MainExecutablePath.appendComponent("clang");
1285 MainExecutablePath.appendComponent("1.0");
1286 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001287
1288 // We pass true to ignore sysroot so that we *always* look for clang headers
1289 // relative to our executable, never relative to -isysroot.
1290 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1291 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001292 }
1293
Nico Weber0fca0222008-08-22 09:25:22 +00001294 if (!nostdinc)
1295 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001296
1297 // Now that we have collected all of the include paths, merge them all
1298 // together and tell the preprocessor about them.
1299
Nico Weber0fca0222008-08-22 09:25:22 +00001300 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001301}
1302
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001303//===----------------------------------------------------------------------===//
1304// Driver PreprocessorFactory - For lazily generating preprocessors ...
1305//===----------------------------------------------------------------------===//
1306
1307namespace {
1308class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001309 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001310 Diagnostic &Diags;
1311 const LangOptions &LangInfo;
1312 TargetInfo &Target;
1313 SourceManager &SourceMgr;
1314 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001315 bool InitializeSourceMgr;
1316
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001317public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001318 DriverPreprocessorFactory(const std::string &infile,
1319 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001320 TargetInfo &target, SourceManager &SM,
1321 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001322 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1323 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1324
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001325
1326 virtual ~DriverPreprocessorFactory() {}
1327
1328 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001329 llvm::OwningPtr<PTHManager> PTHMgr;
1330
Ted Kremenek748d5d62009-03-20 00:26:38 +00001331 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1332 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1333 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001334 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001335 }
1336
Ted Kremenek72b1b152009-01-15 18:47:46 +00001337 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001338 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1339 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001340 PTHMgr.reset(PTHManager::Create(x, &Diags,
1341 TokenCache.empty() ? Diagnostic::Error
1342 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001343 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001344
Ted Kremenek22f0d092009-03-22 06:42:39 +00001345 if (Diags.hasErrorOccurred())
1346 exit(1);
1347
Ted Kremenek72b1b152009-01-15 18:47:46 +00001348 // Create the Preprocessor.
1349 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1350 SourceMgr, HeaderInfo,
1351 PTHMgr.get()));
1352
1353 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1354 // That argument is used as the IdentifierInfoLookup argument to
1355 // IdentifierTable's ctor.
1356 if (PTHMgr) {
1357 PTHMgr->setPreprocessor(PP.get());
1358 PP->setPTHManager(PTHMgr.take());
1359 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001360
Chris Lattner51574ea2008-04-19 23:25:44 +00001361 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001362 return NULL;
1363 }
1364
Daniel Dunbar750c3582008-10-24 22:12:41 +00001365 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001366 if (ProgAction != PrintPreprocessedInput) {
1367 std::string ErrStr;
1368 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1369 if (!DFG && !ErrStr.empty()) {
1370 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001371 return NULL;
1372 }
1373 }
1374
Ted Kremenek339b9c22008-04-17 22:31:54 +00001375 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001376 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001377 }
1378};
1379}
Reid Spencer5f016e22007-07-11 17:01:13 +00001380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381//===----------------------------------------------------------------------===//
1382// Basic Parser driver
1383//===----------------------------------------------------------------------===//
1384
Chris Lattner51574ea2008-04-19 23:25:44 +00001385static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001387 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001388
1389 // Parsing the specified input file.
1390 P.ParseTranslationUnit();
1391 delete PA;
1392}
1393
1394//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001395// Code generation options
1396//===----------------------------------------------------------------------===//
1397
1398static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001399GenerateDebugInfo("g",
1400 llvm::cl::desc("Generate source level debug information"));
1401
Daniel Dunbara034ba82009-02-17 19:47:34 +00001402static llvm::cl::opt<std::string>
1403TargetCPU("mcpu",
1404 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1405
Chris Lattner7afae712009-03-16 18:41:18 +00001406static void InitializeCompileOptions(CompileOptions &Opts,
1407 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001408 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001409 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001410 if (OptSize) {
1411 // -Os implies -O2
1412 // FIXME: Diagnose conflicting options.
1413 Opts.OptimizationLevel = 2;
1414 } else {
1415 Opts.OptimizationLevel = OptLevel;
1416 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001417
1418 // FIXME: There are llvm-gcc options to control these selectively.
1419 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1420 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001421 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001422
1423#ifdef NDEBUG
1424 Opts.VerifyModule = 0;
1425#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001426
1427 Opts.CPU = TargetCPU;
1428 Opts.Features.insert(Opts.Features.end(),
1429 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001430
Chris Lattnerbd360642009-03-26 05:00:52 +00001431 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1432
Chris Lattner44502662009-02-18 01:23:44 +00001433 // Handle -ftime-report.
1434 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001435}
1436
1437//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001438// Fix-It Options
1439//===----------------------------------------------------------------------===//
1440static llvm::cl::list<ParsedSourceLocation>
1441FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1442 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1443
1444//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001445// Main driver
1446//===----------------------------------------------------------------------===//
1447
Ted Kremenekdb094a22007-12-05 18:27:04 +00001448/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001449/// action. These consumers can operate on both ASTs that are freshly
1450/// parsed from source files as well as those deserialized from Bitcode.
1451/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001452static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001453 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001454 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001455 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001456 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001457 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001458 default:
1459 return NULL;
1460
1461 case ASTPrint:
1462 return CreateASTPrinter();
1463
1464 case ASTDump:
1465 return CreateASTDumper();
1466
1467 case ASTView:
1468 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001469
Chris Lattner8a5c8092009-02-18 01:20:05 +00001470 case PrintDeclContext:
1471 return CreateDeclContextPrinter();
1472
1473 case EmitHTML:
1474 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001475
Chris Lattner8a5c8092009-02-18 01:20:05 +00001476 case InheritanceView:
1477 return CreateInheritanceViewer(InheritanceViewCls);
1478
1479 case TestSerialization:
1480 return CreateSerializationTest(Diag, FileMgr);
1481
1482 case EmitAssembly:
1483 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001484 case EmitBC:
1485 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001486 BackendAction Act;
1487 if (ProgAction == EmitAssembly)
1488 Act = Backend_EmitAssembly;
1489 else if (ProgAction == EmitLLVM)
1490 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001491 else if (ProgAction == EmitLLVMOnly)
1492 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001493 else
1494 Act = Backend_EmitBC;
1495
1496 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001497 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001498 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001499 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001500 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001501
Chris Lattner8a5c8092009-02-18 01:20:05 +00001502 case SerializeAST:
1503 // FIXME: Allow user to tailor where the file is written.
1504 return CreateASTSerializer(InFile, OutputFile, Diag);
1505
1506 case RewriteObjC:
1507 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001508
Chris Lattner8a5c8092009-02-18 01:20:05 +00001509 case RewriteBlocks:
1510 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1511
1512 case RunAnalysis:
1513 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001514 }
1515}
1516
Reid Spencer5f016e22007-07-11 17:01:13 +00001517/// ProcessInputFile - Process a single input file with the specified state.
1518///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001519static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001520 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001521 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001522 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001523 FixItRewriter *FixItRewrite = 0;
1524
Ted Kremenek85888962008-10-21 00:54:44 +00001525 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001527 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1528 PP.getFileManager(), PP.getLangOptions(),
1529 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001530
1531 if (!Consumer) {
1532 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001533 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001534 return;
1535 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001536
Ted Kremenekdb094a22007-12-05 18:27:04 +00001537 break;
1538
Chris Lattnerc106c102008-10-12 05:03:36 +00001539 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001540 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001541 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001542 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001543 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001544 RawLex.SetKeepWhitespaceMode(true);
1545
1546 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001547 RawLex.LexFromRawLexer(RawTok);
1548 while (RawTok.isNot(tok::eof)) {
1549 PP.DumpToken(RawTok, true);
1550 fprintf(stderr, "\n");
1551 RawLex.LexFromRawLexer(RawTok);
1552 }
1553 ClearSourceMgr = true;
1554 break;
1555 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001557 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001558 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001559 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001560 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 do {
1562 PP.Lex(Tok);
1563 PP.DumpToken(Tok, true);
1564 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001565 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001566 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 break;
1568 }
1569 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001570 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001571 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001573 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 do {
1575 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001576 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001577 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 break;
1579 }
Ted Kremenek85888962008-10-21 00:54:44 +00001580
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001581 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001582 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001583 CacheTokens(PP, OutputFile);
1584 ClearSourceMgr = true;
1585 break;
1586 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001587
Chris Lattner47099742009-02-18 01:51:21 +00001588 case PrintPreprocessedInput: { // -E mode.
1589 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001590 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001591 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 break;
Chris Lattner47099742009-02-18 01:51:21 +00001593 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001594
Chris Lattner47099742009-02-18 01:51:21 +00001595 case ParseNoop: { // -parse-noop
1596 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001597 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001598 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 break;
Chris Lattner47099742009-02-18 01:51:21 +00001600 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001601
Chris Lattner47099742009-02-18 01:51:21 +00001602 case ParsePrintCallbacks: {
1603 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001604 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001605 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 break;
Chris Lattner47099742009-02-18 01:51:21 +00001607 }
1608
1609 case ParseSyntaxOnly: { // -fsyntax-only
1610 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001611 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001612 break;
Chris Lattner47099742009-02-18 01:51:21 +00001613 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001614
1615 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001616 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001617 ClearSourceMgr = true;
1618 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001619
Chris Lattner47099742009-02-18 01:51:21 +00001620 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001621 DoRewriteTest(PP, InFile, OutputFile);
1622 ClearSourceMgr = true;
1623 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001624 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001625
1626 case FixIt:
1627 llvm::TimeRegion Timer(ClangFrontendTimer);
1628 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001629 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor558cb562009-04-02 01:08:08 +00001630 PP.getSourceManager());
Douglas Gregor558cb562009-04-02 01:08:08 +00001631 break;
Chris Lattner47099742009-02-18 01:51:21 +00001632 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001633
1634 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001635 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001636
Douglas Gregor26df2f02009-04-02 19:05:20 +00001637 if (FixItAtLocations.size() > 0) {
1638 // Even without the "-fixit" flag, with may have some specific
1639 // locations where the user has requested fixes. Process those
1640 // locations now.
1641 if (!FixItRewrite)
1642 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1643 PP.getSourceManager());
1644
1645 bool AddedFixitLocation = false;
1646 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1647 Idx != Last; ++Idx) {
1648 RequestedSourceLocation Requested;
1649 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1650 Requested)) {
1651 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1652 FixItAtLocations[Idx].FileName.c_str());
1653 } else {
1654 FixItRewrite->addFixItLocation(Requested);
1655 AddedFixitLocation = true;
1656 }
1657 }
1658
1659 if (!AddedFixitLocation) {
1660 // All of the fix-it locations were bad. Don't fix anything.
1661 delete FixItRewrite;
1662 FixItRewrite = 0;
1663 }
1664 }
1665
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001666 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1667 PP.getSourceManager(),
1668 PP.getTargetInfo(),
1669 PP.getIdentifierTable(),
1670 PP.getSelectorTable(),
1671 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001672
1673
Chris Lattner3599dbe2009-03-28 04:13:34 +00001674 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001675
Douglas Gregor558cb562009-04-02 01:08:08 +00001676 if (FixItRewrite)
1677 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1678
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001679 // If in -disable-free mode, don't deallocate these when they go out of
1680 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001681 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001682 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001683 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001684
1685 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001686 if (CheckDiagnostics(PP))
1687 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001688
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001690 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 PP.PrintStats();
1692 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001693 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001694 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 fprintf(stderr, "\n");
1696 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001697
1698 // For a multi-file compilation, some things are ok with nuking the source
1699 // manager tables, other require stable fileid/macroid's across multiple
1700 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001701 if (ClearSourceMgr)
1702 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001703
1704 if (DisableFree)
1705 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001706}
1707
Ted Kremenek20e97482007-12-12 23:41:08 +00001708static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1709 FileManager& FileMgr) {
1710
1711 if (VerifyDiagnostics) {
1712 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1713 exit (1);
1714 }
1715
1716 llvm::sys::Path Filename(InFile);
1717
1718 if (!Filename.isValid()) {
1719 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1720 exit (1);
1721 }
1722
Chris Lattner557c5b12009-03-28 04:27:18 +00001723 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001724
1725 // Create the memory buffer that contains the contents of the file.
1726 llvm::OwningPtr<llvm::MemoryBuffer>
1727 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1728
1729 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001730 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001731
Chris Lattner557c5b12009-03-28 04:27:18 +00001732 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001733 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1734 InFile.c_str());
1735 exit (1);
1736 }
1737
Ted Kremenek63ea8632007-12-19 19:27:38 +00001738 // Observe that we use the source file name stored in the deserialized
1739 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001740 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001741 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001742 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001743
Ted Kremenek20e97482007-12-12 23:41:08 +00001744 if (!Consumer) {
1745 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1746 exit (1);
1747 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001748
Chris Lattner557c5b12009-03-28 04:27:18 +00001749 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001750
Chris Lattnere66b65c2008-02-06 01:42:25 +00001751 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001752 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1753 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1754 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001755 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001756}
1757
1758
Reid Spencer5f016e22007-07-11 17:01:13 +00001759static llvm::cl::list<std::string>
1760InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1761
Ted Kremenek20e97482007-12-12 23:41:08 +00001762static bool isSerializedFile(const std::string& InFile) {
1763 if (InFile.size() < 4)
1764 return false;
1765
1766 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001767 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001768}
1769
Reid Spencer5f016e22007-07-11 17:01:13 +00001770
1771int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001773 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001774 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001775 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001776
Chris Lattner47099742009-02-18 01:51:21 +00001777 if (TimeReport)
1778 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1779
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 // If no input was specified, read from stdin.
1781 if (InputFilenames.empty())
1782 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001783
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 // Create a file manager object to provide access to and cache the filesystem.
1785 FileManager FileMgr;
1786
Ted Kremenek31e703b2007-12-11 23:28:38 +00001787 // Create the diagnostic client for reporting errors or for
1788 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001789 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001790
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001791 if (!VerifyDiagnostics) {
1792 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001793 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1794 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001795 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001796 !NoShowLocation,
1797 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001798 } else {
1799 // When checking diagnostics, just buffer them up.
1800 TextDiagClient = new TextDiagnosticBuffer();
1801
1802 if (InputFilenames.size() != 1) {
1803 fprintf(stderr,
1804 "-verify only works on single input files for now.\n");
1805 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 }
1807 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001808
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001810 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1811 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001812 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001813 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001814
Chris Lattner4f037832007-12-05 23:24:17 +00001815 // -I- is a deprecated GCC feature, scan for it and reject it.
1816 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1817 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001818 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001819 I_dirs.erase(I_dirs.begin()+i);
1820 --i;
1821 }
1822 }
Chris Lattner11215192008-03-14 06:12:05 +00001823
1824 // Get information about the target being compiled for.
1825 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001826 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1827
Chris Lattner11215192008-03-14 06:12:05 +00001828 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001829 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1830 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001831 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001832 }
Chris Lattner4f037832007-12-05 23:24:17 +00001833
Daniel Dunbard4270232009-01-20 23:17:32 +00001834 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001835 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001836
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001837 llvm::OwningPtr<SourceManager> SourceMgr;
1838
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001840 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001841
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001842 if (isSerializedFile(InFile)) {
1843 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001844 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001845 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001846 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001847
1848 /// Create a SourceManager object. This tracks and owns all the file
1849 /// buffers allocated to a translation unit.
1850 if (!SourceMgr)
1851 SourceMgr.reset(new SourceManager());
1852 else
1853 SourceMgr->clearIDTables();
1854
1855 // Initialize language options, inferring file types from input filenames.
1856 LangOptions LangInfo;
1857 InitializeBaseLanguage();
1858 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001859 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001860 InitializeGCMode(LangInfo);
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +00001861 InitializeSymbolVisibility(LangInfo);
Mike Stump2add4732009-04-01 20:28:16 +00001862 InitializeOverflowChecking(LangInfo);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001863 InitializeLanguageStandard(LangInfo, LK, Target.get());
1864
1865 // Process the -I options and set them in the HeaderInfo.
1866 HeaderSearch HeaderInfo(FileMgr);
1867
1868 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1869
1870 // Set up the preprocessor with these options.
1871 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1872 *SourceMgr.get(), HeaderInfo);
1873
1874 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1875
1876 if (!PP)
1877 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001878
Chris Lattnerf63aea32009-03-04 21:40:56 +00001879 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1880 // always reset to using TextDiagClient.
1881 llvm::OwningPtr<DiagnosticClient> TmpClient;
1882
1883 if (!HTMLDiag.empty()) {
1884 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1885 &PPFactory));
1886 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001887 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001888 else
1889 Diags.setClient(TextDiagClient);
1890
1891 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001892 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001893
1894 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 }
Chris Lattner11215192008-03-14 06:12:05 +00001896
Mike Stump007f2a92009-01-28 02:43:35 +00001897 if (Verbose)
1898 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1899 " hosted on " LLVM_HOSTTRIPLE "\n");
1900
Ted Kremenek7a08e282008-08-07 18:13:12 +00001901 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1903 (NumDiagnostics == 1 ? "" : "s"));
1904
1905 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 FileMgr.PrintStats();
1907 fprintf(stderr, "\n");
1908 }
1909
Daniel Dunbar276373d2008-10-27 22:10:13 +00001910 // If verifying diagnostics and we reached here, all is well.
1911 if (VerifyDiagnostics)
1912 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001913
1914 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001915
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001916 // Managed static deconstruction. Useful for making things like
1917 // -time-passes usable.
1918 llvm::llvm_shutdown();
1919
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001920 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001921}