blob: 5a5ffc32af9963ae92961ffde5d22cd67785242c [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 Dunbar9f9768c2009-03-20 23:49:28 +0000326AllowBuiltins("fbuiltin",
327 llvm::cl::desc("Disable implicit builtin knowledge of functions"),
328 llvm::cl::init(true), llvm::cl::AllowInverse);
Chris Lattner7644f072009-03-13 22:38:49 +0000329
330
331static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000332MathErrno("fmath-errno",
Chris Lattner5ea9d1b2009-02-17 00:30:31 +0000333 llvm::cl::desc("Require math functions to respect errno"),
Chris Lattner5bef8dd2009-02-17 00:35:09 +0000334 llvm::cl::init(true), llvm::cl::AllowInverse);
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000335
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000336//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000337// Language Options
338//===----------------------------------------------------------------------===//
339
340enum LangKind {
341 langkind_unspecified,
342 langkind_c,
343 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000344 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 langkind_cxx,
346 langkind_cxx_cpp,
347 langkind_objc,
348 langkind_objc_cpp,
349 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000350 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000351};
352
Reid Spencer5f016e22007-07-11 17:01:13 +0000353static llvm::cl::opt<LangKind>
354BaseLang("x", llvm::cl::desc("Base language to compile"),
355 llvm::cl::init(langkind_unspecified),
356 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
357 clEnumValN(langkind_cxx, "c++", "C++"),
358 clEnumValN(langkind_objc, "objective-c", "Objective C"),
359 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000360 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000362 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
363 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000365 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
367 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000368 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000370 clEnumValN(langkind_c, "c-header",
371 "C header"),
372 clEnumValN(langkind_objc, "objective-c-header",
373 "Objective-C header"),
374 clEnumValN(langkind_cxx, "c++-header",
375 "C++ header"),
376 clEnumValN(langkind_objcxx, "objective-c++-header",
377 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 clEnumValEnd));
379
380static llvm::cl::opt<bool>
381LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
382 llvm::cl::Hidden);
383static llvm::cl::opt<bool>
384LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
385 llvm::cl::Hidden);
386
Ted Kremenek8904f152007-12-05 23:49:08 +0000387/// InitializeBaseLanguage - Handle the -x foo options.
388static void InitializeBaseLanguage() {
389 if (LangObjC)
390 BaseLang = langkind_objc;
391 else if (LangObjCXX)
392 BaseLang = langkind_objcxx;
393}
394
395static LangKind GetLanguage(const std::string &Filename) {
396 if (BaseLang != langkind_unspecified)
397 return BaseLang;
398
399 std::string::size_type DotPos = Filename.rfind('.');
400
401 if (DotPos == std::string::npos) {
402 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000403 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 }
405
Ted Kremenek8904f152007-12-05 23:49:08 +0000406 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
407 // C header: .h
408 // C++ header: .hh or .H;
409 // assembler no preprocessing: .s
410 // assembler: .S
411 if (Ext == "c")
412 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000413 else if (Ext == "S" ||
414 // If the compiler is run on a .s file, preprocess it as .S
415 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000416 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000417 else if (Ext == "i")
418 return langkind_c_cpp;
419 else if (Ext == "ii")
420 return langkind_cxx_cpp;
421 else if (Ext == "m")
422 return langkind_objc;
423 else if (Ext == "mi")
424 return langkind_objc_cpp;
425 else if (Ext == "mm" || Ext == "M")
426 return langkind_objcxx;
427 else if (Ext == "mii")
428 return langkind_objcxx_cpp;
429 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
430 Ext == "c++" || Ext == "cp" || Ext == "cxx")
431 return langkind_cxx;
432 else
433 return langkind_c;
434}
435
436
Ted Kremenek85888962008-10-21 00:54:44 +0000437static void InitializeCOptions(LangOptions &Options) {
438 // Do nothing.
439}
440
441static void InitializeObjCOptions(LangOptions &Options) {
442 Options.ObjC1 = Options.ObjC2 = 1;
443}
444
445
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000446static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 // FIXME: implement -fpreprocessed mode.
448 bool NoPreprocess = false;
449
Ted Kremenek8904f152007-12-05 23:49:08 +0000450 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000452 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000453 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000454 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000455 case langkind_c_cpp:
456 NoPreprocess = true;
457 // FALLTHROUGH
458 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000459 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 break;
461 case langkind_cxx_cpp:
462 NoPreprocess = true;
463 // FALLTHROUGH
464 case langkind_cxx:
465 Options.CPlusPlus = 1;
466 break;
467 case langkind_objc_cpp:
468 NoPreprocess = true;
469 // FALLTHROUGH
470 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000471 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 break;
473 case langkind_objcxx_cpp:
474 NoPreprocess = true;
475 // FALLTHROUGH
476 case langkind_objcxx:
477 Options.ObjC1 = Options.ObjC2 = 1;
478 Options.CPlusPlus = 1;
479 break;
480 }
481}
482
483/// LangStds - Language standards we support.
484enum LangStds {
485 lang_unspecified,
486 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000487 lang_gnu_START,
488 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000489 lang_cxx98, lang_gnucxx98,
490 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000491};
492
493static llvm::cl::opt<LangStds>
494LangStd("std", llvm::cl::desc("Language standard to compile for"),
495 llvm::cl::init(lang_unspecified),
496 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
497 clEnumValN(lang_c89, "c90", "ISO C 1990"),
498 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
499 clEnumValN(lang_c94, "iso9899:199409",
500 "ISO C 1990 with amendment 1"),
501 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000502 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000504 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000506 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000508 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 clEnumValN(lang_gnu99, "gnu9x",
510 "ISO C 1999 with GNU extensions"),
511 clEnumValN(lang_cxx98, "c++98",
512 "ISO C++ 1998 with amendments"),
513 clEnumValN(lang_gnucxx98, "gnu++98",
514 "ISO C++ 1998 with amendments and GNU "
515 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000516 clEnumValN(lang_cxx0x, "c++0x",
517 "Upcoming ISO C++ 200x with amendments"),
518 clEnumValN(lang_gnucxx0x, "gnu++0x",
519 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000520 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 clEnumValEnd));
522
523static llvm::cl::opt<bool>
524NoOperatorNames("fno-operator-names",
525 llvm::cl::desc("Do not treat C++ operator name keywords as "
526 "synonyms for operators"));
527
Anders Carlssonee98ac52007-10-15 02:50:23 +0000528static llvm::cl::opt<bool>
529PascalStrings("fpascal-strings",
530 llvm::cl::desc("Recognize and construct Pascal-style "
531 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000532
533static llvm::cl::opt<bool>
534MSExtensions("fms-extensions",
535 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000536 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000537
538static llvm::cl::opt<bool>
539WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000540 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000541
542static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000543NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000544 llvm::cl::desc("Disallow implicit conversions between "
545 "vectors with a different number of "
546 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000547
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000548static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000549EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"),
550 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
551 llvm::cl::ZeroOrMore);
552
553static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000554EnableHeinousExtensions("fheinous-gnu-extensions",
555 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
556 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
557
558static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000559ObjCNonFragileABI("fobjc-nonfragile-abi",
560 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000561
Daniel Dunbard604c402009-02-04 21:19:06 +0000562static llvm::cl::opt<bool>
563EmitAllDecls("femit-all-decls",
564 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000565
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000566// FIXME: This (and all GCC -f options) really come in -f... and
567// -fno-... forms, and additionally support automagic behavior when
568// they are not defined. For example, -fexceptions defaults to on or
569// off depending on the language. We should support this behavior in
570// some form (perhaps just add a facility for distinguishing when an
571// has its default value from when it has been set to its default
572// value).
573static llvm::cl::opt<bool>
574Exceptions("fexceptions",
575 llvm::cl::desc("Enable support for exception handling."));
576
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000577static llvm::cl::opt<bool>
578GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000579 llvm::cl::desc("Generate output compatible with the standard GNU "
580 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000581
582static llvm::cl::opt<bool>
583NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000584 llvm::cl::desc("Generate output compatible with the NeXT "
585 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000586
Ted Kremenekea644d82008-09-03 21:22:16 +0000587
588
589static llvm::cl::opt<bool>
590Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
591
592static llvm::cl::opt<bool>
593Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
594
Chris Lattner16167a62009-03-02 22:11:07 +0000595static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000596TargetFeatures("mattr", llvm::cl::CommaSeparated,
597 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
598
Douglas Gregor26dce442009-03-10 00:06:19 +0000599static llvm::cl::opt<unsigned>
600TemplateDepth("ftemplate-depth", llvm::cl::init(99),
601 llvm::cl::desc("Maximum depth of recursive template "
602 "instantiation"));
Chris Lattner16167a62009-03-02 22:11:07 +0000603
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000604
605static llvm::cl::opt<bool>
606OptSize("Os", llvm::cl::desc("Optimize for size"));
607
608static llvm::cl::opt<bool>
609NoCommon("fno-common",
610 llvm::cl::desc("Compile common globals like normal definitions"),
611 llvm::cl::ValueDisallowed);
612
613
614// It might be nice to add bounds to the CommandLine library directly.
615struct OptLevelParser : public llvm::cl::parser<unsigned> {
616 bool parse(llvm::cl::Option &O, const char *ArgName,
617 const std::string &Arg, unsigned &Val) {
618 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
619 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000620 if (Val > 3)
621 return O.error(": '" + Arg + "' invalid optimization level!");
622 return false;
623 }
624};
625static llvm::cl::opt<unsigned, false, OptLevelParser>
626OptLevel("O", llvm::cl::Prefix,
627 llvm::cl::desc("Optimization level"),
628 llvm::cl::init(0));
629
Reid Spencer5f016e22007-07-11 17:01:13 +0000630// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000631// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000632static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
633 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000634 // Allow the target to set the default the langauge options as it sees fit.
635 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000636
Chris Lattner6328cc32009-03-03 19:56:18 +0000637 // If there are any -mattr options, pass them to the target for validation and
638 // processing. The driver should have already consolidated all the
639 // target-feature settings and passed them to us in the -mattr list. The
640 // -mattr list is treated by the code generator as a diff against the -mcpu
641 // setting, but the driver should pass all enabled options as "+" settings.
642 // This means that the target should only look at + settings.
643 if (!TargetFeatures.empty()
644 // FIXME: The driver is not quite yet ready for this.
645 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000646 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000647 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
648 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000649 if (Opt != -1) {
650 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000651 fprintf(stderr, "invalid feature '%s'\n",
652 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000653 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000654 fprintf(stderr, "feature '%s': %s\n",
655 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000656 exit(1);
657 }
658 }
659
Ted Kremenekea644d82008-09-03 21:22:16 +0000660 if (Ansi) // "The -ansi option is equivalent to -std=c89."
661 LangStd = lang_c89;
662
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 if (LangStd == lang_unspecified) {
664 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000665 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000666 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000668 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 case langkind_c_cpp:
670 case langkind_objc:
671 case langkind_objc_cpp:
672 LangStd = lang_gnu99;
673 break;
674 case langkind_cxx:
675 case langkind_cxx_cpp:
676 case langkind_objcxx:
677 case langkind_objcxx_cpp:
678 LangStd = lang_gnucxx98;
679 break;
680 }
681 }
682
683 switch (LangStd) {
684 default: assert(0 && "Unknown language standard!");
685
686 // Fall through from newer standards to older ones. This isn't really right.
687 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000688 case lang_gnucxx0x:
689 case lang_cxx0x:
690 Options.CPlusPlus0x = 1;
691 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 case lang_gnucxx98:
693 case lang_cxx98:
694 Options.CPlusPlus = 1;
695 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000696 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 // FALL THROUGH.
698 case lang_gnu99:
699 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 Options.C99 = 1;
701 Options.HexFloats = 1;
702 // FALL THROUGH.
703 case lang_gnu89:
704 Options.BCPLComment = 1; // Only for C99/C++.
705 // FALL THROUGH.
706 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000707 Options.Digraphs = 1; // C94, C99, C++.
708 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 case lang_c89:
710 break;
711 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000712
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000713 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
714 Options.GNUMode = LangStd >= lang_gnu_START;
715
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000716 if (Options.CPlusPlus) {
717 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000718 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000719 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000720
Chris Lattnerd658b562008-04-05 06:32:51 +0000721 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
722 Options.ImplicitInt = 1;
723 else
724 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000725
726 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
727 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000728 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000729 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000730 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000731
Chris Lattner802db9b2008-12-05 00:10:44 +0000732 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
733 // even if they are normally on for the target. In GNU modes (e.g.
734 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000735 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000736 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000737 Options.Blocks = 0;
738
Daniel Dunbar85c49102009-03-15 00:11:28 +0000739 // Never accept '$' in identifiers when preprocessing assembler.
740 if (LK != langkind_asm_cpp)
741 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000742 if (PascalStrings.getPosition())
743 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000744 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000745 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000746 if (NoLaxVectorConversions.getPosition())
747 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000748 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000749 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000750 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000751
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000752 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000753 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000754 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000755 Options.Freestanding = Options.NoBuiltin = 1;
756
Chris Lattner810f6d52009-03-13 17:38:01 +0000757 if (EnableHeinousExtensions)
758 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000759
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000760 Options.MathErrno = MathErrno;
761
Douglas Gregor26dce442009-03-10 00:06:19 +0000762 Options.InstantiationDepth = TemplateDepth;
763
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000764 // Override the default runtime if the user requested it.
765 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000766 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000767 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000768 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000769
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000770 if (ObjCNonFragileABI)
771 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000772
773 if (EmitAllDecls)
774 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000775
776 if (OptSize)
777 Options.OptimizeSize = 1;
778
779 // -Os implies -O2
780 if (Options.OptimizeSize || OptLevel)
781 Options.Optimize = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000782}
783
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000784static llvm::cl::opt<bool>
785ObjCExclusiveGC("fobjc-gc-only",
786 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000787 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000788
789static llvm::cl::opt<bool>
790ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000791 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000792
793void InitializeGCMode(LangOptions &Options) {
794 if (ObjCExclusiveGC)
795 Options.setGCMode(LangOptions::GCOnly);
796 else if (ObjCEnableGC)
797 Options.setGCMode(LangOptions::HybridGC);
798}
799
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000800static llvm::cl::opt<std::string>
801SymbolVisibility("fvisibility",
802 llvm::cl::desc("Set the default visibility to the specific option"));
803
804void InitializeSymbolVisibility(LangOptions &Options) {
805 if (SymbolVisibility.empty())
806 return;
807 std::string Visibility = SymbolVisibility;
808 const char *vkind = Visibility.c_str();
809 if (!strcmp(vkind, "default"))
810 Options.setVisibilityMode(LangOptions::DefaultVisibility);
811 else if (!strcmp(vkind, "protected"))
812 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
813 else if (!strcmp(vkind, "hidden"))
814 Options.setVisibilityMode(LangOptions::HiddenVisibility);
815 else if (!strcmp(vkind, "internal"))
816 Options.setVisibilityMode(LangOptions::InternalVisibility);
817 else
818 fprintf(stderr,
819 "-fvisibility only valid for default|protected|hidden|internal\n");
820}
821
Mike Stump2add4732009-04-01 20:28:16 +0000822static llvm::cl::opt<bool>
823OverflowChecking("ftrapv",
Mike Stump035cf892009-04-02 18:15:54 +0000824 llvm::cl::desc("Trap on integer overflow"),
Mike Stump2add4732009-04-01 20:28:16 +0000825 llvm::cl::init(false));
826
827void InitializeOverflowChecking(LangOptions &Options) {
Mike Stump035cf892009-04-02 18:15:54 +0000828 Options.OverflowChecking = OverflowChecking;
Mike Stump2add4732009-04-01 20:28:16 +0000829}
Reid Spencer5f016e22007-07-11 17:01:13 +0000830//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000831// Target Triple Processing.
832//===----------------------------------------------------------------------===//
833
834static llvm::cl::opt<std::string>
835TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000836 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000837
Chris Lattner42e67372008-03-05 01:18:20 +0000838static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000839Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000840
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000841static llvm::cl::opt<std::string>
842MacOSVersionMin("mmacosx-version-min",
843 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
844
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000845// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
846// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000847
848// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000849static void HandleMacOSVersionMin(std::string &Triple) {
850 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
851 if (DarwinDashIdx == std::string::npos) {
852 fprintf(stderr,
853 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
854 exit(1);
855 }
856 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
857
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000858 // Remove the number.
859 Triple.resize(DarwinNumIdx);
860
861 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
862 bool MacOSVersionMinIsInvalid = false;
863 int VersionNum = 0;
864 if (MacOSVersionMin.size() < 4 ||
865 MacOSVersionMin.substr(0, 3) != "10." ||
866 !isdigit(MacOSVersionMin[3])) {
867 MacOSVersionMinIsInvalid = true;
868 } else {
869 const char *Start = MacOSVersionMin.c_str()+3;
870 char *End = 0;
871 VersionNum = (int)strtol(Start, &End, 10);
872
Chris Lattner079f2c462008-09-30 20:30:12 +0000873 // The version number must be in the range 0-9.
874 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
875
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000876 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
877 Triple += llvm::itostr(VersionNum+4);
878
Chris Lattner079f2c462008-09-30 20:30:12 +0000879 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
880 // Add the period piece (.7) to the end of the triple. This gives us
881 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000882 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000883 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
884 MacOSVersionMinIsInvalid = true;
885 }
886 }
887
888 if (MacOSVersionMinIsInvalid) {
889 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000890 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000891 MacOSVersionMin.c_str());
892 exit(1);
893 }
894}
895
896/// CreateTargetTriple - Process the various options that affect the target
897/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000898static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000899 // Initialize base triple. If a -triple option has been specified, use
900 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000901 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000902 if (Triple.empty())
903 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000904
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000905 // If -arch foo was specified, remove the architecture from the triple we have
906 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000907
908 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000909 if (!Arch.empty()) {
910 // Decompose the base triple into "arch" and suffix.
911 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000912
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000913 if (FirstDashIdx == std::string::npos) {
914 fprintf(stderr,
915 "Malformed target triple: \"%s\" ('-' could not be found).\n",
916 Triple.c_str());
917 exit(1);
918 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000919
920 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
921 if (Arch == "ppc")
922 Arch = "powerpc";
923 else if (Arch == "ppc64")
924 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000925
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000926 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
927 }
928
929 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
930 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000931 if (!MacOSVersionMin.empty())
932 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000933
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000934 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000935}
936
937//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000938// Preprocessor Initialization
939//===----------------------------------------------------------------------===//
940
941// FIXME: Preprocessor builtins to support.
942// -A... - Play with #assertions
943// -undef - Undefine all predefined macros
944
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000945// FIXME: -imacros
946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947static llvm::cl::list<std::string>
948D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
949 llvm::cl::desc("Predefine the specified macro"));
950static llvm::cl::list<std::string>
951U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
952 llvm::cl::desc("Undefine the specified macro"));
953
Chris Lattner64299f82008-01-10 01:53:41 +0000954static llvm::cl::list<std::string>
955ImplicitIncludes("include", llvm::cl::value_desc("file"),
956 llvm::cl::desc("Include file before parsing"));
957
Ted Kremenek748d5d62009-03-20 00:26:38 +0000958static llvm::cl::opt<std::string>
959ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
960 llvm::cl::desc("Include file before parsing"));
961
Reid Spencer5f016e22007-07-11 17:01:13 +0000962// Append a #define line to Buf for Macro. Macro should be of the form XXX,
963// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
964// "#define XXX Y z W". To get a #define with no value, use "XXX=".
965static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
966 const char *Command = "#define ") {
967 Buf.insert(Buf.end(), Command, Command+strlen(Command));
968 if (const char *Equal = strchr(Macro, '=')) {
969 // Turn the = into ' '.
970 Buf.insert(Buf.end(), Macro, Equal);
971 Buf.push_back(' ');
Chris Lattner0b514152009-04-07 06:02:44 +0000972
973 // Per GCC -D semantics, the macro ends at \n if it exists.
974 const char *End = strpbrk(Equal, "\n\r");
975 if (End == 0) End = Equal+strlen(Equal);
976
977 Buf.insert(Buf.end(), Equal+1, End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 } else {
979 // Push "macroname 1".
980 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
981 Buf.push_back(' ');
982 Buf.push_back('1');
983 }
984 Buf.push_back('\n');
985}
986
Chris Lattner64299f82008-01-10 01:53:41 +0000987/// AddImplicitInclude - Add an implicit #include of the specified file to the
988/// predefines buffer.
989static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
990 const char *Inc = "#include \"";
991 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
992 Buf.insert(Buf.end(), File.begin(), File.end());
993 Buf.push_back('"');
994 Buf.push_back('\n');
995}
996
Ted Kremenek748d5d62009-03-20 00:26:38 +0000997/// AddImplicitIncludePTH - Add an implicit #include using the original file
998/// used to generate a PTH cache.
999static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
1000 PTHManager *P = PP.getPTHManager();
1001 assert(P && "No PTHManager.");
1002 const char *OriginalFile = P->getOriginalSourceFile();
1003
1004 if (!OriginalFile) {
1005 assert(!ImplicitIncludePTH.empty());
1006 fprintf(stderr, "error: PTH file '%s' does not designate an original "
1007 "source header file for -include-pth\n",
1008 ImplicitIncludePTH.c_str());
1009 exit (1);
1010 }
1011
1012 AddImplicitInclude(Buf, OriginalFile);
1013}
Reid Spencer5f016e22007-07-11 17:01:13 +00001014
Chris Lattner53b0dab2007-10-09 22:10:18 +00001015/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +00001016/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001017///
Chris Lattner51574ea2008-04-19 23:25:44 +00001018static bool InitializePreprocessor(Preprocessor &PP,
1019 bool InitializeSourceMgr,
1020 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +00001021 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +00001022
Chris Lattner53b0dab2007-10-09 22:10:18 +00001023 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +00001024 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +00001025
1026 if (InitializeSourceMgr) {
1027 if (InFile != "-") {
1028 const FileEntry *File = FileMgr.getFile(InFile);
1029 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +00001030 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001031 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1032 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +00001033 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001034 }
1035 } else {
1036 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +00001037
1038 // If stdin was empty, SB is null. Cons up an empty memory
1039 // buffer now.
1040 if (!SB) {
1041 const char *EmptyStr = "";
1042 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1043 }
1044
1045 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +00001046 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001047 PP.getDiagnostics().Report(FullSourceLoc(),
1048 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +00001049 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001050 }
Chris Lattner53b0dab2007-10-09 22:10:18 +00001051 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 }
Sam Bishop1102d6b2008-04-14 14:41:57 +00001053
Chris Lattneraa391972008-04-19 23:09:31 +00001054 std::vector<char> PredefineBuffer;
1055
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +00001057 unsigned d = 0, D = D_macros.size();
1058 unsigned u = 0, U = U_macros.size();
1059 while (d < D || u < U) {
1060 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1061 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1062 else
1063 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1064 }
1065
Chris Lattner64299f82008-01-10 01:53:41 +00001066 // FIXME: Read any files specified by -imacros.
1067
Ted Kremenek748d5d62009-03-20 00:26:38 +00001068 // Add implicit #includes from -include and -include-pth.
1069 bool handledPTH = ImplicitIncludePTH.empty();
1070 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +00001071 if (!handledPTH &&
1072 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +00001073 AddImplicitIncludePTH(PredefineBuffer, PP);
1074 handledPTH = true;
1075 }
1076
Chris Lattner64299f82008-01-10 01:53:41 +00001077 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001078 }
1079 if (!handledPTH && !ImplicitIncludePTH.empty())
1080 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001081
Chris Lattneraa391972008-04-19 23:09:31 +00001082 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001083 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +00001084 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001085
1086 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +00001087 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001088}
1089
1090//===----------------------------------------------------------------------===//
1091// Preprocessor include path information.
1092//===----------------------------------------------------------------------===//
1093
1094// This tool exports a large number of command line options to control how the
1095// preprocessor searches for header files. At root, however, the Preprocessor
1096// object takes a very simple interface: a list of directories to search for
1097//
1098// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001099// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001100//
Reid Spencer5f016e22007-07-11 17:01:13 +00001101
1102static llvm::cl::opt<bool>
1103nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1104
1105// Various command line options. These four add directories to each chain.
1106static llvm::cl::list<std::string>
1107F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1108 llvm::cl::desc("Add directory to framework include search path"));
1109static llvm::cl::list<std::string>
1110I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1111 llvm::cl::desc("Add directory to include search path"));
1112static llvm::cl::list<std::string>
1113idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1114 llvm::cl::desc("Add directory to AFTER include search path"));
1115static llvm::cl::list<std::string>
1116iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1117 llvm::cl::desc("Add directory to QUOTE include search path"));
1118static llvm::cl::list<std::string>
1119isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1120 llvm::cl::desc("Add directory to SYSTEM include search path"));
1121
1122// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1123static llvm::cl::list<std::string>
1124iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1125 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1126static llvm::cl::list<std::string>
1127iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1128 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1129static llvm::cl::list<std::string>
1130iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1131 llvm::cl::Prefix,
1132 llvm::cl::desc("Set directory to include search path with prefix"));
1133
Chris Lattner0c946412007-08-26 17:47:35 +00001134static llvm::cl::opt<std::string>
1135isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1136 llvm::cl::desc("Set the system root directory (usually /)"));
1137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140/// InitializeIncludePaths - Process the -I options and set them in the
1141/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001142void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1143 FileManager &FM, const LangOptions &Lang) {
1144 InitHeaderSearch Init(Headers, Verbose, isysroot);
1145
Ted Kremenekf3721112008-05-31 00:27:00 +00001146 // Handle -I... and -F... options, walking the lists in parallel.
1147 unsigned Iidx = 0, Fidx = 0;
1148 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1149 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001150 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001151 ++Iidx;
1152 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001153 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001154 ++Fidx;
1155 }
1156 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001157
Ted Kremenekf3721112008-05-31 00:27:00 +00001158 // Consume what's left from whatever list was longer.
1159 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001160 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001161 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001162 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001163
1164 // Handle -idirafter... options.
1165 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001166 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1167 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001168
1169 // Handle -iquote... options.
1170 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001171 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001172
1173 // Handle -isystem... options.
1174 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001175 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001176
1177 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1178 // parallel, processing the values in order of occurance to get the right
1179 // prefixes.
1180 {
1181 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1182 unsigned iprefix_idx = 0;
1183 unsigned iwithprefix_idx = 0;
1184 unsigned iwithprefixbefore_idx = 0;
1185 bool iprefix_done = iprefix_vals.empty();
1186 bool iwithprefix_done = iwithprefix_vals.empty();
1187 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1188 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1189 if (!iprefix_done &&
1190 (iwithprefix_done ||
1191 iprefix_vals.getPosition(iprefix_idx) <
1192 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1193 (iwithprefixbefore_done ||
1194 iprefix_vals.getPosition(iprefix_idx) <
1195 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1196 Prefix = iprefix_vals[iprefix_idx];
1197 ++iprefix_idx;
1198 iprefix_done = iprefix_idx == iprefix_vals.size();
1199 } else if (!iwithprefix_done &&
1200 (iwithprefixbefore_done ||
1201 iwithprefix_vals.getPosition(iwithprefix_idx) <
1202 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001203 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1204 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 ++iwithprefix_idx;
1206 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1207 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001208 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1209 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 ++iwithprefixbefore_idx;
1211 iwithprefixbefore_done =
1212 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1213 }
1214 }
1215 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001216
Nico Weber0fca0222008-08-22 09:25:22 +00001217 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001218
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001219 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001220 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001221 llvm::sys::Path::GetMainExecutable(Argv0,
1222 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001223 if (!MainExecutablePath.isEmpty()) {
1224 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1225 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001226
1227 // Get foo/lib/clang/1.0/include
1228 //
1229 // FIXME: Don't embed version here.
1230 MainExecutablePath.appendComponent("lib");
1231 MainExecutablePath.appendComponent("clang");
1232 MainExecutablePath.appendComponent("1.0");
1233 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001234
1235 // We pass true to ignore sysroot so that we *always* look for clang headers
1236 // relative to our executable, never relative to -isysroot.
1237 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1238 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001239 }
1240
Nico Weber0fca0222008-08-22 09:25:22 +00001241 if (!nostdinc)
1242 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001243
1244 // Now that we have collected all of the include paths, merge them all
1245 // together and tell the preprocessor about them.
1246
Nico Weber0fca0222008-08-22 09:25:22 +00001247 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001248}
1249
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001250//===----------------------------------------------------------------------===//
1251// Driver PreprocessorFactory - For lazily generating preprocessors ...
1252//===----------------------------------------------------------------------===//
1253
1254namespace {
1255class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001256 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001257 Diagnostic &Diags;
1258 const LangOptions &LangInfo;
1259 TargetInfo &Target;
1260 SourceManager &SourceMgr;
1261 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001262 bool InitializeSourceMgr;
1263
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001264public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001265 DriverPreprocessorFactory(const std::string &infile,
1266 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001267 TargetInfo &target, SourceManager &SM,
1268 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001269 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1270 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1271
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001272
1273 virtual ~DriverPreprocessorFactory() {}
1274
1275 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001276 llvm::OwningPtr<PTHManager> PTHMgr;
1277
Ted Kremenek748d5d62009-03-20 00:26:38 +00001278 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1279 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1280 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001281 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001282 }
1283
Ted Kremenek72b1b152009-01-15 18:47:46 +00001284 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001285 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1286 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001287 PTHMgr.reset(PTHManager::Create(x, &Diags,
1288 TokenCache.empty() ? Diagnostic::Error
1289 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001290 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001291
Ted Kremenek22f0d092009-03-22 06:42:39 +00001292 if (Diags.hasErrorOccurred())
1293 exit(1);
1294
Ted Kremenek72b1b152009-01-15 18:47:46 +00001295 // Create the Preprocessor.
1296 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1297 SourceMgr, HeaderInfo,
1298 PTHMgr.get()));
1299
1300 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1301 // That argument is used as the IdentifierInfoLookup argument to
1302 // IdentifierTable's ctor.
1303 if (PTHMgr) {
1304 PTHMgr->setPreprocessor(PP.get());
1305 PP->setPTHManager(PTHMgr.take());
1306 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001307
Chris Lattner51574ea2008-04-19 23:25:44 +00001308 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001309 return NULL;
1310 }
1311
Daniel Dunbar750c3582008-10-24 22:12:41 +00001312 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001313 if (ProgAction != PrintPreprocessedInput) {
1314 std::string ErrStr;
1315 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1316 if (!DFG && !ErrStr.empty()) {
1317 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001318 return NULL;
1319 }
1320 }
1321
Ted Kremenek339b9c22008-04-17 22:31:54 +00001322 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001323 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001324 }
1325};
1326}
Reid Spencer5f016e22007-07-11 17:01:13 +00001327
Reid Spencer5f016e22007-07-11 17:01:13 +00001328//===----------------------------------------------------------------------===//
1329// Basic Parser driver
1330//===----------------------------------------------------------------------===//
1331
Chris Lattner51574ea2008-04-19 23:25:44 +00001332static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001334 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001335
1336 // Parsing the specified input file.
1337 P.ParseTranslationUnit();
1338 delete PA;
1339}
1340
1341//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001342// Code generation options
1343//===----------------------------------------------------------------------===//
1344
1345static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001346GenerateDebugInfo("g",
1347 llvm::cl::desc("Generate source level debug information"));
1348
Daniel Dunbara034ba82009-02-17 19:47:34 +00001349static llvm::cl::opt<std::string>
1350TargetCPU("mcpu",
1351 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1352
Chris Lattner7afae712009-03-16 18:41:18 +00001353static void InitializeCompileOptions(CompileOptions &Opts,
1354 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001355 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001356 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001357 if (OptSize) {
1358 // -Os implies -O2
1359 // FIXME: Diagnose conflicting options.
1360 Opts.OptimizationLevel = 2;
1361 } else {
1362 Opts.OptimizationLevel = OptLevel;
1363 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001364
1365 // FIXME: There are llvm-gcc options to control these selectively.
1366 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1367 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001368 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001369
1370#ifdef NDEBUG
1371 Opts.VerifyModule = 0;
1372#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001373
1374 Opts.CPU = TargetCPU;
1375 Opts.Features.insert(Opts.Features.end(),
1376 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001377
Chris Lattnerbd360642009-03-26 05:00:52 +00001378 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1379
Chris Lattner44502662009-02-18 01:23:44 +00001380 // Handle -ftime-report.
1381 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001382}
1383
1384//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001385// Fix-It Options
1386//===----------------------------------------------------------------------===//
1387static llvm::cl::list<ParsedSourceLocation>
1388FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1389 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1390
1391//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001392// Main driver
1393//===----------------------------------------------------------------------===//
1394
Ted Kremenekdb094a22007-12-05 18:27:04 +00001395/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001396/// action. These consumers can operate on both ASTs that are freshly
1397/// parsed from source files as well as those deserialized from Bitcode.
1398/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001399static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001400 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001401 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001402 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001403 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001404 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001405 default:
1406 return NULL;
1407
1408 case ASTPrint:
1409 return CreateASTPrinter();
1410
1411 case ASTDump:
1412 return CreateASTDumper();
1413
1414 case ASTView:
1415 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001416
Chris Lattner8a5c8092009-02-18 01:20:05 +00001417 case PrintDeclContext:
1418 return CreateDeclContextPrinter();
1419
1420 case EmitHTML:
1421 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001422
Chris Lattner8a5c8092009-02-18 01:20:05 +00001423 case InheritanceView:
1424 return CreateInheritanceViewer(InheritanceViewCls);
1425
1426 case TestSerialization:
1427 return CreateSerializationTest(Diag, FileMgr);
1428
1429 case EmitAssembly:
1430 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001431 case EmitBC:
1432 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001433 BackendAction Act;
1434 if (ProgAction == EmitAssembly)
1435 Act = Backend_EmitAssembly;
1436 else if (ProgAction == EmitLLVM)
1437 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001438 else if (ProgAction == EmitLLVMOnly)
1439 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001440 else
1441 Act = Backend_EmitBC;
1442
1443 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001444 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001445 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001446 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001447 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001448
Chris Lattner8a5c8092009-02-18 01:20:05 +00001449 case SerializeAST:
1450 // FIXME: Allow user to tailor where the file is written.
1451 return CreateASTSerializer(InFile, OutputFile, Diag);
1452
1453 case RewriteObjC:
1454 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001455
Chris Lattner8a5c8092009-02-18 01:20:05 +00001456 case RewriteBlocks:
1457 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1458
1459 case RunAnalysis:
1460 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001461 }
1462}
1463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464/// ProcessInputFile - Process a single input file with the specified state.
1465///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001466static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001467 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001468 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001469 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001470 FixItRewriter *FixItRewrite = 0;
1471
Ted Kremenek85888962008-10-21 00:54:44 +00001472 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001474 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1475 PP.getFileManager(), PP.getLangOptions(),
1476 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001477
1478 if (!Consumer) {
1479 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001480 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001481 return;
1482 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001483
Ted Kremenekdb094a22007-12-05 18:27:04 +00001484 break;
1485
Chris Lattnerc106c102008-10-12 05:03:36 +00001486 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001487 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001488 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001489 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001490 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001491 RawLex.SetKeepWhitespaceMode(true);
1492
1493 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001494 RawLex.LexFromRawLexer(RawTok);
1495 while (RawTok.isNot(tok::eof)) {
1496 PP.DumpToken(RawTok, true);
1497 fprintf(stderr, "\n");
1498 RawLex.LexFromRawLexer(RawTok);
1499 }
1500 ClearSourceMgr = true;
1501 break;
1502 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001504 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001505 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001506 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001507 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 do {
1509 PP.Lex(Tok);
1510 PP.DumpToken(Tok, true);
1511 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001512 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001513 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 break;
1515 }
1516 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001517 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001518 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001520 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 do {
1522 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001523 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001524 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 break;
1526 }
Ted Kremenek85888962008-10-21 00:54:44 +00001527
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001528 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001529 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001530 CacheTokens(PP, OutputFile);
1531 ClearSourceMgr = true;
1532 break;
1533 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001534
Chris Lattner47099742009-02-18 01:51:21 +00001535 case PrintPreprocessedInput: { // -E mode.
1536 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001537 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001538 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 break;
Chris Lattner47099742009-02-18 01:51:21 +00001540 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001541
Chris Lattner47099742009-02-18 01:51:21 +00001542 case ParseNoop: { // -parse-noop
1543 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001544 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001545 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 break;
Chris Lattner47099742009-02-18 01:51:21 +00001547 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001548
Chris Lattner47099742009-02-18 01:51:21 +00001549 case ParsePrintCallbacks: {
1550 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001551 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001552 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 break;
Chris Lattner47099742009-02-18 01:51:21 +00001554 }
1555
1556 case ParseSyntaxOnly: { // -fsyntax-only
1557 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001558 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001559 break;
Chris Lattner47099742009-02-18 01:51:21 +00001560 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001561
1562 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001563 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001564 ClearSourceMgr = true;
1565 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001566
Chris Lattner47099742009-02-18 01:51:21 +00001567 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001568 DoRewriteTest(PP, InFile, OutputFile);
1569 ClearSourceMgr = true;
1570 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001571 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001572
1573 case FixIt:
1574 llvm::TimeRegion Timer(ClangFrontendTimer);
1575 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001576 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor558cb562009-04-02 01:08:08 +00001577 PP.getSourceManager());
Douglas Gregor558cb562009-04-02 01:08:08 +00001578 break;
Chris Lattner47099742009-02-18 01:51:21 +00001579 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001580
1581 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001582 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001583
Douglas Gregor26df2f02009-04-02 19:05:20 +00001584 if (FixItAtLocations.size() > 0) {
1585 // Even without the "-fixit" flag, with may have some specific
1586 // locations where the user has requested fixes. Process those
1587 // locations now.
1588 if (!FixItRewrite)
1589 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1590 PP.getSourceManager());
1591
1592 bool AddedFixitLocation = false;
1593 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1594 Idx != Last; ++Idx) {
1595 RequestedSourceLocation Requested;
1596 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1597 Requested)) {
1598 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1599 FixItAtLocations[Idx].FileName.c_str());
1600 } else {
1601 FixItRewrite->addFixItLocation(Requested);
1602 AddedFixitLocation = true;
1603 }
1604 }
1605
1606 if (!AddedFixitLocation) {
1607 // All of the fix-it locations were bad. Don't fix anything.
1608 delete FixItRewrite;
1609 FixItRewrite = 0;
1610 }
1611 }
1612
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001613 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1614 PP.getSourceManager(),
1615 PP.getTargetInfo(),
1616 PP.getIdentifierTable(),
1617 PP.getSelectorTable(),
1618 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001619
1620
Chris Lattner3599dbe2009-03-28 04:13:34 +00001621 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001622
Douglas Gregor558cb562009-04-02 01:08:08 +00001623 if (FixItRewrite)
1624 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1625
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001626 // If in -disable-free mode, don't deallocate these when they go out of
1627 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001628 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001629 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001630 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001631
1632 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001633 if (CheckDiagnostics(PP))
1634 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001635
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001637 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 PP.PrintStats();
1639 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001640 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001641 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 fprintf(stderr, "\n");
1643 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001644
1645 // For a multi-file compilation, some things are ok with nuking the source
1646 // manager tables, other require stable fileid/macroid's across multiple
1647 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001648 if (ClearSourceMgr)
1649 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001650
1651 if (DisableFree)
1652 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001653}
1654
Ted Kremenek20e97482007-12-12 23:41:08 +00001655static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1656 FileManager& FileMgr) {
1657
1658 if (VerifyDiagnostics) {
1659 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1660 exit (1);
1661 }
1662
1663 llvm::sys::Path Filename(InFile);
1664
1665 if (!Filename.isValid()) {
1666 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1667 exit (1);
1668 }
1669
Chris Lattner557c5b12009-03-28 04:27:18 +00001670 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001671
1672 // Create the memory buffer that contains the contents of the file.
1673 llvm::OwningPtr<llvm::MemoryBuffer>
1674 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1675
1676 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001677 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001678
Chris Lattner557c5b12009-03-28 04:27:18 +00001679 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001680 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1681 InFile.c_str());
1682 exit (1);
1683 }
1684
Ted Kremenek63ea8632007-12-19 19:27:38 +00001685 // Observe that we use the source file name stored in the deserialized
1686 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001687 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001688 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001689 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001690
Ted Kremenek20e97482007-12-12 23:41:08 +00001691 if (!Consumer) {
1692 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1693 exit (1);
1694 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001695
Chris Lattner557c5b12009-03-28 04:27:18 +00001696 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001697
Chris Lattnere66b65c2008-02-06 01:42:25 +00001698 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001699 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1700 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1701 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001702 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001703}
1704
1705
Reid Spencer5f016e22007-07-11 17:01:13 +00001706static llvm::cl::list<std::string>
1707InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1708
Ted Kremenek20e97482007-12-12 23:41:08 +00001709static bool isSerializedFile(const std::string& InFile) {
1710 if (InFile.size() < 4)
1711 return false;
1712
1713 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001714 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001715}
1716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717
1718int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001720 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001721 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001722 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001723
Chris Lattner47099742009-02-18 01:51:21 +00001724 if (TimeReport)
1725 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1726
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // If no input was specified, read from stdin.
1728 if (InputFilenames.empty())
1729 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001730
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 // Create a file manager object to provide access to and cache the filesystem.
1732 FileManager FileMgr;
1733
Ted Kremenek31e703b2007-12-11 23:28:38 +00001734 // Create the diagnostic client for reporting errors or for
1735 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001736 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001737
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001738 if (!VerifyDiagnostics) {
1739 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001740 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1741 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001742 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001743 !NoShowLocation,
1744 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001745 } else {
1746 // When checking diagnostics, just buffer them up.
1747 TextDiagClient = new TextDiagnosticBuffer();
1748
1749 if (InputFilenames.size() != 1) {
1750 fprintf(stderr,
1751 "-verify only works on single input files for now.\n");
1752 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 }
1754 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001755
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001757 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1758 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001759 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001760 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001761
Chris Lattner4f037832007-12-05 23:24:17 +00001762 // -I- is a deprecated GCC feature, scan for it and reject it.
1763 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1764 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001765 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001766 I_dirs.erase(I_dirs.begin()+i);
1767 --i;
1768 }
1769 }
Chris Lattner11215192008-03-14 06:12:05 +00001770
1771 // Get information about the target being compiled for.
1772 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001773 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1774
Chris Lattner11215192008-03-14 06:12:05 +00001775 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001776 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1777 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001778 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001779 }
Chris Lattner4f037832007-12-05 23:24:17 +00001780
Daniel Dunbard4270232009-01-20 23:17:32 +00001781 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001782 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001783
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001784 llvm::OwningPtr<SourceManager> SourceMgr;
1785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001787 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001788
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001789 if (isSerializedFile(InFile)) {
1790 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001791 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001792 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001793 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001794
1795 /// Create a SourceManager object. This tracks and owns all the file
1796 /// buffers allocated to a translation unit.
1797 if (!SourceMgr)
1798 SourceMgr.reset(new SourceManager());
1799 else
1800 SourceMgr->clearIDTables();
1801
1802 // Initialize language options, inferring file types from input filenames.
1803 LangOptions LangInfo;
1804 InitializeBaseLanguage();
1805 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001806 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001807 InitializeGCMode(LangInfo);
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +00001808 InitializeSymbolVisibility(LangInfo);
Mike Stump2add4732009-04-01 20:28:16 +00001809 InitializeOverflowChecking(LangInfo);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001810 InitializeLanguageStandard(LangInfo, LK, Target.get());
1811
1812 // Process the -I options and set them in the HeaderInfo.
1813 HeaderSearch HeaderInfo(FileMgr);
1814
1815 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1816
1817 // Set up the preprocessor with these options.
1818 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1819 *SourceMgr.get(), HeaderInfo);
1820
1821 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1822
1823 if (!PP)
1824 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001825
Chris Lattnerf63aea32009-03-04 21:40:56 +00001826 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1827 // always reset to using TextDiagClient.
1828 llvm::OwningPtr<DiagnosticClient> TmpClient;
1829
1830 if (!HTMLDiag.empty()) {
1831 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1832 &PPFactory));
1833 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001834 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001835 else
1836 Diags.setClient(TextDiagClient);
1837
1838 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001839 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001840
1841 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 }
Chris Lattner11215192008-03-14 06:12:05 +00001843
Mike Stump007f2a92009-01-28 02:43:35 +00001844 if (Verbose)
1845 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1846 " hosted on " LLVM_HOSTTRIPLE "\n");
1847
Ted Kremenek7a08e282008-08-07 18:13:12 +00001848 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1850 (NumDiagnostics == 1 ? "" : "s"));
1851
1852 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 FileMgr.PrintStats();
1854 fprintf(stderr, "\n");
1855 }
1856
Daniel Dunbar276373d2008-10-27 22:10:13 +00001857 // If verifying diagnostics and we reached here, all is well.
1858 if (VerifyDiagnostics)
1859 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001860
1861 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001862
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001863 // Managed static deconstruction. Useful for making things like
1864 // -time-passes usable.
1865 llvm::llvm_shutdown();
1866
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001867 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001868}