blob: 37233134dadb3c66c89a07295adba6e84e57c754 [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"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000036#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000037#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000038#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000039#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000040#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000041#include "clang/AST/ASTContext.h"
42#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000043#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044#include "clang/Parse/Parser.h"
45#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000046#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include "clang/Basic/FileManager.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000050#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000051#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/StringExtras.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000055#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000056#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000057#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000058#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000059#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000060#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000061#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000062#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000063#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000064#include <cstdlib>
65
Reid Spencer5f016e22007-07-11 17:01:13 +000066using namespace clang;
67
68//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000069// Source Location Parser
70//===----------------------------------------------------------------------===//
71
72/// \brief A source location that has been parsed on the command line.
73struct ParsedSourceLocation {
74 std::string FileName;
75 unsigned Line;
76 unsigned Column;
77
78 /// \brief Try to resolve the file name of a parsed source location.
79 ///
80 /// \returns true if there was an error, false otherwise.
81 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
82};
83
84bool
85ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
86 RequestedSourceLocation &Result) {
87 const FileEntry *File = FileMgr.getFile(FileName);
88 if (!File)
89 return true;
90
91 Result.File = File;
92 Result.Line = Line;
93 Result.Column = Column;
94 return false;
95}
96
97namespace llvm {
98 namespace cl {
99 /// \brief Command-line option parser that parses source locations.
100 ///
101 /// Source locations are of the form filename:line:column.
102 template<>
103 class parser<ParsedSourceLocation>
104 : public basic_parser<ParsedSourceLocation> {
105 public:
106 bool parse(Option &O, const char *ArgName,
107 const std::string &ArgValue,
108 ParsedSourceLocation &Val);
109 };
110
111 bool
112 parser<ParsedSourceLocation>::
113 parse(Option &O, const char *ArgName, const std::string &ArgValue,
114 ParsedSourceLocation &Val) {
115 using namespace clang;
116
117 const char *ExpectedFormat
118 = "source location must be of the form filename:line:column";
119 std::string::size_type SecondColon = ArgValue.rfind(':');
120 if (SecondColon == std::string::npos) {
121 std::fprintf(stderr, "%s\n", ExpectedFormat);
122 return true;
123 }
124 char *EndPtr;
125 long Column
126 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
127 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
128 std::fprintf(stderr, "%s\n", ExpectedFormat);
129 return true;
130 }
131
132 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
133 if (SecondColon == std::string::npos) {
134 std::fprintf(stderr, "%s\n", ExpectedFormat);
135 return true;
136 }
137 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
138 if (EndPtr != ArgValue.c_str() + SecondColon) {
139 std::fprintf(stderr, "%s\n", ExpectedFormat);
140 return true;
141 }
142
143 Val.FileName = ArgValue.substr(0, FirstColon);
144 Val.Line = Line;
145 Val.Column = Column;
146 return false;
147 }
148 }
149}
150
151//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000152// Global options.
153//===----------------------------------------------------------------------===//
154
Chris Lattner47099742009-02-18 01:51:21 +0000155/// ClangFrontendTimer - The front-end activities should charge time to it with
156/// TimeRegion. The -ftime-report option controls whether this will do
157/// anything.
158llvm::Timer *ClangFrontendTimer = 0;
159
Daniel Dunbard3db4012008-10-16 16:54:18 +0000160static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162static llvm::cl::opt<bool>
163Verbose("v", llvm::cl::desc("Enable verbose output"));
164static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000165Stats("print-stats",
166 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000167static llvm::cl::opt<bool>
168DisableFree("disable-free",
169 llvm::cl::desc("Disable freeing of memory on exit"),
170 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +0000171
172enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000173 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000174 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000175 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000176 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000177 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000178 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000179 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000181 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000182 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000183 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +0000184 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000185 ASTPrint, // Parse ASTs and print them.
186 ASTDump, // Parse ASTs and dump them.
187 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000188 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000189 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 ParsePrintCallbacks, // Parse and print each callback.
191 ParseSyntaxOnly, // Parse and perform semantic analysis.
192 ParseNoop, // Parse with noop callbacks.
193 RunPreprocessorOnly, // Just lex, no output.
194 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000195 DumpTokens, // Dump out preprocessed tokens.
196 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000197 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000198 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000199 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000200 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000201};
202
203static llvm::cl::opt<ProgActions>
204ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
205 llvm::cl::init(ParseSyntaxOnly),
206 llvm::cl::values(
207 clEnumValN(RunPreprocessorOnly, "Eonly",
208 "Just run preprocessor, no output (for timings)"),
209 clEnumValN(PrintPreprocessedInput, "E",
210 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000211 clEnumValN(DumpRawTokens, "dump-raw-tokens",
212 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000213 clEnumValN(RunAnalysis, "analyze",
214 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000215 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 "Run preprocessor, dump internal rep of tokens"),
217 clEnumValN(ParseNoop, "parse-noop",
218 "Run parser with noop callbacks (for timings)"),
219 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
220 "Run parser and perform semantic analysis"),
221 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
222 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000223 clEnumValN(EmitHTML, "emit-html",
224 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000225 clEnumValN(ASTPrint, "ast-print",
226 "Build ASTs and then pretty-print them"),
227 clEnumValN(ASTDump, "ast-dump",
228 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000229 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000230 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000231 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000232 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000233 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000234 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000235 clEnumValN(GeneratePCH, "emit-pch",
236 "Generate pre-compiled header file"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000237 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000238 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000239 clEnumValN(EmitAssembly, "S",
240 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000242 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000243 clEnumValN(EmitBC, "emit-llvm-bc",
244 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000245 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
246 "Build ASTs and convert to LLVM, discarding output"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000247 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000248 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000249 clEnumValN(RewriteTest, "rewrite-test",
250 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000251 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000252 "Rewrite ObjC into C (code rewriter example)"),
253 clEnumValN(RewriteMacros, "rewrite-macros",
254 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000255 clEnumValN(RewriteBlocks, "rewrite-blocks",
256 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000257 clEnumValN(FixIt, "fixit",
258 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 clEnumValEnd));
260
Ted Kremenekccc76472007-12-19 19:47:59 +0000261
262static llvm::cl::opt<std::string>
263OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000264 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000265 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000266
Ted Kremenekc2e72992008-12-02 19:57:31 +0000267
268//===----------------------------------------------------------------------===//
269// PTH.
270//===----------------------------------------------------------------------===//
271
272static llvm::cl::opt<std::string>
273TokenCache("token-cache", llvm::cl::value_desc("path"),
274 llvm::cl::desc("Use specified token cache file"));
275
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000276//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000277// Diagnostic Options
278//===----------------------------------------------------------------------===//
279
Ted Kremenek41193e42007-09-26 19:42:19 +0000280static llvm::cl::opt<bool>
281VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000282 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000283
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000284static llvm::cl::opt<std::string>
285HTMLDiag("html-diags",
286 llvm::cl::desc("Generate HTML to report diagnostics"),
287 llvm::cl::value_desc("HTML directory"));
288
Nico Weberfd54ebc2008-08-05 23:33:20 +0000289static llvm::cl::opt<bool>
290NoShowColumn("fno-show-column",
291 llvm::cl::desc("Do not include column number on diagnostics"));
292
293static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000294NoShowLocation("fno-show-source-location",
295 llvm::cl::desc("Do not include source location information with"
296 " diagnostics"));
297
298static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000299NoCaretDiagnostics("fno-caret-diagnostics",
300 llvm::cl::desc("Do not include source line and caret with"
301 " diagnostics"));
302
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000303static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000304NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
305 llvm::cl::desc("Do not include fixit information in"
306 " diagnostics"));
307
308static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000309PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
310 llvm::cl::desc("Print source range spans in numeric form"));
311
312static llvm::cl::alias
313PrintSourceRangeInfo2("fprint-source-range-info",
314 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
315 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000316
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000317static llvm::cl::opt<bool>
318PrintDiagnosticOption("fdiagnostics-show-option",
319 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000322// C++ Visualization.
323//===----------------------------------------------------------------------===//
324
325static llvm::cl::opt<std::string>
326InheritanceViewCls("cxx-inheritance-view",
327 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000328 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000329
330//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000331// Builtin Options
332//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000333
334static llvm::cl::opt<bool>
335TimeReport("ftime-report",
336 llvm::cl::desc("Print the amount of time each "
337 "phase of compilation takes"));
338
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000339static llvm::cl::opt<bool>
340Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000341 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000342 "freestanding environment"));
343
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000344static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000345AllowBuiltins("fbuiltin", llvm::cl::init(true),
346 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000347
348
349static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000350MathErrno("fmath-errno", llvm::cl::init(true),
351 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000352
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000353//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000354// Language Options
355//===----------------------------------------------------------------------===//
356
357enum LangKind {
358 langkind_unspecified,
359 langkind_c,
360 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000361 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 langkind_cxx,
363 langkind_cxx_cpp,
364 langkind_objc,
365 langkind_objc_cpp,
366 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000367 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000368};
369
Reid Spencer5f016e22007-07-11 17:01:13 +0000370static llvm::cl::opt<LangKind>
371BaseLang("x", llvm::cl::desc("Base language to compile"),
372 llvm::cl::init(langkind_unspecified),
373 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
374 clEnumValN(langkind_cxx, "c++", "C++"),
375 clEnumValN(langkind_objc, "objective-c", "Objective C"),
376 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000377 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000379 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
380 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000382 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
384 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000385 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000387 clEnumValN(langkind_c, "c-header",
388 "C header"),
389 clEnumValN(langkind_objc, "objective-c-header",
390 "Objective-C header"),
391 clEnumValN(langkind_cxx, "c++-header",
392 "C++ header"),
393 clEnumValN(langkind_objcxx, "objective-c++-header",
394 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 clEnumValEnd));
396
397static llvm::cl::opt<bool>
398LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
399 llvm::cl::Hidden);
400static llvm::cl::opt<bool>
401LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
402 llvm::cl::Hidden);
403
Chris Lattner2c78b872009-04-14 23:22:57 +0000404static llvm::cl::opt<bool>
405ObjCExclusiveGC("fobjc-gc-only",
406 llvm::cl::desc("Use GC exclusively for Objective-C related "
407 "memory management"));
408
409static llvm::cl::opt<bool>
410ObjCEnableGC("fobjc-gc",
411 llvm::cl::desc("Enable Objective-C garbage collection"));
412
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000413static llvm::cl::opt<bool>
414ObjCEnableGCBitmapPrint("print-ivar-layout",
415 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
416
Chris Lattner2c78b872009-04-14 23:22:57 +0000417static llvm::cl::opt<LangOptions::VisibilityMode>
418SymbolVisibility("fvisibility",
419 llvm::cl::desc("Set the default symbol visibility:"),
420 llvm::cl::init(LangOptions::Default),
421 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
422 "Use default symbol visibility"),
423 clEnumValN(LangOptions::Hidden, "hidden",
424 "Use hidden symbol visibility"),
425 clEnumValN(LangOptions::Protected,"protected",
426 "Use protected symbol visibility"),
427 clEnumValEnd));
428
429static llvm::cl::opt<bool>
430OverflowChecking("ftrapv",
431 llvm::cl::desc("Trap on integer overflow"),
432 llvm::cl::init(false));
433
434
Ted Kremenek8904f152007-12-05 23:49:08 +0000435/// InitializeBaseLanguage - Handle the -x foo options.
436static void InitializeBaseLanguage() {
437 if (LangObjC)
438 BaseLang = langkind_objc;
439 else if (LangObjCXX)
440 BaseLang = langkind_objcxx;
441}
442
443static LangKind GetLanguage(const std::string &Filename) {
444 if (BaseLang != langkind_unspecified)
445 return BaseLang;
446
447 std::string::size_type DotPos = Filename.rfind('.');
448
449 if (DotPos == std::string::npos) {
450 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000451 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 }
453
Ted Kremenek8904f152007-12-05 23:49:08 +0000454 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
455 // C header: .h
456 // C++ header: .hh or .H;
457 // assembler no preprocessing: .s
458 // assembler: .S
459 if (Ext == "c")
460 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000461 else if (Ext == "S" ||
462 // If the compiler is run on a .s file, preprocess it as .S
463 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000464 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000465 else if (Ext == "i")
466 return langkind_c_cpp;
467 else if (Ext == "ii")
468 return langkind_cxx_cpp;
469 else if (Ext == "m")
470 return langkind_objc;
471 else if (Ext == "mi")
472 return langkind_objc_cpp;
473 else if (Ext == "mm" || Ext == "M")
474 return langkind_objcxx;
475 else if (Ext == "mii")
476 return langkind_objcxx_cpp;
477 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
478 Ext == "c++" || Ext == "cp" || Ext == "cxx")
479 return langkind_cxx;
480 else
481 return langkind_c;
482}
483
484
Ted Kremenek85888962008-10-21 00:54:44 +0000485static void InitializeCOptions(LangOptions &Options) {
486 // Do nothing.
487}
488
489static void InitializeObjCOptions(LangOptions &Options) {
490 Options.ObjC1 = Options.ObjC2 = 1;
491}
492
493
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000494static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 // FIXME: implement -fpreprocessed mode.
496 bool NoPreprocess = false;
497
Ted Kremenek8904f152007-12-05 23:49:08 +0000498 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000500 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000501 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000502 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 case langkind_c_cpp:
504 NoPreprocess = true;
505 // FALLTHROUGH
506 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000507 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 break;
509 case langkind_cxx_cpp:
510 NoPreprocess = true;
511 // FALLTHROUGH
512 case langkind_cxx:
513 Options.CPlusPlus = 1;
514 break;
515 case langkind_objc_cpp:
516 NoPreprocess = true;
517 // FALLTHROUGH
518 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000519 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 break;
521 case langkind_objcxx_cpp:
522 NoPreprocess = true;
523 // FALLTHROUGH
524 case langkind_objcxx:
525 Options.ObjC1 = Options.ObjC2 = 1;
526 Options.CPlusPlus = 1;
527 break;
528 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000529
530 if (ObjCExclusiveGC)
531 Options.setGCMode(LangOptions::GCOnly);
532 else if (ObjCEnableGC)
533 Options.setGCMode(LangOptions::HybridGC);
534
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000535 if (ObjCEnableGCBitmapPrint)
536 Options.ObjCGCBitmapPrint = 1;
537
Chris Lattner2c78b872009-04-14 23:22:57 +0000538 Options.setVisibilityMode(SymbolVisibility);
539 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000540}
541
542/// LangStds - Language standards we support.
543enum LangStds {
544 lang_unspecified,
545 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000546 lang_gnu_START,
547 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000548 lang_cxx98, lang_gnucxx98,
549 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000550};
551
552static llvm::cl::opt<LangStds>
553LangStd("std", llvm::cl::desc("Language standard to compile for"),
554 llvm::cl::init(lang_unspecified),
555 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
556 clEnumValN(lang_c89, "c90", "ISO C 1990"),
557 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
558 clEnumValN(lang_c94, "iso9899:199409",
559 "ISO C 1990 with amendment 1"),
560 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000561 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000563 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000565 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000567 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 clEnumValN(lang_gnu99, "gnu9x",
569 "ISO C 1999 with GNU extensions"),
570 clEnumValN(lang_cxx98, "c++98",
571 "ISO C++ 1998 with amendments"),
572 clEnumValN(lang_gnucxx98, "gnu++98",
573 "ISO C++ 1998 with amendments and GNU "
574 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000575 clEnumValN(lang_cxx0x, "c++0x",
576 "Upcoming ISO C++ 200x with amendments"),
577 clEnumValN(lang_gnucxx0x, "gnu++0x",
578 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000579 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 clEnumValEnd));
581
582static llvm::cl::opt<bool>
583NoOperatorNames("fno-operator-names",
584 llvm::cl::desc("Do not treat C++ operator name keywords as "
585 "synonyms for operators"));
586
Anders Carlssonee98ac52007-10-15 02:50:23 +0000587static llvm::cl::opt<bool>
588PascalStrings("fpascal-strings",
589 llvm::cl::desc("Recognize and construct Pascal-style "
590 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000591
592static llvm::cl::opt<bool>
593MSExtensions("fms-extensions",
594 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000595 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000596
597static llvm::cl::opt<bool>
598WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000599 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000600
601static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000602NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000603 llvm::cl::desc("Disallow implicit conversions between "
604 "vectors with a different number of "
605 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000606
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000607static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000608EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000609
610static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000611EnableHeinousExtensions("fheinous-gnu-extensions",
612 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
613 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
614
615static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000616ObjCNonFragileABI("fobjc-nonfragile-abi",
617 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000618
Daniel Dunbard604c402009-02-04 21:19:06 +0000619static llvm::cl::opt<bool>
620EmitAllDecls("femit-all-decls",
621 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000622
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000623// FIXME: This (and all GCC -f options) really come in -f... and
624// -fno-... forms, and additionally support automagic behavior when
625// they are not defined. For example, -fexceptions defaults to on or
626// off depending on the language. We should support this behavior in
627// some form (perhaps just add a facility for distinguishing when an
628// has its default value from when it has been set to its default
629// value).
630static llvm::cl::opt<bool>
631Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000632 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000633
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000634static llvm::cl::opt<bool>
635GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000636 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000637 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000638
639static llvm::cl::opt<bool>
640NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000641 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000642 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000643
Ted Kremenekea644d82008-09-03 21:22:16 +0000644
645
646static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000647Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000648
Chris Lattner16167a62009-03-02 22:11:07 +0000649static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000650TargetFeatures("mattr", llvm::cl::CommaSeparated,
651 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
652
Douglas Gregor26dce442009-03-10 00:06:19 +0000653static llvm::cl::opt<unsigned>
654TemplateDepth("ftemplate-depth", llvm::cl::init(99),
655 llvm::cl::desc("Maximum depth of recursive template "
656 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000657static llvm::cl::opt<bool>
658DollarsInIdents("fdollars-in-identifiers",
659 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000660
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000661
662static llvm::cl::opt<bool>
663OptSize("Os", llvm::cl::desc("Optimize for size"));
664
665static llvm::cl::opt<bool>
666NoCommon("fno-common",
667 llvm::cl::desc("Compile common globals like normal definitions"),
668 llvm::cl::ValueDisallowed);
669
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000670static llvm::cl::opt<std::string>
671MainFileName("main-file-name",
672 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000673
674// It might be nice to add bounds to the CommandLine library directly.
675struct OptLevelParser : public llvm::cl::parser<unsigned> {
676 bool parse(llvm::cl::Option &O, const char *ArgName,
677 const std::string &Arg, unsigned &Val) {
678 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
679 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000680 if (Val > 3)
681 return O.error(": '" + Arg + "' invalid optimization level!");
682 return false;
683 }
684};
685static llvm::cl::opt<unsigned, false, OptLevelParser>
686OptLevel("O", llvm::cl::Prefix,
687 llvm::cl::desc("Optimization level"),
688 llvm::cl::init(0));
689
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000690static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000691PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
692
693static llvm::cl::opt<bool>
694StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000695
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000696static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
697 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000698 // Allow the target to set the default the langauge options as it sees fit.
699 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000700
Chris Lattner6328cc32009-03-03 19:56:18 +0000701 // If there are any -mattr options, pass them to the target for validation and
702 // processing. The driver should have already consolidated all the
703 // target-feature settings and passed them to us in the -mattr list. The
704 // -mattr list is treated by the code generator as a diff against the -mcpu
705 // setting, but the driver should pass all enabled options as "+" settings.
706 // This means that the target should only look at + settings.
Chris Lattner4d417652009-04-13 06:33:49 +0000707 if (!TargetFeatures.empty()) {
Chris Lattner16167a62009-03-02 22:11:07 +0000708 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000709 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
710 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000711 if (Opt != -1) {
712 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000713 fprintf(stderr, "invalid feature '%s'\n",
714 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000715 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000716 fprintf(stderr, "feature '%s': %s\n",
717 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000718 exit(1);
719 }
720 }
721
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 if (LangStd == lang_unspecified) {
723 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000724 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000725 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000727 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 case langkind_c_cpp:
729 case langkind_objc:
730 case langkind_objc_cpp:
731 LangStd = lang_gnu99;
732 break;
733 case langkind_cxx:
734 case langkind_cxx_cpp:
735 case langkind_objcxx:
736 case langkind_objcxx_cpp:
737 LangStd = lang_gnucxx98;
738 break;
739 }
740 }
741
742 switch (LangStd) {
743 default: assert(0 && "Unknown language standard!");
744
745 // Fall through from newer standards to older ones. This isn't really right.
746 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000747 case lang_gnucxx0x:
748 case lang_cxx0x:
749 Options.CPlusPlus0x = 1;
750 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 case lang_gnucxx98:
752 case lang_cxx98:
753 Options.CPlusPlus = 1;
754 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000755 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 // FALL THROUGH.
757 case lang_gnu99:
758 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 Options.C99 = 1;
760 Options.HexFloats = 1;
761 // FALL THROUGH.
762 case lang_gnu89:
763 Options.BCPLComment = 1; // Only for C99/C++.
764 // FALL THROUGH.
765 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000766 Options.Digraphs = 1; // C94, C99, C++.
767 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000768 case lang_c89:
769 break;
770 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000771
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000772 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
773 Options.GNUMode = LangStd >= lang_gnu_START;
774
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000775 if (Options.CPlusPlus) {
776 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000777 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000778 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000779
Chris Lattnerd658b562008-04-05 06:32:51 +0000780 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
781 Options.ImplicitInt = 1;
782 else
783 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000784
Daniel Dunbard573d262009-04-07 22:13:21 +0000785 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
786 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000787 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000788 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000789 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000790
Chris Lattner802db9b2008-12-05 00:10:44 +0000791 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
792 // even if they are normally on for the target. In GNU modes (e.g.
793 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000794 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000795 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000796 Options.Blocks = 0;
797
Chris Lattner01638a62009-04-19 07:06:52 +0000798 // Default to not accepting '$' in identifiers when preprocessing assembler,
799 // but do accept when preprocessing C. FIXME: these defaults are right for
800 // darwin, are they right everywhere?
801 Options.DollarIdents = LK != langkind_asm_cpp;
802 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000803 Options.DollarIdents = DollarsInIdents;
804
Chris Lattnerae0ee032008-12-04 23:20:07 +0000805 if (PascalStrings.getPosition())
806 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000807 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000808 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000809 if (NoLaxVectorConversions.getPosition())
810 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000811 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000812 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000813 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000814
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000815 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000816 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000817 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000818 Options.Freestanding = Options.NoBuiltin = 1;
819
Chris Lattner810f6d52009-03-13 17:38:01 +0000820 if (EnableHeinousExtensions)
821 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000822
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000823 Options.MathErrno = MathErrno;
824
Douglas Gregor26dce442009-03-10 00:06:19 +0000825 Options.InstantiationDepth = TemplateDepth;
826
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000827 // Override the default runtime if the user requested it.
828 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000829 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000830 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000831 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000832
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000833 if (ObjCNonFragileABI)
834 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000835
836 if (EmitAllDecls)
837 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000838
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000839 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
840 // support.
841 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000842
843 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000844 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000845 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000846
847 assert(PICLevel <= 2 && "Invalid value for -pic-level");
848 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000849
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000850 Options.GNUInline = !Options.C99;
851 // FIXME: This is affected by other options (-fno-inline).
852 Options.NoInline = !OptSize && !OptLevel;
853
854 Options.Static = StaticDefine;
855
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000856 if (MainFileName.getPosition())
857 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000858}
859
860//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000861// Target Triple Processing.
862//===----------------------------------------------------------------------===//
863
864static llvm::cl::opt<std::string>
865TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000866 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000867
Chris Lattner42e67372008-03-05 01:18:20 +0000868static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000869Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000870
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000871static llvm::cl::opt<std::string>
872MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000873 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000874
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000875// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
876// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000877
878// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000879static void HandleMacOSVersionMin(std::string &Triple) {
880 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
881 if (DarwinDashIdx == std::string::npos) {
882 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000883 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000884 exit(1);
885 }
886 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
887
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000888 // Remove the number.
889 Triple.resize(DarwinNumIdx);
890
891 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
892 bool MacOSVersionMinIsInvalid = false;
893 int VersionNum = 0;
894 if (MacOSVersionMin.size() < 4 ||
895 MacOSVersionMin.substr(0, 3) != "10." ||
896 !isdigit(MacOSVersionMin[3])) {
897 MacOSVersionMinIsInvalid = true;
898 } else {
899 const char *Start = MacOSVersionMin.c_str()+3;
900 char *End = 0;
901 VersionNum = (int)strtol(Start, &End, 10);
902
Chris Lattner079f2c462008-09-30 20:30:12 +0000903 // The version number must be in the range 0-9.
904 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
905
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000906 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
907 Triple += llvm::itostr(VersionNum+4);
908
Chris Lattner079f2c462008-09-30 20:30:12 +0000909 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
910 // Add the period piece (.7) to the end of the triple. This gives us
911 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000912 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000913 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
914 MacOSVersionMinIsInvalid = true;
915 }
916 }
917
918 if (MacOSVersionMinIsInvalid) {
919 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000920 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000921 MacOSVersionMin.c_str());
922 exit(1);
923 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000924 else if (VersionNum <= 4 &&
925 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
926 fprintf(stderr,
927 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
928 MacOSVersionMin.c_str());
929 exit(1);
930 }
931
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000932}
933
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000934static llvm::cl::opt<std::string>
935IPhoneOSVersionMin("miphoneos-version-min",
936 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
937
938// If -miphoneos-version-min=2.2 is specified, change the triple from being
939// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
940// 9 as the default major Darwin number, and encode the iPhone OS version
941// number in the minor version and revision.
942
943// FIXME: We should have the driver do this instead.
944static void HandleIPhoneOSVersionMin(std::string &Triple) {
945 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
946 if (DarwinDashIdx == std::string::npos) {
947 fprintf(stderr,
948 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
949 exit(1);
950 }
951 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
952
953 // Remove the number.
954 Triple.resize(DarwinNumIdx);
955
956 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
957 bool IPhoneOSVersionMinIsInvalid = false;
958 int VersionNum = 0;
959 if (IPhoneOSVersionMin.size() < 3 ||
960 !isdigit(IPhoneOSVersionMin[0])) {
961 IPhoneOSVersionMinIsInvalid = true;
962 } else {
963 const char *Start = IPhoneOSVersionMin.c_str();
964 char *End = 0;
965 VersionNum = (int)strtol(Start, &End, 10);
966
967 // The version number must be in the range 0-9.
968 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
969
970 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
971 Triple += "9." + llvm::itostr(VersionNum);
972
973 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
974 // Add the period piece (.2) to the end of the triple. This gives us
975 // something like ...-darwin9.2.2
976 Triple += End;
977 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
978 IPhoneOSVersionMinIsInvalid = true;
979 }
980 }
981
982 if (IPhoneOSVersionMinIsInvalid) {
983 fprintf(stderr,
984 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
985 IPhoneOSVersionMin.c_str());
986 exit(1);
987 }
988}
989
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000990/// CreateTargetTriple - Process the various options that affect the target
991/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000992static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000993 // Initialize base triple. If a -triple option has been specified, use
994 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000995 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000996 if (Triple.empty())
997 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +0000998
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000999 // If -arch foo was specified, remove the architecture from the triple we have
1000 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +00001001
1002 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001003 if (!Arch.empty()) {
1004 // Decompose the base triple into "arch" and suffix.
1005 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001006
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001007 if (FirstDashIdx == std::string::npos) {
1008 fprintf(stderr,
1009 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1010 Triple.c_str());
1011 exit(1);
1012 }
Chris Lattner37e217c2009-03-24 16:18:41 +00001013
1014 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1015 if (Arch == "ppc")
1016 Arch = "powerpc";
1017 else if (Arch == "ppc64")
1018 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +00001019
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001020 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1021 }
1022
1023 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1024 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +00001025 if (!MacOSVersionMin.empty())
1026 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +00001027 else if (!IPhoneOSVersionMin.empty())
1028 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +00001029
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001030 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +00001031}
1032
1033//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +00001034// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001035//===----------------------------------------------------------------------===//
1036
Douglas Gregore1d918e2009-04-10 23:10:45 +00001037static bool InitializeSourceManager(Preprocessor &PP,
1038 const std::string &InFile) {
1039 // Figure out where to get and map in the main file.
1040 SourceManager &SourceMgr = PP.getSourceManager();
1041 FileManager &FileMgr = PP.getFileManager();
1042
1043 if (InFile != "-") {
1044 const FileEntry *File = FileMgr.getFile(InFile);
1045 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1046 if (SourceMgr.getMainFileID().isInvalid()) {
1047 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1048 << InFile.c_str();
1049 return true;
1050 }
1051 } else {
1052 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1053
1054 // If stdin was empty, SB is null. Cons up an empty memory
1055 // buffer now.
1056 if (!SB) {
1057 const char *EmptyStr = "";
1058 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1059 }
1060
1061 SourceMgr.createMainFileIDForMemBuffer(SB);
1062 if (SourceMgr.getMainFileID().isInvalid()) {
1063 PP.getDiagnostics().Report(FullSourceLoc(),
1064 diag::err_fe_error_reading_stdin);
1065 return true;
1066 }
1067 }
1068
1069 return false;
1070}
1071
Chris Lattneraa391972008-04-19 23:09:31 +00001072
Chris Lattnere116ccf2009-04-21 05:40:52 +00001073//===----------------------------------------------------------------------===//
1074// Preprocessor Initialization
1075//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001076
Chris Lattnere116ccf2009-04-21 05:40:52 +00001077// FIXME: Preprocessor builtins to support.
1078// -A... - Play with #assertions
1079// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001080
Chris Lattnere116ccf2009-04-21 05:40:52 +00001081static llvm::cl::list<std::string>
1082D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1083 llvm::cl::desc("Predefine the specified macro"));
1084static llvm::cl::list<std::string>
1085U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1086 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001087
Chris Lattnere116ccf2009-04-21 05:40:52 +00001088static llvm::cl::list<std::string>
1089ImplicitIncludes("include", llvm::cl::value_desc("file"),
1090 llvm::cl::desc("Include file before parsing"));
1091static llvm::cl::list<std::string>
1092ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1093 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001094
Chris Lattnere116ccf2009-04-21 05:40:52 +00001095static llvm::cl::opt<std::string>
1096ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1097 llvm::cl::desc("Include precompiled header file"));
1098
1099static llvm::cl::opt<std::string>
1100ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1101 llvm::cl::desc("Include file before parsing"));
1102
Reid Spencer5f016e22007-07-11 17:01:13 +00001103
1104//===----------------------------------------------------------------------===//
1105// Preprocessor include path information.
1106//===----------------------------------------------------------------------===//
1107
1108// This tool exports a large number of command line options to control how the
1109// preprocessor searches for header files. At root, however, the Preprocessor
1110// object takes a very simple interface: a list of directories to search for
1111//
1112// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001113// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001114//
Reid Spencer5f016e22007-07-11 17:01:13 +00001115
1116static llvm::cl::opt<bool>
1117nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1118
1119// Various command line options. These four add directories to each chain.
1120static llvm::cl::list<std::string>
1121F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1122 llvm::cl::desc("Add directory to framework include search path"));
1123static llvm::cl::list<std::string>
1124I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1125 llvm::cl::desc("Add directory to include search path"));
1126static llvm::cl::list<std::string>
1127idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1128 llvm::cl::desc("Add directory to AFTER include search path"));
1129static llvm::cl::list<std::string>
1130iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1131 llvm::cl::desc("Add directory to QUOTE include search path"));
1132static llvm::cl::list<std::string>
1133isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1134 llvm::cl::desc("Add directory to SYSTEM include search path"));
1135
1136// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1137static llvm::cl::list<std::string>
1138iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1139 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1140static llvm::cl::list<std::string>
1141iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1142 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1143static llvm::cl::list<std::string>
1144iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1145 llvm::cl::Prefix,
1146 llvm::cl::desc("Set directory to include search path with prefix"));
1147
Chris Lattner0c946412007-08-26 17:47:35 +00001148static llvm::cl::opt<std::string>
1149isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1150 llvm::cl::desc("Set the system root directory (usually /)"));
1151
Reid Spencer5f016e22007-07-11 17:01:13 +00001152// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001153
Reid Spencer5f016e22007-07-11 17:01:13 +00001154/// InitializeIncludePaths - Process the -I options and set them in the
1155/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001156void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1157 FileManager &FM, const LangOptions &Lang) {
1158 InitHeaderSearch Init(Headers, Verbose, isysroot);
1159
Ted Kremenekf3721112008-05-31 00:27:00 +00001160 // Handle -I... and -F... options, walking the lists in parallel.
1161 unsigned Iidx = 0, Fidx = 0;
1162 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1163 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001164 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001165 ++Iidx;
1166 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001167 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001168 ++Fidx;
1169 }
1170 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001171
Ted Kremenekf3721112008-05-31 00:27:00 +00001172 // Consume what's left from whatever list was longer.
1173 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001174 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001175 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001176 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001177
1178 // Handle -idirafter... options.
1179 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001180 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1181 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001182
1183 // Handle -iquote... options.
1184 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001185 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001186
1187 // Handle -isystem... options.
1188 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001189 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001190
1191 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1192 // parallel, processing the values in order of occurance to get the right
1193 // prefixes.
1194 {
1195 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1196 unsigned iprefix_idx = 0;
1197 unsigned iwithprefix_idx = 0;
1198 unsigned iwithprefixbefore_idx = 0;
1199 bool iprefix_done = iprefix_vals.empty();
1200 bool iwithprefix_done = iwithprefix_vals.empty();
1201 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1202 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1203 if (!iprefix_done &&
1204 (iwithprefix_done ||
1205 iprefix_vals.getPosition(iprefix_idx) <
1206 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1207 (iwithprefixbefore_done ||
1208 iprefix_vals.getPosition(iprefix_idx) <
1209 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1210 Prefix = iprefix_vals[iprefix_idx];
1211 ++iprefix_idx;
1212 iprefix_done = iprefix_idx == iprefix_vals.size();
1213 } else if (!iwithprefix_done &&
1214 (iwithprefixbefore_done ||
1215 iwithprefix_vals.getPosition(iwithprefix_idx) <
1216 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001217 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1218 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 ++iwithprefix_idx;
1220 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1221 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001222 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1223 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 ++iwithprefixbefore_idx;
1225 iwithprefixbefore_done =
1226 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1227 }
1228 }
1229 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001230
Nico Weber0fca0222008-08-22 09:25:22 +00001231 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001232
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001233 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001234 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001235 llvm::sys::Path::GetMainExecutable(Argv0,
1236 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001237 if (!MainExecutablePath.isEmpty()) {
1238 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1239 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001240
1241 // Get foo/lib/clang/1.0/include
1242 //
1243 // FIXME: Don't embed version here.
1244 MainExecutablePath.appendComponent("lib");
1245 MainExecutablePath.appendComponent("clang");
1246 MainExecutablePath.appendComponent("1.0");
1247 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001248
1249 // We pass true to ignore sysroot so that we *always* look for clang headers
1250 // relative to our executable, never relative to -isysroot.
1251 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1252 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001253 }
1254
Nico Weber0fca0222008-08-22 09:25:22 +00001255 if (!nostdinc)
1256 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001257
1258 // Now that we have collected all of the include paths, merge them all
1259 // together and tell the preprocessor about them.
1260
Nico Weber0fca0222008-08-22 09:25:22 +00001261 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001262}
1263
Chris Lattnere116ccf2009-04-21 05:40:52 +00001264void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1265{
1266 // Add macros from the command line.
1267 unsigned d = 0, D = D_macros.size();
1268 unsigned u = 0, U = U_macros.size();
1269 while (d < D || u < U) {
1270 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1271 InitOpts.addMacroDef(D_macros[d++]);
1272 else
1273 InitOpts.addMacroUndef(U_macros[u++]);
1274 }
1275
1276 // If -imacros are specified, include them now. These are processed before
1277 // any -include directives.
1278 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1279 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1280
1281 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1282 // We want to add these paths to the predefines buffer in order, make a
1283 // temporary vector to sort by their occurrence.
1284 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1285
1286 if (!ImplicitIncludePTH.empty())
1287 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1288 &ImplicitIncludePTH));
1289 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1290 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1291 &ImplicitIncludes[i]));
1292 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1293
1294
1295 // Now that they are ordered by position, add to the predefines buffer.
1296 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1297 std::string *Ptr = OrderedPaths[i].second;
1298 if (!ImplicitIncludes.empty() &&
1299 Ptr >= &ImplicitIncludes[0] &&
1300 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1301 InitOpts.addInclude(*Ptr, false);
1302 } else {
1303 assert(Ptr == &ImplicitIncludePTH);
1304 InitOpts.addInclude(*Ptr, true);
1305 }
1306 }
1307 }
1308}
1309
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001310//===----------------------------------------------------------------------===//
1311// Driver PreprocessorFactory - For lazily generating preprocessors ...
1312//===----------------------------------------------------------------------===//
1313
1314namespace {
1315class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001316 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001317 Diagnostic &Diags;
1318 const LangOptions &LangInfo;
1319 TargetInfo &Target;
1320 SourceManager &SourceMgr;
1321 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001322
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001323public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001324 DriverPreprocessorFactory(const std::string &infile,
1325 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001326 TargetInfo &target, SourceManager &SM,
1327 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001328 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001329 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001330
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001331
1332 virtual ~DriverPreprocessorFactory() {}
1333
1334 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001335 llvm::OwningPtr<PTHManager> PTHMgr;
1336
Ted Kremenek748d5d62009-03-20 00:26:38 +00001337 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1338 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1339 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001340 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001341 }
1342
Ted Kremenek72b1b152009-01-15 18:47:46 +00001343 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001344 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1345 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001346 PTHMgr.reset(PTHManager::Create(x, &Diags,
1347 TokenCache.empty() ? Diagnostic::Error
1348 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001349 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001350
Ted Kremenek22f0d092009-03-22 06:42:39 +00001351 if (Diags.hasErrorOccurred())
1352 exit(1);
1353
Ted Kremenek72b1b152009-01-15 18:47:46 +00001354 // Create the Preprocessor.
1355 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1356 SourceMgr, HeaderInfo,
1357 PTHMgr.get()));
1358
1359 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1360 // That argument is used as the IdentifierInfoLookup argument to
1361 // IdentifierTable's ctor.
1362 if (PTHMgr) {
1363 PTHMgr->setPreprocessor(PP.get());
1364 PP->setPTHManager(PTHMgr.take());
1365 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001366
Chris Lattnere116ccf2009-04-21 05:40:52 +00001367 PreprocessorInitOptions InitOpts;
1368 InitializePreprocessorInitOptions(InitOpts);
1369 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001370 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001371
Daniel Dunbar750c3582008-10-24 22:12:41 +00001372 /// FIXME: PP can only handle one callback
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001373 if (ProgAction != PrintPreprocessedInput) {
1374 std::string ErrStr;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001375 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
Daniel Dunbara5a7bd02009-03-30 00:34:04 +00001376 if (!DFG && !ErrStr.empty()) {
1377 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001378 return 0;
Daniel Dunbar750c3582008-10-24 22:12:41 +00001379 }
1380 }
1381
Douglas Gregore1d918e2009-04-10 23:10:45 +00001382 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001383 }
1384};
1385}
Reid Spencer5f016e22007-07-11 17:01:13 +00001386
Reid Spencer5f016e22007-07-11 17:01:13 +00001387//===----------------------------------------------------------------------===//
1388// Basic Parser driver
1389//===----------------------------------------------------------------------===//
1390
Chris Lattner51574ea2008-04-19 23:25:44 +00001391static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001393 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001394
1395 // Parsing the specified input file.
1396 P.ParseTranslationUnit();
1397 delete PA;
1398}
1399
1400//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001401// Code generation options
1402//===----------------------------------------------------------------------===//
1403
1404static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001405GenerateDebugInfo("g",
1406 llvm::cl::desc("Generate source level debug information"));
1407
Daniel Dunbara034ba82009-02-17 19:47:34 +00001408static llvm::cl::opt<std::string>
1409TargetCPU("mcpu",
1410 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1411
Chris Lattner7afae712009-03-16 18:41:18 +00001412static void InitializeCompileOptions(CompileOptions &Opts,
1413 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001414 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001415 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001416 if (OptSize) {
1417 // -Os implies -O2
1418 // FIXME: Diagnose conflicting options.
1419 Opts.OptimizationLevel = 2;
1420 } else {
1421 Opts.OptimizationLevel = OptLevel;
1422 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001423
1424 // FIXME: There are llvm-gcc options to control these selectively.
1425 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1426 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001427 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001428
1429#ifdef NDEBUG
1430 Opts.VerifyModule = 0;
1431#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001432
1433 Opts.CPU = TargetCPU;
1434 Opts.Features.insert(Opts.Features.end(),
1435 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001436
Chris Lattnerbd360642009-03-26 05:00:52 +00001437 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1438
Chris Lattner44502662009-02-18 01:23:44 +00001439 // Handle -ftime-report.
1440 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001441}
1442
1443//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001444// Fix-It Options
1445//===----------------------------------------------------------------------===//
1446static llvm::cl::list<ParsedSourceLocation>
1447FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1448 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1449
1450//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001451// -dump-build-information Stuff
1452//===----------------------------------------------------------------------===//
1453
1454static llvm::cl::opt<std::string>
1455DumpBuildInformation("dump-build-information",
1456 llvm::cl::value_desc("filename"),
1457 llvm::cl::desc("output a dump of some build information to a file"));
1458
1459static llvm::raw_ostream *BuildLogFile = 0;
1460
1461/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1462/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1463namespace {
1464class LoggingDiagnosticClient : public DiagnosticClient {
1465 llvm::OwningPtr<DiagnosticClient> Chain1;
1466 llvm::OwningPtr<DiagnosticClient> Chain2;
1467public:
1468
1469 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1470 // Output diags both where requested...
1471 Chain1.reset(Normal);
1472 // .. and to our log file.
1473 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1474 !NoShowColumn,
1475 !NoCaretDiagnostics,
1476 !NoShowLocation,
1477 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001478 PrintDiagnosticOption,
1479 !NoDiagnosticsFixIt));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001480 }
1481
1482 virtual void setLangOptions(const LangOptions *LO) {
1483 Chain1->setLangOptions(LO);
1484 Chain2->setLangOptions(LO);
1485 }
1486
1487 virtual bool IncludeInDiagnosticCounts() const {
1488 return Chain1->IncludeInDiagnosticCounts();
1489 }
1490
1491 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1492 const DiagnosticInfo &Info) {
1493 Chain1->HandleDiagnostic(DiagLevel, Info);
1494 Chain2->HandleDiagnostic(DiagLevel, Info);
1495 }
1496};
1497} // end anonymous namespace.
1498
1499static void SetUpBuildDumpLog(unsigned argc, char **argv,
1500 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1501
1502 std::string ErrorInfo;
1503 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1504 ErrorInfo);
1505
1506 if (!ErrorInfo.empty()) {
1507 llvm::errs() << "error opening -dump-build-information file '"
1508 << DumpBuildInformation << "', option ignored!\n";
1509 delete BuildLogFile;
1510 BuildLogFile = 0;
1511 DumpBuildInformation = "";
1512 return;
1513 }
1514
1515 (*BuildLogFile) << "clang-cc command line arguments: ";
1516 for (unsigned i = 0; i != argc; ++i)
1517 (*BuildLogFile) << argv[i] << ' ';
1518 (*BuildLogFile) << '\n';
1519
1520 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1521 // the diagnostic producers and the normal receiver.
1522 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1523}
1524
1525
1526
1527//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001528// Main driver
1529//===----------------------------------------------------------------------===//
1530
Ted Kremenekdb094a22007-12-05 18:27:04 +00001531/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001532/// action. These consumers can operate on both ASTs that are freshly
1533/// parsed from source files as well as those deserialized from Bitcode.
1534/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001535static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001536 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001537 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001538 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001539 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001540 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001541 default:
1542 return NULL;
1543
1544 case ASTPrint:
1545 return CreateASTPrinter();
1546
1547 case ASTDump:
1548 return CreateASTDumper();
1549
1550 case ASTView:
1551 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001552
Chris Lattner8a5c8092009-02-18 01:20:05 +00001553 case PrintDeclContext:
1554 return CreateDeclContextPrinter();
1555
1556 case EmitHTML:
1557 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001558
Chris Lattner8a5c8092009-02-18 01:20:05 +00001559 case InheritanceView:
1560 return CreateInheritanceViewer(InheritanceViewCls);
1561
1562 case TestSerialization:
1563 return CreateSerializationTest(Diag, FileMgr);
1564
1565 case EmitAssembly:
1566 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001567 case EmitBC:
1568 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001569 BackendAction Act;
1570 if (ProgAction == EmitAssembly)
1571 Act = Backend_EmitAssembly;
1572 else if (ProgAction == EmitLLVM)
1573 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001574 else if (ProgAction == EmitLLVMOnly)
1575 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001576 else
1577 Act = Backend_EmitBC;
1578
1579 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001580 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001581 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001582 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001583 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001584
Chris Lattner8a5c8092009-02-18 01:20:05 +00001585 case SerializeAST:
1586 // FIXME: Allow user to tailor where the file is written.
1587 return CreateASTSerializer(InFile, OutputFile, Diag);
1588
Douglas Gregor2cf26342009-04-09 22:27:44 +00001589 case GeneratePCH:
Chris Lattner0b1fb982009-04-10 17:15:23 +00001590 assert(PP && "Generate PCH doesn't work from serialized file yet");
1591 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001592
Chris Lattner8a5c8092009-02-18 01:20:05 +00001593 case RewriteObjC:
1594 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001595
Chris Lattner8a5c8092009-02-18 01:20:05 +00001596 case RewriteBlocks:
1597 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1598
1599 case RunAnalysis:
1600 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001601 }
1602}
1603
Reid Spencer5f016e22007-07-11 17:01:13 +00001604/// ProcessInputFile - Process a single input file with the specified state.
1605///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001606static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001607 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001608 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001609 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001610 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001611 bool CompleteTranslationUnit = true;
Douglas Gregor558cb562009-04-02 01:08:08 +00001612
Ted Kremenek85888962008-10-21 00:54:44 +00001613 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001615 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1616 PP.getFileManager(), PP.getLangOptions(),
1617 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001618
1619 if (!Consumer) {
1620 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001621 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001622 return;
1623 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001624
Douglas Gregorf807fe02009-04-14 16:27:31 +00001625 if (ProgAction == GeneratePCH)
1626 CompleteTranslationUnit = false;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001627 break;
1628
Chris Lattnerc106c102008-10-12 05:03:36 +00001629 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001630 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001631 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001632 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001633 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001634 RawLex.SetKeepWhitespaceMode(true);
1635
1636 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001637 RawLex.LexFromRawLexer(RawTok);
1638 while (RawTok.isNot(tok::eof)) {
1639 PP.DumpToken(RawTok, true);
1640 fprintf(stderr, "\n");
1641 RawLex.LexFromRawLexer(RawTok);
1642 }
1643 ClearSourceMgr = true;
1644 break;
1645 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001647 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001648 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001649 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001650 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 do {
1652 PP.Lex(Tok);
1653 PP.DumpToken(Tok, true);
1654 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001655 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001656 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 break;
1658 }
1659 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner47099742009-02-18 01:51:21 +00001660 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001661 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001663 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 do {
1665 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001666 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001667 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 break;
1669 }
Ted Kremenek85888962008-10-21 00:54:44 +00001670
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001671 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001672 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001673 CacheTokens(PP, OutputFile);
1674 ClearSourceMgr = true;
1675 break;
1676 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001677
Chris Lattner47099742009-02-18 01:51:21 +00001678 case PrintPreprocessedInput: { // -E mode.
1679 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnere988bc22008-01-27 23:55:11 +00001680 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001681 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 break;
Chris Lattner47099742009-02-18 01:51:21 +00001683 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001684
Chris Lattner47099742009-02-18 01:51:21 +00001685 case ParseNoop: { // -parse-noop
1686 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001687 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001688 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 break;
Chris Lattner47099742009-02-18 01:51:21 +00001690 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001691
Chris Lattner47099742009-02-18 01:51:21 +00001692 case ParsePrintCallbacks: {
1693 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001694 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001695 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 break;
Chris Lattner47099742009-02-18 01:51:21 +00001697 }
1698
1699 case ParseSyntaxOnly: { // -fsyntax-only
1700 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001701 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001702 break;
Chris Lattner47099742009-02-18 01:51:21 +00001703 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001704
1705 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001706 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001707 ClearSourceMgr = true;
1708 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001709
Chris Lattner47099742009-02-18 01:51:21 +00001710 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001711 DoRewriteTest(PP, InFile, OutputFile);
1712 ClearSourceMgr = true;
1713 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001714 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001715
1716 case FixIt:
1717 llvm::TimeRegion Timer(ClangFrontendTimer);
1718 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001719 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001720 PP.getSourceManager(),
1721 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001722 break;
Chris Lattner47099742009-02-18 01:51:21 +00001723 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001724
1725 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001726 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001727
Douglas Gregor26df2f02009-04-02 19:05:20 +00001728 if (FixItAtLocations.size() > 0) {
1729 // Even without the "-fixit" flag, with may have some specific
1730 // locations where the user has requested fixes. Process those
1731 // locations now.
1732 if (!FixItRewrite)
1733 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001734 PP.getSourceManager(),
1735 PP.getLangOptions());
Douglas Gregor26df2f02009-04-02 19:05:20 +00001736
1737 bool AddedFixitLocation = false;
1738 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1739 Idx != Last; ++Idx) {
1740 RequestedSourceLocation Requested;
1741 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1742 Requested)) {
1743 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1744 FixItAtLocations[Idx].FileName.c_str());
1745 } else {
1746 FixItRewrite->addFixItLocation(Requested);
1747 AddedFixitLocation = true;
1748 }
1749 }
1750
1751 if (!AddedFixitLocation) {
1752 // All of the fix-it locations were bad. Don't fix anything.
1753 delete FixItRewrite;
1754 FixItRewrite = 0;
1755 }
1756 }
1757
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001758 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1759 PP.getSourceManager(),
1760 PP.getTargetInfo(),
1761 PP.getIdentifierTable(),
1762 PP.getSelectorTable(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001763 /* FreeMemory = */ !DisableFree,
1764 /* size_reserve = */0,
1765 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001766
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767 if (!ImplicitIncludePCH.empty()) {
1768 // The user has asked us to include a precompiled header. Load
1769 // the precompiled header into the AST context.
Douglas Gregore1d918e2009-04-10 23:10:45 +00001770 llvm::OwningPtr<PCHReader> Reader(new PCHReader(PP, *ContextOwner.get()));
1771 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1772 case PCHReader::Success: {
1773 // Attach the PCH reader to the AST context as an external AST
1774 // source, so that declarations will be deserialized from the
1775 // PCH file as needed.
1776 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
1777 ContextOwner->setExternalSource(Source);
1778
1779 // Clear out the predefines buffer, because all of the
1780 // predefines are already in the PCH file.
1781 PP.setPredefines("");
1782 break;
1783 }
1784
1785 case PCHReader::Failure:
1786 // Unrecoverable failure: don't even try to process the input
1787 // file.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001788 return;
1789
Douglas Gregore1d918e2009-04-10 23:10:45 +00001790 case PCHReader::IgnorePCH:
1791 // No suitable PCH file could be found. Just ignore the
1792 // -include-pch option entirely.
Douglas Gregor2deaea32009-04-22 18:49:13 +00001793
1794 // We delayed the initialization of builtins in the hope of
1795 // loading the PCH file. Since the PCH file could not be
1796 // loaded, initialize builtins now.
1797 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001798 break;
1799 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001800
1801 // Finish preprocessor initialization. We do this now (rather
1802 // than earlier) because this initialization creates new source
1803 // location entries in the source manager, which must come after
1804 // the source location entries for the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +00001805 if (InitializeSourceManager(PP, InFile))
Douglas Gregor14f79002009-04-10 03:52:48 +00001806 return;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001807 }
1808
Douglas Gregorf807fe02009-04-14 16:27:31 +00001809 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1810 CompleteTranslationUnit);
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001811
Douglas Gregor558cb562009-04-02 01:08:08 +00001812 if (FixItRewrite)
1813 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1814
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001815 // If in -disable-free mode, don't deallocate these when they go out of
1816 // scope.
Chris Lattner3599dbe2009-03-28 04:13:34 +00001817 if (DisableFree)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001818 ContextOwner.take();
Ted Kremenek46157b52009-01-28 04:29:29 +00001819 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001820
1821 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001822 if (CheckDiagnostics(PP))
1823 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001824
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001826 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 PP.PrintStats();
1828 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001829 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001830 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001831 fprintf(stderr, "\n");
1832 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001833
1834 // For a multi-file compilation, some things are ok with nuking the source
1835 // manager tables, other require stable fileid/macroid's across multiple
1836 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001837 if (ClearSourceMgr)
1838 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001839
1840 if (DisableFree)
1841 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001842}
1843
Ted Kremenek20e97482007-12-12 23:41:08 +00001844static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1845 FileManager& FileMgr) {
1846
1847 if (VerifyDiagnostics) {
1848 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1849 exit (1);
1850 }
1851
1852 llvm::sys::Path Filename(InFile);
1853
1854 if (!Filename.isValid()) {
1855 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1856 exit (1);
1857 }
1858
Chris Lattner557c5b12009-03-28 04:27:18 +00001859 llvm::OwningPtr<ASTContext> Ctx;
Chris Lattner5f737cc2009-03-28 03:49:26 +00001860
1861 // Create the memory buffer that contains the contents of the file.
1862 llvm::OwningPtr<llvm::MemoryBuffer>
1863 MBuffer(llvm::MemoryBuffer::getFile(Filename.c_str()));
1864
1865 if (MBuffer)
Chris Lattner557c5b12009-03-28 04:27:18 +00001866 Ctx.reset(ASTContext::ReadASTBitcodeBuffer(*MBuffer, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001867
Chris Lattner557c5b12009-03-28 04:27:18 +00001868 if (!Ctx) {
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001869 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1870 InFile.c_str());
1871 exit (1);
1872 }
1873
Ted Kremenek63ea8632007-12-19 19:27:38 +00001874 // Observe that we use the source file name stored in the deserialized
1875 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001876 llvm::OwningPtr<ASTConsumer>
Chris Lattner557c5b12009-03-28 04:27:18 +00001877 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, Ctx->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001878 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001879
Ted Kremenek20e97482007-12-12 23:41:08 +00001880 if (!Consumer) {
1881 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1882 exit (1);
1883 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001884
Chris Lattner557c5b12009-03-28 04:27:18 +00001885 Consumer->Initialize(*Ctx);
Nico Weber7bfaaae2008-08-10 19:59:06 +00001886
Chris Lattnere66b65c2008-02-06 01:42:25 +00001887 // FIXME: We need to inform Consumer about completed TagDecls as well.
Chris Lattner557c5b12009-03-28 04:27:18 +00001888 TranslationUnitDecl *TUD = Ctx->getTranslationUnitDecl();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001889 for (DeclContext::decl_iterator I = TUD->decls_begin(*Ctx),
1890 E = TUD->decls_end(*Ctx);
Chris Lattner557c5b12009-03-28 04:27:18 +00001891 I != E; ++I)
Chris Lattner682bf922009-03-29 16:50:03 +00001892 Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
Ted Kremenek20e97482007-12-12 23:41:08 +00001893}
1894
1895
Reid Spencer5f016e22007-07-11 17:01:13 +00001896static llvm::cl::list<std::string>
1897InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1898
Ted Kremenek20e97482007-12-12 23:41:08 +00001899static bool isSerializedFile(const std::string& InFile) {
1900 if (InFile.size() < 4)
1901 return false;
1902
1903 const char* s = InFile.c_str()+InFile.size()-4;
Chris Lattnerf63aea32009-03-04 21:40:56 +00001904 return s[0] == '.' && s[1] == 'a' && s[2] == 's' && s[3] == 't';
Ted Kremenek20e97482007-12-12 23:41:08 +00001905}
1906
Reid Spencer5f016e22007-07-11 17:01:13 +00001907
1908int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001910 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001911 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001912 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001913
Chris Lattner47099742009-02-18 01:51:21 +00001914 if (TimeReport)
1915 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1916
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 // If no input was specified, read from stdin.
1918 if (InputFilenames.empty())
1919 InputFilenames.push_back("-");
Chris Lattnerb2509e12009-02-18 01:12:43 +00001920
Ted Kremenek31e703b2007-12-11 23:28:38 +00001921 // Create the diagnostic client for reporting errors or for
1922 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001923 llvm::OwningPtr<DiagnosticClient> DiagClient;
1924 if (VerifyDiagnostics) {
1925 // When checking diagnostics, just buffer them up.
1926 DiagClient.reset(new TextDiagnosticBuffer());
1927 if (InputFilenames.size() != 1) {
1928 fprintf(stderr, "-verify only works on single input files for now.\n");
1929 return 1;
1930 }
1931 if (!HTMLDiag.empty()) {
1932 fprintf(stderr, "-verify and -html-diags don't work together\n");
1933 return 1;
1934 }
1935 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001936 // Print diagnostics to stderr by default.
Chris Lattner409d4e72009-04-17 20:40:01 +00001937 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00001938 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001939 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001940 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00001941 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001942 PrintDiagnosticOption,
1943 !NoDiagnosticsFixIt));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001944 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00001945 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001947
1948 if (!DumpBuildInformation.empty()) {
1949 if (!HTMLDiag.empty()) {
1950 fprintf(stderr,
1951 "-dump-build-information and -html-diags don't work together\n");
1952 return 1;
1953 }
1954
1955 SetUpBuildDumpLog(argc, argv, DiagClient);
1956 }
1957
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001960 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001961 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001962 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001963
Chris Lattner4f037832007-12-05 23:24:17 +00001964 // -I- is a deprecated GCC feature, scan for it and reject it.
1965 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1966 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001967 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001968 I_dirs.erase(I_dirs.begin()+i);
1969 --i;
1970 }
1971 }
Chris Lattner11215192008-03-14 06:12:05 +00001972
1973 // Get information about the target being compiled for.
1974 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001975 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1976
Chris Lattner11215192008-03-14 06:12:05 +00001977 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001978 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1979 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001980 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001981 }
Chris Lattner4f037832007-12-05 23:24:17 +00001982
Daniel Dunbard4270232009-01-20 23:17:32 +00001983 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001984 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001985
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001986 llvm::OwningPtr<SourceManager> SourceMgr;
1987
Chris Lattner2c78b872009-04-14 23:22:57 +00001988 // Create a file manager object to provide access to and cache the filesystem.
1989 FileManager FileMgr;
1990
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001992 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001993
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001994 if (isSerializedFile(InFile)) {
Ted Kremenek20e97482007-12-12 23:41:08 +00001995 ProcessSerializedFile(InFile,Diags,FileMgr);
Chris Lattnerf63aea32009-03-04 21:40:56 +00001996 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001997 }
Chris Lattnerf63aea32009-03-04 21:40:56 +00001998
1999 /// Create a SourceManager object. This tracks and owns all the file
2000 /// buffers allocated to a translation unit.
2001 if (!SourceMgr)
2002 SourceMgr.reset(new SourceManager());
2003 else
2004 SourceMgr->clearIDTables();
2005
2006 // Initialize language options, inferring file types from input filenames.
2007 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002008 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00002009
Chris Lattnerf63aea32009-03-04 21:40:56 +00002010 InitializeBaseLanguage();
2011 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002012 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002013 InitializeLanguageStandard(LangInfo, LK, Target.get());
2014
2015 // Process the -I options and set them in the HeaderInfo.
2016 HeaderSearch HeaderInfo(FileMgr);
2017
Chris Lattner2c78b872009-04-14 23:22:57 +00002018
Chris Lattnerf63aea32009-03-04 21:40:56 +00002019 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2020
2021 // Set up the preprocessor with these options.
2022 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2023 *SourceMgr.get(), HeaderInfo);
2024
2025 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2026
2027 if (!PP)
2028 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002029
Douglas Gregore1d918e2009-04-10 23:10:45 +00002030 if (ImplicitIncludePCH.empty() &&
2031 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregor14f79002009-04-10 03:52:48 +00002032 continue;
2033
Chris Lattner409d4e72009-04-17 20:40:01 +00002034 if (!HTMLDiag.empty())
2035 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002036
2037 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002038 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002039
Chris Lattner40469652009-04-17 20:16:08 +00002040 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002041 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 }
Chris Lattner11215192008-03-14 06:12:05 +00002043
Mike Stump007f2a92009-01-28 02:43:35 +00002044 if (Verbose)
2045 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2046 " hosted on " LLVM_HOSTTRIPLE "\n");
2047
Ted Kremenek7a08e282008-08-07 18:13:12 +00002048 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2050 (NumDiagnostics == 1 ? "" : "s"));
2051
2052 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 FileMgr.PrintStats();
2054 fprintf(stderr, "\n");
2055 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002056
2057 delete ClangFrontendTimer;
2058 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00002059
Daniel Dunbar276373d2008-10-27 22:10:13 +00002060 // If verifying diagnostics and we reached here, all is well.
2061 if (VerifyDiagnostics)
2062 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00002063
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002064 // Managed static deconstruction. Useful for making things like
2065 // -time-passes usable.
2066 llvm::llvm_shutdown();
2067
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002068 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002069}