blob: 9fa0d79e691bdcf86af9f99a507c63862463460c [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenek377a3192009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor133d2552009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattner94269d72009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000036#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000037#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000038#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000039#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000040#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000041#include "clang/AST/ASTContext.h"
42#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000043#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000044#include "clang/Parse/Parser.h"
45#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000046#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000047#include "clang/Basic/FileManager.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/TargetInfo.h"
Daniel Dunbarae81a792009-05-06 04:07:06 +000050#include "clang/Basic/Version.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000051#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000052#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000053#include "llvm/ADT/StringExtras.h"
Daniel Dunbar07181d72009-05-06 03:16:41 +000054#include "llvm/ADT/StringMap.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000055#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000056#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000057#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000058#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000059#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000060#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000061#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000062#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000063#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000064#include "llvm/System/Path.h"
Douglas Gregor3dd11e82009-05-03 03:52:38 +000065#include "llvm/System/Process.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000066#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000067#include <cstdlib>
Douglas Gregor3dd11e82009-05-03 03:52:38 +000068#if HAVE_SYS_TYPES_H
Douglas Gregor965a13c2009-05-02 00:03:46 +000069# include <sys/types.h>
70#endif
Douglas Gregor24b48b02009-04-02 19:05:20 +000071
Chris Lattner4b009652007-07-25 00:24:17 +000072using namespace clang;
73
74//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000075// Source Location Parser
76//===----------------------------------------------------------------------===//
77
78/// \brief A source location that has been parsed on the command line.
79struct ParsedSourceLocation {
80 std::string FileName;
81 unsigned Line;
82 unsigned Column;
83
84 /// \brief Try to resolve the file name of a parsed source location.
85 ///
86 /// \returns true if there was an error, false otherwise.
87 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
88};
89
90bool
91ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
92 RequestedSourceLocation &Result) {
93 const FileEntry *File = FileMgr.getFile(FileName);
94 if (!File)
95 return true;
96
97 Result.File = File;
98 Result.Line = Line;
99 Result.Column = Column;
100 return false;
101}
102
103namespace llvm {
104 namespace cl {
105 /// \brief Command-line option parser that parses source locations.
106 ///
107 /// Source locations are of the form filename:line:column.
108 template<>
109 class parser<ParsedSourceLocation>
110 : public basic_parser<ParsedSourceLocation> {
111 public:
112 bool parse(Option &O, const char *ArgName,
113 const std::string &ArgValue,
114 ParsedSourceLocation &Val);
115 };
116
117 bool
118 parser<ParsedSourceLocation>::
119 parse(Option &O, const char *ArgName, const std::string &ArgValue,
120 ParsedSourceLocation &Val) {
121 using namespace clang;
122
123 const char *ExpectedFormat
124 = "source location must be of the form filename:line:column";
125 std::string::size_type SecondColon = ArgValue.rfind(':');
126 if (SecondColon == std::string::npos) {
127 std::fprintf(stderr, "%s\n", ExpectedFormat);
128 return true;
129 }
130 char *EndPtr;
131 long Column
132 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
133 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
134 std::fprintf(stderr, "%s\n", ExpectedFormat);
135 return true;
136 }
137
138 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
139 if (SecondColon == std::string::npos) {
140 std::fprintf(stderr, "%s\n", ExpectedFormat);
141 return true;
142 }
143 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
144 if (EndPtr != ArgValue.c_str() + SecondColon) {
145 std::fprintf(stderr, "%s\n", ExpectedFormat);
146 return true;
147 }
148
149 Val.FileName = ArgValue.substr(0, FirstColon);
150 Val.Line = Line;
151 Val.Column = Column;
152 return false;
153 }
154 }
155}
156
157//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000158// Global options.
159//===----------------------------------------------------------------------===//
160
Chris Lattnerefe33382009-02-18 01:51:21 +0000161/// ClangFrontendTimer - The front-end activities should charge time to it with
162/// TimeRegion. The -ftime-report option controls whether this will do
163/// anything.
164llvm::Timer *ClangFrontendTimer = 0;
165
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000166static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000167
Chris Lattner4b009652007-07-25 00:24:17 +0000168static llvm::cl::opt<bool>
169Verbose("v", llvm::cl::desc("Enable verbose output"));
170static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000171Stats("print-stats",
172 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000173static llvm::cl::opt<bool>
174DisableFree("disable-free",
175 llvm::cl::desc("Disable freeing of memory on exit"),
176 llvm::cl::init(false));
Daniel Dunbarbb56def2009-04-27 21:19:07 +0000177static llvm::cl::opt<bool>
178EmptyInputOnly("empty-input-only",
179 llvm::cl::desc("Force running on an empty input file"));
Chris Lattner4b009652007-07-25 00:24:17 +0000180
181enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000182 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000183 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000184 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000185 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000186 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000187 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000188 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000189 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000190 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000191 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000192 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000193 ASTPrint, // Parse ASTs and print them.
194 ASTDump, // Parse ASTs and dump them.
Douglas Gregord7915fd2009-04-26 02:02:08 +0000195 ASTDumpFull, // Parse ASTs and dump them, including the
196 // contents of a PCH file.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000197 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000198 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000199 ParsePrintCallbacks, // Parse and print each callback.
200 ParseSyntaxOnly, // Parse and perform semantic analysis.
201 ParseNoop, // Parse with noop callbacks.
202 RunPreprocessorOnly, // Just lex, no output.
203 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000204 DumpTokens, // Dump out preprocessed tokens.
205 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000206 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000207 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000208 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000209 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000210};
211
212static llvm::cl::opt<ProgActions>
213ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
214 llvm::cl::init(ParseSyntaxOnly),
215 llvm::cl::values(
216 clEnumValN(RunPreprocessorOnly, "Eonly",
217 "Just run preprocessor, no output (for timings)"),
218 clEnumValN(PrintPreprocessedInput, "E",
219 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000220 clEnumValN(DumpRawTokens, "dump-raw-tokens",
221 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000222 clEnumValN(RunAnalysis, "analyze",
223 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000224 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000225 "Run preprocessor, dump internal rep of tokens"),
226 clEnumValN(ParseNoop, "parse-noop",
227 "Run parser with noop callbacks (for timings)"),
228 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
229 "Run parser and perform semantic analysis"),
230 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
231 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000232 clEnumValN(EmitHTML, "emit-html",
233 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000234 clEnumValN(ASTPrint, "ast-print",
235 "Build ASTs and then pretty-print them"),
236 clEnumValN(ASTDump, "ast-dump",
237 "Build ASTs and then debug dump them"),
Douglas Gregord7915fd2009-04-26 02:02:08 +0000238 clEnumValN(ASTDumpFull, "ast-dump-full",
239 "Build ASTs and then debug dump them, including PCH"),
Chris Lattner664dd082007-10-11 00:37:43 +0000240 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000241 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000242 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000243 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000244 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000245 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000246 clEnumValN(GeneratePCH, "emit-pch",
247 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000248 clEnumValN(EmitAssembly, "S",
249 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000250 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000251 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000252 clEnumValN(EmitBC, "emit-llvm-bc",
253 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000254 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
255 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000256 clEnumValN(RewriteTest, "rewrite-test",
257 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000258 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000259 "Rewrite ObjC into C (code rewriter example)"),
260 clEnumValN(RewriteMacros, "rewrite-macros",
261 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000262 clEnumValN(RewriteBlocks, "rewrite-blocks",
263 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000264 clEnumValN(FixIt, "fixit",
265 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000266 clEnumValEnd));
267
Ted Kremenekd01eae62007-12-19 19:47:59 +0000268
269static llvm::cl::opt<std::string>
270OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000271 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000272 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000273
Ted Kremenek57f25b22008-12-02 19:57:31 +0000274
275//===----------------------------------------------------------------------===//
276// PTH.
277//===----------------------------------------------------------------------===//
278
279static llvm::cl::opt<std::string>
280TokenCache("token-cache", llvm::cl::value_desc("path"),
281 llvm::cl::desc("Use specified token cache file"));
282
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000283//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000284// Diagnostic Options
285//===----------------------------------------------------------------------===//
286
Ted Kremenek10389cf2007-09-26 19:42:19 +0000287static llvm::cl::opt<bool>
288VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000289 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000290
Ted Kremenekfd75e312008-03-27 06:17:42 +0000291static llvm::cl::opt<std::string>
292HTMLDiag("html-diags",
293 llvm::cl::desc("Generate HTML to report diagnostics"),
294 llvm::cl::value_desc("HTML directory"));
295
Nico Weber0e13eaa2008-08-05 23:33:20 +0000296static llvm::cl::opt<bool>
297NoShowColumn("fno-show-column",
298 llvm::cl::desc("Do not include column number on diagnostics"));
299
300static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000301NoShowLocation("fno-show-source-location",
302 llvm::cl::desc("Do not include source location information with"
303 " diagnostics"));
304
305static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000306NoCaretDiagnostics("fno-caret-diagnostics",
307 llvm::cl::desc("Do not include source line and caret with"
308 " diagnostics"));
309
Chris Lattner695a4f52009-03-13 01:08:23 +0000310static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000311NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
312 llvm::cl::desc("Do not include fixit information in"
313 " diagnostics"));
314
315static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000316PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
317 llvm::cl::desc("Print source range spans in numeric form"));
318
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000319static llvm::cl::opt<bool>
320PrintDiagnosticOption("fdiagnostics-show-option",
321 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000322
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000323static llvm::cl::opt<unsigned>
324MessageLength("fmessage-length",
325 llvm::cl::desc("Format message diagnostics so that they fit "
326 "within N columns or fewer, when possible."),
327 llvm::cl::value_desc("N"));
328
Chris Lattner4b009652007-07-25 00:24:17 +0000329//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000330// C++ Visualization.
331//===----------------------------------------------------------------------===//
332
333static llvm::cl::opt<std::string>
334InheritanceViewCls("cxx-inheritance-view",
335 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000336 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000337
338//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000339// Builtin Options
340//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000341
342static llvm::cl::opt<bool>
343TimeReport("ftime-report",
344 llvm::cl::desc("Print the amount of time each "
345 "phase of compilation takes"));
346
Douglas Gregor23d23262009-02-14 20:49:29 +0000347static llvm::cl::opt<bool>
348Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000349 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000350 "freestanding environment"));
351
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000352static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000353AllowBuiltins("fbuiltin", llvm::cl::init(true),
354 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000355
356
357static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000358MathErrno("fmath-errno", llvm::cl::init(true),
359 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000360
Douglas Gregor23d23262009-02-14 20:49:29 +0000361//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000362// Language Options
363//===----------------------------------------------------------------------===//
364
365enum LangKind {
366 langkind_unspecified,
367 langkind_c,
368 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000369 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000370 langkind_cxx,
371 langkind_cxx_cpp,
372 langkind_objc,
373 langkind_objc_cpp,
374 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000375 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000376};
377
Chris Lattner4b009652007-07-25 00:24:17 +0000378static llvm::cl::opt<LangKind>
379BaseLang("x", llvm::cl::desc("Base language to compile"),
380 llvm::cl::init(langkind_unspecified),
381 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
382 clEnumValN(langkind_cxx, "c++", "C++"),
383 clEnumValN(langkind_objc, "objective-c", "Objective C"),
384 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000385 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000386 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000387 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
388 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000389 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000390 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000391 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
392 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000393 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000394 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000395 clEnumValN(langkind_c, "c-header",
396 "C header"),
397 clEnumValN(langkind_objc, "objective-c-header",
398 "Objective-C header"),
399 clEnumValN(langkind_cxx, "c++-header",
400 "C++ header"),
401 clEnumValN(langkind_objcxx, "objective-c++-header",
402 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000403 clEnumValEnd));
404
405static llvm::cl::opt<bool>
406LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
407 llvm::cl::Hidden);
408static llvm::cl::opt<bool>
409LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
410 llvm::cl::Hidden);
411
Chris Lattnere1be6022009-04-14 23:22:57 +0000412static llvm::cl::opt<bool>
413ObjCExclusiveGC("fobjc-gc-only",
414 llvm::cl::desc("Use GC exclusively for Objective-C related "
415 "memory management"));
416
417static llvm::cl::opt<bool>
418ObjCEnableGC("fobjc-gc",
419 llvm::cl::desc("Enable Objective-C garbage collection"));
420
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000421static llvm::cl::opt<bool>
422ObjCEnableGCBitmapPrint("print-ivar-layout",
423 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
424
Chris Lattnere1be6022009-04-14 23:22:57 +0000425static llvm::cl::opt<LangOptions::VisibilityMode>
426SymbolVisibility("fvisibility",
427 llvm::cl::desc("Set the default symbol visibility:"),
428 llvm::cl::init(LangOptions::Default),
429 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
430 "Use default symbol visibility"),
431 clEnumValN(LangOptions::Hidden, "hidden",
432 "Use hidden symbol visibility"),
433 clEnumValN(LangOptions::Protected,"protected",
434 "Use protected symbol visibility"),
435 clEnumValEnd));
436
437static llvm::cl::opt<bool>
438OverflowChecking("ftrapv",
439 llvm::cl::desc("Trap on integer overflow"),
440 llvm::cl::init(false));
441
442
Ted Kremenek11ad8952007-12-05 23:49:08 +0000443/// InitializeBaseLanguage - Handle the -x foo options.
444static void InitializeBaseLanguage() {
445 if (LangObjC)
446 BaseLang = langkind_objc;
447 else if (LangObjCXX)
448 BaseLang = langkind_objcxx;
449}
450
451static LangKind GetLanguage(const std::string &Filename) {
452 if (BaseLang != langkind_unspecified)
453 return BaseLang;
454
455 std::string::size_type DotPos = Filename.rfind('.');
456
457 if (DotPos == std::string::npos) {
458 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000459 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000460 }
461
Ted Kremenek11ad8952007-12-05 23:49:08 +0000462 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
463 // C header: .h
464 // C++ header: .hh or .H;
465 // assembler no preprocessing: .s
466 // assembler: .S
467 if (Ext == "c")
468 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000469 else if (Ext == "S" ||
470 // If the compiler is run on a .s file, preprocess it as .S
471 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000472 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000473 else if (Ext == "i")
474 return langkind_c_cpp;
475 else if (Ext == "ii")
476 return langkind_cxx_cpp;
477 else if (Ext == "m")
478 return langkind_objc;
479 else if (Ext == "mi")
480 return langkind_objc_cpp;
481 else if (Ext == "mm" || Ext == "M")
482 return langkind_objcxx;
483 else if (Ext == "mii")
484 return langkind_objcxx_cpp;
485 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
486 Ext == "c++" || Ext == "cp" || Ext == "cxx")
487 return langkind_cxx;
488 else
489 return langkind_c;
490}
491
492
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000493static void InitializeCOptions(LangOptions &Options) {
494 // Do nothing.
495}
496
497static void InitializeObjCOptions(LangOptions &Options) {
498 Options.ObjC1 = Options.ObjC2 = 1;
499}
500
501
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000502static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000503 // FIXME: implement -fpreprocessed mode.
504 bool NoPreprocess = false;
505
Ted Kremenek11ad8952007-12-05 23:49:08 +0000506 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000507 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000508 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000509 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000510 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000511 case langkind_c_cpp:
512 NoPreprocess = true;
513 // FALLTHROUGH
514 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000515 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000516 break;
517 case langkind_cxx_cpp:
518 NoPreprocess = true;
519 // FALLTHROUGH
520 case langkind_cxx:
521 Options.CPlusPlus = 1;
522 break;
523 case langkind_objc_cpp:
524 NoPreprocess = true;
525 // FALLTHROUGH
526 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000527 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000528 break;
529 case langkind_objcxx_cpp:
530 NoPreprocess = true;
531 // FALLTHROUGH
532 case langkind_objcxx:
533 Options.ObjC1 = Options.ObjC2 = 1;
534 Options.CPlusPlus = 1;
535 break;
536 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000537
538 if (ObjCExclusiveGC)
539 Options.setGCMode(LangOptions::GCOnly);
540 else if (ObjCEnableGC)
541 Options.setGCMode(LangOptions::HybridGC);
542
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000543 if (ObjCEnableGCBitmapPrint)
544 Options.ObjCGCBitmapPrint = 1;
545
Chris Lattnere1be6022009-04-14 23:22:57 +0000546 Options.setVisibilityMode(SymbolVisibility);
547 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000548}
549
550/// LangStds - Language standards we support.
551enum LangStds {
552 lang_unspecified,
553 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000554 lang_gnu_START,
555 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000556 lang_cxx98, lang_gnucxx98,
557 lang_cxx0x, lang_gnucxx0x
558};
559
560static llvm::cl::opt<LangStds>
561LangStd("std", llvm::cl::desc("Language standard to compile for"),
562 llvm::cl::init(lang_unspecified),
563 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
564 clEnumValN(lang_c89, "c90", "ISO C 1990"),
565 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
566 clEnumValN(lang_c94, "iso9899:199409",
567 "ISO C 1990 with amendment 1"),
568 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000569 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000570 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000571 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000572 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000573 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000574 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000575 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000576 clEnumValN(lang_gnu99, "gnu9x",
577 "ISO C 1999 with GNU extensions"),
578 clEnumValN(lang_cxx98, "c++98",
579 "ISO C++ 1998 with amendments"),
580 clEnumValN(lang_gnucxx98, "gnu++98",
581 "ISO C++ 1998 with amendments and GNU "
582 "extensions (default for C++)"),
583 clEnumValN(lang_cxx0x, "c++0x",
584 "Upcoming ISO C++ 200x with amendments"),
585 clEnumValN(lang_gnucxx0x, "gnu++0x",
586 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000587 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000588 clEnumValEnd));
589
590static llvm::cl::opt<bool>
591NoOperatorNames("fno-operator-names",
592 llvm::cl::desc("Do not treat C++ operator name keywords as "
593 "synonyms for operators"));
594
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000595static llvm::cl::opt<bool>
596PascalStrings("fpascal-strings",
597 llvm::cl::desc("Recognize and construct Pascal-style "
598 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000599
600static llvm::cl::opt<bool>
601MSExtensions("fms-extensions",
602 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000603 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000604
605static llvm::cl::opt<bool>
606WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000607 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000608
609static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000610NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000611 llvm::cl::desc("Disallow implicit conversions between "
612 "vectors with a different number of "
613 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000614
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000615static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000616EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000617
618static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000619EnableHeinousExtensions("fheinous-gnu-extensions",
620 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
621 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
622
623static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000624ObjCNonFragileABI("fobjc-nonfragile-abi",
625 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000626
Daniel Dunbar5523e862009-05-04 05:16:21 +0000627
628static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000629EmitAllDecls("femit-all-decls",
630 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000631
Daniel Dunbar91692d92008-08-11 17:36:14 +0000632static llvm::cl::opt<bool>
633Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000634 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000635
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000636static llvm::cl::opt<bool>
637GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000638 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000639 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000640
641static llvm::cl::opt<bool>
642NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000643 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000644 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000645
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000646
647
648static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000649Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000650
Douglas Gregor375733c2009-03-10 00:06:19 +0000651static llvm::cl::opt<unsigned>
652TemplateDepth("ftemplate-depth", llvm::cl::init(99),
653 llvm::cl::desc("Maximum depth of recursive template "
654 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000655static llvm::cl::opt<bool>
656DollarsInIdents("fdollars-in-identifiers",
657 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000658
Anders Carlssondfd77642009-04-06 17:37:10 +0000659
660static llvm::cl::opt<bool>
661OptSize("Os", llvm::cl::desc("Optimize for size"));
662
663static llvm::cl::opt<bool>
664NoCommon("fno-common",
665 llvm::cl::desc("Compile common globals like normal definitions"),
666 llvm::cl::ValueDisallowed);
667
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000668static llvm::cl::opt<std::string>
669MainFileName("main-file-name",
670 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000671
672// It might be nice to add bounds to the CommandLine library directly.
673struct OptLevelParser : public llvm::cl::parser<unsigned> {
674 bool parse(llvm::cl::Option &O, const char *ArgName,
675 const std::string &Arg, unsigned &Val) {
676 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
677 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000678 if (Val > 3)
679 return O.error(": '" + Arg + "' invalid optimization level!");
680 return false;
681 }
682};
683static llvm::cl::opt<unsigned, false, OptLevelParser>
684OptLevel("O", llvm::cl::Prefix,
685 llvm::cl::desc("Optimization level"),
686 llvm::cl::init(0));
687
Daniel Dunbare079c712009-04-08 03:03:23 +0000688static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000689PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
690
691static llvm::cl::opt<bool>
692StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000693
Daniel Dunbar34542952008-08-23 08:43:39 +0000694static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000695 TargetInfo *Target,
696 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000697 // Allow the target to set the default the langauge options as it sees fit.
698 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000699
700 // Pass the map of target features to the target for validation and
701 // processing.
702 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000703
Chris Lattner4b009652007-07-25 00:24:17 +0000704 if (LangStd == lang_unspecified) {
705 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000706 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000707 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000708 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000709 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000710 case langkind_c_cpp:
711 case langkind_objc:
712 case langkind_objc_cpp:
713 LangStd = lang_gnu99;
714 break;
715 case langkind_cxx:
716 case langkind_cxx_cpp:
717 case langkind_objcxx:
718 case langkind_objcxx_cpp:
719 LangStd = lang_gnucxx98;
720 break;
721 }
722 }
723
724 switch (LangStd) {
725 default: assert(0 && "Unknown language standard!");
726
727 // Fall through from newer standards to older ones. This isn't really right.
728 // FIXME: Enable specifically the right features based on the language stds.
729 case lang_gnucxx0x:
730 case lang_cxx0x:
731 Options.CPlusPlus0x = 1;
732 // FALL THROUGH
733 case lang_gnucxx98:
734 case lang_cxx98:
735 Options.CPlusPlus = 1;
736 Options.CXXOperatorNames = !NoOperatorNames;
737 // FALL THROUGH.
738 case lang_gnu99:
739 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000740 Options.C99 = 1;
741 Options.HexFloats = 1;
742 // FALL THROUGH.
743 case lang_gnu89:
744 Options.BCPLComment = 1; // Only for C99/C++.
745 // FALL THROUGH.
746 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000747 Options.Digraphs = 1; // C94, C99, C++.
748 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000749 case lang_c89:
750 break;
751 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000752
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000753 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
754 Options.GNUMode = LangStd >= lang_gnu_START;
755
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000756 if (Options.CPlusPlus) {
757 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000758 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000759 }
Chris Lattner4b009652007-07-25 00:24:17 +0000760
Chris Lattner6ab935b2008-04-05 06:32:51 +0000761 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
762 Options.ImplicitInt = 1;
763 else
764 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000765
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000766 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
767 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000768 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000769 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000770 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000771
Chris Lattner58d5ba52008-12-05 00:10:44 +0000772 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
773 // even if they are normally on for the target. In GNU modes (e.g.
774 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000775 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000776 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000777 Options.Blocks = 0;
778
Chris Lattner284784c2009-04-19 07:06:52 +0000779 // Default to not accepting '$' in identifiers when preprocessing assembler,
780 // but do accept when preprocessing C. FIXME: these defaults are right for
781 // darwin, are they right everywhere?
782 Options.DollarIdents = LK != langkind_asm_cpp;
783 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000784 Options.DollarIdents = DollarsInIdents;
785
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000786 if (PascalStrings.getPosition())
787 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000788 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000789 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000790 if (NoLaxVectorConversions.getPosition())
791 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000792 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000793 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000794 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000795
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000796 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000797 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000798 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000799 Options.Freestanding = Options.NoBuiltin = 1;
800
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000801 if (EnableHeinousExtensions)
802 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000803
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000804 Options.MathErrno = MathErrno;
805
Douglas Gregor375733c2009-03-10 00:06:19 +0000806 Options.InstantiationDepth = TemplateDepth;
807
Chris Lattnerddae7102008-12-04 22:54:33 +0000808 // Override the default runtime if the user requested it.
809 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000810 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000811 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000812 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000813
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000814 if (ObjCNonFragileABI)
815 Options.ObjCNonFragileABI = 1;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000816
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000817 if (EmitAllDecls)
818 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000819
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000820 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
821 // support.
822 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000823
824 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000825 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000826 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000827
828 assert(PICLevel <= 2 && "Invalid value for -pic-level");
829 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000830
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000831 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000832 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000833 Options.NoInline = !OptSize && !OptLevel;
834
835 Options.Static = StaticDefine;
836
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000837 if (MainFileName.getPosition())
838 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000839}
840
841//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000842// Target Triple Processing.
843//===----------------------------------------------------------------------===//
844
845static llvm::cl::opt<std::string>
846TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000847 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000848
Chris Lattnerfc457002008-03-05 01:18:20 +0000849static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000850Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000851
Chris Lattner2b168e02008-09-30 01:13:12 +0000852static llvm::cl::opt<std::string>
853MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000854 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000855
Chris Lattner01de9c82008-09-30 20:16:56 +0000856// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
857// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000858
859// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000860static void HandleMacOSVersionMin(std::string &Triple) {
861 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
862 if (DarwinDashIdx == std::string::npos) {
863 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000864 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000865 exit(1);
866 }
867 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
868
Chris Lattner01de9c82008-09-30 20:16:56 +0000869 // Remove the number.
870 Triple.resize(DarwinNumIdx);
871
872 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
873 bool MacOSVersionMinIsInvalid = false;
874 int VersionNum = 0;
875 if (MacOSVersionMin.size() < 4 ||
876 MacOSVersionMin.substr(0, 3) != "10." ||
877 !isdigit(MacOSVersionMin[3])) {
878 MacOSVersionMinIsInvalid = true;
879 } else {
880 const char *Start = MacOSVersionMin.c_str()+3;
881 char *End = 0;
882 VersionNum = (int)strtol(Start, &End, 10);
883
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000884 // The version number must be in the range 0-9.
885 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
886
Chris Lattner01de9c82008-09-30 20:16:56 +0000887 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
888 Triple += llvm::itostr(VersionNum+4);
889
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000890 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
891 // Add the period piece (.7) to the end of the triple. This gives us
892 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000893 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000894 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
895 MacOSVersionMinIsInvalid = true;
896 }
897 }
898
899 if (MacOSVersionMinIsInvalid) {
900 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000901 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000902 MacOSVersionMin.c_str());
903 exit(1);
904 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000905 else if (VersionNum <= 4 &&
906 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
907 fprintf(stderr,
908 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
909 MacOSVersionMin.c_str());
910 exit(1);
911 }
912
Chris Lattner01de9c82008-09-30 20:16:56 +0000913}
914
Daniel Dunbar93f64532009-04-10 19:52:24 +0000915static llvm::cl::opt<std::string>
916IPhoneOSVersionMin("miphoneos-version-min",
917 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
918
919// If -miphoneos-version-min=2.2 is specified, change the triple from being
920// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
921// 9 as the default major Darwin number, and encode the iPhone OS version
922// number in the minor version and revision.
923
924// FIXME: We should have the driver do this instead.
925static void HandleIPhoneOSVersionMin(std::string &Triple) {
926 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
927 if (DarwinDashIdx == std::string::npos) {
928 fprintf(stderr,
929 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
930 exit(1);
931 }
932 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
933
934 // Remove the number.
935 Triple.resize(DarwinNumIdx);
936
937 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
938 bool IPhoneOSVersionMinIsInvalid = false;
939 int VersionNum = 0;
940 if (IPhoneOSVersionMin.size() < 3 ||
941 !isdigit(IPhoneOSVersionMin[0])) {
942 IPhoneOSVersionMinIsInvalid = true;
943 } else {
944 const char *Start = IPhoneOSVersionMin.c_str();
945 char *End = 0;
946 VersionNum = (int)strtol(Start, &End, 10);
947
948 // The version number must be in the range 0-9.
949 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
950
951 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
952 Triple += "9." + llvm::itostr(VersionNum);
953
954 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
955 // Add the period piece (.2) to the end of the triple. This gives us
956 // something like ...-darwin9.2.2
957 Triple += End;
958 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
959 IPhoneOSVersionMinIsInvalid = true;
960 }
961 }
962
963 if (IPhoneOSVersionMinIsInvalid) {
964 fprintf(stderr,
965 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
966 IPhoneOSVersionMin.c_str());
967 exit(1);
968 }
969}
970
Chris Lattner01de9c82008-09-30 20:16:56 +0000971/// CreateTargetTriple - Process the various options that affect the target
972/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000973static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000974 // Initialize base triple. If a -triple option has been specified, use
975 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000976 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000977 if (Triple.empty())
978 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000979
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000980 // If -arch foo was specified, remove the architecture from the triple we have
981 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000982
983 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000984 if (!Arch.empty()) {
985 // Decompose the base triple into "arch" and suffix.
986 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000987
Chris Lattner2b168e02008-09-30 01:13:12 +0000988 if (FirstDashIdx == std::string::npos) {
989 fprintf(stderr,
990 "Malformed target triple: \"%s\" ('-' could not be found).\n",
991 Triple.c_str());
992 exit(1);
993 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +0000994
995 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
996 if (Arch == "ppc")
997 Arch = "powerpc";
998 else if (Arch == "ppc64")
999 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001000
Chris Lattner2b168e02008-09-30 01:13:12 +00001001 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1002 }
1003
1004 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1005 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001006 if (!MacOSVersionMin.empty())
1007 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001008 else if (!IPhoneOSVersionMin.empty())
1009 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001010
Chris Lattner2b168e02008-09-30 01:13:12 +00001011 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001012}
1013
1014//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001015// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001016//===----------------------------------------------------------------------===//
1017
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001018static bool InitializeSourceManager(Preprocessor &PP,
1019 const std::string &InFile) {
1020 // Figure out where to get and map in the main file.
1021 SourceManager &SourceMgr = PP.getSourceManager();
1022 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001023
1024 if (EmptyInputOnly) {
1025 const char *EmptyStr = "";
1026 llvm::MemoryBuffer *SB =
1027 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1028 SourceMgr.createMainFileIDForMemBuffer(SB);
1029 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001030 const FileEntry *File = FileMgr.getFile(InFile);
1031 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1032 if (SourceMgr.getMainFileID().isInvalid()) {
1033 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1034 << InFile.c_str();
1035 return true;
1036 }
1037 } else {
1038 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1039
1040 // If stdin was empty, SB is null. Cons up an empty memory
1041 // buffer now.
1042 if (!SB) {
1043 const char *EmptyStr = "";
1044 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1045 }
1046
1047 SourceMgr.createMainFileIDForMemBuffer(SB);
1048 if (SourceMgr.getMainFileID().isInvalid()) {
1049 PP.getDiagnostics().Report(FullSourceLoc(),
1050 diag::err_fe_error_reading_stdin);
1051 return true;
1052 }
1053 }
1054
1055 return false;
1056}
1057
Chris Lattner47b6a162008-04-19 23:09:31 +00001058
Chris Lattner94269d72009-04-21 05:40:52 +00001059//===----------------------------------------------------------------------===//
1060// Preprocessor Initialization
1061//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001062
Chris Lattner94269d72009-04-21 05:40:52 +00001063// FIXME: Preprocessor builtins to support.
1064// -A... - Play with #assertions
1065// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001066
Chris Lattner94269d72009-04-21 05:40:52 +00001067static llvm::cl::list<std::string>
1068D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1069 llvm::cl::desc("Predefine the specified macro"));
1070static llvm::cl::list<std::string>
1071U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1072 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001073
Chris Lattner94269d72009-04-21 05:40:52 +00001074static llvm::cl::list<std::string>
1075ImplicitIncludes("include", llvm::cl::value_desc("file"),
1076 llvm::cl::desc("Include file before parsing"));
1077static llvm::cl::list<std::string>
1078ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1079 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001080
Chris Lattner94269d72009-04-21 05:40:52 +00001081static llvm::cl::opt<std::string>
1082ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1083 llvm::cl::desc("Include precompiled header file"));
1084
1085static llvm::cl::opt<std::string>
1086ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1087 llvm::cl::desc("Include file before parsing"));
1088
Chris Lattner4b009652007-07-25 00:24:17 +00001089
1090//===----------------------------------------------------------------------===//
1091// Preprocessor include path information.
1092//===----------------------------------------------------------------------===//
1093
1094// This tool exports a large number of command line options to control how the
1095// preprocessor searches for header files. At root, however, the Preprocessor
1096// object takes a very simple interface: a list of directories to search for
1097//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001098// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001099// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001100//
Chris Lattner4b009652007-07-25 00:24:17 +00001101
1102static llvm::cl::opt<bool>
1103nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1104
1105// Various command line options. These four add directories to each chain.
1106static llvm::cl::list<std::string>
1107F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1108 llvm::cl::desc("Add directory to framework include search path"));
1109static llvm::cl::list<std::string>
1110I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1111 llvm::cl::desc("Add directory to include search path"));
1112static llvm::cl::list<std::string>
1113idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1114 llvm::cl::desc("Add directory to AFTER include search path"));
1115static llvm::cl::list<std::string>
1116iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1117 llvm::cl::desc("Add directory to QUOTE include search path"));
1118static llvm::cl::list<std::string>
1119isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1120 llvm::cl::desc("Add directory to SYSTEM include search path"));
1121
1122// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1123static llvm::cl::list<std::string>
1124iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1125 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1126static llvm::cl::list<std::string>
1127iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1128 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1129static llvm::cl::list<std::string>
1130iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1131 llvm::cl::Prefix,
1132 llvm::cl::desc("Set directory to include search path with prefix"));
1133
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001134static llvm::cl::opt<std::string>
1135isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1136 llvm::cl::desc("Set the system root directory (usually /)"));
1137
Chris Lattner4b009652007-07-25 00:24:17 +00001138// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001139
Chris Lattner4b009652007-07-25 00:24:17 +00001140/// InitializeIncludePaths - Process the -I options and set them in the
1141/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001142void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1143 FileManager &FM, const LangOptions &Lang) {
1144 InitHeaderSearch Init(Headers, Verbose, isysroot);
1145
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001146 // Handle -I... and -F... options, walking the lists in parallel.
1147 unsigned Iidx = 0, Fidx = 0;
1148 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1149 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001150 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001151 ++Iidx;
1152 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001153 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001154 ++Fidx;
1155 }
1156 }
Chris Lattner4b009652007-07-25 00:24:17 +00001157
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001158 // Consume what's left from whatever list was longer.
1159 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001160 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001161 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001162 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001163
1164 // Handle -idirafter... options.
1165 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001166 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1167 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001168
1169 // Handle -iquote... options.
1170 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001171 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001172
1173 // Handle -isystem... options.
1174 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001175 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001176
1177 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1178 // parallel, processing the values in order of occurance to get the right
1179 // prefixes.
1180 {
1181 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1182 unsigned iprefix_idx = 0;
1183 unsigned iwithprefix_idx = 0;
1184 unsigned iwithprefixbefore_idx = 0;
1185 bool iprefix_done = iprefix_vals.empty();
1186 bool iwithprefix_done = iwithprefix_vals.empty();
1187 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1188 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1189 if (!iprefix_done &&
1190 (iwithprefix_done ||
1191 iprefix_vals.getPosition(iprefix_idx) <
1192 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1193 (iwithprefixbefore_done ||
1194 iprefix_vals.getPosition(iprefix_idx) <
1195 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1196 Prefix = iprefix_vals[iprefix_idx];
1197 ++iprefix_idx;
1198 iprefix_done = iprefix_idx == iprefix_vals.size();
1199 } else if (!iwithprefix_done &&
1200 (iwithprefixbefore_done ||
1201 iwithprefix_vals.getPosition(iwithprefix_idx) <
1202 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001203 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1204 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001205 ++iwithprefix_idx;
1206 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1207 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001208 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1209 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001210 ++iwithprefixbefore_idx;
1211 iwithprefixbefore_done =
1212 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1213 }
1214 }
1215 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001216
Nico Weber770e3882008-08-22 09:25:22 +00001217 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001218
Daniel Dunbar4e604292009-02-21 20:52:41 +00001219 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001220 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001221 llvm::sys::Path::GetMainExecutable(Argv0,
1222 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001223 if (!MainExecutablePath.isEmpty()) {
1224 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1225 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001226
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001227 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001228 MainExecutablePath.appendComponent("lib");
1229 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001230 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001231 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001232
1233 // We pass true to ignore sysroot so that we *always* look for clang headers
1234 // relative to our executable, never relative to -isysroot.
1235 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1236 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001237 }
1238
Nico Weber770e3882008-08-22 09:25:22 +00001239 if (!nostdinc)
1240 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001241
1242 // Now that we have collected all of the include paths, merge them all
1243 // together and tell the preprocessor about them.
1244
Nico Weber770e3882008-08-22 09:25:22 +00001245 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001246}
1247
Chris Lattner94269d72009-04-21 05:40:52 +00001248void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1249{
1250 // Add macros from the command line.
1251 unsigned d = 0, D = D_macros.size();
1252 unsigned u = 0, U = U_macros.size();
1253 while (d < D || u < U) {
1254 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1255 InitOpts.addMacroDef(D_macros[d++]);
1256 else
1257 InitOpts.addMacroUndef(U_macros[u++]);
1258 }
1259
1260 // If -imacros are specified, include them now. These are processed before
1261 // any -include directives.
1262 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1263 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1264
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001265 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1266 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner94269d72009-04-21 05:40:52 +00001267 // We want to add these paths to the predefines buffer in order, make a
1268 // temporary vector to sort by their occurrence.
1269 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1270
1271 if (!ImplicitIncludePTH.empty())
1272 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1273 &ImplicitIncludePTH));
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001274 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1275 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1276 &ImplicitIncludePCH));
Chris Lattner94269d72009-04-21 05:40:52 +00001277 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1278 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1279 &ImplicitIncludes[i]));
1280 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1281
1282
1283 // Now that they are ordered by position, add to the predefines buffer.
1284 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1285 std::string *Ptr = OrderedPaths[i].second;
1286 if (!ImplicitIncludes.empty() &&
1287 Ptr >= &ImplicitIncludes[0] &&
1288 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1289 InitOpts.addInclude(*Ptr, false);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001290 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner94269d72009-04-21 05:40:52 +00001291 InitOpts.addInclude(*Ptr, true);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001292 } else {
1293 // We end up here when we're producing preprocessed output and
1294 // we loaded a PCH file. In this case, just include the header
1295 // file that was used to build the precompiled header.
1296 assert(Ptr == &ImplicitIncludePCH);
1297 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1298 if (!OriginalFile.empty()) {
1299 InitOpts.addInclude(OriginalFile, false);
1300 ImplicitIncludePCH.clear();
1301 }
Chris Lattner94269d72009-04-21 05:40:52 +00001302 }
1303 }
1304 }
1305}
1306
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001307//===----------------------------------------------------------------------===//
1308// Driver PreprocessorFactory - For lazily generating preprocessors ...
1309//===----------------------------------------------------------------------===//
1310
1311namespace {
1312class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001313 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001314 Diagnostic &Diags;
1315 const LangOptions &LangInfo;
1316 TargetInfo &Target;
1317 SourceManager &SourceMgr;
1318 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001319
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001320public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001321 DriverPreprocessorFactory(const std::string &infile,
1322 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001323 TargetInfo &target, SourceManager &SM,
1324 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001325 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001326 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001327
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001328
1329 virtual ~DriverPreprocessorFactory() {}
1330
1331 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001332 llvm::OwningPtr<PTHManager> PTHMgr;
1333
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001334 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1335 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1336 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001337 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001338 }
1339
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001340 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001341 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1342 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001343 PTHMgr.reset(PTHManager::Create(x, &Diags,
1344 TokenCache.empty() ? Diagnostic::Error
1345 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001346 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001347
Ted Kremenek6348cc62009-03-22 06:42:39 +00001348 if (Diags.hasErrorOccurred())
1349 exit(1);
1350
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001351 // Create the Preprocessor.
1352 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1353 SourceMgr, HeaderInfo,
1354 PTHMgr.get()));
1355
1356 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1357 // That argument is used as the IdentifierInfoLookup argument to
1358 // IdentifierTable's ctor.
1359 if (PTHMgr) {
1360 PTHMgr->setPreprocessor(PP.get());
1361 PP->setPTHManager(PTHMgr.take());
1362 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001363
Chris Lattner94269d72009-04-21 05:40:52 +00001364 PreprocessorInitOptions InitOpts;
1365 InitializePreprocessorInitOptions(InitOpts);
1366 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001367 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001368
Daniel Dunbarebfb1bc2009-05-03 09:35:25 +00001369 std::string ErrStr;
1370 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1371 if (!DFG && !ErrStr.empty()) {
1372 fprintf(stderr, "%s", ErrStr.c_str());
1373 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001374 }
1375
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001376 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001377 }
1378};
1379}
Chris Lattner4b009652007-07-25 00:24:17 +00001380
Chris Lattner4b009652007-07-25 00:24:17 +00001381//===----------------------------------------------------------------------===//
1382// Basic Parser driver
1383//===----------------------------------------------------------------------===//
1384
Chris Lattner9d818a22008-04-19 23:25:44 +00001385static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001386 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001387 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001388
1389 // Parsing the specified input file.
1390 P.ParseTranslationUnit();
1391 delete PA;
1392}
1393
1394//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001395// Code generation options
1396//===----------------------------------------------------------------------===//
1397
1398static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001399GenerateDebugInfo("g",
1400 llvm::cl::desc("Generate source level debug information"));
1401
Daniel Dunbar9101a632009-02-17 19:47:34 +00001402static llvm::cl::opt<std::string>
1403TargetCPU("mcpu",
1404 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1405
Daniel Dunbar07181d72009-05-06 03:16:41 +00001406static llvm::cl::list<std::string>
1407TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1408
1409/// ComputeTargetFeatures - Recompute the target feature list to only
1410/// be the list of things that are enabled, based on the target cpu
1411/// and feature list.
1412static void ComputeFeatureMap(TargetInfo *Target,
1413 llvm::StringMap<bool> &Features) {
1414 assert(Features.empty() && "invalid map");
1415
1416 // Initialize the feature map based on the target.
1417 Target->getDefaultFeatures(TargetCPU, Features);
1418
1419 // Apply the user specified deltas.
1420 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1421 ie = TargetFeatures.end(); it != ie; ++it) {
1422 const char *Name = it->c_str();
1423
1424 // FIXME: Don't handle errors like this.
1425 if (Name[0] != '-' && Name[0] != '+') {
1426 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1427 Name);
1428 exit(1);
1429 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001430 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1431 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1432 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001433 exit(1);
1434 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001435 }
1436}
1437
Chris Lattner8a9615c2009-03-16 18:41:18 +00001438static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001439 const LangOptions &LangOpts,
1440 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001441 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001442 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001443 if (OptSize) {
1444 // -Os implies -O2
1445 // FIXME: Diagnose conflicting options.
1446 Opts.OptimizationLevel = 2;
1447 } else {
1448 Opts.OptimizationLevel = OptLevel;
1449 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001450
1451 // FIXME: There are llvm-gcc options to control these selectively.
1452 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1453 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001454 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001455
1456#ifdef NDEBUG
1457 Opts.VerifyModule = 0;
1458#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001459
1460 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001461 Opts.Features.clear();
1462 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1463 ie = Features.end(); it != ie; ++it) {
1464 // FIXME: If we are completely confident that we have the right
1465 // set, we only need to pass the minuses.
1466 std::string Name(it->second ? "+" : "-");
1467 Name += it->first();
1468 Opts.Features.push_back(Name);
1469 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001470
Chris Lattnerf04a7562009-03-26 05:00:52 +00001471 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1472
Chris Lattnere8f70712009-02-18 01:23:44 +00001473 // Handle -ftime-report.
1474 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001475}
1476
1477//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001478// Fix-It Options
1479//===----------------------------------------------------------------------===//
1480static llvm::cl::list<ParsedSourceLocation>
1481FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1482 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1483
1484//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001485// -dump-build-information Stuff
1486//===----------------------------------------------------------------------===//
1487
1488static llvm::cl::opt<std::string>
1489DumpBuildInformation("dump-build-information",
1490 llvm::cl::value_desc("filename"),
1491 llvm::cl::desc("output a dump of some build information to a file"));
1492
1493static llvm::raw_ostream *BuildLogFile = 0;
1494
1495/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1496/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1497namespace {
1498class LoggingDiagnosticClient : public DiagnosticClient {
1499 llvm::OwningPtr<DiagnosticClient> Chain1;
1500 llvm::OwningPtr<DiagnosticClient> Chain2;
1501public:
1502
1503 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1504 // Output diags both where requested...
1505 Chain1.reset(Normal);
1506 // .. and to our log file.
1507 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1508 !NoShowColumn,
1509 !NoCaretDiagnostics,
1510 !NoShowLocation,
1511 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001512 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001513 !NoDiagnosticsFixIt,
1514 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001515 }
1516
1517 virtual void setLangOptions(const LangOptions *LO) {
1518 Chain1->setLangOptions(LO);
1519 Chain2->setLangOptions(LO);
1520 }
1521
1522 virtual bool IncludeInDiagnosticCounts() const {
1523 return Chain1->IncludeInDiagnosticCounts();
1524 }
1525
1526 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1527 const DiagnosticInfo &Info) {
1528 Chain1->HandleDiagnostic(DiagLevel, Info);
1529 Chain2->HandleDiagnostic(DiagLevel, Info);
1530 }
1531};
1532} // end anonymous namespace.
1533
1534static void SetUpBuildDumpLog(unsigned argc, char **argv,
1535 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1536
1537 std::string ErrorInfo;
1538 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1539 ErrorInfo);
1540
1541 if (!ErrorInfo.empty()) {
1542 llvm::errs() << "error opening -dump-build-information file '"
1543 << DumpBuildInformation << "', option ignored!\n";
1544 delete BuildLogFile;
1545 BuildLogFile = 0;
1546 DumpBuildInformation = "";
1547 return;
1548 }
1549
1550 (*BuildLogFile) << "clang-cc command line arguments: ";
1551 for (unsigned i = 0; i != argc; ++i)
1552 (*BuildLogFile) << argv[i] << ' ';
1553 (*BuildLogFile) << '\n';
1554
1555 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1556 // the diagnostic producers and the normal receiver.
1557 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1558}
1559
1560
1561
1562//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001563// Main driver
1564//===----------------------------------------------------------------------===//
1565
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001566/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001567/// action. These consumers can operate on both ASTs that are freshly
1568/// parsed from source files as well as those deserialized from Bitcode.
1569/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001570static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001571 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001572 const LangOptions& LangOpts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001573 const llvm::StringMap<bool>& Features,
Chris Lattner21f72d62008-04-16 06:11:58 +00001574 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001575 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001576 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001577 default:
1578 return NULL;
1579
1580 case ASTPrint:
1581 return CreateASTPrinter();
1582
1583 case ASTDump:
Douglas Gregord7915fd2009-04-26 02:02:08 +00001584 return CreateASTDumper(false);
1585
1586 case ASTDumpFull:
1587 return CreateASTDumper(true);
Chris Lattner7f902922009-02-18 01:20:05 +00001588
1589 case ASTView:
1590 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001591
Chris Lattner7f902922009-02-18 01:20:05 +00001592 case PrintDeclContext:
1593 return CreateDeclContextPrinter();
1594
1595 case EmitHTML:
1596 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001597
Chris Lattner7f902922009-02-18 01:20:05 +00001598 case InheritanceView:
1599 return CreateInheritanceViewer(InheritanceViewCls);
1600
Chris Lattner7f902922009-02-18 01:20:05 +00001601 case EmitAssembly:
1602 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001603 case EmitBC:
1604 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001605 BackendAction Act;
1606 if (ProgAction == EmitAssembly)
1607 Act = Backend_EmitAssembly;
1608 else if (ProgAction == EmitLLVM)
1609 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001610 else if (ProgAction == EmitLLVMOnly)
1611 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001612 else
1613 Act = Backend_EmitBC;
1614
1615 CompileOptions Opts;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001616 InitializeCompileOptions(Opts, LangOpts, Features);
Chris Lattner7f902922009-02-18 01:20:05 +00001617 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001618 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001619 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001620
Douglas Gregorc34897d2009-04-09 22:27:44 +00001621 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001622 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001623
Chris Lattner7f902922009-02-18 01:20:05 +00001624 case RewriteObjC:
1625 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001626
Chris Lattner7f902922009-02-18 01:20:05 +00001627 case RewriteBlocks:
1628 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1629
1630 case RunAnalysis:
1631 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001632 }
1633}
1634
Chris Lattner4b009652007-07-25 00:24:17 +00001635/// ProcessInputFile - Process a single input file with the specified state.
1636///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001637static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001638 const std::string &InFile, ProgActions PA,
1639 const llvm::StringMap<bool> &Features) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001640 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001641 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001642 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001643 bool CompleteTranslationUnit = true;
Douglas Gregor133d2552009-04-02 01:08:08 +00001644
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001645 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001646 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001647 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1648 PP.getFileManager(), PP.getLangOptions(),
Daniel Dunbar07181d72009-05-06 03:16:41 +00001649 Features, &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001650
1651 if (!Consumer) {
1652 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001653 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001654 return;
1655 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001656
Douglas Gregore0d5c562009-04-14 16:27:31 +00001657 if (ProgAction == GeneratePCH)
1658 CompleteTranslationUnit = false;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001659 break;
1660
Chris Lattneraf669fb2008-10-12 05:03:36 +00001661 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001662 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001663 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001664 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001665 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001666 RawLex.SetKeepWhitespaceMode(true);
1667
1668 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001669 RawLex.LexFromRawLexer(RawTok);
1670 while (RawTok.isNot(tok::eof)) {
1671 PP.DumpToken(RawTok, true);
1672 fprintf(stderr, "\n");
1673 RawLex.LexFromRawLexer(RawTok);
1674 }
1675 ClearSourceMgr = true;
1676 break;
1677 }
Chris Lattner4b009652007-07-25 00:24:17 +00001678 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001679 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001680 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001681 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001682 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001683 do {
1684 PP.Lex(Tok);
1685 PP.DumpToken(Tok, true);
1686 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001687 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001688 ClearSourceMgr = true;
1689 break;
1690 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001691 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001692 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001693
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001694 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001695 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001696 CacheTokens(PP, OutputFile);
1697 ClearSourceMgr = true;
1698 break;
1699 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001700
Chris Lattner772a7c12009-04-27 22:02:30 +00001701 case PrintPreprocessedInput:
Chris Lattner4b009652007-07-25 00:24:17 +00001702 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001703
Chris Lattner270d29a2009-04-27 21:45:14 +00001704 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001705 break;
1706
Chris Lattnerefe33382009-02-18 01:51:21 +00001707 case ParsePrintCallbacks: {
1708 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001709 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001710 ClearSourceMgr = true;
1711 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001712 }
1713
1714 case ParseSyntaxOnly: { // -fsyntax-only
1715 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001716 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001717 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001718 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001719
1720 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001721 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001722 ClearSourceMgr = true;
1723 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001724
Chris Lattnerefe33382009-02-18 01:51:21 +00001725 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001726 DoRewriteTest(PP, InFile, OutputFile);
1727 ClearSourceMgr = true;
1728 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001729 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001730
1731 case FixIt:
1732 llvm::TimeRegion Timer(ClangFrontendTimer);
1733 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001734 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001735 PP.getSourceManager(),
1736 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001737 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001738 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001739
Chris Lattner38a4f182009-04-27 21:25:27 +00001740 if (FixItAtLocations.size() > 0) {
1741 // Even without the "-fixit" flag, with may have some specific
1742 // locations where the user has requested fixes. Process those
1743 // locations now.
1744 if (!FixItRewrite)
1745 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1746 PP.getSourceManager(),
1747 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001748
Chris Lattner38a4f182009-04-27 21:25:27 +00001749 bool AddedFixitLocation = false;
1750 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1751 Idx != Last; ++Idx) {
1752 RequestedSourceLocation Requested;
1753 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1754 Requested)) {
1755 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1756 FixItAtLocations[Idx].FileName.c_str());
1757 } else {
1758 FixItRewrite->addFixItLocation(Requested);
1759 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001760 }
1761 }
1762
Chris Lattner38a4f182009-04-27 21:25:27 +00001763 if (!AddedFixitLocation) {
1764 // All of the fix-it locations were bad. Don't fix anything.
1765 delete FixItRewrite;
1766 FixItRewrite = 0;
1767 }
1768 }
1769
1770 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001771 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001772 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1773 PP.getSourceManager(),
1774 PP.getTargetInfo(),
1775 PP.getIdentifierTable(),
1776 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001777 /* FreeMemory = */ !DisableFree,
1778 /* size_reserve = */0,
1779 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00001780 llvm::OwningPtr<PCHReader> Reader;
1781 llvm::OwningPtr<ExternalASTSource> Source;
1782
Chris Lattner270d29a2009-04-27 21:45:14 +00001783 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001784 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1785
Chris Lattner270d29a2009-04-27 21:45:14 +00001786 // The user has asked us to include a precompiled header. Load
1787 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001788 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1789 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00001790 // Set the predefines buffer as suggested by the PCH
1791 // reader. Typically, the predefines buffer will be empty.
1792 PP.setPredefines(Reader->getSuggestedPredefines());
1793
Chris Lattner270d29a2009-04-27 21:45:14 +00001794 // Attach the PCH reader to the AST context as an external AST
1795 // source, so that declarations will be deserialized from the
1796 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00001797 if (ContextOwner) {
1798 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001799 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00001800 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001801 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001802 }
1803
Chris Lattner270d29a2009-04-27 21:45:14 +00001804 case PCHReader::Failure:
1805 // Unrecoverable failure: don't even try to process the input
1806 // file.
1807 return;
1808
1809 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001810 // No suitable PCH file could be found. Return an error.
1811 return;
1812
1813#if 0
1814 // FIXME: We can recover from failed attempts to load PCH
1815 // files. This code will do so, if we ever want to enable it.
1816
Chris Lattner270d29a2009-04-27 21:45:14 +00001817 // We delayed the initialization of builtins in the hope of
1818 // loading the PCH file. Since the PCH file could not be
1819 // loaded, initialize builtins now.
1820 if (ContextOwner)
1821 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001822#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00001823 }
1824
1825 // Finish preprocessor initialization. We do this now (rather
1826 // than earlier) because this initialization creates new source
1827 // location entries in the source manager, which must come after
1828 // the source location entries for the PCH file.
1829 if (InitializeSourceManager(PP, InFile))
1830 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00001831 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001832
Chris Lattner270d29a2009-04-27 21:45:14 +00001833
1834 // If we have an ASTConsumer, run the parser with it.
1835 if (Consumer)
1836 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1837 CompleteTranslationUnit);
1838
1839 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
1840 llvm::TimeRegion Timer(ClangFrontendTimer);
1841 Token Tok;
1842 // Start parsing the specified input file.
1843 PP.EnterMainSourceFile();
1844 do {
1845 PP.Lex(Tok);
1846 } while (Tok.isNot(tok::eof));
1847 ClearSourceMgr = true;
1848 } else if (PA == ParseNoop) { // -parse-noop
1849 llvm::TimeRegion Timer(ClangFrontendTimer);
1850 ParseFile(PP, new MinimalAction(PP));
1851 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00001852 } else if (PA == PrintPreprocessedInput){ // -E mode.
1853 llvm::TimeRegion Timer(ClangFrontendTimer);
1854 DoPrintPreprocessedInput(PP, OutputFile);
1855 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00001856 }
1857
Chris Lattner38a4f182009-04-27 21:25:27 +00001858 if (FixItRewrite)
1859 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1860
1861 // If in -disable-free mode, don't deallocate ASTContext.
1862 if (DisableFree)
1863 ContextOwner.take();
1864 else
1865 ContextOwner.reset(); // Delete ASTContext
1866
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001867 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001868 if (CheckDiagnostics(PP))
1869 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001870
Chris Lattner4b009652007-07-25 00:24:17 +00001871 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001872 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001873 PP.PrintStats();
1874 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001875 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001876 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001877 fprintf(stderr, "\n");
1878 }
1879
1880 // For a multi-file compilation, some things are ok with nuking the source
1881 // manager tables, other require stable fileid/macroid's across multiple
1882 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001883 if (ClearSourceMgr)
1884 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001885
1886 if (DisableFree)
1887 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001888}
1889
1890static llvm::cl::list<std::string>
1891InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1892
Chris Lattner4b009652007-07-25 00:24:17 +00001893int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001894 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001895 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001896 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001897 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001898
Chris Lattnerefe33382009-02-18 01:51:21 +00001899 if (TimeReport)
1900 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1901
Chris Lattner4b009652007-07-25 00:24:17 +00001902 // If no input was specified, read from stdin.
1903 if (InputFilenames.empty())
1904 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00001905
Ted Kremenekb240e822007-12-11 23:28:38 +00001906 // Create the diagnostic client for reporting errors or for
1907 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00001908 llvm::OwningPtr<DiagnosticClient> DiagClient;
1909 if (VerifyDiagnostics) {
1910 // When checking diagnostics, just buffer them up.
1911 DiagClient.reset(new TextDiagnosticBuffer());
1912 if (InputFilenames.size() != 1) {
1913 fprintf(stderr, "-verify only works on single input files for now.\n");
1914 return 1;
1915 }
1916 if (!HTMLDiag.empty()) {
1917 fprintf(stderr, "-verify and -html-diags don't work together\n");
1918 return 1;
1919 }
1920 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00001921 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00001922
1923 // If -fmessage-length=N was not specified, determine whether this
1924 // is a terminal and, if so, implicitly define -fmessage-length
1925 // appropriately.
1926 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00001927 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00001928
Chris Lattner5f7937d2009-04-17 20:40:01 +00001929 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00001930 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001931 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001932 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00001933 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001934 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001935 !NoDiagnosticsFixIt,
1936 MessageLength));
Ted Kremenek5c341732008-08-07 17:49:57 +00001937 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00001938 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00001939 }
Chris Lattner94859302009-04-17 21:05:01 +00001940
1941 if (!DumpBuildInformation.empty()) {
1942 if (!HTMLDiag.empty()) {
1943 fprintf(stderr,
1944 "-dump-build-information and -html-diags don't work together\n");
1945 return 1;
1946 }
1947
1948 SetUpBuildDumpLog(argc, argv, DiagClient);
1949 }
1950
Ted Kremenek5c341732008-08-07 17:49:57 +00001951
Chris Lattner4b009652007-07-25 00:24:17 +00001952 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001953 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001954 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001955 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001956
Chris Lattner45a56e02007-12-05 23:24:17 +00001957 // -I- is a deprecated GCC feature, scan for it and reject it.
1958 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1959 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001960 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001961 I_dirs.erase(I_dirs.begin()+i);
1962 --i;
1963 }
1964 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001965
1966 // Get information about the target being compiled for.
1967 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001968 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1969
Chris Lattner2c77d852008-03-14 06:12:05 +00001970 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001971 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1972 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001973 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001974 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001975
Daniel Dunbar9c321102009-01-20 23:17:32 +00001976 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001977 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001978
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001979 llvm::OwningPtr<SourceManager> SourceMgr;
1980
Chris Lattnere1be6022009-04-14 23:22:57 +00001981 // Create a file manager object to provide access to and cache the filesystem.
1982 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001983
Daniel Dunbar07181d72009-05-06 03:16:41 +00001984 // Compute the feature set, unfortunately this effects the language!
1985 llvm::StringMap<bool> Features;
1986 ComputeFeatureMap(Target.get(), Features);
1987
Chris Lattner4b009652007-07-25 00:24:17 +00001988 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001989 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001990
Chris Lattner2b989562009-03-04 21:40:56 +00001991 /// Create a SourceManager object. This tracks and owns all the file
1992 /// buffers allocated to a translation unit.
1993 if (!SourceMgr)
1994 SourceMgr.reset(new SourceManager());
1995 else
1996 SourceMgr->clearIDTables();
1997
1998 // Initialize language options, inferring file types from input filenames.
1999 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002000 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002001
Chris Lattner2b989562009-03-04 21:40:56 +00002002 InitializeBaseLanguage();
2003 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002004 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002005 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002006
2007 // Process the -I options and set them in the HeaderInfo.
2008 HeaderSearch HeaderInfo(FileMgr);
2009
Chris Lattnere1be6022009-04-14 23:22:57 +00002010
Chris Lattner2b989562009-03-04 21:40:56 +00002011 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2012
2013 // Set up the preprocessor with these options.
2014 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2015 *SourceMgr.get(), HeaderInfo);
2016
2017 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2018
2019 if (!PP)
2020 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002021
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002022 if (ImplicitIncludePCH.empty() &&
2023 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002024 continue;
2025
Chris Lattner5f7937d2009-04-17 20:40:01 +00002026 if (!HTMLDiag.empty())
2027 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002028
2029 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002030 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002031
Chris Lattner2961dc52009-04-17 20:16:08 +00002032 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002033 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002034 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002035
Mike Stump91d01352009-01-28 02:43:35 +00002036 if (Verbose)
2037 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2038 " hosted on " LLVM_HOSTTRIPLE "\n");
2039
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002040 if (!NoCaretDiagnostics)
2041 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2042 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2043 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002044
2045 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002046 FileMgr.PrintStats();
2047 fprintf(stderr, "\n");
2048 }
Chris Lattner94859302009-04-17 21:05:01 +00002049
2050 delete ClangFrontendTimer;
2051 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002052
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002053 // If verifying diagnostics and we reached here, all is well.
2054 if (VerifyDiagnostics)
2055 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002056
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002057 // Managed static deconstruction. Useful for making things like
2058 // -time-passes usable.
2059 llvm::llvm_shutdown();
2060
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002061 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002062}