blob: 2843848f313cd608dc3dae45e5d441c6d6decaec [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenekc2542b62009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000031#include "clang/Frontend/PathDiagnosticClients.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000032#include "clang/Frontend/TextDiagnosticBuffer.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000039#include "clang/AST/ASTContext.h"
40#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000041#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "clang/Parse/Parser.h"
43#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000044#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045#include "clang/Basic/FileManager.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000048#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000049#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000050#include "llvm/ADT/StringExtras.h"
51#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000053#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000055#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000056#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000057#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000058#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000059#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000060#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000061#include <cstdlib>
62
Reid Spencer5f016e22007-07-11 17:01:13 +000063using namespace clang;
64
65//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-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//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000149// Global options.
150//===----------------------------------------------------------------------===//
151
Chris Lattner47099742009-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 Dunbard3db4012008-10-16 16:54:18 +0000157static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000158
Reid Spencer5f016e22007-07-11 17:01:13 +0000159static llvm::cl::opt<bool>
160Verbose("v", llvm::cl::desc("Enable verbose output"));
161static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000162Stats("print-stats",
163 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-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));
Reid Spencer5f016e22007-07-11 17:01:13 +0000168
169enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000170 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000171 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000172 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000173 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000174 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000175 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000176 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000178 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000179 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000180 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +0000181 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-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 Xu2d75d6f2009-01-13 01:29:24 +0000185 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000186 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000192 DumpTokens, // Dump out preprocessed tokens.
193 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000194 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000195 GeneratePTH, // Generate pre-tokenized header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000196 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000207 clEnumValN(DumpRawTokens, "dump-raw-tokens",
208 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000209 clEnumValN(RunAnalysis, "analyze",
210 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000211 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek6a340832008-03-18 21:19:49 +0000219 clEnumValN(EmitHTML, "emit-html",
220 "Output input source as HTML"),
Chris Lattner3b427b32007-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 Lattnerea254db2007-10-11 00:37:43 +0000225 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000226 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000227 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000228 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000229 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000230 "Generate pre-tokenized header file"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000231 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000232 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000233 clEnumValN(EmitAssembly, "S",
234 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000236 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000237 clEnumValN(EmitBC, "emit-llvm-bc",
238 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000239 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
240 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000241 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000242 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000243 clEnumValN(RewriteTest, "rewrite-test",
244 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000245 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-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 Naroff13188952008-09-18 14:10:13 +0000249 clEnumValN(RewriteBlocks, "rewrite-blocks",
250 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000251 clEnumValN(FixIt, "fixit",
252 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 clEnumValEnd));
254
Ted Kremenekccc76472007-12-19 19:47:59 +0000255
256static llvm::cl::opt<std::string>
257OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000258 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000259 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000260
Ted Kremenekc2e72992008-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 Guptae8b9f5b2008-05-08 08:54:20 +0000270//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000271// Diagnostic Options
272//===----------------------------------------------------------------------===//
273
Ted Kremenek41193e42007-09-26 19:42:19 +0000274static llvm::cl::opt<bool>
275VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000276 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000277
Ted Kremenek88f5cde2008-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 Weberfd54ebc2008-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 Lattner65f5e642009-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 Weberfd54ebc2008-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 Lattner1fbee5d2009-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 Weberfd54ebc2008-08-05 23:33:20 +0000301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-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 Dunbard77b2512009-01-14 18:56:36 +0000309 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000310
311//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000312// Builtin Options
313//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-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 Gregor3573c0c2009-02-14 20:49:29 +0000320static llvm::cl::opt<bool>
321Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000322 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000323 "freestanding environment"));
324
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000325static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000326AllowBuiltins("fbuiltin", llvm::cl::init(true),
327 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000328
329
330static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000331MathErrno("fmath-errno", llvm::cl::init(true),
332 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000333
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000334//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000335// Language Options
336//===----------------------------------------------------------------------===//
337
338enum LangKind {
339 langkind_unspecified,
340 langkind_c,
341 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000342 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 langkind_cxx,
344 langkind_cxx_cpp,
345 langkind_objc,
346 langkind_objc_cpp,
347 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000348 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000349};
350
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbard2ea3862009-01-29 23:50:47 +0000358 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000360 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
361 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000363 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
365 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000366 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-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"),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek8904f152007-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 Lattner9b2f6c42008-01-04 19:12:28 +0000401 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 }
403
Ted Kremenek8904f152007-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 Lattnerd9cd4c92009-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 Lattnera778d7d2008-10-22 17:29:21 +0000414 return langkind_asm_cpp;
Ted Kremenek8904f152007-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 Kremenek85888962008-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 Dunbar0b5b0da2009-04-01 05:09:09 +0000444static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 // FIXME: implement -fpreprocessed mode.
446 bool NoPreprocess = false;
447
Ted Kremenek8904f152007-12-05 23:49:08 +0000448 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000450 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000451 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000452 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 case langkind_c_cpp:
454 NoPreprocess = true;
455 // FALLTHROUGH
456 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000457 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek85888962008-10-21 00:54:44 +0000469 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenekea644d82008-09-03 21:22:16 +0000485 lang_gnu_START,
486 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000487 lang_cxx98, lang_gnucxx98,
488 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000489};
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 Lattner50748f42009-04-06 17:17:55 +0000500 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000502 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000504 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000506 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +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++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000514 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 Greif5f8d1db2009-03-11 23:07:18 +0000518 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlssonee98ac52007-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 Naroffd62701b2008-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 Gupta56cf96b2008-05-08 08:28:14 +0000534 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000535
536static llvm::cl::opt<bool>
537WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000538 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000539
540static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000541NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-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 Lattnerae0ee032008-12-04 23:20:07 +0000545
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000546static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000547EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000548
549static llvm::cl::opt<bool>
Chris Lattner810f6d52009-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 Stumpa0f02aa2009-02-02 22:57:57 +0000555ObjCNonFragileABI("fobjc-nonfragile-abi",
556 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000557
Daniel Dunbard604c402009-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 Kremenek01d9dbf2008-04-29 04:37:03 +0000561
Daniel Dunbar6379a7a2008-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 Dunbarf77ac862008-08-11 21:35:06 +0000573static llvm::cl::opt<bool>
574GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000575 llvm::cl::desc("Generate output compatible with the standard GNU "
576 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000577
578static llvm::cl::opt<bool>
579NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000580 llvm::cl::desc("Generate output compatible with the NeXT "
581 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000582
Ted Kremenekea644d82008-09-03 21:22:16 +0000583
584
585static llvm::cl::opt<bool>
586Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
587
Chris Lattner16167a62009-03-02 22:11:07 +0000588static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000589TargetFeatures("mattr", llvm::cl::CommaSeparated,
590 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
591
Douglas Gregor26dce442009-03-10 00:06:19 +0000592static llvm::cl::opt<unsigned>
593TemplateDepth("ftemplate-depth", llvm::cl::init(99),
594 llvm::cl::desc("Maximum depth of recursive template "
595 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000596
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000597
598static llvm::cl::opt<bool>
599OptSize("Os", llvm::cl::desc("Optimize for size"));
600
601static llvm::cl::opt<bool>
602NoCommon("fno-common",
603 llvm::cl::desc("Compile common globals like normal definitions"),
604 llvm::cl::ValueDisallowed);
605
606
607// It might be nice to add bounds to the CommandLine library directly.
608struct OptLevelParser : public llvm::cl::parser<unsigned> {
609 bool parse(llvm::cl::Option &O, const char *ArgName,
610 const std::string &Arg, unsigned &Val) {
611 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
612 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000613 if (Val > 3)
614 return O.error(": '" + Arg + "' invalid optimization level!");
615 return false;
616 }
617};
618static llvm::cl::opt<unsigned, false, OptLevelParser>
619OptLevel("O", llvm::cl::Prefix,
620 llvm::cl::desc("Optimization level"),
621 llvm::cl::init(0));
622
Reid Spencer5f016e22007-07-11 17:01:13 +0000623// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000624// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000625static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
626 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000627 // Allow the target to set the default the langauge options as it sees fit.
628 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000629
Chris Lattner6328cc32009-03-03 19:56:18 +0000630 // If there are any -mattr options, pass them to the target for validation and
631 // processing. The driver should have already consolidated all the
632 // target-feature settings and passed them to us in the -mattr list. The
633 // -mattr list is treated by the code generator as a diff against the -mcpu
634 // setting, but the driver should pass all enabled options as "+" settings.
635 // This means that the target should only look at + settings.
636 if (!TargetFeatures.empty()
637 // FIXME: The driver is not quite yet ready for this.
638 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000639 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000640 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
641 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000642 if (Opt != -1) {
643 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000644 fprintf(stderr, "invalid feature '%s'\n",
645 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000646 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000647 fprintf(stderr, "feature '%s': %s\n",
648 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000649 exit(1);
650 }
651 }
652
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 if (LangStd == lang_unspecified) {
654 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000655 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000656 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000658 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 case langkind_c_cpp:
660 case langkind_objc:
661 case langkind_objc_cpp:
662 LangStd = lang_gnu99;
663 break;
664 case langkind_cxx:
665 case langkind_cxx_cpp:
666 case langkind_objcxx:
667 case langkind_objcxx_cpp:
668 LangStd = lang_gnucxx98;
669 break;
670 }
671 }
672
673 switch (LangStd) {
674 default: assert(0 && "Unknown language standard!");
675
676 // Fall through from newer standards to older ones. This isn't really right.
677 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000678 case lang_gnucxx0x:
679 case lang_cxx0x:
680 Options.CPlusPlus0x = 1;
681 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 case lang_gnucxx98:
683 case lang_cxx98:
684 Options.CPlusPlus = 1;
685 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000686 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 // FALL THROUGH.
688 case lang_gnu99:
689 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 Options.C99 = 1;
691 Options.HexFloats = 1;
692 // FALL THROUGH.
693 case lang_gnu89:
694 Options.BCPLComment = 1; // Only for C99/C++.
695 // FALL THROUGH.
696 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000697 Options.Digraphs = 1; // C94, C99, C++.
698 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 case lang_c89:
700 break;
701 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000702
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000703 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
704 Options.GNUMode = LangStd >= lang_gnu_START;
705
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000706 if (Options.CPlusPlus) {
707 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000708 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000709 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000710
Chris Lattnerd658b562008-04-05 06:32:51 +0000711 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
712 Options.ImplicitInt = 1;
713 else
714 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000715
Daniel Dunbard573d262009-04-07 22:13:21 +0000716 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
717 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000718 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000719 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000720 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000721
Chris Lattner802db9b2008-12-05 00:10:44 +0000722 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
723 // even if they are normally on for the target. In GNU modes (e.g.
724 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000725 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000726 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000727 Options.Blocks = 0;
728
Daniel Dunbar85c49102009-03-15 00:11:28 +0000729 // Never accept '$' in identifiers when preprocessing assembler.
730 if (LK != langkind_asm_cpp)
731 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000732 if (PascalStrings.getPosition())
733 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000734 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000735 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000736 if (NoLaxVectorConversions.getPosition())
737 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000738 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000739 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000740 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000741
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000742 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000743 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000744 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000745 Options.Freestanding = Options.NoBuiltin = 1;
746
Chris Lattner810f6d52009-03-13 17:38:01 +0000747 if (EnableHeinousExtensions)
748 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000749
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000750 Options.MathErrno = MathErrno;
751
Douglas Gregor26dce442009-03-10 00:06:19 +0000752 Options.InstantiationDepth = TemplateDepth;
753
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000754 // Override the default runtime if the user requested it.
755 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000756 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000757 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000758 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000759
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000760 if (ObjCNonFragileABI)
761 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000762
763 if (EmitAllDecls)
764 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000765
766 if (OptSize)
767 Options.OptimizeSize = 1;
768
769 // -Os implies -O2
770 if (Options.OptimizeSize || OptLevel)
771 Options.Optimize = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000772}
773
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000774static llvm::cl::opt<bool>
775ObjCExclusiveGC("fobjc-gc-only",
776 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000777 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000778
779static llvm::cl::opt<bool>
780ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000781 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000782
783void InitializeGCMode(LangOptions &Options) {
784 if (ObjCExclusiveGC)
785 Options.setGCMode(LangOptions::GCOnly);
786 else if (ObjCEnableGC)
787 Options.setGCMode(LangOptions::HybridGC);
788}
789
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000790static llvm::cl::opt<std::string>
791SymbolVisibility("fvisibility",
792 llvm::cl::desc("Set the default visibility to the specific option"));
793
794void InitializeSymbolVisibility(LangOptions &Options) {
795 if (SymbolVisibility.empty())
796 return;
797 std::string Visibility = SymbolVisibility;
798 const char *vkind = Visibility.c_str();
799 if (!strcmp(vkind, "default"))
800 Options.setVisibilityMode(LangOptions::DefaultVisibility);
801 else if (!strcmp(vkind, "protected"))
802 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
803 else if (!strcmp(vkind, "hidden"))
804 Options.setVisibilityMode(LangOptions::HiddenVisibility);
805 else if (!strcmp(vkind, "internal"))
806 Options.setVisibilityMode(LangOptions::InternalVisibility);
807 else
808 fprintf(stderr,
809 "-fvisibility only valid for default|protected|hidden|internal\n");
810}
811
Mike Stump2add4732009-04-01 20:28:16 +0000812static llvm::cl::opt<bool>
813OverflowChecking("ftrapv",
Mike Stump035cf892009-04-02 18:15:54 +0000814 llvm::cl::desc("Trap on integer overflow"),
Mike Stump2add4732009-04-01 20:28:16 +0000815 llvm::cl::init(false));
816
817void InitializeOverflowChecking(LangOptions &Options) {
Mike Stump035cf892009-04-02 18:15:54 +0000818 Options.OverflowChecking = OverflowChecking;
Mike Stump2add4732009-04-01 20:28:16 +0000819}
Reid Spencer5f016e22007-07-11 17:01:13 +0000820//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000821// Target Triple Processing.
822//===----------------------------------------------------------------------===//
823
824static llvm::cl::opt<std::string>
825TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000826 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000827
Chris Lattner42e67372008-03-05 01:18:20 +0000828static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000829Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000830
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000831static llvm::cl::opt<std::string>
832MacOSVersionMin("mmacosx-version-min",
833 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
834
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000835// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
836// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000837
838// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000839static void HandleMacOSVersionMin(std::string &Triple) {
840 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
841 if (DarwinDashIdx == std::string::npos) {
842 fprintf(stderr,
843 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
844 exit(1);
845 }
846 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
847
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000848 // Remove the number.
849 Triple.resize(DarwinNumIdx);
850
851 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
852 bool MacOSVersionMinIsInvalid = false;
853 int VersionNum = 0;
854 if (MacOSVersionMin.size() < 4 ||
855 MacOSVersionMin.substr(0, 3) != "10." ||
856 !isdigit(MacOSVersionMin[3])) {
857 MacOSVersionMinIsInvalid = true;
858 } else {
859 const char *Start = MacOSVersionMin.c_str()+3;
860 char *End = 0;
861 VersionNum = (int)strtol(Start, &End, 10);
862
Chris Lattner079f2c462008-09-30 20:30:12 +0000863 // The version number must be in the range 0-9.
864 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
865
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000866 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
867 Triple += llvm::itostr(VersionNum+4);
868
Chris Lattner079f2c462008-09-30 20:30:12 +0000869 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
870 // Add the period piece (.7) to the end of the triple. This gives us
871 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000872 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000873 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
874 MacOSVersionMinIsInvalid = true;
875 }
876 }
877
878 if (MacOSVersionMinIsInvalid) {
879 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000880 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000881 MacOSVersionMin.c_str());
882 exit(1);
883 }
884}
885
886/// CreateTargetTriple - Process the various options that affect the target
887/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000888static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000889 // Initialize base triple. If a -triple option has been specified, use
890 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000891 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000892 if (Triple.empty())
893 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000894
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000895 // If -arch foo was specified, remove the architecture from the triple we have
896 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000897
898 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000899 if (!Arch.empty()) {
900 // Decompose the base triple into "arch" and suffix.
901 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000902
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000903 if (FirstDashIdx == std::string::npos) {
904 fprintf(stderr,
905 "Malformed target triple: \"%s\" ('-' could not be found).\n",
906 Triple.c_str());
907 exit(1);
908 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000909
910 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
911 if (Arch == "ppc")
912 Arch = "powerpc";
913 else if (Arch == "ppc64")
914 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000915
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000916 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
917 }
918
919 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
920 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000921 if (!MacOSVersionMin.empty())
922 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000923
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000924 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000925}
926
927//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000928// Preprocessor Initialization
929//===----------------------------------------------------------------------===//
930
931// FIXME: Preprocessor builtins to support.
932// -A... - Play with #assertions
933// -undef - Undefine all predefined macros
934
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000935// FIXME: -imacros
936
Reid Spencer5f016e22007-07-11 17:01:13 +0000937static llvm::cl::list<std::string>
938D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
939 llvm::cl::desc("Predefine the specified macro"));
940static llvm::cl::list<std::string>
941U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
942 llvm::cl::desc("Undefine the specified macro"));
943
Chris Lattner64299f82008-01-10 01:53:41 +0000944static llvm::cl::list<std::string>
945ImplicitIncludes("include", llvm::cl::value_desc("file"),
946 llvm::cl::desc("Include file before parsing"));
947
Ted Kremenek748d5d62009-03-20 00:26:38 +0000948static llvm::cl::opt<std::string>
949ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
950 llvm::cl::desc("Include file before parsing"));
951
Reid Spencer5f016e22007-07-11 17:01:13 +0000952// Append a #define line to Buf for Macro. Macro should be of the form XXX,
953// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
954// "#define XXX Y z W". To get a #define with no value, use "XXX=".
955static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
956 const char *Command = "#define ") {
957 Buf.insert(Buf.end(), Command, Command+strlen(Command));
958 if (const char *Equal = strchr(Macro, '=')) {
959 // Turn the = into ' '.
960 Buf.insert(Buf.end(), Macro, Equal);
961 Buf.push_back(' ');
Chris Lattner0b514152009-04-07 06:02:44 +0000962
963 // Per GCC -D semantics, the macro ends at \n if it exists.
964 const char *End = strpbrk(Equal, "\n\r");
Chris Lattner3eb2fc82009-04-07 18:18:09 +0000965 if (End) {
966 fprintf(stderr, "warning: macro '%s' contains embeded newline, text "
967 "after the newline is ignored.\n",
968 std::string(Macro, Equal).c_str());
969 } else {
970 End = Equal+strlen(Equal);
971 }
Chris Lattner0b514152009-04-07 06:02:44 +0000972
973 Buf.insert(Buf.end(), Equal+1, End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 } else {
975 // Push "macroname 1".
976 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
977 Buf.push_back(' ');
978 Buf.push_back('1');
979 }
980 Buf.push_back('\n');
981}
982
Chris Lattner64299f82008-01-10 01:53:41 +0000983/// AddImplicitInclude - Add an implicit #include of the specified file to the
984/// predefines buffer.
985static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
986 const char *Inc = "#include \"";
987 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
988 Buf.insert(Buf.end(), File.begin(), File.end());
989 Buf.push_back('"');
990 Buf.push_back('\n');
991}
992
Ted Kremenek748d5d62009-03-20 00:26:38 +0000993/// AddImplicitIncludePTH - Add an implicit #include using the original file
994/// used to generate a PTH cache.
995static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
996 PTHManager *P = PP.getPTHManager();
997 assert(P && "No PTHManager.");
998 const char *OriginalFile = P->getOriginalSourceFile();
999
1000 if (!OriginalFile) {
1001 assert(!ImplicitIncludePTH.empty());
1002 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1003 "source header file for -include-pth\n",
1004 ImplicitIncludePTH.c_str());
1005 exit (1);
1006 }
1007
1008 AddImplicitInclude(Buf, OriginalFile);
1009}
Reid Spencer5f016e22007-07-11 17:01:13 +00001010
Chris Lattner53b0dab2007-10-09 22:10:18 +00001011/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +00001012/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001013///
Chris Lattner51574ea2008-04-19 23:25:44 +00001014static bool InitializePreprocessor(Preprocessor &PP,
1015 bool InitializeSourceMgr,
1016 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +00001017 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +00001018
Chris Lattner53b0dab2007-10-09 22:10:18 +00001019 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +00001020 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +00001021
1022 if (InitializeSourceMgr) {
1023 if (InFile != "-") {
1024 const FileEntry *File = FileMgr.getFile(InFile);
1025 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +00001026 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001027 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1028 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +00001029 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001030 }
1031 } else {
1032 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +00001033
1034 // If stdin was empty, SB is null. Cons up an empty memory
1035 // buffer now.
1036 if (!SB) {
1037 const char *EmptyStr = "";
1038 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1039 }
1040
1041 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +00001042 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001043 PP.getDiagnostics().Report(FullSourceLoc(),
1044 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +00001045 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001046 }
Chris Lattner53b0dab2007-10-09 22:10:18 +00001047 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 }
Sam Bishop1102d6b2008-04-14 14:41:57 +00001049
Chris Lattneraa391972008-04-19 23:09:31 +00001050 std::vector<char> PredefineBuffer;
1051
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +00001053 unsigned d = 0, D = D_macros.size();
1054 unsigned u = 0, U = U_macros.size();
1055 while (d < D || u < U) {
1056 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1057 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1058 else
1059 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1060 }
1061
Chris Lattner64299f82008-01-10 01:53:41 +00001062 // FIXME: Read any files specified by -imacros.
1063
Ted Kremenek748d5d62009-03-20 00:26:38 +00001064 // Add implicit #includes from -include and -include-pth.
1065 bool handledPTH = ImplicitIncludePTH.empty();
1066 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +00001067 if (!handledPTH &&
1068 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +00001069 AddImplicitIncludePTH(PredefineBuffer, PP);
1070 handledPTH = true;
1071 }
1072
Chris Lattner64299f82008-01-10 01:53:41 +00001073 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001074 }
1075 if (!handledPTH && !ImplicitIncludePTH.empty())
1076 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001077
Chris Lattneraa391972008-04-19 23:09:31 +00001078 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001079 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +00001080 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001081
1082 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +00001083 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001084}
1085
1086//===----------------------------------------------------------------------===//
1087// Preprocessor include path information.
1088//===----------------------------------------------------------------------===//
1089
1090// This tool exports a large number of command line options to control how the
1091// preprocessor searches for header files. At root, however, the Preprocessor
1092// object takes a very simple interface: a list of directories to search for
1093//
1094// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001095// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001096//
Reid Spencer5f016e22007-07-11 17:01:13 +00001097
1098static llvm::cl::opt<bool>
1099nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1100
1101// Various command line options. These four add directories to each chain.
1102static llvm::cl::list<std::string>
1103F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1104 llvm::cl::desc("Add directory to framework include search path"));
1105static llvm::cl::list<std::string>
1106I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1107 llvm::cl::desc("Add directory to include search path"));
1108static llvm::cl::list<std::string>
1109idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1110 llvm::cl::desc("Add directory to AFTER include search path"));
1111static llvm::cl::list<std::string>
1112iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1113 llvm::cl::desc("Add directory to QUOTE include search path"));
1114static llvm::cl::list<std::string>
1115isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1116 llvm::cl::desc("Add directory to SYSTEM include search path"));
1117
1118// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1119static llvm::cl::list<std::string>
1120iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1121 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1122static llvm::cl::list<std::string>
1123iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1124 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1125static llvm::cl::list<std::string>
1126iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1127 llvm::cl::Prefix,
1128 llvm::cl::desc("Set directory to include search path with prefix"));
1129
Chris Lattner0c946412007-08-26 17:47:35 +00001130static llvm::cl::opt<std::string>
1131isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1132 llvm::cl::desc("Set the system root directory (usually /)"));
1133
Reid Spencer5f016e22007-07-11 17:01:13 +00001134// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001135
Reid Spencer5f016e22007-07-11 17:01:13 +00001136/// InitializeIncludePaths - Process the -I options and set them in the
1137/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001138void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1139 FileManager &FM, const LangOptions &Lang) {
1140 InitHeaderSearch Init(Headers, Verbose, isysroot);
1141
Ted Kremenekf3721112008-05-31 00:27:00 +00001142 // Handle -I... and -F... options, walking the lists in parallel.
1143 unsigned Iidx = 0, Fidx = 0;
1144 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1145 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001146 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001147 ++Iidx;
1148 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001149 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001150 ++Fidx;
1151 }
1152 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001153
Ted Kremenekf3721112008-05-31 00:27:00 +00001154 // Consume what's left from whatever list was longer.
1155 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001156 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001157 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001158 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001159
1160 // Handle -idirafter... options.
1161 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001162 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1163 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001164
1165 // Handle -iquote... options.
1166 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001167 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001168
1169 // Handle -isystem... options.
1170 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001171 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001172
1173 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1174 // parallel, processing the values in order of occurance to get the right
1175 // prefixes.
1176 {
1177 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1178 unsigned iprefix_idx = 0;
1179 unsigned iwithprefix_idx = 0;
1180 unsigned iwithprefixbefore_idx = 0;
1181 bool iprefix_done = iprefix_vals.empty();
1182 bool iwithprefix_done = iwithprefix_vals.empty();
1183 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1184 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1185 if (!iprefix_done &&
1186 (iwithprefix_done ||
1187 iprefix_vals.getPosition(iprefix_idx) <
1188 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1189 (iwithprefixbefore_done ||
1190 iprefix_vals.getPosition(iprefix_idx) <
1191 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1192 Prefix = iprefix_vals[iprefix_idx];
1193 ++iprefix_idx;
1194 iprefix_done = iprefix_idx == iprefix_vals.size();
1195 } else if (!iwithprefix_done &&
1196 (iwithprefixbefore_done ||
1197 iwithprefix_vals.getPosition(iwithprefix_idx) <
1198 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001199 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1200 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 ++iwithprefix_idx;
1202 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1203 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001204 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1205 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 ++iwithprefixbefore_idx;
1207 iwithprefixbefore_done =
1208 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1209 }
1210 }
1211 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001212
Nico Weber0fca0222008-08-22 09:25:22 +00001213 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001214
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001215 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001216 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001217 llvm::sys::Path::GetMainExecutable(Argv0,
1218 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001219 if (!MainExecutablePath.isEmpty()) {
1220 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1221 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001222
1223 // Get foo/lib/clang/1.0/include
1224 //
1225 // FIXME: Don't embed version here.
1226 MainExecutablePath.appendComponent("lib");
1227 MainExecutablePath.appendComponent("clang");
1228 MainExecutablePath.appendComponent("1.0");
1229 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001230
1231 // We pass true to ignore sysroot so that we *always* look for clang headers
1232 // relative to our executable, never relative to -isysroot.
1233 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1234 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001235 }
1236
Nico Weber0fca0222008-08-22 09:25:22 +00001237 if (!nostdinc)
1238 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001239
1240 // Now that we have collected all of the include paths, merge them all
1241 // together and tell the preprocessor about them.
1242
Nico Weber0fca0222008-08-22 09:25:22 +00001243 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001244}
1245
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001246//===----------------------------------------------------------------------===//
1247// Driver PreprocessorFactory - For lazily generating preprocessors ...
1248//===----------------------------------------------------------------------===//
1249
1250namespace {
1251class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001252 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001253 Diagnostic &Diags;
1254 const LangOptions &LangInfo;
1255 TargetInfo &Target;
1256 SourceManager &SourceMgr;
1257 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001258 bool InitializeSourceMgr;
1259
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001260public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001261 DriverPreprocessorFactory(const std::string &infile,
1262 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001263 TargetInfo &target, SourceManager &SM,
1264 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001265 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1266 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1267
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001268
1269 virtual ~DriverPreprocessorFactory() {}
1270
1271 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001272 llvm::OwningPtr<PTHManager> PTHMgr;
1273
Ted Kremenek748d5d62009-03-20 00:26:38 +00001274 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1275 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1276 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001277 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001278 }
1279
Ted Kremenek72b1b152009-01-15 18:47:46 +00001280 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001281 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1282 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001283 PTHMgr.reset(PTHManager::Create(x, &Diags,
1284 TokenCache.empty() ? Diagnostic::Error
1285 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001286 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001287
Ted Kremenek22f0d092009-03-22 06:42:39 +00001288 if (Diags.hasErrorOccurred())
1289 exit(1);
1290
Ted Kremenek72b1b152009-01-15 18:47:46 +00001291 // Create the Preprocessor.
1292 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1293 SourceMgr, HeaderInfo,
1294 PTHMgr.get()));
1295
1296 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1297 // That argument is used as the IdentifierInfoLookup argument to
1298 // IdentifierTable's ctor.
1299 if (PTHMgr) {
1300 PTHMgr->setPreprocessor(PP.get());
1301 PP->setPTHManager(PTHMgr.take());
1302 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001303
Chris Lattner51574ea2008-04-19 23:25:44 +00001304 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001305 return NULL;
1306 }
1307
Daniel Dunbar750c3582008-10-24 22:12:41 +00001308 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001309 if (ProgAction != PrintPreprocessedInput) {
1310 std::string ErrStr;
1311 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1312 if (!DFG && !ErrStr.empty()) {
1313 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001314 return NULL;
1315 }
1316 }
1317
Ted Kremenek339b9c22008-04-17 22:31:54 +00001318 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001319 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001320 }
1321};
1322}
Reid Spencer5f016e22007-07-11 17:01:13 +00001323
Reid Spencer5f016e22007-07-11 17:01:13 +00001324//===----------------------------------------------------------------------===//
1325// Basic Parser driver
1326//===----------------------------------------------------------------------===//
1327
Chris Lattner51574ea2008-04-19 23:25:44 +00001328static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001330 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001331
1332 // Parsing the specified input file.
1333 P.ParseTranslationUnit();
1334 delete PA;
1335}
1336
1337//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001338// Code generation options
1339//===----------------------------------------------------------------------===//
1340
1341static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001342GenerateDebugInfo("g",
1343 llvm::cl::desc("Generate source level debug information"));
1344
Daniel Dunbara034ba82009-02-17 19:47:34 +00001345static llvm::cl::opt<std::string>
1346TargetCPU("mcpu",
1347 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1348
Chris Lattner7afae712009-03-16 18:41:18 +00001349static void InitializeCompileOptions(CompileOptions &Opts,
1350 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001351 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001352 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001353 if (OptSize) {
1354 // -Os implies -O2
1355 // FIXME: Diagnose conflicting options.
1356 Opts.OptimizationLevel = 2;
1357 } else {
1358 Opts.OptimizationLevel = OptLevel;
1359 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001360
1361 // FIXME: There are llvm-gcc options to control these selectively.
1362 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1363 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001364 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001365
1366#ifdef NDEBUG
1367 Opts.VerifyModule = 0;
1368#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001369
1370 Opts.CPU = TargetCPU;
1371 Opts.Features.insert(Opts.Features.end(),
1372 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001373
Chris Lattnerbd360642009-03-26 05:00:52 +00001374 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1375
Chris Lattner44502662009-02-18 01:23:44 +00001376 // Handle -ftime-report.
1377 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001378}
1379
1380//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001381// Fix-It Options
1382//===----------------------------------------------------------------------===//
1383static llvm::cl::list<ParsedSourceLocation>
1384FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1385 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1386
1387//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001388// Main driver
1389//===----------------------------------------------------------------------===//
1390
Ted Kremenekdb094a22007-12-05 18:27:04 +00001391/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001392/// action. These consumers can operate on both ASTs that are freshly
1393/// parsed from source files as well as those deserialized from Bitcode.
1394/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001395static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001396 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001397 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001398 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001399 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001400 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001401 default:
1402 return NULL;
1403
1404 case ASTPrint:
1405 return CreateASTPrinter();
1406
1407 case ASTDump:
1408 return CreateASTDumper();
1409
1410 case ASTView:
1411 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001412
Chris Lattner8a5c8092009-02-18 01:20:05 +00001413 case PrintDeclContext:
1414 return CreateDeclContextPrinter();
1415
1416 case EmitHTML:
1417 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001418
Chris Lattner8a5c8092009-02-18 01:20:05 +00001419 case InheritanceView:
1420 return CreateInheritanceViewer(InheritanceViewCls);
1421
1422 case TestSerialization:
1423 return CreateSerializationTest(Diag, FileMgr);
1424
1425 case EmitAssembly:
1426 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001427 case EmitBC:
1428 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001429 BackendAction Act;
1430 if (ProgAction == EmitAssembly)
1431 Act = Backend_EmitAssembly;
1432 else if (ProgAction == EmitLLVM)
1433 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001434 else if (ProgAction == EmitLLVMOnly)
1435 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001436 else
1437 Act = Backend_EmitBC;
1438
1439 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001440 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001441 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001442 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001443 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001444
Chris Lattner8a5c8092009-02-18 01:20:05 +00001445 case SerializeAST:
1446 // FIXME: Allow user to tailor where the file is written.
1447 return CreateASTSerializer(InFile, OutputFile, Diag);
1448
1449 case RewriteObjC:
1450 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001451
Chris Lattner8a5c8092009-02-18 01:20:05 +00001452 case RewriteBlocks:
1453 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1454
1455 case RunAnalysis:
1456 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001457 }
1458}
1459
Reid Spencer5f016e22007-07-11 17:01:13 +00001460/// ProcessInputFile - Process a single input file with the specified state.
1461///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001462static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001463 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001464 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001465 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001466 FixItRewriter *FixItRewrite = 0;
1467
Ted Kremenek85888962008-10-21 00:54:44 +00001468 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001470 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1471 PP.getFileManager(), PP.getLangOptions(),
1472 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001473
1474 if (!Consumer) {
1475 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001476 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001477 return;
1478 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001479
Ted Kremenekdb094a22007-12-05 18:27:04 +00001480 break;
1481
Chris Lattnerc106c102008-10-12 05:03:36 +00001482 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001483 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001484 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001485 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001486 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001487 RawLex.SetKeepWhitespaceMode(true);
1488
1489 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001490 RawLex.LexFromRawLexer(RawTok);
1491 while (RawTok.isNot(tok::eof)) {
1492 PP.DumpToken(RawTok, true);
1493 fprintf(stderr, "\n");
1494 RawLex.LexFromRawLexer(RawTok);
1495 }
1496 ClearSourceMgr = true;
1497 break;
1498 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001500 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001501 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001502 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001503 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 do {
1505 PP.Lex(Tok);
1506 PP.DumpToken(Tok, true);
1507 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001508 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001509 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 break;
1511 }
1512 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001513 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001514 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001516 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 do {
1518 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001519 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001520 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 break;
1522 }
Ted Kremenek85888962008-10-21 00:54:44 +00001523
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001524 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001525 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001526 CacheTokens(PP, OutputFile);
1527 ClearSourceMgr = true;
1528 break;
1529 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001530
Chris Lattner47099742009-02-18 01:51:21 +00001531 case PrintPreprocessedInput: { // -E mode.
1532 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001533 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001534 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 break;
Chris Lattner47099742009-02-18 01:51:21 +00001536 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001537
Chris Lattner47099742009-02-18 01:51:21 +00001538 case ParseNoop: { // -parse-noop
1539 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001540 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001541 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 break;
Chris Lattner47099742009-02-18 01:51:21 +00001543 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001544
Chris Lattner47099742009-02-18 01:51:21 +00001545 case ParsePrintCallbacks: {
1546 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001547 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001548 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 break;
Chris Lattner47099742009-02-18 01:51:21 +00001550 }
1551
1552 case ParseSyntaxOnly: { // -fsyntax-only
1553 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001554 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001555 break;
Chris Lattner47099742009-02-18 01:51:21 +00001556 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001557
1558 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001559 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001560 ClearSourceMgr = true;
1561 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001562
Chris Lattner47099742009-02-18 01:51:21 +00001563 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001564 DoRewriteTest(PP, InFile, OutputFile);
1565 ClearSourceMgr = true;
1566 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001567 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001568
1569 case FixIt:
1570 llvm::TimeRegion Timer(ClangFrontendTimer);
1571 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001572 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor558cb562009-04-02 01:08:08 +00001573 PP.getSourceManager());
Douglas Gregor558cb562009-04-02 01:08:08 +00001574 break;
Chris Lattner47099742009-02-18 01:51:21 +00001575 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001576
1577 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001578 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001579
Douglas Gregor26df2f02009-04-02 19:05:20 +00001580 if (FixItAtLocations.size() > 0) {
1581 // Even without the "-fixit" flag, with may have some specific
1582 // locations where the user has requested fixes. Process those
1583 // locations now.
1584 if (!FixItRewrite)
1585 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1586 PP.getSourceManager());
1587
1588 bool AddedFixitLocation = false;
1589 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1590 Idx != Last; ++Idx) {
1591 RequestedSourceLocation Requested;
1592 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1593 Requested)) {
1594 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1595 FixItAtLocations[Idx].FileName.c_str());
1596 } else {
1597 FixItRewrite->addFixItLocation(Requested);
1598 AddedFixitLocation = true;
1599 }
1600 }
1601
1602 if (!AddedFixitLocation) {
1603 // All of the fix-it locations were bad. Don't fix anything.
1604 delete FixItRewrite;
1605 FixItRewrite = 0;
1606 }
1607 }
1608
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001609 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1610 PP.getSourceManager(),
1611 PP.getTargetInfo(),
1612 PP.getIdentifierTable(),
1613 PP.getSelectorTable(),
1614 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001615
1616
Chris Lattner3599dbe2009-03-28 04:13:34 +00001617 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001618
Douglas Gregor558cb562009-04-02 01:08:08 +00001619 if (FixItRewrite)
1620 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1621
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001622 // If in -disable-free mode, don't deallocate these when they go out of
1623 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001624 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001625 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001626 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001627
1628 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001629 if (CheckDiagnostics(PP))
1630 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001631
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001633 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 PP.PrintStats();
1635 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001636 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001637 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 fprintf(stderr, "\n");
1639 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001640
1641 // For a multi-file compilation, some things are ok with nuking the source
1642 // manager tables, other require stable fileid/macroid's across multiple
1643 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001644 if (ClearSourceMgr)
1645 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001646
1647 if (DisableFree)
1648 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001649}
1650
Ted Kremenek20e97482007-12-12 23:41:08 +00001651static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1652 FileManager& FileMgr) {
1653
1654 if (VerifyDiagnostics) {
1655 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1656 exit (1);
1657 }
1658
1659 llvm::sys::Path Filename(InFile);
1660
1661 if (!Filename.isValid()) {
1662 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1663 exit (1);
1664 }
1665
Chris Lattner557c5b12009-03-28 04:27:18 +00001666 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001667
1668 // Create the memory buffer that contains the contents of the file.
1669 llvm::OwningPtr<llvm::MemoryBuffer>
1670 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1671
1672 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001673 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001674
Chris Lattner557c5b12009-03-28 04:27:18 +00001675 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001676 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1677 InFile.c_str());
1678 exit (1);
1679 }
1680
Ted Kremenek63ea8632007-12-19 19:27:38 +00001681 // Observe that we use the source file name stored in the deserialized
1682 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001683 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001684 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001685 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001686
Ted Kremenek20e97482007-12-12 23:41:08 +00001687 if (!Consumer) {
1688 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1689 exit (1);
1690 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001691
Chris Lattner557c5b12009-03-28 04:27:18 +00001692 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001693
Chris Lattnere66b65c2008-02-06 01:42:25 +00001694 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001695 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1696 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1697 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001698 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001699}
1700
1701
Reid Spencer5f016e22007-07-11 17:01:13 +00001702static llvm::cl::list<std::string>
1703InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1704
Ted Kremenek20e97482007-12-12 23:41:08 +00001705static bool isSerializedFile(const std::string& InFile) {
1706 if (InFile.size() < 4)
1707 return false;
1708
1709 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001710 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001711}
1712
Reid Spencer5f016e22007-07-11 17:01:13 +00001713
1714int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001716 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001717 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001718 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001719
Chris Lattner47099742009-02-18 01:51:21 +00001720 if (TimeReport)
1721 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1722
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 // If no input was specified, read from stdin.
1724 if (InputFilenames.empty())
1725 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001726
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // Create a file manager object to provide access to and cache the filesystem.
1728 FileManager FileMgr;
1729
Ted Kremenek31e703b2007-12-11 23:28:38 +00001730 // Create the diagnostic client for reporting errors or for
1731 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001732 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001733
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001734 if (!VerifyDiagnostics) {
1735 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001736 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1737 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001738 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001739 !NoShowLocation,
1740 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001741 } else {
1742 // When checking diagnostics, just buffer them up.
1743 TextDiagClient = new TextDiagnosticBuffer();
1744
1745 if (InputFilenames.size() != 1) {
1746 fprintf(stderr,
1747 "-verify only works on single input files for now.\n");
1748 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 }
1750 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001751
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001753 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1754 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001755 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001756 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001757
Chris Lattner4f037832007-12-05 23:24:17 +00001758 // -I- is a deprecated GCC feature, scan for it and reject it.
1759 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1760 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001761 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001762 I_dirs.erase(I_dirs.begin()+i);
1763 --i;
1764 }
1765 }
Chris Lattner11215192008-03-14 06:12:05 +00001766
1767 // Get information about the target being compiled for.
1768 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001769 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1770
Chris Lattner11215192008-03-14 06:12:05 +00001771 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001772 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1773 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001774 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001775 }
Chris Lattner4f037832007-12-05 23:24:17 +00001776
Daniel Dunbard4270232009-01-20 23:17:32 +00001777 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001778 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001779
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001780 llvm::OwningPtr<SourceManager> SourceMgr;
1781
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001783 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001784
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001785 if (isSerializedFile(InFile)) {
1786 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001787 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001788 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001789 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001790
1791 /// Create a SourceManager object. This tracks and owns all the file
1792 /// buffers allocated to a translation unit.
1793 if (!SourceMgr)
1794 SourceMgr.reset(new SourceManager());
1795 else
1796 SourceMgr->clearIDTables();
1797
1798 // Initialize language options, inferring file types from input filenames.
1799 LangOptions LangInfo;
1800 InitializeBaseLanguage();
1801 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001802 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001803 InitializeGCMode(LangInfo);
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +00001804 InitializeSymbolVisibility(LangInfo);
Mike Stump2add4732009-04-01 20:28:16 +00001805 InitializeOverflowChecking(LangInfo);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001806 InitializeLanguageStandard(LangInfo, LK, Target.get());
1807
1808 // Process the -I options and set them in the HeaderInfo.
1809 HeaderSearch HeaderInfo(FileMgr);
1810
1811 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1812
1813 // Set up the preprocessor with these options.
1814 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1815 *SourceMgr.get(), HeaderInfo);
1816
1817 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1818
1819 if (!PP)
1820 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001821
Chris Lattnerf63aea32009-03-04 21:40:56 +00001822 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1823 // always reset to using TextDiagClient.
1824 llvm::OwningPtr<DiagnosticClient> TmpClient;
1825
1826 if (!HTMLDiag.empty()) {
1827 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1828 &PPFactory));
1829 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001830 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001831 else
1832 Diags.setClient(TextDiagClient);
1833
1834 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001835 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001836
1837 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 }
Chris Lattner11215192008-03-14 06:12:05 +00001839
Mike Stump007f2a92009-01-28 02:43:35 +00001840 if (Verbose)
1841 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1842 " hosted on " LLVM_HOSTTRIPLE "\n");
1843
Ted Kremenek7a08e282008-08-07 18:13:12 +00001844 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1846 (NumDiagnostics == 1 ? "" : "s"));
1847
1848 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 FileMgr.PrintStats();
1850 fprintf(stderr, "\n");
1851 }
1852
Daniel Dunbar276373d2008-10-27 22:10:13 +00001853 // If verifying diagnostics and we reached here, all is well.
1854 if (VerifyDiagnostics)
1855 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001856
1857 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001858
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001859 // Managed static deconstruction. Useful for making things like
1860 // -time-passes usable.
1861 llvm::llvm_shutdown();
1862
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001863 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001864}