blob: 4e5ff5d2595794380d8a92d686c65a9e94fdad47 [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
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000306static llvm::cl::opt<bool>
307PrintDiagnosticOption("fdiagnostics-show-option",
308 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000309
Chris Lattner4b009652007-07-25 00:24:17 +0000310//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000311// C++ Visualization.
312//===----------------------------------------------------------------------===//
313
314static llvm::cl::opt<std::string>
315InheritanceViewCls("cxx-inheritance-view",
316 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000317 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000318
319//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000320// Builtin Options
321//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000322
323static llvm::cl::opt<bool>
324TimeReport("ftime-report",
325 llvm::cl::desc("Print the amount of time each "
326 "phase of compilation takes"));
327
Douglas Gregor23d23262009-02-14 20:49:29 +0000328static llvm::cl::opt<bool>
329Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000330 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000331 "freestanding environment"));
332
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000333static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000334AllowBuiltins("fbuiltin", llvm::cl::init(true),
335 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000336
337
338static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000339MathErrno("fmath-errno", llvm::cl::init(true),
340 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000341
Douglas Gregor23d23262009-02-14 20:49:29 +0000342//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000343// Language Options
344//===----------------------------------------------------------------------===//
345
346enum LangKind {
347 langkind_unspecified,
348 langkind_c,
349 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000350 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000351 langkind_cxx,
352 langkind_cxx_cpp,
353 langkind_objc,
354 langkind_objc_cpp,
355 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000356 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000357};
358
Chris Lattner4b009652007-07-25 00:24:17 +0000359static llvm::cl::opt<LangKind>
360BaseLang("x", llvm::cl::desc("Base language to compile"),
361 llvm::cl::init(langkind_unspecified),
362 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
363 clEnumValN(langkind_cxx, "c++", "C++"),
364 clEnumValN(langkind_objc, "objective-c", "Objective C"),
365 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000366 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000367 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000368 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
369 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000370 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000371 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000372 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
373 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000374 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000375 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000376 clEnumValN(langkind_c, "c-header",
377 "C header"),
378 clEnumValN(langkind_objc, "objective-c-header",
379 "Objective-C header"),
380 clEnumValN(langkind_cxx, "c++-header",
381 "C++ header"),
382 clEnumValN(langkind_objcxx, "objective-c++-header",
383 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000384 clEnumValEnd));
385
386static llvm::cl::opt<bool>
387LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
388 llvm::cl::Hidden);
389static llvm::cl::opt<bool>
390LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
391 llvm::cl::Hidden);
392
Chris Lattnere1be6022009-04-14 23:22:57 +0000393static llvm::cl::opt<bool>
394ObjCExclusiveGC("fobjc-gc-only",
395 llvm::cl::desc("Use GC exclusively for Objective-C related "
396 "memory management"));
397
398static llvm::cl::opt<bool>
399ObjCEnableGC("fobjc-gc",
400 llvm::cl::desc("Enable Objective-C garbage collection"));
401
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000402static llvm::cl::opt<bool>
403ObjCEnableGCBitmapPrint("print-ivar-layout",
404 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
405
Chris Lattnere1be6022009-04-14 23:22:57 +0000406static llvm::cl::opt<LangOptions::VisibilityMode>
407SymbolVisibility("fvisibility",
408 llvm::cl::desc("Set the default symbol visibility:"),
409 llvm::cl::init(LangOptions::Default),
410 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
411 "Use default symbol visibility"),
412 clEnumValN(LangOptions::Hidden, "hidden",
413 "Use hidden symbol visibility"),
414 clEnumValN(LangOptions::Protected,"protected",
415 "Use protected symbol visibility"),
416 clEnumValEnd));
417
418static llvm::cl::opt<bool>
419OverflowChecking("ftrapv",
420 llvm::cl::desc("Trap on integer overflow"),
421 llvm::cl::init(false));
422
423
Ted Kremenek11ad8952007-12-05 23:49:08 +0000424/// InitializeBaseLanguage - Handle the -x foo options.
425static void InitializeBaseLanguage() {
426 if (LangObjC)
427 BaseLang = langkind_objc;
428 else if (LangObjCXX)
429 BaseLang = langkind_objcxx;
430}
431
432static LangKind GetLanguage(const std::string &Filename) {
433 if (BaseLang != langkind_unspecified)
434 return BaseLang;
435
436 std::string::size_type DotPos = Filename.rfind('.');
437
438 if (DotPos == std::string::npos) {
439 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000440 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000441 }
442
Ted Kremenek11ad8952007-12-05 23:49:08 +0000443 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
444 // C header: .h
445 // C++ header: .hh or .H;
446 // assembler no preprocessing: .s
447 // assembler: .S
448 if (Ext == "c")
449 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000450 else if (Ext == "S" ||
451 // If the compiler is run on a .s file, preprocess it as .S
452 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000453 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000454 else if (Ext == "i")
455 return langkind_c_cpp;
456 else if (Ext == "ii")
457 return langkind_cxx_cpp;
458 else if (Ext == "m")
459 return langkind_objc;
460 else if (Ext == "mi")
461 return langkind_objc_cpp;
462 else if (Ext == "mm" || Ext == "M")
463 return langkind_objcxx;
464 else if (Ext == "mii")
465 return langkind_objcxx_cpp;
466 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
467 Ext == "c++" || Ext == "cp" || Ext == "cxx")
468 return langkind_cxx;
469 else
470 return langkind_c;
471}
472
473
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000474static void InitializeCOptions(LangOptions &Options) {
475 // Do nothing.
476}
477
478static void InitializeObjCOptions(LangOptions &Options) {
479 Options.ObjC1 = Options.ObjC2 = 1;
480}
481
482
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000483static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000484 // FIXME: implement -fpreprocessed mode.
485 bool NoPreprocess = false;
486
Ted Kremenek11ad8952007-12-05 23:49:08 +0000487 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000488 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000489 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000490 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000491 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000492 case langkind_c_cpp:
493 NoPreprocess = true;
494 // FALLTHROUGH
495 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000496 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000497 break;
498 case langkind_cxx_cpp:
499 NoPreprocess = true;
500 // FALLTHROUGH
501 case langkind_cxx:
502 Options.CPlusPlus = 1;
503 break;
504 case langkind_objc_cpp:
505 NoPreprocess = true;
506 // FALLTHROUGH
507 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000508 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000509 break;
510 case langkind_objcxx_cpp:
511 NoPreprocess = true;
512 // FALLTHROUGH
513 case langkind_objcxx:
514 Options.ObjC1 = Options.ObjC2 = 1;
515 Options.CPlusPlus = 1;
516 break;
517 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000518
519 if (ObjCExclusiveGC)
520 Options.setGCMode(LangOptions::GCOnly);
521 else if (ObjCEnableGC)
522 Options.setGCMode(LangOptions::HybridGC);
523
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000524 if (ObjCEnableGCBitmapPrint)
525 Options.ObjCGCBitmapPrint = 1;
526
Chris Lattnere1be6022009-04-14 23:22:57 +0000527 Options.setVisibilityMode(SymbolVisibility);
528 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000529}
530
531/// LangStds - Language standards we support.
532enum LangStds {
533 lang_unspecified,
534 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000535 lang_gnu_START,
536 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000537 lang_cxx98, lang_gnucxx98,
538 lang_cxx0x, lang_gnucxx0x
539};
540
541static llvm::cl::opt<LangStds>
542LangStd("std", llvm::cl::desc("Language standard to compile for"),
543 llvm::cl::init(lang_unspecified),
544 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
545 clEnumValN(lang_c89, "c90", "ISO C 1990"),
546 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
547 clEnumValN(lang_c94, "iso9899:199409",
548 "ISO C 1990 with amendment 1"),
549 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000550 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000551 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000552 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000553 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000554 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000555 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000556 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000557 clEnumValN(lang_gnu99, "gnu9x",
558 "ISO C 1999 with GNU extensions"),
559 clEnumValN(lang_cxx98, "c++98",
560 "ISO C++ 1998 with amendments"),
561 clEnumValN(lang_gnucxx98, "gnu++98",
562 "ISO C++ 1998 with amendments and GNU "
563 "extensions (default for C++)"),
564 clEnumValN(lang_cxx0x, "c++0x",
565 "Upcoming ISO C++ 200x with amendments"),
566 clEnumValN(lang_gnucxx0x, "gnu++0x",
567 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000568 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000569 clEnumValEnd));
570
571static llvm::cl::opt<bool>
572NoOperatorNames("fno-operator-names",
573 llvm::cl::desc("Do not treat C++ operator name keywords as "
574 "synonyms for operators"));
575
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000576static llvm::cl::opt<bool>
577PascalStrings("fpascal-strings",
578 llvm::cl::desc("Recognize and construct Pascal-style "
579 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000580
581static llvm::cl::opt<bool>
582MSExtensions("fms-extensions",
583 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000584 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000585
586static llvm::cl::opt<bool>
587WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000588 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000589
590static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000591NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000592 llvm::cl::desc("Disallow implicit conversions between "
593 "vectors with a different number of "
594 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000595
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000596static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000597EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000598
599static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000600EnableHeinousExtensions("fheinous-gnu-extensions",
601 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
602 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
603
604static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000605ObjCNonFragileABI("fobjc-nonfragile-abi",
606 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000607
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000608static llvm::cl::opt<bool>
609EmitAllDecls("femit-all-decls",
610 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000611
Daniel Dunbar91692d92008-08-11 17:36:14 +0000612// FIXME: This (and all GCC -f options) really come in -f... and
613// -fno-... forms, and additionally support automagic behavior when
614// they are not defined. For example, -fexceptions defaults to on or
615// off depending on the language. We should support this behavior in
616// some form (perhaps just add a facility for distinguishing when an
617// has its default value from when it has been set to its default
618// value).
619static llvm::cl::opt<bool>
620Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000621 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000622
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000623static llvm::cl::opt<bool>
624GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000625 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000626 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000627
628static llvm::cl::opt<bool>
629NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000630 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000631 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000632
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000633
634
635static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000636Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000637
Chris Lattner738d3f62009-03-02 22:11:07 +0000638static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000639TargetFeatures("mattr", llvm::cl::CommaSeparated,
640 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
641
Douglas Gregor375733c2009-03-10 00:06:19 +0000642static llvm::cl::opt<unsigned>
643TemplateDepth("ftemplate-depth", llvm::cl::init(99),
644 llvm::cl::desc("Maximum depth of recursive template "
645 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000646static llvm::cl::opt<bool>
647DollarsInIdents("fdollars-in-identifiers",
648 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000649
Anders Carlssondfd77642009-04-06 17:37:10 +0000650
651static llvm::cl::opt<bool>
652OptSize("Os", llvm::cl::desc("Optimize for size"));
653
654static llvm::cl::opt<bool>
655NoCommon("fno-common",
656 llvm::cl::desc("Compile common globals like normal definitions"),
657 llvm::cl::ValueDisallowed);
658
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000659static llvm::cl::opt<std::string>
660MainFileName("main-file-name",
661 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000662
663// It might be nice to add bounds to the CommandLine library directly.
664struct OptLevelParser : public llvm::cl::parser<unsigned> {
665 bool parse(llvm::cl::Option &O, const char *ArgName,
666 const std::string &Arg, unsigned &Val) {
667 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
668 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000669 if (Val > 3)
670 return O.error(": '" + Arg + "' invalid optimization level!");
671 return false;
672 }
673};
674static llvm::cl::opt<unsigned, false, OptLevelParser>
675OptLevel("O", llvm::cl::Prefix,
676 llvm::cl::desc("Optimization level"),
677 llvm::cl::init(0));
678
Daniel Dunbare079c712009-04-08 03:03:23 +0000679static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000680PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
681
682static llvm::cl::opt<bool>
683StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000684
Daniel Dunbar34542952008-08-23 08:43:39 +0000685static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
686 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000687 // Allow the target to set the default the langauge options as it sees fit.
688 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000689
Chris Lattnerf6790a82009-03-03 19:56:18 +0000690 // If there are any -mattr options, pass them to the target for validation and
691 // processing. The driver should have already consolidated all the
692 // target-feature settings and passed them to us in the -mattr list. The
693 // -mattr list is treated by the code generator as a diff against the -mcpu
694 // setting, but the driver should pass all enabled options as "+" settings.
695 // This means that the target should only look at + settings.
Chris Lattner880d38e2009-04-13 06:33:49 +0000696 if (!TargetFeatures.empty()) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000697 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000698 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
699 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000700 if (Opt != -1) {
701 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000702 fprintf(stderr, "invalid feature '%s'\n",
703 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000704 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000705 fprintf(stderr, "feature '%s': %s\n",
706 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000707 exit(1);
708 }
709 }
710
Chris Lattner4b009652007-07-25 00:24:17 +0000711 if (LangStd == lang_unspecified) {
712 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000713 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000714 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000715 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000716 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000717 case langkind_c_cpp:
718 case langkind_objc:
719 case langkind_objc_cpp:
720 LangStd = lang_gnu99;
721 break;
722 case langkind_cxx:
723 case langkind_cxx_cpp:
724 case langkind_objcxx:
725 case langkind_objcxx_cpp:
726 LangStd = lang_gnucxx98;
727 break;
728 }
729 }
730
731 switch (LangStd) {
732 default: assert(0 && "Unknown language standard!");
733
734 // Fall through from newer standards to older ones. This isn't really right.
735 // FIXME: Enable specifically the right features based on the language stds.
736 case lang_gnucxx0x:
737 case lang_cxx0x:
738 Options.CPlusPlus0x = 1;
739 // FALL THROUGH
740 case lang_gnucxx98:
741 case lang_cxx98:
742 Options.CPlusPlus = 1;
743 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000744 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000745 // FALL THROUGH.
746 case lang_gnu99:
747 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000748 Options.C99 = 1;
749 Options.HexFloats = 1;
750 // FALL THROUGH.
751 case lang_gnu89:
752 Options.BCPLComment = 1; // Only for C99/C++.
753 // FALL THROUGH.
754 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000755 Options.Digraphs = 1; // C94, C99, C++.
756 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000757 case lang_c89:
758 break;
759 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000760
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000761 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
762 Options.GNUMode = LangStd >= lang_gnu_START;
763
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000764 if (Options.CPlusPlus) {
765 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000766 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000767 }
Chris Lattner4b009652007-07-25 00:24:17 +0000768
Chris Lattner6ab935b2008-04-05 06:32:51 +0000769 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
770 Options.ImplicitInt = 1;
771 else
772 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000773
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000774 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
775 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000776 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000777 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000778 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000779
Chris Lattner58d5ba52008-12-05 00:10:44 +0000780 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
781 // even if they are normally on for the target. In GNU modes (e.g.
782 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000783 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000784 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000785 Options.Blocks = 0;
786
Chris Lattner284784c2009-04-19 07:06:52 +0000787 // Default to not accepting '$' in identifiers when preprocessing assembler,
788 // but do accept when preprocessing C. FIXME: these defaults are right for
789 // darwin, are they right everywhere?
790 Options.DollarIdents = LK != langkind_asm_cpp;
791 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000792 Options.DollarIdents = DollarsInIdents;
793
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000794 if (PascalStrings.getPosition())
795 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000796 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000797 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000798 if (NoLaxVectorConversions.getPosition())
799 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000800 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000801 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000802 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000803
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000804 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000805 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000806 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000807 Options.Freestanding = Options.NoBuiltin = 1;
808
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000809 if (EnableHeinousExtensions)
810 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000811
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000812 Options.MathErrno = MathErrno;
813
Douglas Gregor375733c2009-03-10 00:06:19 +0000814 Options.InstantiationDepth = TemplateDepth;
815
Chris Lattnerddae7102008-12-04 22:54:33 +0000816 // Override the default runtime if the user requested it.
817 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000818 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000819 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000820 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000821
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000822 if (ObjCNonFragileABI)
823 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000824
825 if (EmitAllDecls)
826 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000827
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000828 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
829 // support.
830 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000831
832 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000833 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000834 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000835
836 assert(PICLevel <= 2 && "Invalid value for -pic-level");
837 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000838
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000839 Options.GNUInline = !Options.C99;
840 // FIXME: This is affected by other options (-fno-inline).
841 Options.NoInline = !OptSize && !OptLevel;
842
843 Options.Static = StaticDefine;
844
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000845 if (MainFileName.getPosition())
846 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000847}
848
849//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000850// Target Triple Processing.
851//===----------------------------------------------------------------------===//
852
853static llvm::cl::opt<std::string>
854TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000855 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000856
Chris Lattnerfc457002008-03-05 01:18:20 +0000857static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000858Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000859
Chris Lattner2b168e02008-09-30 01:13:12 +0000860static llvm::cl::opt<std::string>
861MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000862 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000863
Chris Lattner01de9c82008-09-30 20:16:56 +0000864// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
865// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000866
867// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000868static void HandleMacOSVersionMin(std::string &Triple) {
869 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
870 if (DarwinDashIdx == std::string::npos) {
871 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000872 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000873 exit(1);
874 }
875 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
876
Chris Lattner01de9c82008-09-30 20:16:56 +0000877 // Remove the number.
878 Triple.resize(DarwinNumIdx);
879
880 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
881 bool MacOSVersionMinIsInvalid = false;
882 int VersionNum = 0;
883 if (MacOSVersionMin.size() < 4 ||
884 MacOSVersionMin.substr(0, 3) != "10." ||
885 !isdigit(MacOSVersionMin[3])) {
886 MacOSVersionMinIsInvalid = true;
887 } else {
888 const char *Start = MacOSVersionMin.c_str()+3;
889 char *End = 0;
890 VersionNum = (int)strtol(Start, &End, 10);
891
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000892 // The version number must be in the range 0-9.
893 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
894
Chris Lattner01de9c82008-09-30 20:16:56 +0000895 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
896 Triple += llvm::itostr(VersionNum+4);
897
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000898 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
899 // Add the period piece (.7) to the end of the triple. This gives us
900 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000901 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000902 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
903 MacOSVersionMinIsInvalid = true;
904 }
905 }
906
907 if (MacOSVersionMinIsInvalid) {
908 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000909 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000910 MacOSVersionMin.c_str());
911 exit(1);
912 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000913 else if (VersionNum <= 4 &&
914 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
915 fprintf(stderr,
916 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
917 MacOSVersionMin.c_str());
918 exit(1);
919 }
920
Chris Lattner01de9c82008-09-30 20:16:56 +0000921}
922
Daniel Dunbar93f64532009-04-10 19:52:24 +0000923static llvm::cl::opt<std::string>
924IPhoneOSVersionMin("miphoneos-version-min",
925 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
926
927// If -miphoneos-version-min=2.2 is specified, change the triple from being
928// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
929// 9 as the default major Darwin number, and encode the iPhone OS version
930// number in the minor version and revision.
931
932// FIXME: We should have the driver do this instead.
933static void HandleIPhoneOSVersionMin(std::string &Triple) {
934 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
935 if (DarwinDashIdx == std::string::npos) {
936 fprintf(stderr,
937 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
938 exit(1);
939 }
940 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
941
942 // Remove the number.
943 Triple.resize(DarwinNumIdx);
944
945 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
946 bool IPhoneOSVersionMinIsInvalid = false;
947 int VersionNum = 0;
948 if (IPhoneOSVersionMin.size() < 3 ||
949 !isdigit(IPhoneOSVersionMin[0])) {
950 IPhoneOSVersionMinIsInvalid = true;
951 } else {
952 const char *Start = IPhoneOSVersionMin.c_str();
953 char *End = 0;
954 VersionNum = (int)strtol(Start, &End, 10);
955
956 // The version number must be in the range 0-9.
957 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
958
959 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
960 Triple += "9." + llvm::itostr(VersionNum);
961
962 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
963 // Add the period piece (.2) to the end of the triple. This gives us
964 // something like ...-darwin9.2.2
965 Triple += End;
966 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
967 IPhoneOSVersionMinIsInvalid = true;
968 }
969 }
970
971 if (IPhoneOSVersionMinIsInvalid) {
972 fprintf(stderr,
973 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
974 IPhoneOSVersionMin.c_str());
975 exit(1);
976 }
977}
978
Chris Lattner01de9c82008-09-30 20:16:56 +0000979/// CreateTargetTriple - Process the various options that affect the target
980/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000981static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000982 // Initialize base triple. If a -triple option has been specified, use
983 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000984 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000985 if (Triple.empty())
986 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000987
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000988 // If -arch foo was specified, remove the architecture from the triple we have
989 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000990
991 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000992 if (!Arch.empty()) {
993 // Decompose the base triple into "arch" and suffix.
994 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000995
Chris Lattner2b168e02008-09-30 01:13:12 +0000996 if (FirstDashIdx == std::string::npos) {
997 fprintf(stderr,
998 "Malformed target triple: \"%s\" ('-' could not be found).\n",
999 Triple.c_str());
1000 exit(1);
1001 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +00001002
1003 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1004 if (Arch == "ppc")
1005 Arch = "powerpc";
1006 else if (Arch == "ppc64")
1007 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001008
Chris Lattner2b168e02008-09-30 01:13:12 +00001009 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1010 }
1011
1012 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1013 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001014 if (!MacOSVersionMin.empty())
1015 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001016 else if (!IPhoneOSVersionMin.empty())
1017 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001018
Chris Lattner2b168e02008-09-30 01:13:12 +00001019 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001020}
1021
1022//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001023// Preprocessor Initialization
1024//===----------------------------------------------------------------------===//
1025
1026// FIXME: Preprocessor builtins to support.
1027// -A... - Play with #assertions
1028// -undef - Undefine all predefined macros
1029
Chris Lattner695a4f52009-03-13 01:08:23 +00001030// FIXME: -imacros
1031
Chris Lattner4b009652007-07-25 00:24:17 +00001032static llvm::cl::list<std::string>
1033D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1034 llvm::cl::desc("Predefine the specified macro"));
1035static llvm::cl::list<std::string>
1036U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1037 llvm::cl::desc("Undefine the specified macro"));
1038
Chris Lattner008da782008-01-10 01:53:41 +00001039static llvm::cl::list<std::string>
1040ImplicitIncludes("include", llvm::cl::value_desc("file"),
1041 llvm::cl::desc("Include file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001042static llvm::cl::list<std::string>
1043ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1044 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner008da782008-01-10 01:53:41 +00001045
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001046static llvm::cl::opt<std::string>
1047ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1048 llvm::cl::desc("Include file before parsing"));
1049
Douglas Gregorc34897d2009-04-09 22:27:44 +00001050static llvm::cl::opt<std::string>
1051ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1052 llvm::cl::desc("Include precompiled header file"));
1053
Chris Lattner4b009652007-07-25 00:24:17 +00001054// Append a #define line to Buf for Macro. Macro should be of the form XXX,
1055// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
1056// "#define XXX Y z W". To get a #define with no value, use "XXX=".
1057static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
1058 const char *Command = "#define ") {
1059 Buf.insert(Buf.end(), Command, Command+strlen(Command));
1060 if (const char *Equal = strchr(Macro, '=')) {
1061 // Turn the = into ' '.
1062 Buf.insert(Buf.end(), Macro, Equal);
1063 Buf.push_back(' ');
Chris Lattner39baafb2009-04-07 06:02:44 +00001064
1065 // Per GCC -D semantics, the macro ends at \n if it exists.
1066 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner39c610d2009-04-07 18:18:09 +00001067 if (End) {
Chris Lattnerd93f7902009-04-08 03:36:03 +00001068 fprintf(stderr, "warning: macro '%s' contains embedded newline, text "
Chris Lattner39c610d2009-04-07 18:18:09 +00001069 "after the newline is ignored.\n",
1070 std::string(Macro, Equal).c_str());
1071 } else {
1072 End = Equal+strlen(Equal);
1073 }
Chris Lattner39baafb2009-04-07 06:02:44 +00001074
1075 Buf.insert(Buf.end(), Equal+1, End);
Chris Lattner4b009652007-07-25 00:24:17 +00001076 } else {
1077 // Push "macroname 1".
1078 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
1079 Buf.push_back(' ');
1080 Buf.push_back('1');
1081 }
1082 Buf.push_back('\n');
1083}
1084
Daniel Dunbar43b91692009-04-09 00:51:16 +00001085/// Add the quoted name of an implicit include file.
1086static void AddQuotedIncludePath(std::vector<char> &Buf,
1087 const std::string &File) {
1088 // Implicit include paths are relative to the current working
1089 // directory; resolve them now instead of using the normal machinery
1090 // (which would look relative to the input file).
1091 llvm::sys::Path Path(File);
1092 Path.makeAbsolute();
1093
Chris Lattner6ac92a32009-04-08 20:10:57 +00001094 // Escape double quotes etc.
Daniel Dunbar43b91692009-04-09 00:51:16 +00001095 Buf.push_back('"');
1096 std::string EscapedFile = Lexer::Stringify(Path.toString());
Chris Lattner6ac92a32009-04-08 20:10:57 +00001097 Buf.insert(Buf.end(), EscapedFile.begin(), EscapedFile.end());
Chris Lattner008da782008-01-10 01:53:41 +00001098 Buf.push_back('"');
Daniel Dunbar43b91692009-04-09 00:51:16 +00001099}
1100
1101/// AddImplicitInclude - Add an implicit #include of the specified file to the
1102/// predefines buffer.
1103static void AddImplicitInclude(std::vector<char> &Buf,
1104 const std::string &File) {
1105 const char *Inc = "#include ";
1106 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
1107 AddQuotedIncludePath(Buf, File);
Chris Lattner008da782008-01-10 01:53:41 +00001108 Buf.push_back('\n');
1109}
1110
Chris Lattner0e004a12009-04-08 18:24:34 +00001111static void AddImplicitIncludeMacros(std::vector<char> &Buf,
1112 const std::string &File) {
Daniel Dunbar43b91692009-04-09 00:51:16 +00001113 const char *Inc = "#__include_macros ";
Chris Lattner0e004a12009-04-08 18:24:34 +00001114 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
Daniel Dunbar43b91692009-04-09 00:51:16 +00001115 AddQuotedIncludePath(Buf, File);
Chris Lattner0e004a12009-04-08 18:24:34 +00001116 Buf.push_back('\n');
Chris Lattnera6e44112009-04-08 20:53:24 +00001117 // Marker token to stop the __include_macros fetch loop.
1118 const char *Marker = "##\n"; // ##?
1119 Buf.insert(Buf.end(), Marker, Marker+strlen(Marker));
Chris Lattner0e004a12009-04-08 18:24:34 +00001120}
1121
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001122/// AddImplicitIncludePTH - Add an implicit #include using the original file
1123/// used to generate a PTH cache.
Chris Lattner0e004a12009-04-08 18:24:34 +00001124static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor &PP) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001125 PTHManager *P = PP.getPTHManager();
1126 assert(P && "No PTHManager.");
1127 const char *OriginalFile = P->getOriginalSourceFile();
1128
1129 if (!OriginalFile) {
1130 assert(!ImplicitIncludePTH.empty());
1131 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1132 "source header file for -include-pth\n",
1133 ImplicitIncludePTH.c_str());
1134 exit (1);
1135 }
1136
1137 AddImplicitInclude(Buf, OriginalFile);
1138}
Chris Lattner4b009652007-07-25 00:24:17 +00001139
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001140/// PickFP - This is used to pick a value based on the FP semantics of the
1141/// specified FP model.
1142template <typename T>
1143static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
1144 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
1145 if (Sem == &llvm::APFloat::IEEEsingle)
1146 return IEEESingleVal;
1147 if (Sem == &llvm::APFloat::IEEEdouble)
1148 return IEEEDoubleVal;
1149 if (Sem == &llvm::APFloat::x87DoubleExtended)
1150 return X87DoubleExtendedVal;
1151 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
1152 return PPCDoubleDoubleVal;
1153}
1154
1155static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
1156 const llvm::fltSemantics *Sem) {
1157 const char *DenormMin, *Epsilon, *Max, *Min;
1158 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
1159 "3.64519953188247460253e-4951L",
1160 "4.94065645841246544176568792868221e-324L");
1161 int Digits = PickFP(Sem, 6, 15, 18, 31);
1162 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
1163 "1.08420217248550443401e-19L",
1164 "4.94065645841246544176568792868221e-324L");
1165 int HasInifinity = 1, HasQuietNaN = 1;
1166 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
1167 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
1168 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
1169 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
1170 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
1171 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
1172 "3.36210314311209350626e-4932L",
1173 "2.00416836000897277799610805135016e-292L");
1174 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
1175 "1.18973149535723176502e+4932L",
1176 "1.79769313486231580793728971405301e+308L");
1177
1178 char MacroBuf[60];
1179 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
1180 DefineBuiltinMacro(Buf, MacroBuf);
1181 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
1182 DefineBuiltinMacro(Buf, MacroBuf);
1183 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
1184 DefineBuiltinMacro(Buf, MacroBuf);
1185 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
1186 DefineBuiltinMacro(Buf, MacroBuf);
1187 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
1188 DefineBuiltinMacro(Buf, MacroBuf);
1189 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
1190 DefineBuiltinMacro(Buf, MacroBuf);
1191 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
1192 DefineBuiltinMacro(Buf, MacroBuf);
1193 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
1194 DefineBuiltinMacro(Buf, MacroBuf);
1195 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
1196 DefineBuiltinMacro(Buf, MacroBuf);
1197 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
1198 DefineBuiltinMacro(Buf, MacroBuf);
1199 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
1200 DefineBuiltinMacro(Buf, MacroBuf);
1201 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
1202 DefineBuiltinMacro(Buf, MacroBuf);
1203 sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix);
1204 DefineBuiltinMacro(Buf, MacroBuf);
1205}
1206
1207
1208/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
1209/// named MacroName with the max value for a type with width 'TypeWidth' a
1210/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
1211static void DefineTypeSize(const char *MacroName, unsigned TypeWidth,
1212 const char *ValSuffix, bool isSigned,
1213 std::vector<char> &Buf) {
1214 char MacroBuf[60];
1215 long long MaxVal;
1216 if (isSigned)
1217 MaxVal = (1LL << (TypeWidth - 1)) - 1;
1218 else
1219 MaxVal = ~0LL >> (64-TypeWidth);
1220
1221 sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix);
1222 DefineBuiltinMacro(Buf, MacroBuf);
1223}
1224
1225static void DefineType(const char *MacroName, TargetInfo::IntType Ty,
1226 std::vector<char> &Buf) {
1227 char MacroBuf[60];
1228 sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty));
1229 DefineBuiltinMacro(Buf, MacroBuf);
1230}
1231
1232
1233static void InitializePredefinedMacros(const TargetInfo &TI,
1234 const LangOptions &LangOpts,
1235 std::vector<char> &Buf) {
1236 char MacroBuf[60];
1237 // Compiler version introspection macros.
1238 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
1239 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
1240
1241 // Currently claim to be compatible with GCC 4.2.1-5621.
1242 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
1243 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
1244 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
1245 DefineBuiltinMacro(Buf, "__GNUC__=4");
1246 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
1247 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\"");
1248
1249
1250 // Initialize language-specific preprocessor defines.
1251
1252 // These should all be defined in the preprocessor according to the
1253 // current language configuration.
1254 if (!LangOpts.Microsoft)
1255 DefineBuiltinMacro(Buf, "__STDC__=1");
1256 if (LangOpts.AsmPreprocessor)
1257 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
1258 if (LangOpts.C99 && !LangOpts.CPlusPlus)
1259 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
1260 else if (0) // STDC94 ?
1261 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
1262
1263 // Standard conforming mode?
1264 if (!LangOpts.GNUMode)
1265 DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1");
1266
1267 if (LangOpts.CPlusPlus0x)
1268 DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__");
1269
1270 if (LangOpts.Freestanding)
1271 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0");
1272 else
1273 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
1274
1275 if (LangOpts.ObjC1) {
1276 DefineBuiltinMacro(Buf, "__OBJC__=1");
1277 if (LangOpts.ObjCNonFragileABI) {
1278 DefineBuiltinMacro(Buf, "__OBJC2__=1");
1279 DefineBuiltinMacro(Buf, "OBJC_ZEROCOST_EXCEPTIONS=1");
1280 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
1281 }
1282
1283 if (LangOpts.getGCMode() != LangOptions::NonGC)
1284 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
1285
1286 if (LangOpts.NeXTRuntime)
1287 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
1288 }
1289
1290 // darwin_constant_cfstrings controls this. This is also dependent
1291 // on other things like the runtime I believe. This is set even for C code.
1292 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
1293
1294 if (LangOpts.ObjC2)
1295 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
1296
1297 if (LangOpts.PascalStrings)
1298 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
1299
1300 if (LangOpts.Blocks) {
1301 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
1302 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
1303 }
1304
1305 if (LangOpts.CPlusPlus) {
1306 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
1307 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
1308 DefineBuiltinMacro(Buf, "__GNUG__=4");
1309 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
1310 DefineBuiltinMacro(Buf, "__cplusplus=1");
1311 DefineBuiltinMacro(Buf, "__private_extern__=extern");
1312 }
1313
1314 // Filter out some microsoft extensions when trying to parse in ms-compat
1315 // mode.
1316 if (LangOpts.Microsoft) {
1317 DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
1318 DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__");
1319 DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__");
1320 DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__");
1321 DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__");
1322 }
1323
1324 if (LangOpts.Optimize)
1325 DefineBuiltinMacro(Buf, "__OPTIMIZE__=1");
1326 if (LangOpts.OptimizeSize)
1327 DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1");
1328
1329 // Initialize target-specific preprocessor defines.
1330
1331 // Define type sizing macros based on the target properties.
1332 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
1333 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
1334
1335 unsigned IntMaxWidth;
1336 const char *IntMaxSuffix;
1337 if (TI.getIntMaxType() == TargetInfo::SignedLongLong) {
1338 IntMaxWidth = TI.getLongLongWidth();
1339 IntMaxSuffix = "LL";
1340 } else if (TI.getIntMaxType() == TargetInfo::SignedLong) {
1341 IntMaxWidth = TI.getLongWidth();
1342 IntMaxSuffix = "L";
1343 } else {
1344 assert(TI.getIntMaxType() == TargetInfo::SignedInt);
1345 IntMaxWidth = TI.getIntWidth();
1346 IntMaxSuffix = "";
1347 }
1348
1349 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
1350 DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf);
1351 DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf);
1352 DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf);
1353 DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf);
1354 DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf);
1355 DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf);
1356
1357 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
1358 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
1359 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
1360 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf);
1361 DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
1362 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
1363 // FIXME: TargetInfo hookize __WINT_TYPE__.
1364 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
1365
1366 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
1367 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
1368 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
1369
1370 // Define a __POINTER_WIDTH__ macro for stdint.h.
1371 sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0));
1372 DefineBuiltinMacro(Buf, MacroBuf);
1373
1374 if (!TI.isCharSigned())
1375 DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__");
1376
1377 // Define fixed-sized integer types for stdint.h
1378 assert(TI.getCharWidth() == 8 && "unsupported target types");
1379 assert(TI.getShortWidth() == 16 && "unsupported target types");
1380 DefineBuiltinMacro(Buf, "__INT8_TYPE__=char");
1381 DefineBuiltinMacro(Buf, "__INT16_TYPE__=short");
1382
1383 if (TI.getIntWidth() == 32)
1384 DefineBuiltinMacro(Buf, "__INT32_TYPE__=int");
1385 else {
1386 assert(TI.getLongLongWidth() == 32 && "unsupported target types");
1387 DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long");
1388 }
1389
1390 // 16-bit targets doesn't necessarily have a 64-bit type.
1391 if (TI.getLongLongWidth() == 64)
1392 DefineBuiltinMacro(Buf, "__INT64_TYPE__=long long");
1393
1394 // Add __builtin_va_list typedef.
1395 {
1396 const char *VAList = TI.getVAListDeclaration();
1397 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
1398 Buf.push_back('\n');
1399 }
1400
1401 if (const char *Prefix = TI.getUserLabelPrefix()) {
1402 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
1403 DefineBuiltinMacro(Buf, MacroBuf);
1404 }
1405
1406 // Build configuration options. FIXME: these should be controlled by
1407 // command line options or something.
1408 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
1409
1410 if (LangOpts.Static)
1411 DefineBuiltinMacro(Buf, "__STATIC__=1");
1412 else
1413 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
1414
1415 if (LangOpts.GNUInline)
1416 DefineBuiltinMacro(Buf, "__GNUC_GNU_INLINE__=1");
1417 else
1418 DefineBuiltinMacro(Buf, "__GNUC_STDC_INLINE__=1");
1419
1420 if (LangOpts.NoInline)
1421 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
1422
1423 if (unsigned PICLevel = LangOpts.PICLevel) {
1424 sprintf(MacroBuf, "__PIC__=%d", PICLevel);
1425 DefineBuiltinMacro(Buf, MacroBuf);
1426
1427 sprintf(MacroBuf, "__pic__=%d", PICLevel);
1428 DefineBuiltinMacro(Buf, MacroBuf);
1429 }
1430
1431 // Macros to control C99 numerics and <float.h>
1432 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
1433 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
1434 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
1435 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
1436 DefineBuiltinMacro(Buf, MacroBuf);
1437
1438 // Get other target #defines.
1439 TI.getTargetDefines(LangOpts, Buf);
1440}
1441
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001442static bool InitializeSourceManager(Preprocessor &PP,
1443 const std::string &InFile) {
1444 // Figure out where to get and map in the main file.
1445 SourceManager &SourceMgr = PP.getSourceManager();
1446 FileManager &FileMgr = PP.getFileManager();
1447
1448 if (InFile != "-") {
1449 const FileEntry *File = FileMgr.getFile(InFile);
1450 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1451 if (SourceMgr.getMainFileID().isInvalid()) {
1452 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1453 << InFile.c_str();
1454 return true;
1455 }
1456 } else {
1457 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1458
1459 // If stdin was empty, SB is null. Cons up an empty memory
1460 // buffer now.
1461 if (!SB) {
1462 const char *EmptyStr = "";
1463 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1464 }
1465
1466 SourceMgr.createMainFileIDForMemBuffer(SB);
1467 if (SourceMgr.getMainFileID().isInvalid()) {
1468 PP.getDiagnostics().Report(FullSourceLoc(),
1469 diag::err_fe_error_reading_stdin);
1470 return true;
1471 }
1472 }
1473
1474 return false;
1475}
1476
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001477/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +00001478/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001479///
Chris Lattner9d818a22008-04-19 23:25:44 +00001480static bool InitializePreprocessor(Preprocessor &PP,
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001481 const std::string &InFile) {
Chris Lattner47b6a162008-04-19 23:09:31 +00001482 std::vector<char> PredefineBuffer;
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001483
1484 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
1485 InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
1486 PredefineBuffer);
1487
1488 // Add on the predefines from the driver. Wrap in a #line directive to report
1489 // that they come from the command line.
1490 const char *LineDirective = "# 1 \"<command line>\" 1\n";
1491 PredefineBuffer.insert(PredefineBuffer.end(),
1492 LineDirective, LineDirective+strlen(LineDirective));
1493
Chris Lattner47b6a162008-04-19 23:09:31 +00001494
Chris Lattner4b009652007-07-25 00:24:17 +00001495 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +00001496 unsigned d = 0, D = D_macros.size();
1497 unsigned u = 0, U = U_macros.size();
1498 while (d < D || u < U) {
1499 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1500 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1501 else
1502 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1503 }
1504
Chris Lattnerb62396d2009-04-08 20:15:42 +00001505 // If -imacros are specified, include them now. These are processed before
1506 // any -include directives.
1507
1508 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1509 AddImplicitIncludeMacros(PredefineBuffer, ImplicitMacroIncludes[i]);
Chris Lattner008da782008-01-10 01:53:41 +00001510
Chris Lattnerb62396d2009-04-08 20:15:42 +00001511 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1512 // We want to add these paths to the predefines buffer in order, make a
1513 // temporary vector to sort by their occurrence.
Chris Lattner0e004a12009-04-08 18:24:34 +00001514 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1515
1516 if (!ImplicitIncludePTH.empty())
1517 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1518 &ImplicitIncludePTH));
1519 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1520 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1521 &ImplicitIncludes[i]));
Chris Lattner0e004a12009-04-08 18:24:34 +00001522 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1523
1524 // Now that they are ordered by position, add to the predefines buffer.
1525 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1526 std::string *Ptr = OrderedPaths[i].second;
1527 if (!ImplicitIncludes.empty() &&
1528 Ptr >= &ImplicitIncludes[0] &&
1529 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1530 AddImplicitInclude(PredefineBuffer, *Ptr);
Chris Lattner0e004a12009-04-08 18:24:34 +00001531 } else {
Chris Lattnerb62396d2009-04-08 20:15:42 +00001532 assert(Ptr == &ImplicitIncludePTH);
1533 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner0e004a12009-04-08 18:24:34 +00001534 }
1535 }
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001536 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001537
Chris Lattnera9a0dd52009-04-10 21:58:23 +00001538 LineDirective = "# 2 \"<built-in>\" 2\n";
1539 PredefineBuffer.insert(PredefineBuffer.end(),
1540 LineDirective, LineDirective+strlen(LineDirective));
1541
Chris Lattner47b6a162008-04-19 23:09:31 +00001542 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001543 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +00001544 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001545
1546 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +00001547 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001548}
1549
1550//===----------------------------------------------------------------------===//
1551// Preprocessor include path information.
1552//===----------------------------------------------------------------------===//
1553
1554// This tool exports a large number of command line options to control how the
1555// preprocessor searches for header files. At root, however, the Preprocessor
1556// object takes a very simple interface: a list of directories to search for
1557//
1558// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001559// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001560//
Chris Lattner4b009652007-07-25 00:24:17 +00001561
1562static llvm::cl::opt<bool>
1563nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1564
1565// Various command line options. These four add directories to each chain.
1566static llvm::cl::list<std::string>
1567F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1568 llvm::cl::desc("Add directory to framework include search path"));
1569static llvm::cl::list<std::string>
1570I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1571 llvm::cl::desc("Add directory to include search path"));
1572static llvm::cl::list<std::string>
1573idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1574 llvm::cl::desc("Add directory to AFTER include search path"));
1575static llvm::cl::list<std::string>
1576iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1577 llvm::cl::desc("Add directory to QUOTE include search path"));
1578static llvm::cl::list<std::string>
1579isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1580 llvm::cl::desc("Add directory to SYSTEM include search path"));
1581
1582// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1583static llvm::cl::list<std::string>
1584iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1585 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1586static llvm::cl::list<std::string>
1587iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1588 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1589static llvm::cl::list<std::string>
1590iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1591 llvm::cl::Prefix,
1592 llvm::cl::desc("Set directory to include search path with prefix"));
1593
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001594static llvm::cl::opt<std::string>
1595isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1596 llvm::cl::desc("Set the system root directory (usually /)"));
1597
Chris Lattner4b009652007-07-25 00:24:17 +00001598// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001599
Chris Lattner4b009652007-07-25 00:24:17 +00001600/// InitializeIncludePaths - Process the -I options and set them in the
1601/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001602void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1603 FileManager &FM, const LangOptions &Lang) {
1604 InitHeaderSearch Init(Headers, Verbose, isysroot);
1605
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001606 // Handle -I... and -F... options, walking the lists in parallel.
1607 unsigned Iidx = 0, Fidx = 0;
1608 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1609 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001610 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001611 ++Iidx;
1612 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001613 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001614 ++Fidx;
1615 }
1616 }
Chris Lattner4b009652007-07-25 00:24:17 +00001617
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001618 // Consume what's left from whatever list was longer.
1619 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001620 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001621 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001622 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001623
1624 // Handle -idirafter... options.
1625 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001626 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1627 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001628
1629 // Handle -iquote... options.
1630 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001631 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001632
1633 // Handle -isystem... options.
1634 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001635 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001636
1637 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1638 // parallel, processing the values in order of occurance to get the right
1639 // prefixes.
1640 {
1641 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1642 unsigned iprefix_idx = 0;
1643 unsigned iwithprefix_idx = 0;
1644 unsigned iwithprefixbefore_idx = 0;
1645 bool iprefix_done = iprefix_vals.empty();
1646 bool iwithprefix_done = iwithprefix_vals.empty();
1647 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1648 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1649 if (!iprefix_done &&
1650 (iwithprefix_done ||
1651 iprefix_vals.getPosition(iprefix_idx) <
1652 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1653 (iwithprefixbefore_done ||
1654 iprefix_vals.getPosition(iprefix_idx) <
1655 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1656 Prefix = iprefix_vals[iprefix_idx];
1657 ++iprefix_idx;
1658 iprefix_done = iprefix_idx == iprefix_vals.size();
1659 } else if (!iwithprefix_done &&
1660 (iwithprefixbefore_done ||
1661 iwithprefix_vals.getPosition(iwithprefix_idx) <
1662 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001663 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1664 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001665 ++iwithprefix_idx;
1666 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1667 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001668 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1669 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001670 ++iwithprefixbefore_idx;
1671 iwithprefixbefore_done =
1672 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1673 }
1674 }
1675 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001676
Nico Weber770e3882008-08-22 09:25:22 +00001677 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001678
Daniel Dunbar4e604292009-02-21 20:52:41 +00001679 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001680 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001681 llvm::sys::Path::GetMainExecutable(Argv0,
1682 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001683 if (!MainExecutablePath.isEmpty()) {
1684 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1685 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001686
1687 // Get foo/lib/clang/1.0/include
1688 //
1689 // FIXME: Don't embed version here.
1690 MainExecutablePath.appendComponent("lib");
1691 MainExecutablePath.appendComponent("clang");
1692 MainExecutablePath.appendComponent("1.0");
1693 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001694
1695 // We pass true to ignore sysroot so that we *always* look for clang headers
1696 // relative to our executable, never relative to -isysroot.
1697 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1698 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001699 }
1700
Nico Weber770e3882008-08-22 09:25:22 +00001701 if (!nostdinc)
1702 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001703
1704 // Now that we have collected all of the include paths, merge them all
1705 // together and tell the preprocessor about them.
1706
Nico Weber770e3882008-08-22 09:25:22 +00001707 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001708}
1709
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001710//===----------------------------------------------------------------------===//
1711// Driver PreprocessorFactory - For lazily generating preprocessors ...
1712//===----------------------------------------------------------------------===//
1713
1714namespace {
1715class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001716 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001717 Diagnostic &Diags;
1718 const LangOptions &LangInfo;
1719 TargetInfo &Target;
1720 SourceManager &SourceMgr;
1721 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001722
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001723public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001724 DriverPreprocessorFactory(const std::string &infile,
1725 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001726 TargetInfo &target, SourceManager &SM,
1727 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001728 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001729 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001730
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001731
1732 virtual ~DriverPreprocessorFactory() {}
1733
1734 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001735 llvm::OwningPtr<PTHManager> PTHMgr;
1736
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001737 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1738 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1739 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001740 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001741 }
1742
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001743 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001744 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1745 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001746 PTHMgr.reset(PTHManager::Create(x, &Diags,
1747 TokenCache.empty() ? Diagnostic::Error
1748 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001749 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001750
Ted Kremenek6348cc62009-03-22 06:42:39 +00001751 if (Diags.hasErrorOccurred())
1752 exit(1);
1753
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001754 // Create the Preprocessor.
1755 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1756 SourceMgr, HeaderInfo,
1757 PTHMgr.get()));
1758
1759 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1760 // That argument is used as the IdentifierInfoLookup argument to
1761 // IdentifierTable's ctor.
1762 if (PTHMgr) {
1763 PTHMgr->setPreprocessor(PP.get());
1764 PP->setPTHManager(PTHMgr.take());
1765 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001766
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001767 if (InitializePreprocessor(*PP, InFile))
1768 return 0;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001769
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001770 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001771 if (ProgAction != PrintPreprocessedInput) {
1772 std::string ErrStr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001773 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001774 if (!DFG && !ErrStr.empty()) {
1775 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001776 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001777 }
1778 }
1779
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001780 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001781 }
1782};
1783}
Chris Lattner4b009652007-07-25 00:24:17 +00001784
Chris Lattner4b009652007-07-25 00:24:17 +00001785//===----------------------------------------------------------------------===//
1786// Basic Parser driver
1787//===----------------------------------------------------------------------===//
1788
Chris Lattner9d818a22008-04-19 23:25:44 +00001789static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001790 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001791 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001792
1793 // Parsing the specified input file.
1794 P.ParseTranslationUnit();
1795 delete PA;
1796}
1797
1798//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001799// Code generation options
1800//===----------------------------------------------------------------------===//
1801
1802static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001803GenerateDebugInfo("g",
1804 llvm::cl::desc("Generate source level debug information"));
1805
Daniel Dunbar9101a632009-02-17 19:47:34 +00001806static llvm::cl::opt<std::string>
1807TargetCPU("mcpu",
1808 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1809
Chris Lattner8a9615c2009-03-16 18:41:18 +00001810static void InitializeCompileOptions(CompileOptions &Opts,
1811 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001812 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001813 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001814 if (OptSize) {
1815 // -Os implies -O2
1816 // FIXME: Diagnose conflicting options.
1817 Opts.OptimizationLevel = 2;
1818 } else {
1819 Opts.OptimizationLevel = OptLevel;
1820 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001821
1822 // FIXME: There are llvm-gcc options to control these selectively.
1823 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1824 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001825 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001826
1827#ifdef NDEBUG
1828 Opts.VerifyModule = 0;
1829#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001830
1831 Opts.CPU = TargetCPU;
1832 Opts.Features.insert(Opts.Features.end(),
1833 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001834
Chris Lattnerf04a7562009-03-26 05:00:52 +00001835 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1836
Chris Lattnere8f70712009-02-18 01:23:44 +00001837 // Handle -ftime-report.
1838 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001839}
1840
1841//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001842// Fix-It Options
1843//===----------------------------------------------------------------------===//
1844static llvm::cl::list<ParsedSourceLocation>
1845FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1846 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1847
1848//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001849// -dump-build-information Stuff
1850//===----------------------------------------------------------------------===//
1851
1852static llvm::cl::opt<std::string>
1853DumpBuildInformation("dump-build-information",
1854 llvm::cl::value_desc("filename"),
1855 llvm::cl::desc("output a dump of some build information to a file"));
1856
1857static llvm::raw_ostream *BuildLogFile = 0;
1858
1859/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1860/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1861namespace {
1862class LoggingDiagnosticClient : public DiagnosticClient {
1863 llvm::OwningPtr<DiagnosticClient> Chain1;
1864 llvm::OwningPtr<DiagnosticClient> Chain2;
1865public:
1866
1867 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1868 // Output diags both where requested...
1869 Chain1.reset(Normal);
1870 // .. and to our log file.
1871 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1872 !NoShowColumn,
1873 !NoCaretDiagnostics,
1874 !NoShowLocation,
1875 PrintSourceRangeInfo,
1876 PrintDiagnosticOption));
1877 }
1878
1879 virtual void setLangOptions(const LangOptions *LO) {
1880 Chain1->setLangOptions(LO);
1881 Chain2->setLangOptions(LO);
1882 }
1883
1884 virtual bool IncludeInDiagnosticCounts() const {
1885 return Chain1->IncludeInDiagnosticCounts();
1886 }
1887
1888 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1889 const DiagnosticInfo &Info) {
1890 Chain1->HandleDiagnostic(DiagLevel, Info);
1891 Chain2->HandleDiagnostic(DiagLevel, Info);
1892 }
1893};
1894} // end anonymous namespace.
1895
1896static void SetUpBuildDumpLog(unsigned argc, char **argv,
1897 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1898
1899 std::string ErrorInfo;
1900 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1901 ErrorInfo);
1902
1903 if (!ErrorInfo.empty()) {
1904 llvm::errs() << "error opening -dump-build-information file '"
1905 << DumpBuildInformation << "', option ignored!\n";
1906 delete BuildLogFile;
1907 BuildLogFile = 0;
1908 DumpBuildInformation = "";
1909 return;
1910 }
1911
1912 (*BuildLogFile) << "clang-cc command line arguments: ";
1913 for (unsigned i = 0; i != argc; ++i)
1914 (*BuildLogFile) << argv[i] << ' ';
1915 (*BuildLogFile) << '\n';
1916
1917 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1918 // the diagnostic producers and the normal receiver.
1919 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1920}
1921
1922
1923
1924//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001925// Main driver
1926//===----------------------------------------------------------------------===//
1927
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001928/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001929/// action. These consumers can operate on both ASTs that are freshly
1930/// parsed from source files as well as those deserialized from Bitcode.
1931/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001932static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001933 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001934 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001935 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001936 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001937 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001938 default:
1939 return NULL;
1940
1941 case ASTPrint:
1942 return CreateASTPrinter();
1943
1944 case ASTDump:
1945 return CreateASTDumper();
1946
1947 case ASTView:
1948 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001949
Chris Lattner7f902922009-02-18 01:20:05 +00001950 case PrintDeclContext:
1951 return CreateDeclContextPrinter();
1952
1953 case EmitHTML:
1954 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001955
Chris Lattner7f902922009-02-18 01:20:05 +00001956 case InheritanceView:
1957 return CreateInheritanceViewer(InheritanceViewCls);
1958
1959 case TestSerialization:
1960 return CreateSerializationTest(Diag, FileMgr);
1961
1962 case EmitAssembly:
1963 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001964 case EmitBC:
1965 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001966 BackendAction Act;
1967 if (ProgAction == EmitAssembly)
1968 Act = Backend_EmitAssembly;
1969 else if (ProgAction == EmitLLVM)
1970 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001971 else if (ProgAction == EmitLLVMOnly)
1972 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001973 else
1974 Act = Backend_EmitBC;
1975
1976 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001977 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001978 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001979 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001980 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001981
Chris Lattner7f902922009-02-18 01:20:05 +00001982 case SerializeAST:
1983 // FIXME: Allow user to tailor where the file is written.
1984 return CreateASTSerializer(InFile, OutputFile, Diag);
1985
Douglas Gregorc34897d2009-04-09 22:27:44 +00001986 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001987 assert(PP && "Generate PCH doesn't work from serialized file yet");
1988 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001989
Chris Lattner7f902922009-02-18 01:20:05 +00001990 case RewriteObjC:
1991 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001992
Chris Lattner7f902922009-02-18 01:20:05 +00001993 case RewriteBlocks:
1994 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1995
1996 case RunAnalysis:
1997 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001998 }
1999}
2000
Chris Lattner4b009652007-07-25 00:24:17 +00002001/// ProcessInputFile - Process a single input file with the specified state.
2002///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00002003static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002004 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00002005 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00002006 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00002007 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00002008 bool CompleteTranslationUnit = true;
Douglas Gregor133d2552009-04-02 01:08:08 +00002009
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002010 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00002011 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00002012 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
2013 PP.getFileManager(), PP.getLangOptions(),
2014 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00002015
2016 if (!Consumer) {
2017 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002018 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00002019 return;
2020 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002021
Douglas Gregore0d5c562009-04-14 16:27:31 +00002022 if (ProgAction == GeneratePCH)
2023 CompleteTranslationUnit = false;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00002024 break;
2025
Chris Lattneraf669fb2008-10-12 05:03:36 +00002026 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00002027 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00002028 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00002029 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00002030 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00002031 RawLex.SetKeepWhitespaceMode(true);
2032
2033 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00002034 RawLex.LexFromRawLexer(RawTok);
2035 while (RawTok.isNot(tok::eof)) {
2036 PP.DumpToken(RawTok, true);
2037 fprintf(stderr, "\n");
2038 RawLex.LexFromRawLexer(RawTok);
2039 }
2040 ClearSourceMgr = true;
2041 break;
2042 }
Chris Lattner4b009652007-07-25 00:24:17 +00002043 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00002044 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00002045 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00002046 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00002047 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00002048 do {
2049 PP.Lex(Tok);
2050 PP.DumpToken(Tok, true);
2051 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00002052 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00002053 ClearSourceMgr = true;
2054 break;
2055 }
2056 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00002057 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00002058 Token Tok;
2059 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00002060 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00002061 do {
2062 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00002063 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00002064 ClearSourceMgr = true;
2065 break;
2066 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002067
Douglas Gregor2a0e8742009-04-02 23:43:50 +00002068 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00002069 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00002070 CacheTokens(PP, OutputFile);
2071 ClearSourceMgr = true;
2072 break;
2073 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002074
Chris Lattnerefe33382009-02-18 01:51:21 +00002075 case PrintPreprocessedInput: { // -E mode.
2076 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00002077 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00002078 ClearSourceMgr = true;
2079 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002080 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00002081
Chris Lattnerefe33382009-02-18 01:51:21 +00002082 case ParseNoop: { // -parse-noop
2083 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00002084 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00002085 ClearSourceMgr = true;
2086 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002087 }
Chris Lattner4b009652007-07-25 00:24:17 +00002088
Chris Lattnerefe33382009-02-18 01:51:21 +00002089 case ParsePrintCallbacks: {
2090 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00002091 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00002092 ClearSourceMgr = true;
2093 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002094 }
2095
2096 case ParseSyntaxOnly: { // -fsyntax-only
2097 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00002098 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00002099 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002100 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00002101
2102 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00002103 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00002104 ClearSourceMgr = true;
2105 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00002106
Chris Lattnerefe33382009-02-18 01:51:21 +00002107 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00002108 DoRewriteTest(PP, InFile, OutputFile);
2109 ClearSourceMgr = true;
2110 break;
Chris Lattner129758d2007-09-16 19:46:59 +00002111 }
Douglas Gregor133d2552009-04-02 01:08:08 +00002112
2113 case FixIt:
2114 llvm::TimeRegion Timer(ClangFrontendTimer);
2115 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00002116 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00002117 PP.getSourceManager(),
2118 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00002119 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00002120 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00002121
2122 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00002123 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00002124
Douglas Gregor24b48b02009-04-02 19:05:20 +00002125 if (FixItAtLocations.size() > 0) {
2126 // Even without the "-fixit" flag, with may have some specific
2127 // locations where the user has requested fixes. Process those
2128 // locations now.
2129 if (!FixItRewrite)
2130 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00002131 PP.getSourceManager(),
2132 PP.getLangOptions());
Douglas Gregor24b48b02009-04-02 19:05:20 +00002133
2134 bool AddedFixitLocation = false;
2135 for (unsigned Idx = 0, Last = FixItAtLocations.size();
2136 Idx != Last; ++Idx) {
2137 RequestedSourceLocation Requested;
2138 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
2139 Requested)) {
2140 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
2141 FixItAtLocations[Idx].FileName.c_str());
2142 } else {
2143 FixItRewrite->addFixItLocation(Requested);
2144 AddedFixitLocation = true;
2145 }
2146 }
2147
2148 if (!AddedFixitLocation) {
2149 // All of the fix-it locations were bad. Don't fix anything.
2150 delete FixItRewrite;
2151 FixItRewrite = 0;
2152 }
2153 }
2154
Chris Lattner143fd6d2009-03-28 01:37:17 +00002155 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
2156 PP.getSourceManager(),
2157 PP.getTargetInfo(),
2158 PP.getIdentifierTable(),
2159 PP.getSelectorTable(),
2160 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00002161
Douglas Gregorc34897d2009-04-09 22:27:44 +00002162 if (!ImplicitIncludePCH.empty()) {
2163 // The user has asked us to include a precompiled header. Load
2164 // the precompiled header into the AST context.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002165 llvm::OwningPtr<PCHReader> Reader(new PCHReader(PP, *ContextOwner.get()));
2166 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2167 case PCHReader::Success: {
2168 // Attach the PCH reader to the AST context as an external AST
2169 // source, so that declarations will be deserialized from the
2170 // PCH file as needed.
2171 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
2172 ContextOwner->setExternalSource(Source);
2173
2174 // Clear out the predefines buffer, because all of the
2175 // predefines are already in the PCH file.
2176 PP.setPredefines("");
2177 break;
2178 }
2179
2180 case PCHReader::Failure:
2181 // Unrecoverable failure: don't even try to process the input
2182 // file.
Douglas Gregorc34897d2009-04-09 22:27:44 +00002183 return;
2184
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002185 case PCHReader::IgnorePCH:
2186 // No suitable PCH file could be found. Just ignore the
2187 // -include-pch option entirely.
2188 break;
2189 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00002190
2191 // Finish preprocessor initialization. We do this now (rather
2192 // than earlier) because this initialization creates new source
2193 // location entries in the source manager, which must come after
2194 // the source location entries for the PCH file.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002195 if (InitializeSourceManager(PP, InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002196 return;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002197 }
2198
Douglas Gregore0d5c562009-04-14 16:27:31 +00002199 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2200 CompleteTranslationUnit);
Chris Lattner143fd6d2009-03-28 01:37:17 +00002201
Douglas Gregor133d2552009-04-02 01:08:08 +00002202 if (FixItRewrite)
2203 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2204
Chris Lattner143fd6d2009-03-28 01:37:17 +00002205 // If in -disable-free mode, don't deallocate these when they go out of
2206 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00002207 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00002208 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00002209 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002210
2211 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002212 if (CheckDiagnostics(PP))
2213 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002214
Chris Lattner4b009652007-07-25 00:24:17 +00002215 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002216 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002217 PP.PrintStats();
2218 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002219 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002220 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002221 fprintf(stderr, "\n");
2222 }
2223
2224 // For a multi-file compilation, some things are ok with nuking the source
2225 // manager tables, other require stable fileid/macroid's across multiple
2226 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002227 if (ClearSourceMgr)
2228 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002229
2230 if (DisableFree)
2231 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00002232}
2233
Ted Kremenek80d53372007-12-12 23:41:08 +00002234static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
2235 FileManager& FileMgr) {
2236
2237 if (VerifyDiagnostics) {
2238 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
2239 exit (1);
2240 }
2241
2242 llvm::sys::Path Filename(InFile);
2243
2244 if (!Filename.isValid()) {
2245 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
2246 exit (1);
2247 }
2248
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002249 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00002250
2251 // Create the memory buffer that contains the contents of the file.
2252 llvm::OwningPtr<llvm::MemoryBuffer>
2253 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
2254
2255 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002256 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00002257
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002258 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00002259 fprintf(stderr, "error: file '%s' could not be deserialized\n",
2260 InFile.c_str());
2261 exit (1);
2262 }
2263
Ted Kremenekab749372007-12-19 19:27:38 +00002264 // Observe that we use the source file name stored in the deserialized
2265 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00002266 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002267 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00002268 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00002269
Ted Kremenek80d53372007-12-12 23:41:08 +00002270 if (!Consumer) {
2271 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
2272 exit (1);
2273 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00002274
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002275 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00002276
Chris Lattner8d72ee02008-02-06 01:42:25 +00002277 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002278 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002279 for (DeclContext::decl_iterator I = TUD->decls_begin(*Ctx),
2280 E = TUD->decls_end(*Ctx);
Chris Lattnerf4fbc442009-03-28 04:27:18 +00002281 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00002282 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00002283}
2284
2285
Chris Lattner4b009652007-07-25 00:24:17 +00002286static llvm::cl::list<std::string>
2287InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2288
Ted Kremenek80d53372007-12-12 23:41:08 +00002289static bool isSerializedFile(const std::string& InFile) {
2290 if (InFile.size() < 4)
2291 return false;
2292
2293 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00002294 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00002295}
2296
Chris Lattner4b009652007-07-25 00:24:17 +00002297
2298int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002299 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002300 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002301 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002302 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00002303
Chris Lattnerefe33382009-02-18 01:51:21 +00002304 if (TimeReport)
2305 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2306
Chris Lattner4b009652007-07-25 00:24:17 +00002307 // If no input was specified, read from stdin.
2308 if (InputFilenames.empty())
2309 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00002310
Ted Kremenekb240e822007-12-11 23:28:38 +00002311 // Create the diagnostic client for reporting errors or for
2312 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002313 llvm::OwningPtr<DiagnosticClient> DiagClient;
2314 if (VerifyDiagnostics) {
2315 // When checking diagnostics, just buffer them up.
2316 DiagClient.reset(new TextDiagnosticBuffer());
2317 if (InputFilenames.size() != 1) {
2318 fprintf(stderr, "-verify only works on single input files for now.\n");
2319 return 1;
2320 }
2321 if (!HTMLDiag.empty()) {
2322 fprintf(stderr, "-verify and -html-diags don't work together\n");
2323 return 1;
2324 }
2325 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002326 // Print diagnostics to stderr by default.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002327 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002328 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002329 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002330 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002331 PrintSourceRangeInfo,
Chris Lattner5f7937d2009-04-17 20:40:01 +00002332 PrintDiagnosticOption));
Ted Kremenek5c341732008-08-07 17:49:57 +00002333 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002334 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002335 }
Chris Lattner94859302009-04-17 21:05:01 +00002336
2337 if (!DumpBuildInformation.empty()) {
2338 if (!HTMLDiag.empty()) {
2339 fprintf(stderr,
2340 "-dump-build-information and -html-diags don't work together\n");
2341 return 1;
2342 }
2343
2344 SetUpBuildDumpLog(argc, argv, DiagClient);
2345 }
2346
Ted Kremenek5c341732008-08-07 17:49:57 +00002347
Chris Lattner4b009652007-07-25 00:24:17 +00002348 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002349 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002350 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002351 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002352
Chris Lattner45a56e02007-12-05 23:24:17 +00002353 // -I- is a deprecated GCC feature, scan for it and reject it.
2354 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2355 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002356 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002357 I_dirs.erase(I_dirs.begin()+i);
2358 --i;
2359 }
2360 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002361
2362 // Get information about the target being compiled for.
2363 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002364 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2365
Chris Lattner2c77d852008-03-14 06:12:05 +00002366 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002367 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2368 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002369 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002370 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002371
Daniel Dunbar9c321102009-01-20 23:17:32 +00002372 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002373 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002374
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002375 llvm::OwningPtr<SourceManager> SourceMgr;
2376
Chris Lattnere1be6022009-04-14 23:22:57 +00002377 // Create a file manager object to provide access to and cache the filesystem.
2378 FileManager FileMgr;
2379
Chris Lattner4b009652007-07-25 00:24:17 +00002380 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002381 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002382
Ted Kremenek5c341732008-08-07 17:49:57 +00002383 if (isSerializedFile(InFile)) {
Ted Kremenek80d53372007-12-12 23:41:08 +00002384 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00002385 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002386 }
Chris Lattner2b989562009-03-04 21:40:56 +00002387
2388 /// Create a SourceManager object. This tracks and owns all the file
2389 /// buffers allocated to a translation unit.
2390 if (!SourceMgr)
2391 SourceMgr.reset(new SourceManager());
2392 else
2393 SourceMgr->clearIDTables();
2394
2395 // Initialize language options, inferring file types from input filenames.
2396 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002397 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002398
Chris Lattner2b989562009-03-04 21:40:56 +00002399 InitializeBaseLanguage();
2400 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002401 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00002402 InitializeLanguageStandard(LangInfo, LK, Target.get());
2403
2404 // Process the -I options and set them in the HeaderInfo.
2405 HeaderSearch HeaderInfo(FileMgr);
2406
Chris Lattnere1be6022009-04-14 23:22:57 +00002407
Chris Lattner2b989562009-03-04 21:40:56 +00002408 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2409
2410 // Set up the preprocessor with these options.
2411 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2412 *SourceMgr.get(), HeaderInfo);
2413
2414 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2415
2416 if (!PP)
2417 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002418
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002419 if (ImplicitIncludePCH.empty() &&
2420 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002421 continue;
2422
Chris Lattner5f7937d2009-04-17 20:40:01 +00002423 if (!HTMLDiag.empty())
2424 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002425
2426 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002427 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00002428
Chris Lattner2961dc52009-04-17 20:16:08 +00002429 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002430 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002431 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002432
Mike Stump91d01352009-01-28 02:43:35 +00002433 if (Verbose)
2434 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2435 " hosted on " LLVM_HOSTTRIPLE "\n");
2436
Ted Kremenekec6c5252008-08-07 18:13:12 +00002437 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00002438 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2439 (NumDiagnostics == 1 ? "" : "s"));
2440
2441 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002442 FileMgr.PrintStats();
2443 fprintf(stderr, "\n");
2444 }
Chris Lattner94859302009-04-17 21:05:01 +00002445
2446 delete ClangFrontendTimer;
2447 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002448
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002449 // If verifying diagnostics and we reached here, all is well.
2450 if (VerifyDiagnostics)
2451 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002452
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002453 // Managed static deconstruction. Useful for making things like
2454 // -time-passes usable.
2455 llvm::llvm_shutdown();
2456
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002457 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002458}