blob: 31515a9c123d1510de0cc468160c2e36972150dc [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenek377a3192009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor133d2552009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000031#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000032#include "clang/Frontend/PCHReader.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000033#include "clang/Frontend/TextDiagnosticBuffer.h"
34#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000035#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000036#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000037#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000038#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000039#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000040#include "clang/AST/ASTContext.h"
41#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000042#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000043#include "clang/Parse/Parser.h"
44#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000045#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000046#include "clang/Basic/FileManager.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000049#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000050#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000051#include "llvm/ADT/StringExtras.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000053#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000054#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000055#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000056#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000057#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000058#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000059#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000060#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000061#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000062#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000063#include <cstdlib>
64
Chris Lattner4b009652007-07-25 00:24:17 +000065using namespace clang;
66
67//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000068// Source Location Parser
69//===----------------------------------------------------------------------===//
70
71/// \brief A source location that has been parsed on the command line.
72struct ParsedSourceLocation {
73 std::string FileName;
74 unsigned Line;
75 unsigned Column;
76
77 /// \brief Try to resolve the file name of a parsed source location.
78 ///
79 /// \returns true if there was an error, false otherwise.
80 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
81};
82
83bool
84ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
85 RequestedSourceLocation &Result) {
86 const FileEntry *File = FileMgr.getFile(FileName);
87 if (!File)
88 return true;
89
90 Result.File = File;
91 Result.Line = Line;
92 Result.Column = Column;
93 return false;
94}
95
96namespace llvm {
97 namespace cl {
98 /// \brief Command-line option parser that parses source locations.
99 ///
100 /// Source locations are of the form filename:line:column.
101 template<>
102 class parser<ParsedSourceLocation>
103 : public basic_parser<ParsedSourceLocation> {
104 public:
105 bool parse(Option &O, const char *ArgName,
106 const std::string &ArgValue,
107 ParsedSourceLocation &Val);
108 };
109
110 bool
111 parser<ParsedSourceLocation>::
112 parse(Option &O, const char *ArgName, const std::string &ArgValue,
113 ParsedSourceLocation &Val) {
114 using namespace clang;
115
116 const char *ExpectedFormat
117 = "source location must be of the form filename:line:column";
118 std::string::size_type SecondColon = ArgValue.rfind(':');
119 if (SecondColon == std::string::npos) {
120 std::fprintf(stderr, "%s\n", ExpectedFormat);
121 return true;
122 }
123 char *EndPtr;
124 long Column
125 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
126 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
127 std::fprintf(stderr, "%s\n", ExpectedFormat);
128 return true;
129 }
130
131 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
132 if (SecondColon == std::string::npos) {
133 std::fprintf(stderr, "%s\n", ExpectedFormat);
134 return true;
135 }
136 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
137 if (EndPtr != ArgValue.c_str() + SecondColon) {
138 std::fprintf(stderr, "%s\n", ExpectedFormat);
139 return true;
140 }
141
142 Val.FileName = ArgValue.substr(0, FirstColon);
143 Val.Line = Line;
144 Val.Column = Column;
145 return false;
146 }
147 }
148}
149
150//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000151// Global options.
152//===----------------------------------------------------------------------===//
153
Chris Lattnerefe33382009-02-18 01:51:21 +0000154/// ClangFrontendTimer - The front-end activities should charge time to it with
155/// TimeRegion. The -ftime-report option controls whether this will do
156/// anything.
157llvm::Timer *ClangFrontendTimer = 0;
158
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000159static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000160
Chris Lattner4b009652007-07-25 00:24:17 +0000161static llvm::cl::opt<bool>
162Verbose("v", llvm::cl::desc("Enable verbose output"));
163static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000164Stats("print-stats",
165 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000166static llvm::cl::opt<bool>
167DisableFree("disable-free",
168 llvm::cl::desc("Disable freeing of memory on exit"),
169 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +0000170
171enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000172 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000173 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000174 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000175 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000176 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000177 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000178 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000179 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000180 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000181 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +0000182 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +0000183 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000184 ASTPrint, // Parse ASTs and print them.
185 ASTDump, // Parse ASTs and dump them.
186 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000187 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000188 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +0000189 ParsePrintCallbacks, // Parse and print each callback.
190 ParseSyntaxOnly, // Parse and perform semantic analysis.
191 ParseNoop, // Parse with noop callbacks.
192 RunPreprocessorOnly, // Just lex, no output.
193 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000194 DumpTokens, // Dump out preprocessed tokens.
195 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000196 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000197 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000198 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000199 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000200};
201
202static llvm::cl::opt<ProgActions>
203ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
204 llvm::cl::init(ParseSyntaxOnly),
205 llvm::cl::values(
206 clEnumValN(RunPreprocessorOnly, "Eonly",
207 "Just run preprocessor, no output (for timings)"),
208 clEnumValN(PrintPreprocessedInput, "E",
209 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000210 clEnumValN(DumpRawTokens, "dump-raw-tokens",
211 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000212 clEnumValN(RunAnalysis, "analyze",
213 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000214 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000215 "Run preprocessor, dump internal rep of tokens"),
216 clEnumValN(ParseNoop, "parse-noop",
217 "Run parser with noop callbacks (for timings)"),
218 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
219 "Run parser and perform semantic analysis"),
220 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
221 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000222 clEnumValN(EmitHTML, "emit-html",
223 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000224 clEnumValN(ASTPrint, "ast-print",
225 "Build ASTs and then pretty-print them"),
226 clEnumValN(ASTDump, "ast-dump",
227 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000228 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000229 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000230 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000231 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000232 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000233 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000234 clEnumValN(GeneratePCH, "emit-pch",
235 "Generate pre-compiled header file"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000236 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000237 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000238 clEnumValN(EmitAssembly, "S",
239 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000240 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000241 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000242 clEnumValN(EmitBC, "emit-llvm-bc",
243 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000244 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
245 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000246 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000247 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000248 clEnumValN(RewriteTest, "rewrite-test",
249 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000250 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000251 "Rewrite ObjC into C (code rewriter example)"),
252 clEnumValN(RewriteMacros, "rewrite-macros",
253 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000254 clEnumValN(RewriteBlocks, "rewrite-blocks",
255 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000256 clEnumValN(FixIt, "fixit",
257 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000258 clEnumValEnd));
259
Ted Kremenekd01eae62007-12-19 19:47:59 +0000260
261static llvm::cl::opt<std::string>
262OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000263 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000264 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000265
Ted Kremenek57f25b22008-12-02 19:57:31 +0000266
267//===----------------------------------------------------------------------===//
268// PTH.
269//===----------------------------------------------------------------------===//
270
271static llvm::cl::opt<std::string>
272TokenCache("token-cache", llvm::cl::value_desc("path"),
273 llvm::cl::desc("Use specified token cache file"));
274
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000275//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000276// Diagnostic Options
277//===----------------------------------------------------------------------===//
278
Ted Kremenek10389cf2007-09-26 19:42:19 +0000279static llvm::cl::opt<bool>
280VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000281 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000282
Ted Kremenekfd75e312008-03-27 06:17:42 +0000283static llvm::cl::opt<std::string>
284HTMLDiag("html-diags",
285 llvm::cl::desc("Generate HTML to report diagnostics"),
286 llvm::cl::value_desc("HTML directory"));
287
Nico Weber0e13eaa2008-08-05 23:33:20 +0000288static llvm::cl::opt<bool>
289NoShowColumn("fno-show-column",
290 llvm::cl::desc("Do not include column number on diagnostics"));
291
292static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000293NoShowLocation("fno-show-source-location",
294 llvm::cl::desc("Do not include source location information with"
295 " diagnostics"));
296
297static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000298NoCaretDiagnostics("fno-caret-diagnostics",
299 llvm::cl::desc("Do not include source line and caret with"
300 " diagnostics"));
301
Chris Lattner695a4f52009-03-13 01:08:23 +0000302static llvm::cl::opt<bool>
303PrintSourceRangeInfo("fprint-source-range-info",
304 llvm::cl::desc("Print source range spans in numeric form"));
305
Nico Weber0e13eaa2008-08-05 23:33:20 +0000306
Chris Lattner4b009652007-07-25 00:24:17 +0000307//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000308// C++ Visualization.
309//===----------------------------------------------------------------------===//
310
311static llvm::cl::opt<std::string>
312InheritanceViewCls("cxx-inheritance-view",
313 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000314 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000315
316//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000317// Builtin Options
318//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000319
320static llvm::cl::opt<bool>
321TimeReport("ftime-report",
322 llvm::cl::desc("Print the amount of time each "
323 "phase of compilation takes"));
324
Douglas Gregor23d23262009-02-14 20:49:29 +0000325static llvm::cl::opt<bool>
326Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000327 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000328 "freestanding environment"));
329
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000330static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000331AllowBuiltins("fbuiltin", llvm::cl::init(true),
332 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000333
334
335static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000336MathErrno("fmath-errno", llvm::cl::init(true),
337 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000338
Douglas Gregor23d23262009-02-14 20:49:29 +0000339//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000340// Language Options
341//===----------------------------------------------------------------------===//
342
343enum LangKind {
344 langkind_unspecified,
345 langkind_c,
346 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000347 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000348 langkind_cxx,
349 langkind_cxx_cpp,
350 langkind_objc,
351 langkind_objc_cpp,
352 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000353 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000354};
355
Chris Lattner4b009652007-07-25 00:24:17 +0000356static llvm::cl::opt<LangKind>
357BaseLang("x", llvm::cl::desc("Base language to compile"),
358 llvm::cl::init(langkind_unspecified),
359 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
360 clEnumValN(langkind_cxx, "c++", "C++"),
361 clEnumValN(langkind_objc, "objective-c", "Objective C"),
362 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000363 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000364 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000365 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
366 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000367 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000368 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000369 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
370 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000371 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000372 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000373 clEnumValN(langkind_c, "c-header",
374 "C header"),
375 clEnumValN(langkind_objc, "objective-c-header",
376 "Objective-C header"),
377 clEnumValN(langkind_cxx, "c++-header",
378 "C++ header"),
379 clEnumValN(langkind_objcxx, "objective-c++-header",
380 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000381 clEnumValEnd));
382
383static llvm::cl::opt<bool>
384LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
385 llvm::cl::Hidden);
386static llvm::cl::opt<bool>
387LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
388 llvm::cl::Hidden);
389
Ted Kremenek11ad8952007-12-05 23:49:08 +0000390/// InitializeBaseLanguage - Handle the -x foo options.
391static void InitializeBaseLanguage() {
392 if (LangObjC)
393 BaseLang = langkind_objc;
394 else if (LangObjCXX)
395 BaseLang = langkind_objcxx;
396}
397
398static LangKind GetLanguage(const std::string &Filename) {
399 if (BaseLang != langkind_unspecified)
400 return BaseLang;
401
402 std::string::size_type DotPos = Filename.rfind('.');
403
404 if (DotPos == std::string::npos) {
405 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000406 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000407 }
408
Ted Kremenek11ad8952007-12-05 23:49:08 +0000409 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
410 // C header: .h
411 // C++ header: .hh or .H;
412 // assembler no preprocessing: .s
413 // assembler: .S
414 if (Ext == "c")
415 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000416 else if (Ext == "S" ||
417 // If the compiler is run on a .s file, preprocess it as .S
418 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000419 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000420 else if (Ext == "i")
421 return langkind_c_cpp;
422 else if (Ext == "ii")
423 return langkind_cxx_cpp;
424 else if (Ext == "m")
425 return langkind_objc;
426 else if (Ext == "mi")
427 return langkind_objc_cpp;
428 else if (Ext == "mm" || Ext == "M")
429 return langkind_objcxx;
430 else if (Ext == "mii")
431 return langkind_objcxx_cpp;
432 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
433 Ext == "c++" || Ext == "cp" || Ext == "cxx")
434 return langkind_cxx;
435 else
436 return langkind_c;
437}
438
439
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000440static void InitializeCOptions(LangOptions &Options) {
441 // Do nothing.
442}
443
444static void InitializeObjCOptions(LangOptions &Options) {
445 Options.ObjC1 = Options.ObjC2 = 1;
446}
447
448
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000449static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000450 // FIXME: implement -fpreprocessed mode.
451 bool NoPreprocess = false;
452
Ted Kremenek11ad8952007-12-05 23:49:08 +0000453 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000454 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000455 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000456 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000457 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000458 case langkind_c_cpp:
459 NoPreprocess = true;
460 // FALLTHROUGH
461 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000462 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000463 break;
464 case langkind_cxx_cpp:
465 NoPreprocess = true;
466 // FALLTHROUGH
467 case langkind_cxx:
468 Options.CPlusPlus = 1;
469 break;
470 case langkind_objc_cpp:
471 NoPreprocess = true;
472 // FALLTHROUGH
473 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000474 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000475 break;
476 case langkind_objcxx_cpp:
477 NoPreprocess = true;
478 // FALLTHROUGH
479 case langkind_objcxx:
480 Options.ObjC1 = Options.ObjC2 = 1;
481 Options.CPlusPlus = 1;
482 break;
483 }
484}
485
486/// LangStds - Language standards we support.
487enum LangStds {
488 lang_unspecified,
489 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000490 lang_gnu_START,
491 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000492 lang_cxx98, lang_gnucxx98,
493 lang_cxx0x, lang_gnucxx0x
494};
495
496static llvm::cl::opt<LangStds>
497LangStd("std", llvm::cl::desc("Language standard to compile for"),
498 llvm::cl::init(lang_unspecified),
499 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
500 clEnumValN(lang_c89, "c90", "ISO C 1990"),
501 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
502 clEnumValN(lang_c94, "iso9899:199409",
503 "ISO C 1990 with amendment 1"),
504 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000505 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000506 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000507 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000508 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000509 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000510 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000511 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000512 clEnumValN(lang_gnu99, "gnu9x",
513 "ISO C 1999 with GNU extensions"),
514 clEnumValN(lang_cxx98, "c++98",
515 "ISO C++ 1998 with amendments"),
516 clEnumValN(lang_gnucxx98, "gnu++98",
517 "ISO C++ 1998 with amendments and GNU "
518 "extensions (default for C++)"),
519 clEnumValN(lang_cxx0x, "c++0x",
520 "Upcoming ISO C++ 200x with amendments"),
521 clEnumValN(lang_gnucxx0x, "gnu++0x",
522 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000523 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000524 clEnumValEnd));
525
526static llvm::cl::opt<bool>
527NoOperatorNames("fno-operator-names",
528 llvm::cl::desc("Do not treat C++ operator name keywords as "
529 "synonyms for operators"));
530
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000531static llvm::cl::opt<bool>
532PascalStrings("fpascal-strings",
533 llvm::cl::desc("Recognize and construct Pascal-style "
534 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000535
536static llvm::cl::opt<bool>
537MSExtensions("fms-extensions",
538 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000539 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000540
541static llvm::cl::opt<bool>
542WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000543 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000544
545static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000546NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000547 llvm::cl::desc("Disallow implicit conversions between "
548 "vectors with a different number of "
549 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000550
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000551static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000552EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000553
554static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000555EnableHeinousExtensions("fheinous-gnu-extensions",
556 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
557 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
558
559static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000560ObjCNonFragileABI("fobjc-nonfragile-abi",
561 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000562
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000563static llvm::cl::opt<bool>
564EmitAllDecls("femit-all-decls",
565 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000566
Daniel Dunbar91692d92008-08-11 17:36:14 +0000567// FIXME: This (and all GCC -f options) really come in -f... and
568// -fno-... forms, and additionally support automagic behavior when
569// they are not defined. For example, -fexceptions defaults to on or
570// off depending on the language. We should support this behavior in
571// some form (perhaps just add a facility for distinguishing when an
572// has its default value from when it has been set to its default
573// value).
574static llvm::cl::opt<bool>
575Exceptions("fexceptions",
576 llvm::cl::desc("Enable support for exception handling."));
577
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000578static llvm::cl::opt<bool>
579GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000580 llvm::cl::desc("Generate output compatible with the standard GNU "
581 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000582
583static llvm::cl::opt<bool>
584NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000585 llvm::cl::desc("Generate output compatible with the NeXT "
586 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000587
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000588
589
590static llvm::cl::opt<bool>
591Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
592
Chris Lattner738d3f62009-03-02 22:11:07 +0000593static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000594TargetFeatures("mattr", llvm::cl::CommaSeparated,
595 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
596
Douglas Gregor375733c2009-03-10 00:06:19 +0000597static llvm::cl::opt<unsigned>
598TemplateDepth("ftemplate-depth", llvm::cl::init(99),
599 llvm::cl::desc("Maximum depth of recursive template "
600 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000601
Anders Carlssondfd77642009-04-06 17:37:10 +0000602
603static llvm::cl::opt<bool>
604OptSize("Os", llvm::cl::desc("Optimize for size"));
605
606static llvm::cl::opt<bool>
607NoCommon("fno-common",
608 llvm::cl::desc("Compile common globals like normal definitions"),
609 llvm::cl::ValueDisallowed);
610
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000611static llvm::cl::opt<std::string>
612MainFileName("main-file-name",
613 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000614
615// It might be nice to add bounds to the CommandLine library directly.
616struct OptLevelParser : public llvm::cl::parser<unsigned> {
617 bool parse(llvm::cl::Option &O, const char *ArgName,
618 const std::string &Arg, unsigned &Val) {
619 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
620 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000621 if (Val > 3)
622 return O.error(": '" + Arg + "' invalid optimization level!");
623 return false;
624 }
625};
626static llvm::cl::opt<unsigned, false, OptLevelParser>
627OptLevel("O", llvm::cl::Prefix,
628 llvm::cl::desc("Optimization level"),
629 llvm::cl::init(0));
630
Daniel Dunbare079c712009-04-08 03:03:23 +0000631static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000632PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
633
634static llvm::cl::opt<bool>
635StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000636
Chris Lattner4b009652007-07-25 00:24:17 +0000637// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000638// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000639static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
640 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000641 // Allow the target to set the default the langauge options as it sees fit.
642 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000643
Chris Lattnerf6790a82009-03-03 19:56:18 +0000644 // If there are any -mattr options, pass them to the target for validation and
645 // processing. The driver should have already consolidated all the
646 // target-feature settings and passed them to us in the -mattr list. The
647 // -mattr list is treated by the code generator as a diff against the -mcpu
648 // setting, but the driver should pass all enabled options as "+" settings.
649 // This means that the target should only look at + settings.
Chris Lattner880d38e2009-04-13 06:33:49 +0000650 if (!TargetFeatures.empty()) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000651 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000652 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
653 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000654 if (Opt != -1) {
655 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000656 fprintf(stderr, "invalid feature '%s'\n",
657 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000658 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000659 fprintf(stderr, "feature '%s': %s\n",
660 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000661 exit(1);
662 }
663 }
664
Chris Lattner4b009652007-07-25 00:24:17 +0000665 if (LangStd == lang_unspecified) {
666 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000667 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000668 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000669 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000670 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000671 case langkind_c_cpp:
672 case langkind_objc:
673 case langkind_objc_cpp:
674 LangStd = lang_gnu99;
675 break;
676 case langkind_cxx:
677 case langkind_cxx_cpp:
678 case langkind_objcxx:
679 case langkind_objcxx_cpp:
680 LangStd = lang_gnucxx98;
681 break;
682 }
683 }
684
685 switch (LangStd) {
686 default: assert(0 && "Unknown language standard!");
687
688 // Fall through from newer standards to older ones. This isn't really right.
689 // FIXME: Enable specifically the right features based on the language stds.
690 case lang_gnucxx0x:
691 case lang_cxx0x:
692 Options.CPlusPlus0x = 1;
693 // FALL THROUGH
694 case lang_gnucxx98:
695 case lang_cxx98:
696 Options.CPlusPlus = 1;
697 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000698 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000699 // FALL THROUGH.
700 case lang_gnu99:
701 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000702 Options.C99 = 1;
703 Options.HexFloats = 1;
704 // FALL THROUGH.
705 case lang_gnu89:
706 Options.BCPLComment = 1; // Only for C99/C++.
707 // FALL THROUGH.
708 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000709 Options.Digraphs = 1; // C94, C99, C++.
710 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000711 case lang_c89:
712 break;
713 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000714
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000715 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
716 Options.GNUMode = LangStd >= lang_gnu_START;
717
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000718 if (Options.CPlusPlus) {
719 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000720 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000721 }
Chris Lattner4b009652007-07-25 00:24:17 +0000722
Chris Lattner6ab935b2008-04-05 06:32:51 +0000723 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
724 Options.ImplicitInt = 1;
725 else
726 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000727
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000728 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
729 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000730 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000731 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000732 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000733
Chris Lattner58d5ba52008-12-05 00:10:44 +0000734 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
735 // even if they are normally on for the target. In GNU modes (e.g.
736 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000737 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000738 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000739 Options.Blocks = 0;
740
Daniel Dunbar551236b2009-03-15 00:11:28 +0000741 // Never accept '$' in identifiers when preprocessing assembler.
742 if (LK != langkind_asm_cpp)
743 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000744 if (PascalStrings.getPosition())
745 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000746 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000747 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000748 if (NoLaxVectorConversions.getPosition())
749 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000750 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000751 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000752 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000753
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000754 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000755 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000756 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000757 Options.Freestanding = Options.NoBuiltin = 1;
758
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000759 if (EnableHeinousExtensions)
760 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000761
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000762 Options.MathErrno = MathErrno;
763
Douglas Gregor375733c2009-03-10 00:06:19 +0000764 Options.InstantiationDepth = TemplateDepth;
765
Chris Lattnerddae7102008-12-04 22:54:33 +0000766 // Override the default runtime if the user requested it.
767 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000768 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000769 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000770 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000771
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000772 if (ObjCNonFragileABI)
773 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000774
775 if (EmitAllDecls)
776 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000777
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000778 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
779 // support.
780 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000781
782 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000783 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000784 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000785
786 assert(PICLevel <= 2 && "Invalid value for -pic-level");
787 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000788
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000789 Options.GNUInline = !Options.C99;
790 // FIXME: This is affected by other options (-fno-inline).
791 Options.NoInline = !OptSize && !OptLevel;
792
793 Options.Static = StaticDefine;
794
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000795 if (MainFileName.getPosition())
796 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000797}
798
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000799static llvm::cl::opt<bool>
800ObjCExclusiveGC("fobjc-gc-only",
801 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000802 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000803
804static llvm::cl::opt<bool>
805ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000806 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000807
808void InitializeGCMode(LangOptions &Options) {
809 if (ObjCExclusiveGC)
810 Options.setGCMode(LangOptions::GCOnly);
811 else if (ObjCEnableGC)
812 Options.setGCMode(LangOptions::HybridGC);
813}
814
Fariborz Jahanian49343332009-04-03 03:28:57 +0000815static llvm::cl::opt<std::string>
816SymbolVisibility("fvisibility",
817 llvm::cl::desc("Set the default visibility to the specific option"));
818
819void InitializeSymbolVisibility(LangOptions &Options) {
820 if (SymbolVisibility.empty())
821 return;
822 std::string Visibility = SymbolVisibility;
823 const char *vkind = Visibility.c_str();
824 if (!strcmp(vkind, "default"))
825 Options.setVisibilityMode(LangOptions::DefaultVisibility);
826 else if (!strcmp(vkind, "protected"))
827 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
828 else if (!strcmp(vkind, "hidden"))
829 Options.setVisibilityMode(LangOptions::HiddenVisibility);
830 else if (!strcmp(vkind, "internal"))
831 Options.setVisibilityMode(LangOptions::InternalVisibility);
832 else
833 fprintf(stderr,
834 "-fvisibility only valid for default|protected|hidden|internal\n");
835}
836
Mike Stumpdb789912009-04-01 20:28:16 +0000837static llvm::cl::opt<bool>
838OverflowChecking("ftrapv",
Mike Stumpf71b7742009-04-02 18:15:54 +0000839 llvm::cl::desc("Trap on integer overflow"),
Mike Stumpdb789912009-04-01 20:28:16 +0000840 llvm::cl::init(false));
841
842void InitializeOverflowChecking(LangOptions &Options) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000843 Options.OverflowChecking = OverflowChecking;
Mike Stumpdb789912009-04-01 20:28:16 +0000844}
Chris Lattner4b009652007-07-25 00:24:17 +0000845//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000846// Target Triple Processing.
847//===----------------------------------------------------------------------===//
848
849static llvm::cl::opt<std::string>
850TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000851 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000852
Chris Lattnerfc457002008-03-05 01:18:20 +0000853static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000854Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000855
Chris Lattner2b168e02008-09-30 01:13:12 +0000856static llvm::cl::opt<std::string>
857MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000858 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000859
Chris Lattner01de9c82008-09-30 20:16:56 +0000860// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
861// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000862
863// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000864static void HandleMacOSVersionMin(std::string &Triple) {
865 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
866 if (DarwinDashIdx == std::string::npos) {
867 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000868 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000869 exit(1);
870 }
871 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
872
Chris Lattner01de9c82008-09-30 20:16:56 +0000873 // Remove the number.
874 Triple.resize(DarwinNumIdx);
875
876 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
877 bool MacOSVersionMinIsInvalid = false;
878 int VersionNum = 0;
879 if (MacOSVersionMin.size() < 4 ||
880 MacOSVersionMin.substr(0, 3) != "10." ||
881 !isdigit(MacOSVersionMin[3])) {
882 MacOSVersionMinIsInvalid = true;
883 } else {
884 const char *Start = MacOSVersionMin.c_str()+3;
885 char *End = 0;
886 VersionNum = (int)strtol(Start, &End, 10);
887
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000888 // The version number must be in the range 0-9.
889 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
890
Chris Lattner01de9c82008-09-30 20:16:56 +0000891 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
892 Triple += llvm::itostr(VersionNum+4);
893
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000894 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
895 // Add the period piece (.7) to the end of the triple. This gives us
896 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000897 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000898 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
899 MacOSVersionMinIsInvalid = true;
900 }
901 }
902
903 if (MacOSVersionMinIsInvalid) {
904 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000905 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000906 MacOSVersionMin.c_str());
907 exit(1);
908 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000909 else if (VersionNum <= 4 &&
910 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
911 fprintf(stderr,
912 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
913 MacOSVersionMin.c_str());
914 exit(1);
915 }
916
Chris Lattner01de9c82008-09-30 20:16:56 +0000917}
918
Daniel Dunbar93f64532009-04-10 19:52:24 +0000919static llvm::cl::opt<std::string>
920IPhoneOSVersionMin("miphoneos-version-min",
921 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
922
923// If -miphoneos-version-min=2.2 is specified, change the triple from being
924// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
925// 9 as the default major Darwin number, and encode the iPhone OS version
926// number in the minor version and revision.
927
928// FIXME: We should have the driver do this instead.
929static void HandleIPhoneOSVersionMin(std::string &Triple) {
930 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
931 if (DarwinDashIdx == std::string::npos) {
932 fprintf(stderr,
933 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
934 exit(1);
935 }
936 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
937
938 // Remove the number.
939 Triple.resize(DarwinNumIdx);
940
941 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
942 bool IPhoneOSVersionMinIsInvalid = false;
943 int VersionNum = 0;
944 if (IPhoneOSVersionMin.size() < 3 ||
945 !isdigit(IPhoneOSVersionMin[0])) {
946 IPhoneOSVersionMinIsInvalid = true;
947 } else {
948 const char *Start = IPhoneOSVersionMin.c_str();
949 char *End = 0;
950 VersionNum = (int)strtol(Start, &End, 10);
951
952 // The version number must be in the range 0-9.
953 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
954
955 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
956 Triple += "9." + llvm::itostr(VersionNum);
957
958 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
959 // Add the period piece (.2) to the end of the triple. This gives us
960 // something like ...-darwin9.2.2
961 Triple += End;
962 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
963 IPhoneOSVersionMinIsInvalid = true;
964 }
965 }
966
967 if (IPhoneOSVersionMinIsInvalid) {
968 fprintf(stderr,
969 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
970 IPhoneOSVersionMin.c_str());
971 exit(1);
972 }
973}
974
Chris Lattner01de9c82008-09-30 20:16:56 +0000975/// CreateTargetTriple - Process the various options that affect the target
976/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000977static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000978 // Initialize base triple. If a -triple option has been specified, use
979 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000980 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000981 if (Triple.empty())
982 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000983
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000984 // If -arch foo was specified, remove the architecture from the triple we have
985 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000986
987 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000988 if (!Arch.empty()) {
989 // Decompose the base triple into "arch" and suffix.
990 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000991
Chris Lattner2b168e02008-09-30 01:13:12 +0000992 if (FirstDashIdx == std::string::npos) {
993 fprintf(stderr,
994 "Malformed target triple: \"%s\" ('-' could not be found).\n",
995 Triple.c_str());
996 exit(1);
997 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000998
999 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1000 if (Arch == "ppc")
1001 Arch = "powerpc";
1002 else if (Arch == "ppc64")
1003 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001004
Chris Lattner2b168e02008-09-30 01:13:12 +00001005 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1006 }
1007
1008 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1009 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001010 if (!MacOSVersionMin.empty())
1011 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001012 else if (!IPhoneOSVersionMin.empty())
1013 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001014
Chris Lattner2b168e02008-09-30 01:13:12 +00001015 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001016}
1017
1018//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001019// Preprocessor Initialization
1020//===----------------------------------------------------------------------===//
1021
1022// FIXME: Preprocessor builtins to support.
1023// -A... - Play with #assertions
1024// -undef - Undefine all predefined macros
1025
Chris Lattner695a4f52009-03-13 01:08:23 +00001026// FIXME: -imacros
1027
Chris Lattner4b009652007-07-25 00:24:17 +00001028static llvm::cl::list<std::string>
1029D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1030 llvm::cl::desc("Predefine the specified macro"));
1031static llvm::cl::list<std::string>
1032U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1033 llvm::cl::desc("Undefine the specified macro"));
1034
Chris Lattner008da782008-01-10 01:53:41 +00001035static llvm::cl::list<std::string>
1036ImplicitIncludes("include", llvm::cl::value_desc("file"),
1037 llvm::cl::desc("Include file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001038static llvm::cl::list<std::string>
1039ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1040 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner008da782008-01-10 01:53:41 +00001041
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001042static llvm::cl::opt<std::string>
1043ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1044 llvm::cl::desc("Include file before parsing"));
1045
Douglas Gregorc34897d2009-04-09 22:27:44 +00001046static llvm::cl::opt<std::string>
1047ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1048 llvm::cl::desc("Include precompiled header file"));
1049
Chris Lattner4b009652007-07-25 00:24:17 +00001050// Append a #define line to Buf for Macro. Macro should be of the form XXX,
1051// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
1052// "#define XXX Y z W". To get a #define with no value, use "XXX=".
1053static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
1054 const char *Command = "#define ") {
1055 Buf.insert(Buf.end(), Command, Command+strlen(Command));
1056 if (const char *Equal = strchr(Macro, '=')) {
1057 // Turn the = into ' '.
1058 Buf.insert(Buf.end(), Macro, Equal);
1059 Buf.push_back(' ');
Chris Lattner39baafb2009-04-07 06:02:44 +00001060
1061 // Per GCC -D semantics, the macro ends at \n if it exists.
1062 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner39c610d2009-04-07 18:18:09 +00001063 if (End) {
Chris Lattnerd93f7902009-04-08 03:36:03 +00001064 fprintf(stderr, "warning: macro '%s' contains embedded newline, text "
Chris Lattner39c610d2009-04-07 18:18:09 +00001065 "after the newline is ignored.\n",
1066 std::string(Macro, Equal).c_str());
1067 } else {
1068 End = Equal+strlen(Equal);
1069 }
Chris Lattner39baafb2009-04-07 06:02:44 +00001070
1071 Buf.insert(Buf.end(), Equal+1, End);
Chris Lattner4b009652007-07-25 00:24:17 +00001072 } else {
1073 // Push "macroname 1".
1074 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
1075 Buf.push_back(' ');
1076 Buf.push_back('1');
1077 }
1078 Buf.push_back('\n');
1079}
1080
Daniel Dunbar43b91692009-04-09 00:51:16 +00001081/// Add the quoted name of an implicit include file.
1082static void AddQuotedIncludePath(std::vector<char> &Buf,
1083 const std::string &File) {
1084 // Implicit include paths are relative to the current working
1085 // directory; resolve them now instead of using the normal machinery
1086 // (which would look relative to the input file).
1087 llvm::sys::Path Path(File);
1088 Path.makeAbsolute();
1089
Chris Lattner6ac92a32009-04-08 20:10:57 +00001090 // Escape double quotes etc.
Daniel Dunbar43b91692009-04-09 00:51:16 +00001091 Buf.push_back('"');
1092 std::string EscapedFile = Lexer::Stringify(Path.toString());
Chris Lattner6ac92a32009-04-08 20:10:57 +00001093 Buf.insert(Buf.end(), EscapedFile.begin(), EscapedFile.end());
Chris Lattner008da782008-01-10 01:53:41 +00001094 Buf.push_back('"');
Daniel Dunbar43b91692009-04-09 00:51:16 +00001095}
1096
1097/// AddImplicitInclude - Add an implicit #include of the specified file to the
1098/// predefines buffer.
1099static void AddImplicitInclude(std::vector<char> &Buf,
1100 const std::string &File) {
1101 const char *Inc = "#include ";
1102 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1103 AddQuotedIncludePath(Buf, File);
Chris Lattner008da782008-01-10 01:53:41 +00001104 Buf.push_back('\n');
1105}
1106
Chris Lattner0e004a12009-04-08 18:24:34 +00001107static void AddImplicitIncludeMacros(std::vector<char> &Buf,
1108 const std::string &File) {
Daniel Dunbar43b91692009-04-09 00:51:16 +00001109 const char *Inc = "#__include_macros ";
Chris Lattner0e004a12009-04-08 18:24:34 +00001110 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
Daniel Dunbar43b91692009-04-09 00:51:16 +00001111 AddQuotedIncludePath(Buf, File);
Chris Lattner0e004a12009-04-08 18:24:34 +00001112 Buf.push_back('\n');
Chris Lattnera6e44112009-04-08 20:53:24 +00001113 // Marker token to stop the __include_macros fetch loop.
1114 const char *Marker = "##\n"; // ##?
1115 Buf.insert(Buf.end(), Marker, Marker+strlen(Marker));
Chris Lattner0e004a12009-04-08 18:24:34 +00001116}
1117
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001118/// AddImplicitIncludePTH - Add an implicit #include using the original file
1119/// used to generate a PTH cache.
Chris Lattner0e004a12009-04-08 18:24:34 +00001120static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor &PP) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001121 PTHManager *P = PP.getPTHManager();
1122 assert(P && "No PTHManager.");
1123 const char *OriginalFile = P->getOriginalSourceFile();
1124
1125 if (!OriginalFile) {
1126 assert(!ImplicitIncludePTH.empty());
1127 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1128 "source header file for -include-pth\n",
1129 ImplicitIncludePTH.c_str());
1130 exit (1);
1131 }
1132
1133 AddImplicitInclude(Buf, OriginalFile);
1134}
Chris Lattner4b009652007-07-25 00:24:17 +00001135
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001136/// PickFP - This is used to pick a value based on the FP semantics of the
1137/// specified FP model.
1138template <typename T>
1139static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
1140 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
1141 if (Sem == &llvm::APFloat::IEEEsingle)
1142 return IEEESingleVal;
1143 if (Sem == &llvm::APFloat::IEEEdouble)
1144 return IEEEDoubleVal;
1145 if (Sem == &llvm::APFloat::x87DoubleExtended)
1146 return X87DoubleExtendedVal;
1147 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
1148 return PPCDoubleDoubleVal;
1149}
1150
1151static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
1152 const llvm::fltSemantics *Sem) {
1153 const char *DenormMin, *Epsilon, *Max, *Min;
1154 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
1155 "3.64519953188247460253e-4951L",
1156 "4.94065645841246544176568792868221e-324L");
1157 int Digits = PickFP(Sem, 6, 15, 18, 31);
1158 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
1159 "1.08420217248550443401e-19L",
1160 "4.94065645841246544176568792868221e-324L");
1161 int HasInifinity = 1, HasQuietNaN = 1;
1162 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
1163 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
1164 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
1165 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
1166 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
1167 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
1168 "3.36210314311209350626e-4932L",
1169 "2.00416836000897277799610805135016e-292L");
1170 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
1171 "1.18973149535723176502e+4932L",
1172 "1.79769313486231580793728971405301e+308L");
1173
1174 char MacroBuf[60];
1175 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
1176 DefineBuiltinMacro(Buf, MacroBuf);
1177 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
1178 DefineBuiltinMacro(Buf, MacroBuf);
1179 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
1180 DefineBuiltinMacro(Buf, MacroBuf);
1181 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
1182 DefineBuiltinMacro(Buf, MacroBuf);
1183 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
1184 DefineBuiltinMacro(Buf, MacroBuf);
1185 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
1186 DefineBuiltinMacro(Buf, MacroBuf);
1187 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
1188 DefineBuiltinMacro(Buf, MacroBuf);
1189 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
1190 DefineBuiltinMacro(Buf, MacroBuf);
1191 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
1192 DefineBuiltinMacro(Buf, MacroBuf);
1193 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
1194 DefineBuiltinMacro(Buf, MacroBuf);
1195 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
1196 DefineBuiltinMacro(Buf, MacroBuf);
1197 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
1198 DefineBuiltinMacro(Buf, MacroBuf);
1199 sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix);
1200 DefineBuiltinMacro(Buf, MacroBuf);
1201}
1202
1203
1204/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
1205/// named MacroName with the max value for a type with width 'TypeWidth' a
1206/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
1207static void DefineTypeSize(const char *MacroName, unsigned TypeWidth,
1208 const char *ValSuffix, bool isSigned,
1209 std::vector<char> &Buf) {
1210 char MacroBuf[60];
1211 long long MaxVal;
1212 if (isSigned)
1213 MaxVal = (1LL << (TypeWidth - 1)) - 1;
1214 else
1215 MaxVal = ~0LL >> (64-TypeWidth);
1216
1217 sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix);
1218 DefineBuiltinMacro(Buf, MacroBuf);
1219}
1220
1221static void DefineType(const char *MacroName, TargetInfo::IntType Ty,
1222 std::vector<char> &Buf) {
1223 char MacroBuf[60];
1224 sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty));
1225 DefineBuiltinMacro(Buf, MacroBuf);
1226}
1227
1228
1229static void InitializePredefinedMacros(const TargetInfo &TI,
1230 const LangOptions &LangOpts,
1231 std::vector<char> &Buf) {
1232 char MacroBuf[60];
1233 // Compiler version introspection macros.
1234 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
1235 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
1236
1237 // Currently claim to be compatible with GCC 4.2.1-5621.
1238 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
1239 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
1240 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
1241 DefineBuiltinMacro(Buf, "__GNUC__=4");
1242 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
1243 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\"");
1244
1245
1246 // Initialize language-specific preprocessor defines.
1247
1248 // These should all be defined in the preprocessor according to the
1249 // current language configuration.
1250 if (!LangOpts.Microsoft)
1251 DefineBuiltinMacro(Buf, "__STDC__=1");
1252 if (LangOpts.AsmPreprocessor)
1253 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
1254 if (LangOpts.C99 && !LangOpts.CPlusPlus)
1255 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
1256 else if (0) // STDC94 ?
1257 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
1258
1259 // Standard conforming mode?
1260 if (!LangOpts.GNUMode)
1261 DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1");
1262
1263 if (LangOpts.CPlusPlus0x)
1264 DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__");
1265
1266 if (LangOpts.Freestanding)
1267 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0");
1268 else
1269 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
1270
1271 if (LangOpts.ObjC1) {
1272 DefineBuiltinMacro(Buf, "__OBJC__=1");
1273 if (LangOpts.ObjCNonFragileABI) {
1274 DefineBuiltinMacro(Buf, "__OBJC2__=1");
1275 DefineBuiltinMacro(Buf, "OBJC_ZEROCOST_EXCEPTIONS=1");
1276 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
1277 }
1278
1279 if (LangOpts.getGCMode() != LangOptions::NonGC)
1280 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
1281
1282 if (LangOpts.NeXTRuntime)
1283 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
1284 }
1285
1286 // darwin_constant_cfstrings controls this. This is also dependent
1287 // on other things like the runtime I believe. This is set even for C code.
1288 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
1289
1290 if (LangOpts.ObjC2)
1291 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
1292
1293 if (LangOpts.PascalStrings)
1294 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
1295
1296 if (LangOpts.Blocks) {
1297 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
1298 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
1299 }
1300
1301 if (LangOpts.CPlusPlus) {
1302 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
1303 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
1304 DefineBuiltinMacro(Buf, "__GNUG__=4");
1305 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
1306 DefineBuiltinMacro(Buf, "__cplusplus=1");
1307 DefineBuiltinMacro(Buf, "__private_extern__=extern");
1308 }
1309
1310 // Filter out some microsoft extensions when trying to parse in ms-compat
1311 // mode.
1312 if (LangOpts.Microsoft) {
1313 DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
1314 DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__");
1315 DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__");
1316 DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__");
1317 DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__");
1318 }
1319
1320 if (LangOpts.Optimize)
1321 DefineBuiltinMacro(Buf, "__OPTIMIZE__=1");
1322 if (LangOpts.OptimizeSize)
1323 DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1");
1324
1325 // Initialize target-specific preprocessor defines.
1326
1327 // Define type sizing macros based on the target properties.
1328 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
1329 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
1330
1331 unsigned IntMaxWidth;
1332 const char *IntMaxSuffix;
1333 if (TI.getIntMaxType() == TargetInfo::SignedLongLong) {
1334 IntMaxWidth = TI.getLongLongWidth();
1335 IntMaxSuffix = "LL";
1336 } else if (TI.getIntMaxType() == TargetInfo::SignedLong) {
1337 IntMaxWidth = TI.getLongWidth();
1338 IntMaxSuffix = "L";
1339 } else {
1340 assert(TI.getIntMaxType() == TargetInfo::SignedInt);
1341 IntMaxWidth = TI.getIntWidth();
1342 IntMaxSuffix = "";
1343 }
1344
1345 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
1346 DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf);
1347 DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf);
1348 DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf);
1349 DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf);
1350 DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf);
1351 DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf);
1352
1353 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
1354 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
1355 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
1356 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf);
1357 DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
1358 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
1359 // FIXME: TargetInfo hookize __WINT_TYPE__.
1360 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
1361
1362 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
1363 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
1364 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
1365
1366 // Define a __POINTER_WIDTH__ macro for stdint.h.
1367 sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0));
1368 DefineBuiltinMacro(Buf, MacroBuf);
1369
1370 if (!TI.isCharSigned())
1371 DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__");
1372
1373 // Define fixed-sized integer types for stdint.h
1374 assert(TI.getCharWidth() == 8 && "unsupported target types");
1375 assert(TI.getShortWidth() == 16 && "unsupported target types");
1376 DefineBuiltinMacro(Buf, "__INT8_TYPE__=char");
1377 DefineBuiltinMacro(Buf, "__INT16_TYPE__=short");
1378
1379 if (TI.getIntWidth() == 32)
1380 DefineBuiltinMacro(Buf, "__INT32_TYPE__=int");
1381 else {
1382 assert(TI.getLongLongWidth() == 32 && "unsupported target types");
1383 DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long");
1384 }
1385
1386 // 16-bit targets doesn't necessarily have a 64-bit type.
1387 if (TI.getLongLongWidth() == 64)
1388 DefineBuiltinMacro(Buf, "__INT64_TYPE__=long long");
1389
1390 // Add __builtin_va_list typedef.
1391 {
1392 const char *VAList = TI.getVAListDeclaration();
1393 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
1394 Buf.push_back('\n');
1395 }
1396
1397 if (const char *Prefix = TI.getUserLabelPrefix()) {
1398 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
1399 DefineBuiltinMacro(Buf, MacroBuf);
1400 }
1401
1402 // Build configuration options. FIXME: these should be controlled by
1403 // command line options or something.
1404 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
1405
1406 if (LangOpts.Static)
1407 DefineBuiltinMacro(Buf, "__STATIC__=1");
1408 else
1409 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
1410
1411 if (LangOpts.GNUInline)
1412 DefineBuiltinMacro(Buf, "__GNUC_GNU_INLINE__=1");
1413 else
1414 DefineBuiltinMacro(Buf, "__GNUC_STDC_INLINE__=1");
1415
1416 if (LangOpts.NoInline)
1417 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
1418
1419 if (unsigned PICLevel = LangOpts.PICLevel) {
1420 sprintf(MacroBuf, "__PIC__=%d", PICLevel);
1421 DefineBuiltinMacro(Buf, MacroBuf);
1422
1423 sprintf(MacroBuf, "__pic__=%d", PICLevel);
1424 DefineBuiltinMacro(Buf, MacroBuf);
1425 }
1426
1427 // Macros to control C99 numerics and <float.h>
1428 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
1429 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
1430 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
1431 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
1432 DefineBuiltinMacro(Buf, MacroBuf);
1433
1434 // Get other target #defines.
1435 TI.getTargetDefines(LangOpts, Buf);
1436}
1437
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001438static bool InitializeSourceManager(Preprocessor &PP,
1439 const std::string &InFile) {
1440 // Figure out where to get and map in the main file.
1441 SourceManager &SourceMgr = PP.getSourceManager();
1442 FileManager &FileMgr = PP.getFileManager();
1443
1444 if (InFile != "-") {
1445 const FileEntry *File = FileMgr.getFile(InFile);
1446 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1447 if (SourceMgr.getMainFileID().isInvalid()) {
1448 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1449 << InFile.c_str();
1450 return true;
1451 }
1452 } else {
1453 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1454
1455 // If stdin was empty, SB is null. Cons up an empty memory
1456 // buffer now.
1457 if (!SB) {
1458 const char *EmptyStr = "";
1459 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1460 }
1461
1462 SourceMgr.createMainFileIDForMemBuffer(SB);
1463 if (SourceMgr.getMainFileID().isInvalid()) {
1464 PP.getDiagnostics().Report(FullSourceLoc(),
1465 diag::err_fe_error_reading_stdin);
1466 return true;
1467 }
1468 }
1469
1470 return false;
1471}
1472
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001473/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +00001474/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001475///
Chris Lattner9d818a22008-04-19 23:25:44 +00001476static bool InitializePreprocessor(Preprocessor &PP,
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001477 const std::string &InFile) {
Chris Lattner47b6a162008-04-19 23:09:31 +00001478 std::vector<char> PredefineBuffer;
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001479
1480 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
1481 InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
1482 PredefineBuffer);
1483
1484 // Add on the predefines from the driver. Wrap in a #line directive to report
1485 // that they come from the command line.
1486 const char *LineDirective = "# 1 \"<command line>\" 1\n";
1487 PredefineBuffer.insert(PredefineBuffer.end(),
1488 LineDirective, LineDirective+strlen(LineDirective));
1489
Chris Lattner47b6a162008-04-19 23:09:31 +00001490
Chris Lattner4b009652007-07-25 00:24:17 +00001491 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +00001492 unsigned d = 0, D = D_macros.size();
1493 unsigned u = 0, U = U_macros.size();
1494 while (d < D || u < U) {
1495 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1496 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1497 else
1498 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1499 }
1500
Chris Lattnerb62396d2009-04-08 20:15:42 +00001501 // If -imacros are specified, include them now. These are processed before
1502 // any -include directives.
1503
1504 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1505 AddImplicitIncludeMacros(PredefineBuffer, ImplicitMacroIncludes[i]);
Chris Lattner008da782008-01-10 01:53:41 +00001506
Chris Lattnerb62396d2009-04-08 20:15:42 +00001507 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1508 // We want to add these paths to the predefines buffer in order, make a
1509 // temporary vector to sort by their occurrence.
Chris Lattner0e004a12009-04-08 18:24:34 +00001510 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1511
1512 if (!ImplicitIncludePTH.empty())
1513 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1514 &ImplicitIncludePTH));
1515 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1516 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1517 &ImplicitIncludes[i]));
Chris Lattner0e004a12009-04-08 18:24:34 +00001518 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1519
1520 // Now that they are ordered by position, add to the predefines buffer.
1521 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1522 std::string *Ptr = OrderedPaths[i].second;
1523 if (!ImplicitIncludes.empty() &&
1524 Ptr >= &ImplicitIncludes[0] &&
1525 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1526 AddImplicitInclude(PredefineBuffer, *Ptr);
Chris Lattner0e004a12009-04-08 18:24:34 +00001527 } else {
Chris Lattnerb62396d2009-04-08 20:15:42 +00001528 assert(Ptr == &ImplicitIncludePTH);
1529 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner0e004a12009-04-08 18:24:34 +00001530 }
1531 }
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001532 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001533
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001534 LineDirective = "# 2 \"<built-in>\" 2\n";
1535 PredefineBuffer.insert(PredefineBuffer.end(),
1536 LineDirective, LineDirective+strlen(LineDirective));
1537
Chris Lattner47b6a162008-04-19 23:09:31 +00001538 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001539 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +00001540 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001541
1542 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +00001543 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001544}
1545
1546//===----------------------------------------------------------------------===//
1547// Preprocessor include path information.
1548//===----------------------------------------------------------------------===//
1549
1550// This tool exports a large number of command line options to control how the
1551// preprocessor searches for header files. At root, however, the Preprocessor
1552// object takes a very simple interface: a list of directories to search for
1553//
1554// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001555// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001556//
Chris Lattner4b009652007-07-25 00:24:17 +00001557
1558static llvm::cl::opt<bool>
1559nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1560
1561// Various command line options. These four add directories to each chain.
1562static llvm::cl::list<std::string>
1563F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1564 llvm::cl::desc("Add directory to framework include search path"));
1565static llvm::cl::list<std::string>
1566I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1567 llvm::cl::desc("Add directory to include search path"));
1568static llvm::cl::list<std::string>
1569idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1570 llvm::cl::desc("Add directory to AFTER include search path"));
1571static llvm::cl::list<std::string>
1572iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1573 llvm::cl::desc("Add directory to QUOTE include search path"));
1574static llvm::cl::list<std::string>
1575isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1576 llvm::cl::desc("Add directory to SYSTEM include search path"));
1577
1578// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1579static llvm::cl::list<std::string>
1580iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1581 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1582static llvm::cl::list<std::string>
1583iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1584 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1585static llvm::cl::list<std::string>
1586iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1587 llvm::cl::Prefix,
1588 llvm::cl::desc("Set directory to include search path with prefix"));
1589
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001590static llvm::cl::opt<std::string>
1591isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1592 llvm::cl::desc("Set the system root directory (usually /)"));
1593
Chris Lattner4b009652007-07-25 00:24:17 +00001594// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001595
Chris Lattner4b009652007-07-25 00:24:17 +00001596/// InitializeIncludePaths - Process the -I options and set them in the
1597/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001598void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1599 FileManager &FM, const LangOptions &Lang) {
1600 InitHeaderSearch Init(Headers, Verbose, isysroot);
1601
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001602 // Handle -I... and -F... options, walking the lists in parallel.
1603 unsigned Iidx = 0, Fidx = 0;
1604 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1605 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001606 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001607 ++Iidx;
1608 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001609 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001610 ++Fidx;
1611 }
1612 }
Chris Lattner4b009652007-07-25 00:24:17 +00001613
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001614 // Consume what's left from whatever list was longer.
1615 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001616 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001617 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001618 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001619
1620 // Handle -idirafter... options.
1621 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001622 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1623 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001624
1625 // Handle -iquote... options.
1626 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001627 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001628
1629 // Handle -isystem... options.
1630 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001631 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001632
1633 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1634 // parallel, processing the values in order of occurance to get the right
1635 // prefixes.
1636 {
1637 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1638 unsigned iprefix_idx = 0;
1639 unsigned iwithprefix_idx = 0;
1640 unsigned iwithprefixbefore_idx = 0;
1641 bool iprefix_done = iprefix_vals.empty();
1642 bool iwithprefix_done = iwithprefix_vals.empty();
1643 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1644 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1645 if (!iprefix_done &&
1646 (iwithprefix_done ||
1647 iprefix_vals.getPosition(iprefix_idx) <
1648 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1649 (iwithprefixbefore_done ||
1650 iprefix_vals.getPosition(iprefix_idx) <
1651 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1652 Prefix = iprefix_vals[iprefix_idx];
1653 ++iprefix_idx;
1654 iprefix_done = iprefix_idx == iprefix_vals.size();
1655 } else if (!iwithprefix_done &&
1656 (iwithprefixbefore_done ||
1657 iwithprefix_vals.getPosition(iwithprefix_idx) <
1658 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001659 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1660 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001661 ++iwithprefix_idx;
1662 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1663 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001664 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1665 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001666 ++iwithprefixbefore_idx;
1667 iwithprefixbefore_done =
1668 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1669 }
1670 }
1671 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001672
Nico Weber770e3882008-08-22 09:25:22 +00001673 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001674
Daniel Dunbar4e604292009-02-21 20:52:41 +00001675 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001676 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001677 llvm::sys::Path::GetMainExecutable(Argv0,
1678 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001679 if (!MainExecutablePath.isEmpty()) {
1680 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1681 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001682
1683 // Get foo/lib/clang/1.0/include
1684 //
1685 // FIXME: Don't embed version here.
1686 MainExecutablePath.appendComponent("lib");
1687 MainExecutablePath.appendComponent("clang");
1688 MainExecutablePath.appendComponent("1.0");
1689 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001690
1691 // We pass true to ignore sysroot so that we *always* look for clang headers
1692 // relative to our executable, never relative to -isysroot.
1693 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1694 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001695 }
1696
Nico Weber770e3882008-08-22 09:25:22 +00001697 if (!nostdinc)
1698 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001699
1700 // Now that we have collected all of the include paths, merge them all
1701 // together and tell the preprocessor about them.
1702
Nico Weber770e3882008-08-22 09:25:22 +00001703 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001704}
1705
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001706//===----------------------------------------------------------------------===//
1707// Driver PreprocessorFactory - For lazily generating preprocessors ...
1708//===----------------------------------------------------------------------===//
1709
1710namespace {
1711class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001712 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001713 Diagnostic &Diags;
1714 const LangOptions &LangInfo;
1715 TargetInfo &Target;
1716 SourceManager &SourceMgr;
1717 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001718
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001719public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001720 DriverPreprocessorFactory(const std::string &infile,
1721 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001722 TargetInfo &target, SourceManager &SM,
1723 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001724 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001725 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001726
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001727
1728 virtual ~DriverPreprocessorFactory() {}
1729
1730 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001731 llvm::OwningPtr<PTHManager> PTHMgr;
1732
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001733 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1734 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1735 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001736 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001737 }
1738
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001739 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001740 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1741 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001742 PTHMgr.reset(PTHManager::Create(x, &Diags,
1743 TokenCache.empty() ? Diagnostic::Error
1744 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001745 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001746
Ted Kremenek6348cc62009-03-22 06:42:39 +00001747 if (Diags.hasErrorOccurred())
1748 exit(1);
1749
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001750 // Create the Preprocessor.
1751 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1752 SourceMgr, HeaderInfo,
1753 PTHMgr.get()));
1754
1755 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1756 // That argument is used as the IdentifierInfoLookup argument to
1757 // IdentifierTable's ctor.
1758 if (PTHMgr) {
1759 PTHMgr->setPreprocessor(PP.get());
1760 PP->setPTHManager(PTHMgr.take());
1761 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001762
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001763 if (InitializePreprocessor(*PP, InFile))
1764 return 0;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001765
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001766 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001767 if (ProgAction != PrintPreprocessedInput) {
1768 std::string ErrStr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001769 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001770 if (!DFG && !ErrStr.empty()) {
1771 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001772 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001773 }
1774 }
1775
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001776 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001777 }
1778};
1779}
Chris Lattner4b009652007-07-25 00:24:17 +00001780
Chris Lattner4b009652007-07-25 00:24:17 +00001781//===----------------------------------------------------------------------===//
1782// Basic Parser driver
1783//===----------------------------------------------------------------------===//
1784
Chris Lattner9d818a22008-04-19 23:25:44 +00001785static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001786 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001787 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001788
1789 // Parsing the specified input file.
1790 P.ParseTranslationUnit();
1791 delete PA;
1792}
1793
1794//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001795// Code generation options
1796//===----------------------------------------------------------------------===//
1797
1798static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001799GenerateDebugInfo("g",
1800 llvm::cl::desc("Generate source level debug information"));
1801
Daniel Dunbar9101a632009-02-17 19:47:34 +00001802static llvm::cl::opt<std::string>
1803TargetCPU("mcpu",
1804 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1805
Chris Lattner8a9615c2009-03-16 18:41:18 +00001806static void InitializeCompileOptions(CompileOptions &Opts,
1807 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001808 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001809 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001810 if (OptSize) {
1811 // -Os implies -O2
1812 // FIXME: Diagnose conflicting options.
1813 Opts.OptimizationLevel = 2;
1814 } else {
1815 Opts.OptimizationLevel = OptLevel;
1816 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001817
1818 // FIXME: There are llvm-gcc options to control these selectively.
1819 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1820 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001821 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001822
1823#ifdef NDEBUG
1824 Opts.VerifyModule = 0;
1825#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001826
1827 Opts.CPU = TargetCPU;
1828 Opts.Features.insert(Opts.Features.end(),
1829 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001830
Chris Lattnerf04a7562009-03-26 05:00:52 +00001831 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1832
Chris Lattnere8f70712009-02-18 01:23:44 +00001833 // Handle -ftime-report.
1834 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001835}
1836
1837//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001838// Fix-It Options
1839//===----------------------------------------------------------------------===//
1840static llvm::cl::list<ParsedSourceLocation>
1841FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1842 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1843
1844//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001845// Main driver
1846//===----------------------------------------------------------------------===//
1847
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001848/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001849/// action. These consumers can operate on both ASTs that are freshly
1850/// parsed from source files as well as those deserialized from Bitcode.
1851/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001852static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001853 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001854 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001855 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001856 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001857 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001858 default:
1859 return NULL;
1860
1861 case ASTPrint:
1862 return CreateASTPrinter();
1863
1864 case ASTDump:
1865 return CreateASTDumper();
1866
1867 case ASTView:
1868 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001869
Chris Lattner7f902922009-02-18 01:20:05 +00001870 case PrintDeclContext:
1871 return CreateDeclContextPrinter();
1872
1873 case EmitHTML:
1874 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001875
Chris Lattner7f902922009-02-18 01:20:05 +00001876 case InheritanceView:
1877 return CreateInheritanceViewer(InheritanceViewCls);
1878
1879 case TestSerialization:
1880 return CreateSerializationTest(Diag, FileMgr);
1881
1882 case EmitAssembly:
1883 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001884 case EmitBC:
1885 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001886 BackendAction Act;
1887 if (ProgAction == EmitAssembly)
1888 Act = Backend_EmitAssembly;
1889 else if (ProgAction == EmitLLVM)
1890 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001891 else if (ProgAction == EmitLLVMOnly)
1892 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001893 else
1894 Act = Backend_EmitBC;
1895
1896 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001897 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001898 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001899 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001900 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001901
Chris Lattner7f902922009-02-18 01:20:05 +00001902 case SerializeAST:
1903 // FIXME: Allow user to tailor where the file is written.
1904 return CreateASTSerializer(InFile, OutputFile, Diag);
1905
Douglas Gregorc34897d2009-04-09 22:27:44 +00001906 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001907 assert(PP && "Generate PCH doesn't work from serialized file yet");
1908 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001909
Chris Lattner7f902922009-02-18 01:20:05 +00001910 case RewriteObjC:
1911 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001912
Chris Lattner7f902922009-02-18 01:20:05 +00001913 case RewriteBlocks:
1914 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1915
1916 case RunAnalysis:
1917 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001918 }
1919}
1920
Chris Lattner4b009652007-07-25 00:24:17 +00001921/// ProcessInputFile - Process a single input file with the specified state.
1922///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001923static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001924 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001925 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001926 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001927 FixItRewriter *FixItRewrite = 0;
1928
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001929 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001930 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001931 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1932 PP.getFileManager(), PP.getLangOptions(),
1933 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001934
1935 if (!Consumer) {
1936 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001937 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001938 return;
1939 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001940
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001941 break;
1942
Chris Lattneraf669fb2008-10-12 05:03:36 +00001943 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001944 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001945 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001946 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001947 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001948 RawLex.SetKeepWhitespaceMode(true);
1949
1950 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001951 RawLex.LexFromRawLexer(RawTok);
1952 while (RawTok.isNot(tok::eof)) {
1953 PP.DumpToken(RawTok, true);
1954 fprintf(stderr, "\n");
1955 RawLex.LexFromRawLexer(RawTok);
1956 }
1957 ClearSourceMgr = true;
1958 break;
1959 }
Chris Lattner4b009652007-07-25 00:24:17 +00001960 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001961 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001962 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001963 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001964 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001965 do {
1966 PP.Lex(Tok);
1967 PP.DumpToken(Tok, true);
1968 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001969 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001970 ClearSourceMgr = true;
1971 break;
1972 }
1973 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001974 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001975 Token Tok;
1976 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001977 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001978 do {
1979 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001980 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001981 ClearSourceMgr = true;
1982 break;
1983 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001984
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001985 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001986 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001987 CacheTokens(PP, OutputFile);
1988 ClearSourceMgr = true;
1989 break;
1990 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001991
Chris Lattnerefe33382009-02-18 01:51:21 +00001992 case PrintPreprocessedInput: { // -E mode.
1993 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001994 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001995 ClearSourceMgr = true;
1996 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001997 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001998
Chris Lattnerefe33382009-02-18 01:51:21 +00001999 case ParseNoop: { // -parse-noop
2000 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00002001 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00002002 ClearSourceMgr = true;
2003 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002004 }
Chris Lattner4b009652007-07-25 00:24:17 +00002005
Chris Lattnerefe33382009-02-18 01:51:21 +00002006 case ParsePrintCallbacks: {
2007 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00002008 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00002009 ClearSourceMgr = true;
2010 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002011 }
2012
2013 case ParseSyntaxOnly: { // -fsyntax-only
2014 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00002015 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00002016 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002017 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00002018
2019 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00002020 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00002021 ClearSourceMgr = true;
2022 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00002023
Chris Lattnerefe33382009-02-18 01:51:21 +00002024 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00002025 DoRewriteTest(PP, InFile, OutputFile);
2026 ClearSourceMgr = true;
2027 break;
Chris Lattner129758d2007-09-16 19:46:59 +00002028 }
Douglas Gregor133d2552009-04-02 01:08:08 +00002029
2030 case FixIt:
2031 llvm::TimeRegion Timer(ClangFrontendTimer);
2032 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00002033 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor133d2552009-04-02 01:08:08 +00002034 PP.getSourceManager());
Douglas Gregor133d2552009-04-02 01:08:08 +00002035 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002036 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00002037
2038 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00002039 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00002040
Douglas Gregor24b48b02009-04-02 19:05:20 +00002041 if (FixItAtLocations.size() > 0) {
2042 // Even without the "-fixit" flag, with may have some specific
2043 // locations where the user has requested fixes. Process those
2044 // locations now.
2045 if (!FixItRewrite)
2046 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
2047 PP.getSourceManager());
2048
2049 bool AddedFixitLocation = false;
2050 for (unsigned Idx = 0, Last = FixItAtLocations.size();
2051 Idx != Last; ++Idx) {
2052 RequestedSourceLocation Requested;
2053 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
2054 Requested)) {
2055 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
2056 FixItAtLocations[Idx].FileName.c_str());
2057 } else {
2058 FixItRewrite->addFixItLocation(Requested);
2059 AddedFixitLocation = true;
2060 }
2061 }
2062
2063 if (!AddedFixitLocation) {
2064 // All of the fix-it locations were bad. Don't fix anything.
2065 delete FixItRewrite;
2066 FixItRewrite = 0;
2067 }
2068 }
2069
Chris Lattner143fd6d2009-03-28 01:37:17 +00002070 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
2071 PP.getSourceManager(),
2072 PP.getTargetInfo(),
2073 PP.getIdentifierTable(),
2074 PP.getSelectorTable(),
2075 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00002076
Douglas Gregorc34897d2009-04-09 22:27:44 +00002077 if (!ImplicitIncludePCH.empty()) {
2078 // The user has asked us to include a precompiled header. Load
2079 // the precompiled header into the AST context.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002080 llvm::OwningPtr<PCHReader> Reader(new PCHReader(PP, *ContextOwner.get()));
2081 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2082 case PCHReader::Success: {
2083 // Attach the PCH reader to the AST context as an external AST
2084 // source, so that declarations will be deserialized from the
2085 // PCH file as needed.
2086 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
2087 ContextOwner->setExternalSource(Source);
2088
2089 // Clear out the predefines buffer, because all of the
2090 // predefines are already in the PCH file.
2091 PP.setPredefines("");
2092 break;
2093 }
2094
2095 case PCHReader::Failure:
2096 // Unrecoverable failure: don't even try to process the input
2097 // file.
Douglas Gregorc34897d2009-04-09 22:27:44 +00002098 return;
2099
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002100 case PCHReader::IgnorePCH:
2101 // No suitable PCH file could be found. Just ignore the
2102 // -include-pch option entirely.
2103 break;
2104 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00002105
2106 // Finish preprocessor initialization. We do this now (rather
2107 // than earlier) because this initialization creates new source
2108 // location entries in the source manager, which must come after
2109 // the source location entries for the PCH file.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002110 if (InitializeSourceManager(PP, InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002111 return;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002112 }
2113
Chris Lattner07b08c02009-03-28 04:13:34 +00002114 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner143fd6d2009-03-28 01:37:17 +00002115
Douglas Gregor133d2552009-04-02 01:08:08 +00002116 if (FixItRewrite)
2117 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2118
Chris Lattner143fd6d2009-03-28 01:37:17 +00002119 // If in -disable-free mode, don't deallocate these when they go out of
2120 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00002121 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00002122 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00002123 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002124
2125 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002126 if (CheckDiagnostics(PP))
2127 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002128
Chris Lattner4b009652007-07-25 00:24:17 +00002129 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002130 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002131 PP.PrintStats();
2132 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002133 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002134 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002135 fprintf(stderr, "\n");
2136 }
2137
2138 // For a multi-file compilation, some things are ok with nuking the source
2139 // manager tables, other require stable fileid/macroid's across multiple
2140 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002141 if (ClearSourceMgr)
2142 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002143
2144 if (DisableFree)
2145 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00002146}
2147
Ted Kremenek80d53372007-12-12 23:41:08 +00002148static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
2149 FileManager& FileMgr) {
2150
2151 if (VerifyDiagnostics) {
2152 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
2153 exit (1);
2154 }
2155
2156 llvm::sys::Path Filename(InFile);
2157
2158 if (!Filename.isValid()) {
2159 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
2160 exit (1);
2161 }
2162
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002163 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00002164
2165 // Create the memory buffer that contains the contents of the file.
2166 llvm::OwningPtr<llvm::MemoryBuffer>
2167 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
2168
2169 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002170 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00002171
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002172 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00002173 fprintf(stderr, "error: file '%s' could not be deserialized\n",
2174 InFile.c_str());
2175 exit (1);
2176 }
2177
Ted Kremenekab749372007-12-19 19:27:38 +00002178 // Observe that we use the source file name stored in the deserialized
2179 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00002180 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002181 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00002182 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00002183
Ted Kremenek80d53372007-12-12 23:41:08 +00002184 if (!Consumer) {
2185 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
2186 exit (1);
2187 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00002188
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002189 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00002190
Chris Lattner8d72ee02008-02-06 01:42:25 +00002191 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002192 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002193 for (DeclContext::decl_iterator I = TUD->decls_begin(*Ctx),
2194 E = TUD->decls_end(*Ctx);
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002195 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00002196 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00002197}
2198
2199
Chris Lattner4b009652007-07-25 00:24:17 +00002200static llvm::cl::list<std::string>
2201InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2202
Ted Kremenek80d53372007-12-12 23:41:08 +00002203static bool isSerializedFile(const std::string& InFile) {
2204 if (InFile.size() < 4)
2205 return false;
2206
2207 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00002208 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00002209}
2210
Chris Lattner4b009652007-07-25 00:24:17 +00002211
2212int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002213 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002214 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002215 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002216 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00002217
Chris Lattnerefe33382009-02-18 01:51:21 +00002218 if (TimeReport)
2219 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2220
Chris Lattner4b009652007-07-25 00:24:17 +00002221 // If no input was specified, read from stdin.
2222 if (InputFilenames.empty())
2223 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00002224
Chris Lattner4b009652007-07-25 00:24:17 +00002225 // Create a file manager object to provide access to and cache the filesystem.
2226 FileManager FileMgr;
2227
Ted Kremenekb240e822007-12-11 23:28:38 +00002228 // Create the diagnostic client for reporting errors or for
2229 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00002230 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00002231
Ted Kremenek5c341732008-08-07 17:49:57 +00002232 if (!VerifyDiagnostics) {
2233 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00002234 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
2235 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002236 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002237 !NoShowLocation,
2238 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00002239 } else {
2240 // When checking diagnostics, just buffer them up.
2241 TextDiagClient = new TextDiagnosticBuffer();
2242
2243 if (InputFilenames.size() != 1) {
2244 fprintf(stderr,
2245 "-verify only works on single input files for now.\n");
2246 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00002247 }
2248 }
Ted Kremenek5c341732008-08-07 17:49:57 +00002249
Chris Lattner4b009652007-07-25 00:24:17 +00002250 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002251 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
2252 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002253 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002254 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002255
Chris Lattner45a56e02007-12-05 23:24:17 +00002256 // -I- is a deprecated GCC feature, scan for it and reject it.
2257 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2258 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002259 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002260 I_dirs.erase(I_dirs.begin()+i);
2261 --i;
2262 }
2263 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002264
2265 // Get information about the target being compiled for.
2266 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002267 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2268
Chris Lattner2c77d852008-03-14 06:12:05 +00002269 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002270 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2271 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002272 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002273 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002274
Daniel Dunbar9c321102009-01-20 23:17:32 +00002275 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002276 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002277
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002278 llvm::OwningPtr<SourceManager> SourceMgr;
2279
Chris Lattner4b009652007-07-25 00:24:17 +00002280 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002281 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002282
Ted Kremenek5c341732008-08-07 17:49:57 +00002283 if (isSerializedFile(InFile)) {
2284 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00002285 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00002286 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002287 }
Chris Lattner2b989562009-03-04 21:40:56 +00002288
2289 /// Create a SourceManager object. This tracks and owns all the file
2290 /// buffers allocated to a translation unit.
2291 if (!SourceMgr)
2292 SourceMgr.reset(new SourceManager());
2293 else
2294 SourceMgr->clearIDTables();
2295
2296 // Initialize language options, inferring file types from input filenames.
2297 LangOptions LangInfo;
2298 InitializeBaseLanguage();
2299 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002300 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00002301 InitializeGCMode(LangInfo);
Fariborz Jahanian49343332009-04-03 03:28:57 +00002302 InitializeSymbolVisibility(LangInfo);
Mike Stumpdb789912009-04-01 20:28:16 +00002303 InitializeOverflowChecking(LangInfo);
Chris Lattner2b989562009-03-04 21:40:56 +00002304 InitializeLanguageStandard(LangInfo, LK, Target.get());
2305
2306 // Process the -I options and set them in the HeaderInfo.
2307 HeaderSearch HeaderInfo(FileMgr);
2308
2309 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2310
2311 // Set up the preprocessor with these options.
2312 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2313 *SourceMgr.get(), HeaderInfo);
2314
2315 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2316
2317 if (!PP)
2318 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002319
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002320 if (ImplicitIncludePCH.empty() &&
2321 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002322 continue;
2323
Chris Lattner2b989562009-03-04 21:40:56 +00002324 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
2325 // always reset to using TextDiagClient.
2326 llvm::OwningPtr<DiagnosticClient> TmpClient;
2327
2328 if (!HTMLDiag.empty()) {
2329 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
2330 &PPFactory));
2331 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00002332 }
Chris Lattner2b989562009-03-04 21:40:56 +00002333 else
2334 Diags.setClient(TextDiagClient);
2335
2336 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002337 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00002338
2339 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00002340 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002341
Mike Stump91d01352009-01-28 02:43:35 +00002342 if (Verbose)
2343 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2344 " hosted on " LLVM_HOSTTRIPLE "\n");
2345
Ted Kremenekec6c5252008-08-07 18:13:12 +00002346 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00002347 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2348 (NumDiagnostics == 1 ? "" : "s"));
2349
2350 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002351 FileMgr.PrintStats();
2352 fprintf(stderr, "\n");
2353 }
2354
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002355 // If verifying diagnostics and we reached here, all is well.
2356 if (VerifyDiagnostics)
2357 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002358
2359 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002360
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002361 // Managed static deconstruction. Useful for making things like
2362 // -time-passes usable.
2363 llvm::llvm_shutdown();
2364
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002365 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002366}