blob: 9260afe4b7dbe6d4aa68d9a4dbae005e9420595e [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"
Daniel Dunbar68952de2009-03-02 06:16:29 +000032#include "clang/Frontend/TextDiagnosticBuffer.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000039#include "clang/AST/ASTContext.h"
40#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000041#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000042#include "clang/Parse/Parser.h"
43#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000044#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000045#include "clang/Basic/FileManager.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000048#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000049#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000050#include "llvm/ADT/StringExtras.h"
51#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000052#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000053#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000054#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000055#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000056#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000057#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000058#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000059#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000060#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000061#include <cstdlib>
62
Chris Lattner4b009652007-07-25 00:24:17 +000063using namespace clang;
64
65//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000066// Source Location Parser
67//===----------------------------------------------------------------------===//
68
69/// \brief A source location that has been parsed on the command line.
70struct ParsedSourceLocation {
71 std::string FileName;
72 unsigned Line;
73 unsigned Column;
74
75 /// \brief Try to resolve the file name of a parsed source location.
76 ///
77 /// \returns true if there was an error, false otherwise.
78 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
79};
80
81bool
82ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
83 RequestedSourceLocation &Result) {
84 const FileEntry *File = FileMgr.getFile(FileName);
85 if (!File)
86 return true;
87
88 Result.File = File;
89 Result.Line = Line;
90 Result.Column = Column;
91 return false;
92}
93
94namespace llvm {
95 namespace cl {
96 /// \brief Command-line option parser that parses source locations.
97 ///
98 /// Source locations are of the form filename:line:column.
99 template<>
100 class parser<ParsedSourceLocation>
101 : public basic_parser<ParsedSourceLocation> {
102 public:
103 bool parse(Option &O, const char *ArgName,
104 const std::string &ArgValue,
105 ParsedSourceLocation &Val);
106 };
107
108 bool
109 parser<ParsedSourceLocation>::
110 parse(Option &O, const char *ArgName, const std::string &ArgValue,
111 ParsedSourceLocation &Val) {
112 using namespace clang;
113
114 const char *ExpectedFormat
115 = "source location must be of the form filename:line:column";
116 std::string::size_type SecondColon = ArgValue.rfind(':');
117 if (SecondColon == std::string::npos) {
118 std::fprintf(stderr, "%s\n", ExpectedFormat);
119 return true;
120 }
121 char *EndPtr;
122 long Column
123 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
124 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
125 std::fprintf(stderr, "%s\n", ExpectedFormat);
126 return true;
127 }
128
129 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
130 if (SecondColon == std::string::npos) {
131 std::fprintf(stderr, "%s\n", ExpectedFormat);
132 return true;
133 }
134 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
135 if (EndPtr != ArgValue.c_str() + SecondColon) {
136 std::fprintf(stderr, "%s\n", ExpectedFormat);
137 return true;
138 }
139
140 Val.FileName = ArgValue.substr(0, FirstColon);
141 Val.Line = Line;
142 Val.Column = Column;
143 return false;
144 }
145 }
146}
147
148//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000149// Global options.
150//===----------------------------------------------------------------------===//
151
Chris Lattnerefe33382009-02-18 01:51:21 +0000152/// ClangFrontendTimer - The front-end activities should charge time to it with
153/// TimeRegion. The -ftime-report option controls whether this will do
154/// anything.
155llvm::Timer *ClangFrontendTimer = 0;
156
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000157static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000158
Chris Lattner4b009652007-07-25 00:24:17 +0000159static llvm::cl::opt<bool>
160Verbose("v", llvm::cl::desc("Enable verbose output"));
161static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000162Stats("print-stats",
163 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000164static llvm::cl::opt<bool>
165DisableFree("disable-free",
166 llvm::cl::desc("Disable freeing of memory on exit"),
167 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +0000168
169enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000170 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000171 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000172 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000173 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000174 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000175 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000176 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000177 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000178 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000179 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek397de012007-12-13 00:37:31 +0000180 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +0000181 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000182 ASTPrint, // Parse ASTs and print them.
183 ASTDump, // Parse ASTs and dump them.
184 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000185 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000186 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +0000187 ParsePrintCallbacks, // Parse and print each callback.
188 ParseSyntaxOnly, // Parse and perform semantic analysis.
189 ParseNoop, // Parse with noop callbacks.
190 RunPreprocessorOnly, // Just lex, no output.
191 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000192 DumpTokens, // Dump out preprocessed tokens.
193 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000194 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000195 GeneratePTH, // Generate pre-tokenized header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000196 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000197};
198
199static llvm::cl::opt<ProgActions>
200ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
201 llvm::cl::init(ParseSyntaxOnly),
202 llvm::cl::values(
203 clEnumValN(RunPreprocessorOnly, "Eonly",
204 "Just run preprocessor, no output (for timings)"),
205 clEnumValN(PrintPreprocessedInput, "E",
206 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000207 clEnumValN(DumpRawTokens, "dump-raw-tokens",
208 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000209 clEnumValN(RunAnalysis, "analyze",
210 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000211 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000212 "Run preprocessor, dump internal rep of tokens"),
213 clEnumValN(ParseNoop, "parse-noop",
214 "Run parser with noop callbacks (for timings)"),
215 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
216 "Run parser and perform semantic analysis"),
217 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
218 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000219 clEnumValN(EmitHTML, "emit-html",
220 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000221 clEnumValN(ASTPrint, "ast-print",
222 "Build ASTs and then pretty-print them"),
223 clEnumValN(ASTDump, "ast-dump",
224 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000225 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000226 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000227 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000228 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000229 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000230 "Generate pre-tokenized header file"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000231 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000232 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000233 clEnumValN(EmitAssembly, "S",
234 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000235 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000236 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000237 clEnumValN(EmitBC, "emit-llvm-bc",
238 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000239 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
240 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000241 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000242 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000243 clEnumValN(RewriteTest, "rewrite-test",
244 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000245 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000246 "Rewrite ObjC into C (code rewriter example)"),
247 clEnumValN(RewriteMacros, "rewrite-macros",
248 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000249 clEnumValN(RewriteBlocks, "rewrite-blocks",
250 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000251 clEnumValN(FixIt, "fixit",
252 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000253 clEnumValEnd));
254
Ted Kremenekd01eae62007-12-19 19:47:59 +0000255
256static llvm::cl::opt<std::string>
257OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000258 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000259 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000260
Ted Kremenek57f25b22008-12-02 19:57:31 +0000261
262//===----------------------------------------------------------------------===//
263// PTH.
264//===----------------------------------------------------------------------===//
265
266static llvm::cl::opt<std::string>
267TokenCache("token-cache", llvm::cl::value_desc("path"),
268 llvm::cl::desc("Use specified token cache file"));
269
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000270//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000271// Diagnostic Options
272//===----------------------------------------------------------------------===//
273
Ted Kremenek10389cf2007-09-26 19:42:19 +0000274static llvm::cl::opt<bool>
275VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000276 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000277
Ted Kremenekfd75e312008-03-27 06:17:42 +0000278static llvm::cl::opt<std::string>
279HTMLDiag("html-diags",
280 llvm::cl::desc("Generate HTML to report diagnostics"),
281 llvm::cl::value_desc("HTML directory"));
282
Nico Weber0e13eaa2008-08-05 23:33:20 +0000283static llvm::cl::opt<bool>
284NoShowColumn("fno-show-column",
285 llvm::cl::desc("Do not include column number on diagnostics"));
286
287static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000288NoShowLocation("fno-show-source-location",
289 llvm::cl::desc("Do not include source location information with"
290 " diagnostics"));
291
292static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000293NoCaretDiagnostics("fno-caret-diagnostics",
294 llvm::cl::desc("Do not include source line and caret with"
295 " diagnostics"));
296
Chris Lattner695a4f52009-03-13 01:08:23 +0000297static llvm::cl::opt<bool>
298PrintSourceRangeInfo("fprint-source-range-info",
299 llvm::cl::desc("Print source range spans in numeric form"));
300
Nico Weber0e13eaa2008-08-05 23:33:20 +0000301
Chris Lattner4b009652007-07-25 00:24:17 +0000302//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000303// C++ Visualization.
304//===----------------------------------------------------------------------===//
305
306static llvm::cl::opt<std::string>
307InheritanceViewCls("cxx-inheritance-view",
308 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000309 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000310
311//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000312// Builtin Options
313//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000314
315static llvm::cl::opt<bool>
316TimeReport("ftime-report",
317 llvm::cl::desc("Print the amount of time each "
318 "phase of compilation takes"));
319
Douglas Gregor23d23262009-02-14 20:49:29 +0000320static llvm::cl::opt<bool>
321Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000322 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000323 "freestanding environment"));
324
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000325static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000326AllowBuiltins("fbuiltin", llvm::cl::init(true),
327 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000328
329
330static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000331MathErrno("fmath-errno", llvm::cl::init(true),
332 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000333
Douglas Gregor23d23262009-02-14 20:49:29 +0000334//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000335// Language Options
336//===----------------------------------------------------------------------===//
337
338enum LangKind {
339 langkind_unspecified,
340 langkind_c,
341 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000342 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000343 langkind_cxx,
344 langkind_cxx_cpp,
345 langkind_objc,
346 langkind_objc_cpp,
347 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000348 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000349};
350
Chris Lattner4b009652007-07-25 00:24:17 +0000351static llvm::cl::opt<LangKind>
352BaseLang("x", llvm::cl::desc("Base language to compile"),
353 llvm::cl::init(langkind_unspecified),
354 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
355 clEnumValN(langkind_cxx, "c++", "C++"),
356 clEnumValN(langkind_objc, "objective-c", "Objective C"),
357 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000358 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000359 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000360 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
361 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000362 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000363 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000364 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
365 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000366 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000367 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000368 clEnumValN(langkind_c, "c-header",
369 "C header"),
370 clEnumValN(langkind_objc, "objective-c-header",
371 "Objective-C header"),
372 clEnumValN(langkind_cxx, "c++-header",
373 "C++ header"),
374 clEnumValN(langkind_objcxx, "objective-c++-header",
375 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000376 clEnumValEnd));
377
378static llvm::cl::opt<bool>
379LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
380 llvm::cl::Hidden);
381static llvm::cl::opt<bool>
382LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
383 llvm::cl::Hidden);
384
Ted Kremenek11ad8952007-12-05 23:49:08 +0000385/// InitializeBaseLanguage - Handle the -x foo options.
386static void InitializeBaseLanguage() {
387 if (LangObjC)
388 BaseLang = langkind_objc;
389 else if (LangObjCXX)
390 BaseLang = langkind_objcxx;
391}
392
393static LangKind GetLanguage(const std::string &Filename) {
394 if (BaseLang != langkind_unspecified)
395 return BaseLang;
396
397 std::string::size_type DotPos = Filename.rfind('.');
398
399 if (DotPos == std::string::npos) {
400 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000401 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000402 }
403
Ted Kremenek11ad8952007-12-05 23:49:08 +0000404 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
405 // C header: .h
406 // C++ header: .hh or .H;
407 // assembler no preprocessing: .s
408 // assembler: .S
409 if (Ext == "c")
410 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000411 else if (Ext == "S" ||
412 // If the compiler is run on a .s file, preprocess it as .S
413 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000414 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000415 else if (Ext == "i")
416 return langkind_c_cpp;
417 else if (Ext == "ii")
418 return langkind_cxx_cpp;
419 else if (Ext == "m")
420 return langkind_objc;
421 else if (Ext == "mi")
422 return langkind_objc_cpp;
423 else if (Ext == "mm" || Ext == "M")
424 return langkind_objcxx;
425 else if (Ext == "mii")
426 return langkind_objcxx_cpp;
427 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
428 Ext == "c++" || Ext == "cp" || Ext == "cxx")
429 return langkind_cxx;
430 else
431 return langkind_c;
432}
433
434
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000435static void InitializeCOptions(LangOptions &Options) {
436 // Do nothing.
437}
438
439static void InitializeObjCOptions(LangOptions &Options) {
440 Options.ObjC1 = Options.ObjC2 = 1;
441}
442
443
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000444static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000445 // FIXME: implement -fpreprocessed mode.
446 bool NoPreprocess = false;
447
Ted Kremenek11ad8952007-12-05 23:49:08 +0000448 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000449 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000450 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000451 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000452 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000453 case langkind_c_cpp:
454 NoPreprocess = true;
455 // FALLTHROUGH
456 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000457 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000458 break;
459 case langkind_cxx_cpp:
460 NoPreprocess = true;
461 // FALLTHROUGH
462 case langkind_cxx:
463 Options.CPlusPlus = 1;
464 break;
465 case langkind_objc_cpp:
466 NoPreprocess = true;
467 // FALLTHROUGH
468 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000469 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000470 break;
471 case langkind_objcxx_cpp:
472 NoPreprocess = true;
473 // FALLTHROUGH
474 case langkind_objcxx:
475 Options.ObjC1 = Options.ObjC2 = 1;
476 Options.CPlusPlus = 1;
477 break;
478 }
479}
480
481/// LangStds - Language standards we support.
482enum LangStds {
483 lang_unspecified,
484 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000485 lang_gnu_START,
486 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000487 lang_cxx98, lang_gnucxx98,
488 lang_cxx0x, lang_gnucxx0x
489};
490
491static llvm::cl::opt<LangStds>
492LangStd("std", llvm::cl::desc("Language standard to compile for"),
493 llvm::cl::init(lang_unspecified),
494 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
495 clEnumValN(lang_c89, "c90", "ISO C 1990"),
496 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
497 clEnumValN(lang_c94, "iso9899:199409",
498 "ISO C 1990 with amendment 1"),
499 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000500 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000501 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000502 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000503 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000504 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000505 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000506 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000507 clEnumValN(lang_gnu99, "gnu9x",
508 "ISO C 1999 with GNU extensions"),
509 clEnumValN(lang_cxx98, "c++98",
510 "ISO C++ 1998 with amendments"),
511 clEnumValN(lang_gnucxx98, "gnu++98",
512 "ISO C++ 1998 with amendments and GNU "
513 "extensions (default for C++)"),
514 clEnumValN(lang_cxx0x, "c++0x",
515 "Upcoming ISO C++ 200x with amendments"),
516 clEnumValN(lang_gnucxx0x, "gnu++0x",
517 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000518 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000519 clEnumValEnd));
520
521static llvm::cl::opt<bool>
522NoOperatorNames("fno-operator-names",
523 llvm::cl::desc("Do not treat C++ operator name keywords as "
524 "synonyms for operators"));
525
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000526static llvm::cl::opt<bool>
527PascalStrings("fpascal-strings",
528 llvm::cl::desc("Recognize and construct Pascal-style "
529 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000530
531static llvm::cl::opt<bool>
532MSExtensions("fms-extensions",
533 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000534 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000535
536static llvm::cl::opt<bool>
537WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000538 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000539
540static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000541NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000542 llvm::cl::desc("Disallow implicit conversions between "
543 "vectors with a different number of "
544 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000545
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000546static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000547EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000548
549static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000550EnableHeinousExtensions("fheinous-gnu-extensions",
551 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
552 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
553
554static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000555ObjCNonFragileABI("fobjc-nonfragile-abi",
556 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000557
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000558static llvm::cl::opt<bool>
559EmitAllDecls("femit-all-decls",
560 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000561
Daniel Dunbar91692d92008-08-11 17:36:14 +0000562// FIXME: This (and all GCC -f options) really come in -f... and
563// -fno-... forms, and additionally support automagic behavior when
564// they are not defined. For example, -fexceptions defaults to on or
565// off depending on the language. We should support this behavior in
566// some form (perhaps just add a facility for distinguishing when an
567// has its default value from when it has been set to its default
568// value).
569static llvm::cl::opt<bool>
570Exceptions("fexceptions",
571 llvm::cl::desc("Enable support for exception handling."));
572
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000573static llvm::cl::opt<bool>
574GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000575 llvm::cl::desc("Generate output compatible with the standard GNU "
576 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000577
578static llvm::cl::opt<bool>
579NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000580 llvm::cl::desc("Generate output compatible with the NeXT "
581 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000582
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000583
584
585static llvm::cl::opt<bool>
586Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
587
588static llvm::cl::opt<bool>
589Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
590
Chris Lattner738d3f62009-03-02 22:11:07 +0000591static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000592TargetFeatures("mattr", llvm::cl::CommaSeparated,
593 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
594
Douglas Gregor375733c2009-03-10 00:06:19 +0000595static llvm::cl::opt<unsigned>
596TemplateDepth("ftemplate-depth", llvm::cl::init(99),
597 llvm::cl::desc("Maximum depth of recursive template "
598 "instantiation"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000599
Anders Carlssondfd77642009-04-06 17:37:10 +0000600
601static llvm::cl::opt<bool>
602OptSize("Os", llvm::cl::desc("Optimize for size"));
603
604static llvm::cl::opt<bool>
605NoCommon("fno-common",
606 llvm::cl::desc("Compile common globals like normal definitions"),
607 llvm::cl::ValueDisallowed);
608
609
610// It might be nice to add bounds to the CommandLine library directly.
611struct OptLevelParser : public llvm::cl::parser<unsigned> {
612 bool parse(llvm::cl::Option &O, const char *ArgName,
613 const std::string &Arg, unsigned &Val) {
614 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
615 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000616 if (Val > 3)
617 return O.error(": '" + Arg + "' invalid optimization level!");
618 return false;
619 }
620};
621static llvm::cl::opt<unsigned, false, OptLevelParser>
622OptLevel("O", llvm::cl::Prefix,
623 llvm::cl::desc("Optimization level"),
624 llvm::cl::init(0));
625
Chris Lattner4b009652007-07-25 00:24:17 +0000626// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000627// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000628static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
629 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000630 // Allow the target to set the default the langauge options as it sees fit.
631 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000632
Chris Lattnerf6790a82009-03-03 19:56:18 +0000633 // If there are any -mattr options, pass them to the target for validation and
634 // processing. The driver should have already consolidated all the
635 // target-feature settings and passed them to us in the -mattr list. The
636 // -mattr list is treated by the code generator as a diff against the -mcpu
637 // setting, but the driver should pass all enabled options as "+" settings.
638 // This means that the target should only look at + settings.
639 if (!TargetFeatures.empty()
640 // FIXME: The driver is not quite yet ready for this.
641 && 0) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000642 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000643 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
644 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000645 if (Opt != -1) {
646 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000647 fprintf(stderr, "invalid feature '%s'\n",
648 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000649 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000650 fprintf(stderr, "feature '%s': %s\n",
651 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000652 exit(1);
653 }
654 }
655
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000656 if (Ansi) // "The -ansi option is equivalent to -std=c89."
657 LangStd = lang_c89;
658
Chris Lattner4b009652007-07-25 00:24:17 +0000659 if (LangStd == lang_unspecified) {
660 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000661 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000662 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000663 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000664 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000665 case langkind_c_cpp:
666 case langkind_objc:
667 case langkind_objc_cpp:
668 LangStd = lang_gnu99;
669 break;
670 case langkind_cxx:
671 case langkind_cxx_cpp:
672 case langkind_objcxx:
673 case langkind_objcxx_cpp:
674 LangStd = lang_gnucxx98;
675 break;
676 }
677 }
678
679 switch (LangStd) {
680 default: assert(0 && "Unknown language standard!");
681
682 // Fall through from newer standards to older ones. This isn't really right.
683 // FIXME: Enable specifically the right features based on the language stds.
684 case lang_gnucxx0x:
685 case lang_cxx0x:
686 Options.CPlusPlus0x = 1;
687 // FALL THROUGH
688 case lang_gnucxx98:
689 case lang_cxx98:
690 Options.CPlusPlus = 1;
691 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000692 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000693 // FALL THROUGH.
694 case lang_gnu99:
695 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000696 Options.C99 = 1;
697 Options.HexFloats = 1;
698 // FALL THROUGH.
699 case lang_gnu89:
700 Options.BCPLComment = 1; // Only for C99/C++.
701 // FALL THROUGH.
702 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000703 Options.Digraphs = 1; // C94, C99, C++.
704 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000705 case lang_c89:
706 break;
707 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000708
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000709 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
710 Options.GNUMode = LangStd >= lang_gnu_START;
711
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000712 if (Options.CPlusPlus) {
713 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000714 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000715 }
Chris Lattner4b009652007-07-25 00:24:17 +0000716
Chris Lattner6ab935b2008-04-05 06:32:51 +0000717 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
718 Options.ImplicitInt = 1;
719 else
720 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000721
722 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
723 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000724 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000725 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000726 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000727
Chris Lattner58d5ba52008-12-05 00:10:44 +0000728 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
729 // even if they are normally on for the target. In GNU modes (e.g.
730 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000731 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000732 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000733 Options.Blocks = 0;
734
Daniel Dunbar551236b2009-03-15 00:11:28 +0000735 // Never accept '$' in identifiers when preprocessing assembler.
736 if (LK != langkind_asm_cpp)
737 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000738 if (PascalStrings.getPosition())
739 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000740 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000741 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000742 if (NoLaxVectorConversions.getPosition())
743 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000744 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000745 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000746 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000747
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000748 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000749 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000750 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000751 Options.Freestanding = Options.NoBuiltin = 1;
752
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000753 if (EnableHeinousExtensions)
754 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000755
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000756 Options.MathErrno = MathErrno;
757
Douglas Gregor375733c2009-03-10 00:06:19 +0000758 Options.InstantiationDepth = TemplateDepth;
759
Chris Lattnerddae7102008-12-04 22:54:33 +0000760 // Override the default runtime if the user requested it.
761 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000762 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000763 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000764 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000765
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000766 if (ObjCNonFragileABI)
767 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000768
769 if (EmitAllDecls)
770 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000771
772 if (OptSize)
773 Options.OptimizeSize = 1;
774
775 // -Os implies -O2
776 if (Options.OptimizeSize || OptLevel)
777 Options.Optimize = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000778}
779
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000780static llvm::cl::opt<bool>
781ObjCExclusiveGC("fobjc-gc-only",
782 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000783 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000784
785static llvm::cl::opt<bool>
786ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000787 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000788
789void InitializeGCMode(LangOptions &Options) {
790 if (ObjCExclusiveGC)
791 Options.setGCMode(LangOptions::GCOnly);
792 else if (ObjCEnableGC)
793 Options.setGCMode(LangOptions::HybridGC);
794}
795
Fariborz Jahanian49343332009-04-03 03:28:57 +0000796static llvm::cl::opt<std::string>
797SymbolVisibility("fvisibility",
798 llvm::cl::desc("Set the default visibility to the specific option"));
799
800void InitializeSymbolVisibility(LangOptions &Options) {
801 if (SymbolVisibility.empty())
802 return;
803 std::string Visibility = SymbolVisibility;
804 const char *vkind = Visibility.c_str();
805 if (!strcmp(vkind, "default"))
806 Options.setVisibilityMode(LangOptions::DefaultVisibility);
807 else if (!strcmp(vkind, "protected"))
808 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
809 else if (!strcmp(vkind, "hidden"))
810 Options.setVisibilityMode(LangOptions::HiddenVisibility);
811 else if (!strcmp(vkind, "internal"))
812 Options.setVisibilityMode(LangOptions::InternalVisibility);
813 else
814 fprintf(stderr,
815 "-fvisibility only valid for default|protected|hidden|internal\n");
816}
817
Mike Stumpdb789912009-04-01 20:28:16 +0000818static llvm::cl::opt<bool>
819OverflowChecking("ftrapv",
Mike Stumpf71b7742009-04-02 18:15:54 +0000820 llvm::cl::desc("Trap on integer overflow"),
Mike Stumpdb789912009-04-01 20:28:16 +0000821 llvm::cl::init(false));
822
823void InitializeOverflowChecking(LangOptions &Options) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000824 Options.OverflowChecking = OverflowChecking;
Mike Stumpdb789912009-04-01 20:28:16 +0000825}
Chris Lattner4b009652007-07-25 00:24:17 +0000826//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000827// Target Triple Processing.
828//===----------------------------------------------------------------------===//
829
830static llvm::cl::opt<std::string>
831TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000832 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000833
Chris Lattnerfc457002008-03-05 01:18:20 +0000834static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000835Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000836
Chris Lattner2b168e02008-09-30 01:13:12 +0000837static llvm::cl::opt<std::string>
838MacOSVersionMin("mmacosx-version-min",
839 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
840
Chris Lattner01de9c82008-09-30 20:16:56 +0000841// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
842// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000843
844// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000845static void HandleMacOSVersionMin(std::string &Triple) {
846 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
847 if (DarwinDashIdx == std::string::npos) {
848 fprintf(stderr,
849 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
850 exit(1);
851 }
852 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
853
Chris Lattner01de9c82008-09-30 20:16:56 +0000854 // Remove the number.
855 Triple.resize(DarwinNumIdx);
856
857 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
858 bool MacOSVersionMinIsInvalid = false;
859 int VersionNum = 0;
860 if (MacOSVersionMin.size() < 4 ||
861 MacOSVersionMin.substr(0, 3) != "10." ||
862 !isdigit(MacOSVersionMin[3])) {
863 MacOSVersionMinIsInvalid = true;
864 } else {
865 const char *Start = MacOSVersionMin.c_str()+3;
866 char *End = 0;
867 VersionNum = (int)strtol(Start, &End, 10);
868
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000869 // The version number must be in the range 0-9.
870 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
871
Chris Lattner01de9c82008-09-30 20:16:56 +0000872 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
873 Triple += llvm::itostr(VersionNum+4);
874
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000875 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
876 // Add the period piece (.7) to the end of the triple. This gives us
877 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000878 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000879 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
880 MacOSVersionMinIsInvalid = true;
881 }
882 }
883
884 if (MacOSVersionMinIsInvalid) {
885 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000886 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000887 MacOSVersionMin.c_str());
888 exit(1);
889 }
890}
891
892/// CreateTargetTriple - Process the various options that affect the target
893/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000894static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000895 // Initialize base triple. If a -triple option has been specified, use
896 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000897 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000898 if (Triple.empty())
899 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000900
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000901 // If -arch foo was specified, remove the architecture from the triple we have
902 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000903
904 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000905 if (!Arch.empty()) {
906 // Decompose the base triple into "arch" and suffix.
907 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000908
Chris Lattner2b168e02008-09-30 01:13:12 +0000909 if (FirstDashIdx == std::string::npos) {
910 fprintf(stderr,
911 "Malformed target triple: \"%s\" ('-' could not be found).\n",
912 Triple.c_str());
913 exit(1);
914 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000915
916 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
917 if (Arch == "ppc")
918 Arch = "powerpc";
919 else if (Arch == "ppc64")
920 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +0000921
Chris Lattner2b168e02008-09-30 01:13:12 +0000922 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
923 }
924
925 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
926 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000927 if (!MacOSVersionMin.empty())
928 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000929
Chris Lattner2b168e02008-09-30 01:13:12 +0000930 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000931}
932
933//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000934// Preprocessor Initialization
935//===----------------------------------------------------------------------===//
936
937// FIXME: Preprocessor builtins to support.
938// -A... - Play with #assertions
939// -undef - Undefine all predefined macros
940
Chris Lattner695a4f52009-03-13 01:08:23 +0000941// FIXME: -imacros
942
Chris Lattner4b009652007-07-25 00:24:17 +0000943static llvm::cl::list<std::string>
944D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
945 llvm::cl::desc("Predefine the specified macro"));
946static llvm::cl::list<std::string>
947U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
948 llvm::cl::desc("Undefine the specified macro"));
949
Chris Lattner008da782008-01-10 01:53:41 +0000950static llvm::cl::list<std::string>
951ImplicitIncludes("include", llvm::cl::value_desc("file"),
952 llvm::cl::desc("Include file before parsing"));
953
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000954static llvm::cl::opt<std::string>
955ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
956 llvm::cl::desc("Include file before parsing"));
957
Chris Lattner4b009652007-07-25 00:24:17 +0000958// Append a #define line to Buf for Macro. Macro should be of the form XXX,
959// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
960// "#define XXX Y z W". To get a #define with no value, use "XXX=".
961static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
962 const char *Command = "#define ") {
963 Buf.insert(Buf.end(), Command, Command+strlen(Command));
964 if (const char *Equal = strchr(Macro, '=')) {
965 // Turn the = into ' '.
966 Buf.insert(Buf.end(), Macro, Equal);
967 Buf.push_back(' ');
Chris Lattner39baafb2009-04-07 06:02:44 +0000968
969 // Per GCC -D semantics, the macro ends at \n if it exists.
970 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner39c610d2009-04-07 18:18:09 +0000971 if (End) {
972 fprintf(stderr, "warning: macro '%s' contains embeded newline, text "
973 "after the newline is ignored.\n",
974 std::string(Macro, Equal).c_str());
975 } else {
976 End = Equal+strlen(Equal);
977 }
Chris Lattner39baafb2009-04-07 06:02:44 +0000978
979 Buf.insert(Buf.end(), Equal+1, End);
Chris Lattner4b009652007-07-25 00:24:17 +0000980 } else {
981 // Push "macroname 1".
982 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
983 Buf.push_back(' ');
984 Buf.push_back('1');
985 }
986 Buf.push_back('\n');
987}
988
Chris Lattner008da782008-01-10 01:53:41 +0000989/// AddImplicitInclude - Add an implicit #include of the specified file to the
990/// predefines buffer.
991static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
992 const char *Inc = "#include \"";
993 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
994 Buf.insert(Buf.end(), File.begin(), File.end());
995 Buf.push_back('"');
996 Buf.push_back('\n');
997}
998
Ted Kremenek2ee90d52009-03-20 00:26:38 +0000999/// AddImplicitIncludePTH - Add an implicit #include using the original file
1000/// used to generate a PTH cache.
1001static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
1002 PTHManager *P = PP.getPTHManager();
1003 assert(P && "No PTHManager.");
1004 const char *OriginalFile = P->getOriginalSourceFile();
1005
1006 if (!OriginalFile) {
1007 assert(!ImplicitIncludePTH.empty());
1008 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1009 "source header file for -include-pth\n",
1010 ImplicitIncludePTH.c_str());
1011 exit (1);
1012 }
1013
1014 AddImplicitInclude(Buf, OriginalFile);
1015}
Chris Lattner4b009652007-07-25 00:24:17 +00001016
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001017/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +00001018/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001019///
Chris Lattner9d818a22008-04-19 23:25:44 +00001020static bool InitializePreprocessor(Preprocessor &PP,
1021 bool InitializeSourceMgr,
1022 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +00001023 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +00001024
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001025 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +00001026 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001027
1028 if (InitializeSourceMgr) {
1029 if (InFile != "-") {
1030 const FileEntry *File = FileMgr.getFile(InFile);
1031 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +00001032 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001033 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1034 << InFile.c_str();
Chris Lattner9d818a22008-04-19 23:25:44 +00001035 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001036 }
1037 } else {
1038 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar99617162009-03-21 17:56:30 +00001039
1040 // If stdin was empty, SB is null. Cons up an empty memory
1041 // buffer now.
1042 if (!SB) {
1043 const char *EmptyStr = "";
1044 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1045 }
1046
1047 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +00001048 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001049 PP.getDiagnostics().Report(FullSourceLoc(),
1050 diag::err_fe_error_reading_stdin);
Chris Lattner9d818a22008-04-19 23:25:44 +00001051 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001052 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001053 }
Chris Lattner4b009652007-07-25 00:24:17 +00001054 }
Sam Bishop61a20782008-04-14 14:41:57 +00001055
Chris Lattner47b6a162008-04-19 23:09:31 +00001056 std::vector<char> PredefineBuffer;
1057
Chris Lattner4b009652007-07-25 00:24:17 +00001058 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +00001059 unsigned d = 0, D = D_macros.size();
1060 unsigned u = 0, U = U_macros.size();
1061 while (d < D || u < U) {
1062 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1063 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1064 else
1065 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1066 }
1067
Chris Lattner008da782008-01-10 01:53:41 +00001068 // FIXME: Read any files specified by -imacros.
1069
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001070 // Add implicit #includes from -include and -include-pth.
1071 bool handledPTH = ImplicitIncludePTH.empty();
1072 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc4ecf322009-03-20 00:40:03 +00001073 if (!handledPTH &&
1074 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001075 AddImplicitIncludePTH(PredefineBuffer, PP);
1076 handledPTH = true;
1077 }
1078
Chris Lattner008da782008-01-10 01:53:41 +00001079 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001080 }
1081 if (!handledPTH && !ImplicitIncludePTH.empty())
1082 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001083
Chris Lattner47b6a162008-04-19 23:09:31 +00001084 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001085 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +00001086 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001087
1088 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +00001089 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001090}
1091
1092//===----------------------------------------------------------------------===//
1093// Preprocessor include path information.
1094//===----------------------------------------------------------------------===//
1095
1096// This tool exports a large number of command line options to control how the
1097// preprocessor searches for header files. At root, however, the Preprocessor
1098// object takes a very simple interface: a list of directories to search for
1099//
1100// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001101// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001102//
Chris Lattner4b009652007-07-25 00:24:17 +00001103
1104static llvm::cl::opt<bool>
1105nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1106
1107// Various command line options. These four add directories to each chain.
1108static llvm::cl::list<std::string>
1109F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1110 llvm::cl::desc("Add directory to framework include search path"));
1111static llvm::cl::list<std::string>
1112I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1113 llvm::cl::desc("Add directory to include search path"));
1114static llvm::cl::list<std::string>
1115idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1116 llvm::cl::desc("Add directory to AFTER include search path"));
1117static llvm::cl::list<std::string>
1118iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1119 llvm::cl::desc("Add directory to QUOTE include search path"));
1120static llvm::cl::list<std::string>
1121isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1122 llvm::cl::desc("Add directory to SYSTEM include search path"));
1123
1124// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1125static llvm::cl::list<std::string>
1126iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1127 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1128static llvm::cl::list<std::string>
1129iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1130 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1131static llvm::cl::list<std::string>
1132iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1133 llvm::cl::Prefix,
1134 llvm::cl::desc("Set directory to include search path with prefix"));
1135
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001136static llvm::cl::opt<std::string>
1137isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1138 llvm::cl::desc("Set the system root directory (usually /)"));
1139
Chris Lattner4b009652007-07-25 00:24:17 +00001140// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001141
Chris Lattner4b009652007-07-25 00:24:17 +00001142/// InitializeIncludePaths - Process the -I options and set them in the
1143/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001144void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1145 FileManager &FM, const LangOptions &Lang) {
1146 InitHeaderSearch Init(Headers, Verbose, isysroot);
1147
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001148 // Handle -I... and -F... options, walking the lists in parallel.
1149 unsigned Iidx = 0, Fidx = 0;
1150 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1151 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001152 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001153 ++Iidx;
1154 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001155 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001156 ++Fidx;
1157 }
1158 }
Chris Lattner4b009652007-07-25 00:24:17 +00001159
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001160 // Consume what's left from whatever list was longer.
1161 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001162 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001163 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001164 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001165
1166 // Handle -idirafter... options.
1167 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001168 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1169 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001170
1171 // Handle -iquote... options.
1172 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001173 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001174
1175 // Handle -isystem... options.
1176 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001177 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001178
1179 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1180 // parallel, processing the values in order of occurance to get the right
1181 // prefixes.
1182 {
1183 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1184 unsigned iprefix_idx = 0;
1185 unsigned iwithprefix_idx = 0;
1186 unsigned iwithprefixbefore_idx = 0;
1187 bool iprefix_done = iprefix_vals.empty();
1188 bool iwithprefix_done = iwithprefix_vals.empty();
1189 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1190 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1191 if (!iprefix_done &&
1192 (iwithprefix_done ||
1193 iprefix_vals.getPosition(iprefix_idx) <
1194 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1195 (iwithprefixbefore_done ||
1196 iprefix_vals.getPosition(iprefix_idx) <
1197 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1198 Prefix = iprefix_vals[iprefix_idx];
1199 ++iprefix_idx;
1200 iprefix_done = iprefix_idx == iprefix_vals.size();
1201 } else if (!iwithprefix_done &&
1202 (iwithprefixbefore_done ||
1203 iwithprefix_vals.getPosition(iwithprefix_idx) <
1204 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001205 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1206 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001207 ++iwithprefix_idx;
1208 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1209 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001210 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1211 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001212 ++iwithprefixbefore_idx;
1213 iwithprefixbefore_done =
1214 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1215 }
1216 }
1217 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001218
Nico Weber770e3882008-08-22 09:25:22 +00001219 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001220
Daniel Dunbar4e604292009-02-21 20:52:41 +00001221 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001222 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001223 llvm::sys::Path::GetMainExecutable(Argv0,
1224 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001225 if (!MainExecutablePath.isEmpty()) {
1226 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1227 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001228
1229 // Get foo/lib/clang/1.0/include
1230 //
1231 // FIXME: Don't embed version here.
1232 MainExecutablePath.appendComponent("lib");
1233 MainExecutablePath.appendComponent("clang");
1234 MainExecutablePath.appendComponent("1.0");
1235 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001236
1237 // We pass true to ignore sysroot so that we *always* look for clang headers
1238 // relative to our executable, never relative to -isysroot.
1239 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1240 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001241 }
1242
Nico Weber770e3882008-08-22 09:25:22 +00001243 if (!nostdinc)
1244 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001245
1246 // Now that we have collected all of the include paths, merge them all
1247 // together and tell the preprocessor about them.
1248
Nico Weber770e3882008-08-22 09:25:22 +00001249 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001250}
1251
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001252//===----------------------------------------------------------------------===//
1253// Driver PreprocessorFactory - For lazily generating preprocessors ...
1254//===----------------------------------------------------------------------===//
1255
1256namespace {
1257class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001258 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001259 Diagnostic &Diags;
1260 const LangOptions &LangInfo;
1261 TargetInfo &Target;
1262 SourceManager &SourceMgr;
1263 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001264 bool InitializeSourceMgr;
1265
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001266public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001267 DriverPreprocessorFactory(const std::string &infile,
1268 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001269 TargetInfo &target, SourceManager &SM,
1270 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001271 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1272 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1273
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001274
1275 virtual ~DriverPreprocessorFactory() {}
1276
1277 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001278 llvm::OwningPtr<PTHManager> PTHMgr;
1279
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001280 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1281 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1282 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001283 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001284 }
1285
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001286 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001287 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1288 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001289 PTHMgr.reset(PTHManager::Create(x, &Diags,
1290 TokenCache.empty() ? Diagnostic::Error
1291 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001292 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001293
Ted Kremenek6348cc62009-03-22 06:42:39 +00001294 if (Diags.hasErrorOccurred())
1295 exit(1);
1296
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001297 // Create the Preprocessor.
1298 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1299 SourceMgr, HeaderInfo,
1300 PTHMgr.get()));
1301
1302 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1303 // That argument is used as the IdentifierInfoLookup argument to
1304 // IdentifierTable's ctor.
1305 if (PTHMgr) {
1306 PTHMgr->setPreprocessor(PP.get());
1307 PP->setPTHManager(PTHMgr.take());
1308 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001309
Chris Lattner9d818a22008-04-19 23:25:44 +00001310 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001311 return NULL;
1312 }
1313
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001314 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001315 if (ProgAction != PrintPreprocessedInput) {
1316 std::string ErrStr;
1317 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1318 if (!DFG && !ErrStr.empty()) {
1319 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001320 return NULL;
1321 }
1322 }
1323
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001324 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001325 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001326 }
1327};
1328}
Chris Lattner4b009652007-07-25 00:24:17 +00001329
Chris Lattner4b009652007-07-25 00:24:17 +00001330//===----------------------------------------------------------------------===//
1331// Basic Parser driver
1332//===----------------------------------------------------------------------===//
1333
Chris Lattner9d818a22008-04-19 23:25:44 +00001334static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001335 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001336 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001337
1338 // Parsing the specified input file.
1339 P.ParseTranslationUnit();
1340 delete PA;
1341}
1342
1343//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001344// Code generation options
1345//===----------------------------------------------------------------------===//
1346
1347static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001348GenerateDebugInfo("g",
1349 llvm::cl::desc("Generate source level debug information"));
1350
Daniel Dunbar9101a632009-02-17 19:47:34 +00001351static llvm::cl::opt<std::string>
1352TargetCPU("mcpu",
1353 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1354
Chris Lattner8a9615c2009-03-16 18:41:18 +00001355static void InitializeCompileOptions(CompileOptions &Opts,
1356 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001357 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001358 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001359 if (OptSize) {
1360 // -Os implies -O2
1361 // FIXME: Diagnose conflicting options.
1362 Opts.OptimizationLevel = 2;
1363 } else {
1364 Opts.OptimizationLevel = OptLevel;
1365 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001366
1367 // FIXME: There are llvm-gcc options to control these selectively.
1368 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1369 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001370 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001371
1372#ifdef NDEBUG
1373 Opts.VerifyModule = 0;
1374#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001375
1376 Opts.CPU = TargetCPU;
1377 Opts.Features.insert(Opts.Features.end(),
1378 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001379
Chris Lattnerf04a7562009-03-26 05:00:52 +00001380 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1381
Chris Lattnere8f70712009-02-18 01:23:44 +00001382 // Handle -ftime-report.
1383 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001384}
1385
1386//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001387// Fix-It Options
1388//===----------------------------------------------------------------------===//
1389static llvm::cl::list<ParsedSourceLocation>
1390FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1391 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1392
1393//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001394// Main driver
1395//===----------------------------------------------------------------------===//
1396
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001397/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001398/// action. These consumers can operate on both ASTs that are freshly
1399/// parsed from source files as well as those deserialized from Bitcode.
1400/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001401static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001402 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001403 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001404 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001405 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001406 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001407 default:
1408 return NULL;
1409
1410 case ASTPrint:
1411 return CreateASTPrinter();
1412
1413 case ASTDump:
1414 return CreateASTDumper();
1415
1416 case ASTView:
1417 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001418
Chris Lattner7f902922009-02-18 01:20:05 +00001419 case PrintDeclContext:
1420 return CreateDeclContextPrinter();
1421
1422 case EmitHTML:
1423 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001424
Chris Lattner7f902922009-02-18 01:20:05 +00001425 case InheritanceView:
1426 return CreateInheritanceViewer(InheritanceViewCls);
1427
1428 case TestSerialization:
1429 return CreateSerializationTest(Diag, FileMgr);
1430
1431 case EmitAssembly:
1432 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001433 case EmitBC:
1434 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001435 BackendAction Act;
1436 if (ProgAction == EmitAssembly)
1437 Act = Backend_EmitAssembly;
1438 else if (ProgAction == EmitLLVM)
1439 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001440 else if (ProgAction == EmitLLVMOnly)
1441 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001442 else
1443 Act = Backend_EmitBC;
1444
1445 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001446 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001447 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001448 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001449 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001450
Chris Lattner7f902922009-02-18 01:20:05 +00001451 case SerializeAST:
1452 // FIXME: Allow user to tailor where the file is written.
1453 return CreateASTSerializer(InFile, OutputFile, Diag);
1454
1455 case RewriteObjC:
1456 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001457
Chris Lattner7f902922009-02-18 01:20:05 +00001458 case RewriteBlocks:
1459 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1460
1461 case RunAnalysis:
1462 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001463 }
1464}
1465
Chris Lattner4b009652007-07-25 00:24:17 +00001466/// ProcessInputFile - Process a single input file with the specified state.
1467///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001468static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001469 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001470 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001471 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001472 FixItRewriter *FixItRewrite = 0;
1473
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001474 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001475 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001476 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1477 PP.getFileManager(), PP.getLangOptions(),
1478 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001479
1480 if (!Consumer) {
1481 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001482 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001483 return;
1484 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001485
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001486 break;
1487
Chris Lattneraf669fb2008-10-12 05:03:36 +00001488 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001489 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001490 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001491 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001492 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001493 RawLex.SetKeepWhitespaceMode(true);
1494
1495 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001496 RawLex.LexFromRawLexer(RawTok);
1497 while (RawTok.isNot(tok::eof)) {
1498 PP.DumpToken(RawTok, true);
1499 fprintf(stderr, "\n");
1500 RawLex.LexFromRawLexer(RawTok);
1501 }
1502 ClearSourceMgr = true;
1503 break;
1504 }
Chris Lattner4b009652007-07-25 00:24:17 +00001505 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001506 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001507 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001508 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001509 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001510 do {
1511 PP.Lex(Tok);
1512 PP.DumpToken(Tok, true);
1513 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001514 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001515 ClearSourceMgr = true;
1516 break;
1517 }
1518 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerefe33382009-02-18 01:51:21 +00001519 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001520 Token Tok;
1521 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001522 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001523 do {
1524 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001525 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001526 ClearSourceMgr = true;
1527 break;
1528 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001529
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001530 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001531 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001532 CacheTokens(PP, OutputFile);
1533 ClearSourceMgr = true;
1534 break;
1535 }
Chris Lattner4b009652007-07-25 00:24:17 +00001536
Chris Lattnerefe33382009-02-18 01:51:21 +00001537 case PrintPreprocessedInput: { // -E mode.
1538 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerefd02a32008-01-27 23:55:11 +00001539 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001540 ClearSourceMgr = true;
1541 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001542 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001543
Chris Lattnerefe33382009-02-18 01:51:21 +00001544 case ParseNoop: { // -parse-noop
1545 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001546 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001547 ClearSourceMgr = true;
1548 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001549 }
Chris Lattner4b009652007-07-25 00:24:17 +00001550
Chris Lattnerefe33382009-02-18 01:51:21 +00001551 case ParsePrintCallbacks: {
1552 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001553 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001554 ClearSourceMgr = true;
1555 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001556 }
1557
1558 case ParseSyntaxOnly: { // -fsyntax-only
1559 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001560 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001561 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001562 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001563
1564 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001565 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001566 ClearSourceMgr = true;
1567 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001568
Chris Lattnerefe33382009-02-18 01:51:21 +00001569 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001570 DoRewriteTest(PP, InFile, OutputFile);
1571 ClearSourceMgr = true;
1572 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001573 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001574
1575 case FixIt:
1576 llvm::TimeRegion Timer(ClangFrontendTimer);
1577 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001578 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor133d2552009-04-02 01:08:08 +00001579 PP.getSourceManager());
Douglas Gregor133d2552009-04-02 01:08:08 +00001580 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001581 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001582
1583 if (Consumer) {
Chris Lattner143fd6d2009-03-28 01:37:17 +00001584 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner143fd6d2009-03-28 01:37:17 +00001585
Douglas Gregor24b48b02009-04-02 19:05:20 +00001586 if (FixItAtLocations.size() > 0) {
1587 // Even without the "-fixit" flag, with may have some specific
1588 // locations where the user has requested fixes. Process those
1589 // locations now.
1590 if (!FixItRewrite)
1591 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1592 PP.getSourceManager());
1593
1594 bool AddedFixitLocation = false;
1595 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1596 Idx != Last; ++Idx) {
1597 RequestedSourceLocation Requested;
1598 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1599 Requested)) {
1600 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1601 FixItAtLocations[Idx].FileName.c_str());
1602 } else {
1603 FixItRewrite->addFixItLocation(Requested);
1604 AddedFixitLocation = true;
1605 }
1606 }
1607
1608 if (!AddedFixitLocation) {
1609 // All of the fix-it locations were bad. Don't fix anything.
1610 delete FixItRewrite;
1611 FixItRewrite = 0;
1612 }
1613 }
1614
Chris Lattner143fd6d2009-03-28 01:37:17 +00001615 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1616 PP.getSourceManager(),
1617 PP.getTargetInfo(),
1618 PP.getIdentifierTable(),
1619 PP.getSelectorTable(),
1620 /* FreeMemory = */ !DisableFree));
Chris Lattner143fd6d2009-03-28 01:37:17 +00001621
1622
Chris Lattner07b08c02009-03-28 04:13:34 +00001623 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner143fd6d2009-03-28 01:37:17 +00001624
Douglas Gregor133d2552009-04-02 01:08:08 +00001625 if (FixItRewrite)
1626 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1627
Chris Lattner143fd6d2009-03-28 01:37:17 +00001628 // If in -disable-free mode, don't deallocate these when they go out of
1629 // scope.
Chris Lattner07b08c02009-03-28 04:13:34 +00001630 if (DisableFree)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001631 ContextOwner.take();
Ted Kremenek88eebed2009-01-28 04:29:29 +00001632 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001633
1634 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001635 if (CheckDiagnostics(PP))
1636 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001637
Chris Lattner4b009652007-07-25 00:24:17 +00001638 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001639 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001640 PP.PrintStats();
1641 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001642 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001643 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001644 fprintf(stderr, "\n");
1645 }
1646
1647 // For a multi-file compilation, some things are ok with nuking the source
1648 // manager tables, other require stable fileid/macroid's across multiple
1649 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001650 if (ClearSourceMgr)
1651 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001652
1653 if (DisableFree)
1654 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001655}
1656
Ted Kremenek80d53372007-12-12 23:41:08 +00001657static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1658 FileManager& FileMgr) {
1659
1660 if (VerifyDiagnostics) {
1661 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1662 exit (1);
1663 }
1664
1665 llvm::sys::Path Filename(InFile);
1666
1667 if (!Filename.isValid()) {
1668 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1669 exit (1);
1670 }
1671
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001672 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner06459ae2009-03-28 03:49:26 +00001673
1674 // Create the memory buffer that contains the contents of the file.
1675 llvm::OwningPtr<llvm::MemoryBuffer>
1676 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1677
1678 if (MBuffer)
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001679 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001680
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001681 if (!Ctx) {
Ted Kremenek2bd42412007-12-13 18:11:11 +00001682 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1683 InFile.c_str());
1684 exit (1);
1685 }
1686
Ted Kremenekab749372007-12-19 19:27:38 +00001687 // Observe that we use the source file name stored in the deserialized
1688 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001689 llvm::OwningPtr<ASTConsumer>
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001690 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001691 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001692
Ted Kremenek80d53372007-12-12 23:41:08 +00001693 if (!Consumer) {
1694 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1695 exit (1);
1696 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001697
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001698 Consumer->Initialize(*Ctx);
Nico Weberd2a6ac92008-08-10 19:59:06 +00001699
Chris Lattner8d72ee02008-02-06 01:42:25 +00001700 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattnerf4fbc442009-03-28 04:27:18 +00001701 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1702 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1703 I != E; ++I)
Chris Lattnera17991f2009-03-29 16:50:03 +00001704 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek80d53372007-12-12 23:41:08 +00001705}
1706
1707
Chris Lattner4b009652007-07-25 00:24:17 +00001708static llvm::cl::list<std::string>
1709InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1710
Ted Kremenek80d53372007-12-12 23:41:08 +00001711static bool isSerializedFile(const std::string& InFile) {
1712 if (InFile.size() < 4)
1713 return false;
1714
1715 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattner2b989562009-03-04 21:40:56 +00001716 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek80d53372007-12-12 23:41:08 +00001717}
1718
Chris Lattner4b009652007-07-25 00:24:17 +00001719
1720int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001721 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001722 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001723 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001724 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001725
Chris Lattnerefe33382009-02-18 01:51:21 +00001726 if (TimeReport)
1727 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1728
Chris Lattner4b009652007-07-25 00:24:17 +00001729 // If no input was specified, read from stdin.
1730 if (InputFilenames.empty())
1731 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001732
Chris Lattner4b009652007-07-25 00:24:17 +00001733 // Create a file manager object to provide access to and cache the filesystem.
1734 FileManager FileMgr;
1735
Ted Kremenekb240e822007-12-11 23:28:38 +00001736 // Create the diagnostic client for reporting errors or for
1737 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001738 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001739
Ted Kremenek5c341732008-08-07 17:49:57 +00001740 if (!VerifyDiagnostics) {
1741 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001742 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1743 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001744 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001745 !NoShowLocation,
1746 PrintSourceRangeInfo);
Ted Kremenek5c341732008-08-07 17:49:57 +00001747 } else {
1748 // When checking diagnostics, just buffer them up.
1749 TextDiagClient = new TextDiagnosticBuffer();
1750
1751 if (InputFilenames.size() != 1) {
1752 fprintf(stderr,
1753 "-verify only works on single input files for now.\n");
1754 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001755 }
1756 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001757
Chris Lattner4b009652007-07-25 00:24:17 +00001758 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001759 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1760 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001761 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001762 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001763
Chris Lattner45a56e02007-12-05 23:24:17 +00001764 // -I- is a deprecated GCC feature, scan for it and reject it.
1765 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1766 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001767 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001768 I_dirs.erase(I_dirs.begin()+i);
1769 --i;
1770 }
1771 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001772
1773 // Get information about the target being compiled for.
1774 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001775 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1776
Chris Lattner2c77d852008-03-14 06:12:05 +00001777 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001778 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1779 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001780 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001781 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001782
Daniel Dunbar9c321102009-01-20 23:17:32 +00001783 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001784 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001785
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001786 llvm::OwningPtr<SourceManager> SourceMgr;
1787
Chris Lattner4b009652007-07-25 00:24:17 +00001788 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001789 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001790
Ted Kremenek5c341732008-08-07 17:49:57 +00001791 if (isSerializedFile(InFile)) {
1792 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001793 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattner2b989562009-03-04 21:40:56 +00001794 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001795 }
Chris Lattner2b989562009-03-04 21:40:56 +00001796
1797 /// Create a SourceManager object. This tracks and owns all the file
1798 /// buffers allocated to a translation unit.
1799 if (!SourceMgr)
1800 SourceMgr.reset(new SourceManager());
1801 else
1802 SourceMgr->clearIDTables();
1803
1804 // Initialize language options, inferring file types from input filenames.
1805 LangOptions LangInfo;
1806 InitializeBaseLanguage();
1807 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001808 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00001809 InitializeGCMode(LangInfo);
Fariborz Jahanian49343332009-04-03 03:28:57 +00001810 InitializeSymbolVisibility(LangInfo);
Mike Stumpdb789912009-04-01 20:28:16 +00001811 InitializeOverflowChecking(LangInfo);
Chris Lattner2b989562009-03-04 21:40:56 +00001812 InitializeLanguageStandard(LangInfo, LK, Target.get());
1813
1814 // Process the -I options and set them in the HeaderInfo.
1815 HeaderSearch HeaderInfo(FileMgr);
1816
1817 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1818
1819 // Set up the preprocessor with these options.
1820 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1821 *SourceMgr.get(), HeaderInfo);
1822
1823 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1824
1825 if (!PP)
1826 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001827
Chris Lattner2b989562009-03-04 21:40:56 +00001828 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1829 // always reset to using TextDiagClient.
1830 llvm::OwningPtr<DiagnosticClient> TmpClient;
1831
1832 if (!HTMLDiag.empty()) {
1833 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1834 &PPFactory));
1835 Diags.setClient(TmpClient.get());
Ted Kremenek80d53372007-12-12 23:41:08 +00001836 }
Chris Lattner2b989562009-03-04 21:40:56 +00001837 else
1838 Diags.setClient(TextDiagClient);
1839
1840 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001841 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00001842
1843 HeaderInfo.ClearFileInfo();
Chris Lattner4b009652007-07-25 00:24:17 +00001844 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001845
Mike Stump91d01352009-01-28 02:43:35 +00001846 if (Verbose)
1847 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1848 " hosted on " LLVM_HOSTTRIPLE "\n");
1849
Ted Kremenekec6c5252008-08-07 18:13:12 +00001850 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001851 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1852 (NumDiagnostics == 1 ? "" : "s"));
1853
1854 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001855 FileMgr.PrintStats();
1856 fprintf(stderr, "\n");
1857 }
1858
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001859 // If verifying diagnostics and we reached here, all is well.
1860 if (VerifyDiagnostics)
1861 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00001862
1863 delete ClangFrontendTimer;
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001864
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001865 // Managed static deconstruction. Useful for making things like
1866 // -time-passes usable.
1867 llvm::llvm_shutdown();
1868
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001869 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001870}