blob: 5a713e4612cdc3f32edcd92ba25494af232d33bb [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
Reid Spencer5f016e22007-07-11 17:01:13 +0000604// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000605// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000606static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
607 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000608 // Allow the target to set the default the langauge options as it sees fit.
609 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000610
Chris Lattner6328cc32009-03-03 19:56:18 +0000611 // If there are any -mattr options, pass them to the target for validation and
612 // processing. The driver should have already consolidated all the
613 // target-feature settings and passed them to us in the -mattr list. The
614 // -mattr list is treated by the code generator as a diff against the -mcpu
615 // setting, but the driver should pass all enabled options as "+" settings.
616 // This means that the target should only look at + settings.
617 if (!TargetFeatures.empty()
618 // FIXME: The driver is not quite yet ready for this.
619 && 0) {
Chris Lattner16167a62009-03-02 22:11:07 +0000620 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000621 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
622 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000623 if (Opt != -1) {
624 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000625 fprintf(stderr, "invalid feature '%s'\n",
626 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000627 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000628 fprintf(stderr, "feature '%s': %s\n",
629 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000630 exit(1);
631 }
632 }
633
Ted Kremenekea644d82008-09-03 21:22:16 +0000634 if (Ansi) // "The -ansi option is equivalent to -std=c89."
635 LangStd = lang_c89;
636
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 if (LangStd == lang_unspecified) {
638 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000639 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000640 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000642 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 case langkind_c_cpp:
644 case langkind_objc:
645 case langkind_objc_cpp:
646 LangStd = lang_gnu99;
647 break;
648 case langkind_cxx:
649 case langkind_cxx_cpp:
650 case langkind_objcxx:
651 case langkind_objcxx_cpp:
652 LangStd = lang_gnucxx98;
653 break;
654 }
655 }
656
657 switch (LangStd) {
658 default: assert(0 && "Unknown language standard!");
659
660 // Fall through from newer standards to older ones. This isn't really right.
661 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000662 case lang_gnucxx0x:
663 case lang_cxx0x:
664 Options.CPlusPlus0x = 1;
665 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 case lang_gnucxx98:
667 case lang_cxx98:
668 Options.CPlusPlus = 1;
669 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000670 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 // FALL THROUGH.
672 case lang_gnu99:
673 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 Options.C99 = 1;
675 Options.HexFloats = 1;
676 // FALL THROUGH.
677 case lang_gnu89:
678 Options.BCPLComment = 1; // Only for C99/C++.
679 // FALL THROUGH.
680 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000681 Options.Digraphs = 1; // C94, C99, C++.
682 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 case lang_c89:
684 break;
685 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000686
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000687 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
688 Options.GNUMode = LangStd >= lang_gnu_START;
689
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000690 if (Options.CPlusPlus) {
691 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000692 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000693 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000694
Chris Lattnerd658b562008-04-05 06:32:51 +0000695 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
696 Options.ImplicitInt = 1;
697 else
698 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000699
700 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
701 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000702 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000703 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000704 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000705
Chris Lattner802db9b2008-12-05 00:10:44 +0000706 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
707 // even if they are normally on for the target. In GNU modes (e.g.
708 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000709 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000710 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000711 Options.Blocks = 0;
712
Daniel Dunbar85c49102009-03-15 00:11:28 +0000713 // Never accept '$' in identifiers when preprocessing assembler.
714 if (LK != langkind_asm_cpp)
715 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000716 if (PascalStrings.getPosition())
717 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000718 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000719 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000720 if (NoLaxVectorConversions.getPosition())
721 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000722 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000723 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000724 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000725
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000726 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000727 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000728 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000729 Options.Freestanding = Options.NoBuiltin = 1;
730
Chris Lattner810f6d52009-03-13 17:38:01 +0000731 if (EnableHeinousExtensions)
732 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000733
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000734 Options.MathErrno = MathErrno;
735
Douglas Gregor26dce442009-03-10 00:06:19 +0000736 Options.InstantiationDepth = TemplateDepth;
737
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000738 // Override the default runtime if the user requested it.
739 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000740 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000741 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000742 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000743
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000744 if (ObjCNonFragileABI)
745 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000746
747 if (EmitAllDecls)
748 Options.EmitAllDecls = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000749}
750
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000751static llvm::cl::opt<bool>
752ObjCExclusiveGC("fobjc-gc-only",
753 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000754 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000755
756static llvm::cl::opt<bool>
757ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000758 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000759
760void InitializeGCMode(LangOptions &Options) {
761 if (ObjCExclusiveGC)
762 Options.setGCMode(LangOptions::GCOnly);
763 else if (ObjCEnableGC)
764 Options.setGCMode(LangOptions::HybridGC);
765}
766
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000767static llvm::cl::opt<std::string>
768SymbolVisibility("fvisibility",
769 llvm::cl::desc("Set the default visibility to the specific option"));
770
771void InitializeSymbolVisibility(LangOptions &Options) {
772 if (SymbolVisibility.empty())
773 return;
774 std::string Visibility = SymbolVisibility;
775 const char *vkind = Visibility.c_str();
776 if (!strcmp(vkind, "default"))
777 Options.setVisibilityMode(LangOptions::DefaultVisibility);
778 else if (!strcmp(vkind, "protected"))
779 Options.setVisibilityMode(LangOptions::ProtectedVisibility);
780 else if (!strcmp(vkind, "hidden"))
781 Options.setVisibilityMode(LangOptions::HiddenVisibility);
782 else if (!strcmp(vkind, "internal"))
783 Options.setVisibilityMode(LangOptions::InternalVisibility);
784 else
785 fprintf(stderr,
786 "-fvisibility only valid for default|protected|hidden|internal\n");
787}
788
Mike Stump2add4732009-04-01 20:28:16 +0000789static llvm::cl::opt<bool>
790OverflowChecking("ftrapv",
Mike Stump035cf892009-04-02 18:15:54 +0000791 llvm::cl::desc("Trap on integer overflow"),
Mike Stump2add4732009-04-01 20:28:16 +0000792 llvm::cl::init(false));
793
794void InitializeOverflowChecking(LangOptions &Options) {
Mike Stump035cf892009-04-02 18:15:54 +0000795 Options.OverflowChecking = OverflowChecking;
Mike Stump2add4732009-04-01 20:28:16 +0000796}
Reid Spencer5f016e22007-07-11 17:01:13 +0000797//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000798// Target Triple Processing.
799//===----------------------------------------------------------------------===//
800
801static llvm::cl::opt<std::string>
802TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000803 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000804
Chris Lattner42e67372008-03-05 01:18:20 +0000805static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000806Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000807
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000808static llvm::cl::opt<std::string>
809MacOSVersionMin("mmacosx-version-min",
810 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
811
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000812// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
813// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000814
815// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000816static void HandleMacOSVersionMin(std::string &Triple) {
817 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
818 if (DarwinDashIdx == std::string::npos) {
819 fprintf(stderr,
820 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
821 exit(1);
822 }
823 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
824
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000825 // Remove the number.
826 Triple.resize(DarwinNumIdx);
827
828 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
829 bool MacOSVersionMinIsInvalid = false;
830 int VersionNum = 0;
831 if (MacOSVersionMin.size() < 4 ||
832 MacOSVersionMin.substr(0, 3) != "10." ||
833 !isdigit(MacOSVersionMin[3])) {
834 MacOSVersionMinIsInvalid = true;
835 } else {
836 const char *Start = MacOSVersionMin.c_str()+3;
837 char *End = 0;
838 VersionNum = (int)strtol(Start, &End, 10);
839
Chris Lattner079f2c462008-09-30 20:30:12 +0000840 // The version number must be in the range 0-9.
841 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
842
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000843 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
844 Triple += llvm::itostr(VersionNum+4);
845
Chris Lattner079f2c462008-09-30 20:30:12 +0000846 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
847 // Add the period piece (.7) to the end of the triple. This gives us
848 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000849 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000850 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
851 MacOSVersionMinIsInvalid = true;
852 }
853 }
854
855 if (MacOSVersionMinIsInvalid) {
856 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000857 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000858 MacOSVersionMin.c_str());
859 exit(1);
860 }
861}
862
863/// CreateTargetTriple - Process the various options that affect the target
864/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000865static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000866 // Initialize base triple. If a -triple option has been specified, use
867 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000868 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000869 if (Triple.empty())
870 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000871
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000872 // If -arch foo was specified, remove the architecture from the triple we have
873 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000874
875 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000876 if (!Arch.empty()) {
877 // Decompose the base triple into "arch" and suffix.
878 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000879
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000880 if (FirstDashIdx == std::string::npos) {
881 fprintf(stderr,
882 "Malformed target triple: \"%s\" ('-' could not be found).\n",
883 Triple.c_str());
884 exit(1);
885 }
Chris Lattner37e217c2009-03-24 16:18:41 +0000886
887 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
888 if (Arch == "ppc")
889 Arch = "powerpc";
890 else if (Arch == "ppc64")
891 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +0000892
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000893 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
894 }
895
896 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
897 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000898 if (!MacOSVersionMin.empty())
899 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000900
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000901 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000902}
903
904//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000905// Preprocessor Initialization
906//===----------------------------------------------------------------------===//
907
908// FIXME: Preprocessor builtins to support.
909// -A... - Play with #assertions
910// -undef - Undefine all predefined macros
911
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000912// FIXME: -imacros
913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914static llvm::cl::list<std::string>
915D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
916 llvm::cl::desc("Predefine the specified macro"));
917static llvm::cl::list<std::string>
918U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
919 llvm::cl::desc("Undefine the specified macro"));
920
Chris Lattner64299f82008-01-10 01:53:41 +0000921static llvm::cl::list<std::string>
922ImplicitIncludes("include", llvm::cl::value_desc("file"),
923 llvm::cl::desc("Include file before parsing"));
924
Ted Kremenek748d5d62009-03-20 00:26:38 +0000925static llvm::cl::opt<std::string>
926ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
927 llvm::cl::desc("Include file before parsing"));
928
Reid Spencer5f016e22007-07-11 17:01:13 +0000929// Append a #define line to Buf for Macro. Macro should be of the form XXX,
930// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
931// "#define XXX Y z W". To get a #define with no value, use "XXX=".
932static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
933 const char *Command = "#define ") {
934 Buf.insert(Buf.end(), Command, Command+strlen(Command));
935 if (const char *Equal = strchr(Macro, '=')) {
936 // Turn the = into ' '.
937 Buf.insert(Buf.end(), Macro, Equal);
938 Buf.push_back(' ');
939 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
940 } else {
941 // Push "macroname 1".
942 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
943 Buf.push_back(' ');
944 Buf.push_back('1');
945 }
946 Buf.push_back('\n');
947}
948
Chris Lattner64299f82008-01-10 01:53:41 +0000949/// AddImplicitInclude - Add an implicit #include of the specified file to the
950/// predefines buffer.
951static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
952 const char *Inc = "#include \"";
953 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
954 Buf.insert(Buf.end(), File.begin(), File.end());
955 Buf.push_back('"');
956 Buf.push_back('\n');
957}
958
Ted Kremenek748d5d62009-03-20 00:26:38 +0000959/// AddImplicitIncludePTH - Add an implicit #include using the original file
960/// used to generate a PTH cache.
961static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor & PP) {
962 PTHManager *P = PP.getPTHManager();
963 assert(P && "No PTHManager.");
964 const char *OriginalFile = P->getOriginalSourceFile();
965
966 if (!OriginalFile) {
967 assert(!ImplicitIncludePTH.empty());
968 fprintf(stderr, "error: PTH file '%s' does not designate an original "
969 "source header file for -include-pth\n",
970 ImplicitIncludePTH.c_str());
971 exit (1);
972 }
973
974 AddImplicitInclude(Buf, OriginalFile);
975}
Reid Spencer5f016e22007-07-11 17:01:13 +0000976
Chris Lattner53b0dab2007-10-09 22:10:18 +0000977/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000978/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000979///
Chris Lattner51574ea2008-04-19 23:25:44 +0000980static bool InitializePreprocessor(Preprocessor &PP,
981 bool InitializeSourceMgr,
982 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000983 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000984
Chris Lattner53b0dab2007-10-09 22:10:18 +0000985 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000986 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000987
988 if (InitializeSourceMgr) {
989 if (InFile != "-") {
990 const FileEntry *File = FileMgr.getFile(InFile);
991 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000992 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +0000993 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
994 << InFile.c_str();
Chris Lattner51574ea2008-04-19 23:25:44 +0000995 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000996 }
997 } else {
998 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Daniel Dunbar56743882009-03-21 17:56:30 +0000999
1000 // If stdin was empty, SB is null. Cons up an empty memory
1001 // buffer now.
1002 if (!SB) {
1003 const char *EmptyStr = "";
1004 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1005 }
1006
1007 SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +00001008 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001009 PP.getDiagnostics().Report(FullSourceLoc(),
1010 diag::err_fe_error_reading_stdin);
Chris Lattner51574ea2008-04-19 23:25:44 +00001011 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001012 }
Chris Lattner53b0dab2007-10-09 22:10:18 +00001013 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 }
Sam Bishop1102d6b2008-04-14 14:41:57 +00001015
Chris Lattneraa391972008-04-19 23:09:31 +00001016 std::vector<char> PredefineBuffer;
1017
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +00001019 unsigned d = 0, D = D_macros.size();
1020 unsigned u = 0, U = U_macros.size();
1021 while (d < D || u < U) {
1022 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1023 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
1024 else
1025 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
1026 }
1027
Chris Lattner64299f82008-01-10 01:53:41 +00001028 // FIXME: Read any files specified by -imacros.
1029
Ted Kremenek748d5d62009-03-20 00:26:38 +00001030 // Add implicit #includes from -include and -include-pth.
1031 bool handledPTH = ImplicitIncludePTH.empty();
1032 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i) {
Ted Kremenekc53b60a2009-03-20 00:40:03 +00001033 if (!handledPTH &&
1034 ImplicitIncludePTH.getPosition() < ImplicitIncludes.getPosition(i)) {
Ted Kremenek748d5d62009-03-20 00:26:38 +00001035 AddImplicitIncludePTH(PredefineBuffer, PP);
1036 handledPTH = true;
1037 }
1038
Chris Lattner64299f82008-01-10 01:53:41 +00001039 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001040 }
1041 if (!handledPTH && !ImplicitIncludePTH.empty())
1042 AddImplicitIncludePTH(PredefineBuffer, PP);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001043
Chris Lattneraa391972008-04-19 23:09:31 +00001044 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +00001045 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +00001046 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +00001047
1048 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +00001049 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001050}
1051
1052//===----------------------------------------------------------------------===//
1053// Preprocessor include path information.
1054//===----------------------------------------------------------------------===//
1055
1056// This tool exports a large number of command line options to control how the
1057// preprocessor searches for header files. At root, however, the Preprocessor
1058// object takes a very simple interface: a list of directories to search for
1059//
1060// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001061// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001062//
Reid Spencer5f016e22007-07-11 17:01:13 +00001063
1064static llvm::cl::opt<bool>
1065nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1066
1067// Various command line options. These four add directories to each chain.
1068static llvm::cl::list<std::string>
1069F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1070 llvm::cl::desc("Add directory to framework include search path"));
1071static llvm::cl::list<std::string>
1072I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1073 llvm::cl::desc("Add directory to include search path"));
1074static llvm::cl::list<std::string>
1075idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1076 llvm::cl::desc("Add directory to AFTER include search path"));
1077static llvm::cl::list<std::string>
1078iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1079 llvm::cl::desc("Add directory to QUOTE include search path"));
1080static llvm::cl::list<std::string>
1081isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1082 llvm::cl::desc("Add directory to SYSTEM include search path"));
1083
1084// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1085static llvm::cl::list<std::string>
1086iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1087 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1088static llvm::cl::list<std::string>
1089iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1090 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1091static llvm::cl::list<std::string>
1092iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1093 llvm::cl::Prefix,
1094 llvm::cl::desc("Set directory to include search path with prefix"));
1095
Chris Lattner0c946412007-08-26 17:47:35 +00001096static llvm::cl::opt<std::string>
1097isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1098 llvm::cl::desc("Set the system root directory (usually /)"));
1099
Reid Spencer5f016e22007-07-11 17:01:13 +00001100// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102/// InitializeIncludePaths - Process the -I options and set them in the
1103/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001104void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1105 FileManager &FM, const LangOptions &Lang) {
1106 InitHeaderSearch Init(Headers, Verbose, isysroot);
1107
Ted Kremenekf3721112008-05-31 00:27:00 +00001108 // Handle -I... and -F... options, walking the lists in parallel.
1109 unsigned Iidx = 0, Fidx = 0;
1110 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1111 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001112 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001113 ++Iidx;
1114 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001115 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001116 ++Fidx;
1117 }
1118 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001119
Ted Kremenekf3721112008-05-31 00:27:00 +00001120 // Consume what's left from whatever list was longer.
1121 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001122 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001123 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001124 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001125
1126 // Handle -idirafter... options.
1127 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001128 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1129 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001130
1131 // Handle -iquote... options.
1132 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001133 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001134
1135 // Handle -isystem... options.
1136 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001137 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001138
1139 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1140 // parallel, processing the values in order of occurance to get the right
1141 // prefixes.
1142 {
1143 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1144 unsigned iprefix_idx = 0;
1145 unsigned iwithprefix_idx = 0;
1146 unsigned iwithprefixbefore_idx = 0;
1147 bool iprefix_done = iprefix_vals.empty();
1148 bool iwithprefix_done = iwithprefix_vals.empty();
1149 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1150 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1151 if (!iprefix_done &&
1152 (iwithprefix_done ||
1153 iprefix_vals.getPosition(iprefix_idx) <
1154 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1155 (iwithprefixbefore_done ||
1156 iprefix_vals.getPosition(iprefix_idx) <
1157 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1158 Prefix = iprefix_vals[iprefix_idx];
1159 ++iprefix_idx;
1160 iprefix_done = iprefix_idx == iprefix_vals.size();
1161 } else if (!iwithprefix_done &&
1162 (iwithprefixbefore_done ||
1163 iwithprefix_vals.getPosition(iwithprefix_idx) <
1164 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001165 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1166 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 ++iwithprefix_idx;
1168 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1169 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001170 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1171 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001172 ++iwithprefixbefore_idx;
1173 iwithprefixbefore_done =
1174 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1175 }
1176 }
1177 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001178
Nico Weber0fca0222008-08-22 09:25:22 +00001179 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001180
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001181 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001182 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001183 llvm::sys::Path::GetMainExecutable(Argv0,
1184 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001185 if (!MainExecutablePath.isEmpty()) {
1186 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1187 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001188
1189 // Get foo/lib/clang/1.0/include
1190 //
1191 // FIXME: Don't embed version here.
1192 MainExecutablePath.appendComponent("lib");
1193 MainExecutablePath.appendComponent("clang");
1194 MainExecutablePath.appendComponent("1.0");
1195 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001196
1197 // We pass true to ignore sysroot so that we *always* look for clang headers
1198 // relative to our executable, never relative to -isysroot.
1199 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1200 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001201 }
1202
Nico Weber0fca0222008-08-22 09:25:22 +00001203 if (!nostdinc)
1204 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001205
1206 // Now that we have collected all of the include paths, merge them all
1207 // together and tell the preprocessor about them.
1208
Nico Weber0fca0222008-08-22 09:25:22 +00001209 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001210}
1211
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001212//===----------------------------------------------------------------------===//
1213// Driver PreprocessorFactory - For lazily generating preprocessors ...
1214//===----------------------------------------------------------------------===//
1215
1216namespace {
1217class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001218 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001219 Diagnostic &Diags;
1220 const LangOptions &LangInfo;
1221 TargetInfo &Target;
1222 SourceManager &SourceMgr;
1223 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001224 bool InitializeSourceMgr;
1225
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001226public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001227 DriverPreprocessorFactory(const std::string &infile,
1228 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001229 TargetInfo &target, SourceManager &SM,
1230 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001231 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1232 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1233
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001234
1235 virtual ~DriverPreprocessorFactory() {}
1236
1237 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001238 llvm::OwningPtr<PTHManager> PTHMgr;
1239
Ted Kremenek748d5d62009-03-20 00:26:38 +00001240 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1241 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1242 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001243 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001244 }
1245
Ted Kremenek72b1b152009-01-15 18:47:46 +00001246 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001247 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1248 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001249 PTHMgr.reset(PTHManager::Create(x, &Diags,
1250 TokenCache.empty() ? Diagnostic::Error
1251 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001252 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001253
Ted Kremenek22f0d092009-03-22 06:42:39 +00001254 if (Diags.hasErrorOccurred())
1255 exit(1);
1256
Ted Kremenek72b1b152009-01-15 18:47:46 +00001257 // Create the Preprocessor.
1258 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1259 SourceMgr, HeaderInfo,
1260 PTHMgr.get()));
1261
1262 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1263 // That argument is used as the IdentifierInfoLookup argument to
1264 // IdentifierTable's ctor.
1265 if (PTHMgr) {
1266 PTHMgr->setPreprocessor(PP.get());
1267 PP->setPTHManager(PTHMgr.take());
1268 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001269
Chris Lattner51574ea2008-04-19 23:25:44 +00001270 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001271 return NULL;
1272 }
1273
Daniel Dunbar750c3582008-10-24 22:12:41 +00001274 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001275 if (ProgAction != PrintPreprocessedInput) {
1276 std::string ErrStr;
1277 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1278 if (!DFG && !ErrStr.empty()) {
1279 fprintf(stderr, "%s", ErrStr.c_str());
Daniel Dunbar750c3582008-10-24 22:12:41 +00001280 return NULL;
1281 }
1282 }
1283
Ted Kremenek339b9c22008-04-17 22:31:54 +00001284 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001285 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001286 }
1287};
1288}
Reid Spencer5f016e22007-07-11 17:01:13 +00001289
Reid Spencer5f016e22007-07-11 17:01:13 +00001290//===----------------------------------------------------------------------===//
1291// Basic Parser driver
1292//===----------------------------------------------------------------------===//
1293
Chris Lattner51574ea2008-04-19 23:25:44 +00001294static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001296 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001297
1298 // Parsing the specified input file.
1299 P.ParseTranslationUnit();
1300 delete PA;
1301}
1302
1303//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001304// Code generation options
1305//===----------------------------------------------------------------------===//
1306
1307static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001308GenerateDebugInfo("g",
1309 llvm::cl::desc("Generate source level debug information"));
1310
1311static llvm::cl::opt<bool>
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00001312OptSize("Os", llvm::cl::desc("Optimize for size"));
Daniel Dunbar70f92432008-10-23 05:50:47 +00001313
Chris Lattnerbd360642009-03-26 05:00:52 +00001314static llvm::cl::opt<bool>
1315NoCommon("fno-common",
Mike Stump1c9b7422009-03-27 20:15:22 +00001316 llvm::cl::desc("Compile common globals like normal definitions"),
Chris Lattner925a7042009-03-28 02:12:08 +00001317 llvm::cl::ValueDisallowed);
Chris Lattnerbd360642009-03-26 05:00:52 +00001318
Daniel Dunbar70f92432008-10-23 05:50:47 +00001319// It might be nice to add bounds to the CommandLine library directly.
1320struct OptLevelParser : public llvm::cl::parser<unsigned> {
1321 bool parse(llvm::cl::Option &O, const char *ArgName,
1322 const std::string &Arg, unsigned &Val) {
1323 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1324 return true;
1325 // FIXME: Support -O4.
1326 if (Val > 3)
1327 return O.error(": '" + Arg + "' invalid optimization level!");
1328 return false;
1329 }
1330};
1331static llvm::cl::opt<unsigned, false, OptLevelParser>
1332OptLevel("O", llvm::cl::Prefix,
1333 llvm::cl::desc("Optimization level"),
1334 llvm::cl::init(0));
1335
Daniel Dunbara034ba82009-02-17 19:47:34 +00001336static llvm::cl::opt<std::string>
1337TargetCPU("mcpu",
1338 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1339
Chris Lattner7afae712009-03-16 18:41:18 +00001340static void InitializeCompileOptions(CompileOptions &Opts,
1341 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001342 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001343 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001344 if (OptSize) {
1345 // -Os implies -O2
1346 // FIXME: Diagnose conflicting options.
1347 Opts.OptimizationLevel = 2;
1348 } else {
1349 Opts.OptimizationLevel = OptLevel;
1350 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001351
1352 // FIXME: There are llvm-gcc options to control these selectively.
1353 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1354 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001355 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001356
1357#ifdef NDEBUG
1358 Opts.VerifyModule = 0;
1359#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001360
1361 Opts.CPU = TargetCPU;
1362 Opts.Features.insert(Opts.Features.end(),
1363 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001364
Chris Lattnerbd360642009-03-26 05:00:52 +00001365 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1366
Chris Lattner44502662009-02-18 01:23:44 +00001367 // Handle -ftime-report.
1368 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001369}
1370
1371//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001372// Fix-It Options
1373//===----------------------------------------------------------------------===//
1374static llvm::cl::list<ParsedSourceLocation>
1375FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1376 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1377
1378//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001379// Main driver
1380//===----------------------------------------------------------------------===//
1381
Ted Kremenekdb094a22007-12-05 18:27:04 +00001382/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001383/// action. These consumers can operate on both ASTs that are freshly
1384/// parsed from source files as well as those deserialized from Bitcode.
1385/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001386static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001387 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001388 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001389 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001390 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001391 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001392 default:
1393 return NULL;
1394
1395 case ASTPrint:
1396 return CreateASTPrinter();
1397
1398 case ASTDump:
1399 return CreateASTDumper();
1400
1401 case ASTView:
1402 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001403
Chris Lattner8a5c8092009-02-18 01:20:05 +00001404 case PrintDeclContext:
1405 return CreateDeclContextPrinter();
1406
1407 case EmitHTML:
1408 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001409
Chris Lattner8a5c8092009-02-18 01:20:05 +00001410 case InheritanceView:
1411 return CreateInheritanceViewer(InheritanceViewCls);
1412
1413 case TestSerialization:
1414 return CreateSerializationTest(Diag, FileMgr);
1415
1416 case EmitAssembly:
1417 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001418 case EmitBC:
1419 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001420 BackendAction Act;
1421 if (ProgAction == EmitAssembly)
1422 Act = Backend_EmitAssembly;
1423 else if (ProgAction == EmitLLVM)
1424 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001425 else if (ProgAction == EmitLLVMOnly)
1426 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001427 else
1428 Act = Backend_EmitBC;
1429
1430 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001431 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001432 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001433 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001434 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001435
Chris Lattner8a5c8092009-02-18 01:20:05 +00001436 case SerializeAST:
1437 // FIXME: Allow user to tailor where the file is written.
1438 return CreateASTSerializer(InFile, OutputFile, Diag);
1439
1440 case RewriteObjC:
1441 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001442
Chris Lattner8a5c8092009-02-18 01:20:05 +00001443 case RewriteBlocks:
1444 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1445
1446 case RunAnalysis:
1447 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001448 }
1449}
1450
Reid Spencer5f016e22007-07-11 17:01:13 +00001451/// ProcessInputFile - Process a single input file with the specified state.
1452///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001453static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001454 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001455 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001456 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001457 FixItRewriter *FixItRewrite = 0;
1458
Ted Kremenek85888962008-10-21 00:54:44 +00001459 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001461 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1462 PP.getFileManager(), PP.getLangOptions(),
1463 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001464
1465 if (!Consumer) {
1466 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001467 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001468 return;
1469 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001470
Ted Kremenekdb094a22007-12-05 18:27:04 +00001471 break;
1472
Chris Lattnerc106c102008-10-12 05:03:36 +00001473 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001474 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001475 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001476 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001477 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001478 RawLex.SetKeepWhitespaceMode(true);
1479
1480 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001481 RawLex.LexFromRawLexer(RawTok);
1482 while (RawTok.isNot(tok::eof)) {
1483 PP.DumpToken(RawTok, true);
1484 fprintf(stderr, "\n");
1485 RawLex.LexFromRawLexer(RawTok);
1486 }
1487 ClearSourceMgr = true;
1488 break;
1489 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001491 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001492 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001493 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001494 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 do {
1496 PP.Lex(Tok);
1497 PP.DumpToken(Tok, true);
1498 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001499 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001500 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 break;
1502 }
1503 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001504 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001505 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 // Start parsing 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);
Chris Lattner057aaf62007-10-09 18:03:42 +00001510 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001511 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 break;
1513 }
Ted Kremenek85888962008-10-21 00:54:44 +00001514
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001515 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001516 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001517 CacheTokens(PP, OutputFile);
1518 ClearSourceMgr = true;
1519 break;
1520 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001521
Chris Lattner47099742009-02-18 01:51:21 +00001522 case PrintPreprocessedInput: { // -E mode.
1523 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001524 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001525 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 break;
Chris Lattner47099742009-02-18 01:51:21 +00001527 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001528
Chris Lattner47099742009-02-18 01:51:21 +00001529 case ParseNoop: { // -parse-noop
1530 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001531 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001532 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 break;
Chris Lattner47099742009-02-18 01:51:21 +00001534 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001535
Chris Lattner47099742009-02-18 01:51:21 +00001536 case ParsePrintCallbacks: {
1537 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001538 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001539 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 break;
Chris Lattner47099742009-02-18 01:51:21 +00001541 }
1542
1543 case ParseSyntaxOnly: { // -fsyntax-only
1544 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001545 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001546 break;
Chris Lattner47099742009-02-18 01:51:21 +00001547 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001548
1549 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001550 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001551 ClearSourceMgr = true;
1552 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001553
Chris Lattner47099742009-02-18 01:51:21 +00001554 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001555 DoRewriteTest(PP, InFile, OutputFile);
1556 ClearSourceMgr = true;
1557 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001558 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001559
1560 case FixIt:
1561 llvm::TimeRegion Timer(ClangFrontendTimer);
1562 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001563 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Douglas Gregor558cb562009-04-02 01:08:08 +00001564 PP.getSourceManager());
Douglas Gregor558cb562009-04-02 01:08:08 +00001565 break;
Chris Lattner47099742009-02-18 01:51:21 +00001566 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001567
1568 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001569 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001570
Douglas Gregor26df2f02009-04-02 19:05:20 +00001571 if (FixItAtLocations.size() > 0) {
1572 // Even without the "-fixit" flag, with may have some specific
1573 // locations where the user has requested fixes. Process those
1574 // locations now.
1575 if (!FixItRewrite)
1576 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1577 PP.getSourceManager());
1578
1579 bool AddedFixitLocation = false;
1580 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1581 Idx != Last; ++Idx) {
1582 RequestedSourceLocation Requested;
1583 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1584 Requested)) {
1585 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1586 FixItAtLocations[Idx].FileName.c_str());
1587 } else {
1588 FixItRewrite->addFixItLocation(Requested);
1589 AddedFixitLocation = true;
1590 }
1591 }
1592
1593 if (!AddedFixitLocation) {
1594 // All of the fix-it locations were bad. Don't fix anything.
1595 delete FixItRewrite;
1596 FixItRewrite = 0;
1597 }
1598 }
1599
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001600 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1601 PP.getSourceManager(),
1602 PP.getTargetInfo(),
1603 PP.getIdentifierTable(),
1604 PP.getSelectorTable(),
1605 /* FreeMemory = */ !DisableFree));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001606
1607
Chris Lattner3599dbe2009-03-28 04:13:34 +00001608 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001609
Douglas Gregor558cb562009-04-02 01:08:08 +00001610 if (FixItRewrite)
1611 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1612
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001613 // If in -disable-free mode, don't deallocate these when they go out of
1614 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001615 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001616 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001617 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001618
1619 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001620 if (CheckDiagnostics(PP))
1621 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001622
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001624 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 PP.PrintStats();
1626 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001627 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001628 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 fprintf(stderr, "\n");
1630 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001631
1632 // For a multi-file compilation, some things are ok with nuking the source
1633 // manager tables, other require stable fileid/macroid's across multiple
1634 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001635 if (ClearSourceMgr)
1636 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001637
1638 if (DisableFree)
1639 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001640}
1641
Ted Kremenek20e97482007-12-12 23:41:08 +00001642static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1643 FileManager& FileMgr) {
1644
1645 if (VerifyDiagnostics) {
1646 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1647 exit (1);
1648 }
1649
1650 llvm::sys::Path Filename(InFile);
1651
1652 if (!Filename.isValid()) {
1653 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1654 exit (1);
1655 }
1656
Chris Lattner557c5b12009-03-28 04:27:18 +00001657 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001658
1659 // Create the memory buffer that contains the contents of the file.
1660 llvm::OwningPtr<llvm::MemoryBuffer>
1661 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1662
1663 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001664 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001665
Chris Lattner557c5b12009-03-28 04:27:18 +00001666 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001667 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1668 InFile.c_str());
1669 exit (1);
1670 }
1671
Ted Kremenek63ea8632007-12-19 19:27:38 +00001672 // Observe that we use the source file name stored in the deserialized
1673 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001674 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001675 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001676 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001677
Ted Kremenek20e97482007-12-12 23:41:08 +00001678 if (!Consumer) {
1679 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1680 exit (1);
1681 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001682
Chris Lattner557c5b12009-03-28 04:27:18 +00001683 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001684
Chris Lattnere66b65c2008-02-06 01:42:25 +00001685 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001686 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
1687 for (DeclContext::decl_iterator I = TUD->decls_begin(), E = TUD->decls_end();
1688 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001689 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001690}
1691
1692
Reid Spencer5f016e22007-07-11 17:01:13 +00001693static llvm::cl::list<std::string>
1694InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1695
Ted Kremenek20e97482007-12-12 23:41:08 +00001696static bool isSerializedFile(const std::string& InFile) {
1697 if (InFile.size() < 4)
1698 return false;
1699
1700 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001701 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001702}
1703
Reid Spencer5f016e22007-07-11 17:01:13 +00001704
1705int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001707 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001708 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001709 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001710
Chris Lattner47099742009-02-18 01:51:21 +00001711 if (TimeReport)
1712 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1713
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 // If no input was specified, read from stdin.
1715 if (InputFilenames.empty())
1716 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001717
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 // Create a file manager object to provide access to and cache the filesystem.
1719 FileManager FileMgr;
1720
Ted Kremenek31e703b2007-12-11 23:28:38 +00001721 // Create the diagnostic client for reporting errors or for
1722 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001723 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001724
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001725 if (!VerifyDiagnostics) {
1726 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001727 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1728 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001729 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001730 !NoShowLocation,
1731 PrintSourceRangeInfo);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001732 } else {
1733 // When checking diagnostics, just buffer them up.
1734 TextDiagClient = new TextDiagnosticBuffer();
1735
1736 if (InputFilenames.size() != 1) {
1737 fprintf(stderr,
1738 "-verify only works on single input files for now.\n");
1739 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 }
1741 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001742
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001744 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1745 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001746 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001747 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001748
Chris Lattner4f037832007-12-05 23:24:17 +00001749 // -I- is a deprecated GCC feature, scan for it and reject it.
1750 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1751 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001752 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001753 I_dirs.erase(I_dirs.begin()+i);
1754 --i;
1755 }
1756 }
Chris Lattner11215192008-03-14 06:12:05 +00001757
1758 // Get information about the target being compiled for.
1759 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001760 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1761
Chris Lattner11215192008-03-14 06:12:05 +00001762 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001763 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1764 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001765 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001766 }
Chris Lattner4f037832007-12-05 23:24:17 +00001767
Daniel Dunbard4270232009-01-20 23:17:32 +00001768 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001769 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001770
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001771 llvm::OwningPtr<SourceManager> SourceMgr;
1772
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001774 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001775
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001776 if (isSerializedFile(InFile)) {
1777 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001778 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001779 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001780 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001781
1782 /// Create a SourceManager object. This tracks and owns all the file
1783 /// buffers allocated to a translation unit.
1784 if (!SourceMgr)
1785 SourceMgr.reset(new SourceManager());
1786 else
1787 SourceMgr->clearIDTables();
1788
1789 // Initialize language options, inferring file types from input filenames.
1790 LangOptions LangInfo;
1791 InitializeBaseLanguage();
1792 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001793 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001794 InitializeGCMode(LangInfo);
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +00001795 InitializeSymbolVisibility(LangInfo);
Mike Stump2add4732009-04-01 20:28:16 +00001796 InitializeOverflowChecking(LangInfo);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001797 InitializeLanguageStandard(LangInfo, LK, Target.get());
1798
1799 // Process the -I options and set them in the HeaderInfo.
1800 HeaderSearch HeaderInfo(FileMgr);
1801
1802 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1803
1804 // Set up the preprocessor with these options.
1805 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1806 *SourceMgr.get(), HeaderInfo);
1807
1808 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1809
1810 if (!PP)
1811 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001812
Chris Lattnerf63aea32009-03-04 21:40:56 +00001813 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1814 // always reset to using TextDiagClient.
1815 llvm::OwningPtr<DiagnosticClient> TmpClient;
1816
1817 if (!HTMLDiag.empty()) {
1818 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1819 &PPFactory));
1820 Diags.setClient(TmpClient.get());
Ted Kremenek20e97482007-12-12 23:41:08 +00001821 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001822 else
1823 Diags.setClient(TextDiagClient);
1824
1825 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00001826 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001827
1828 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 }
Chris Lattner11215192008-03-14 06:12:05 +00001830
Mike Stump007f2a92009-01-28 02:43:35 +00001831 if (Verbose)
1832 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1833 " hosted on " LLVM_HOSTTRIPLE "\n");
1834
Ted Kremenek7a08e282008-08-07 18:13:12 +00001835 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1837 (NumDiagnostics == 1 ? "" : "s"));
1838
1839 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 FileMgr.PrintStats();
1841 fprintf(stderr, "\n");
1842 }
1843
Daniel Dunbar276373d2008-10-27 22:10:13 +00001844 // If verifying diagnostics and we reached here, all is well.
1845 if (VerifyDiagnostics)
1846 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00001847
1848 delete ClangFrontendTimer;
Daniel Dunbar276373d2008-10-27 22:10:13 +00001849
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001850 // Managed static deconstruction. Useful for making things like
1851 // -time-passes usable.
1852 llvm::llvm_shutdown();
1853
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001854 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001855}