blob: 12a537b5cb253a813c42d8b2da7bde1d5b291b3b [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"
Chris Lattner01de9c82008-09-30 20:16:56 +000050#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000051#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000052#include "llvm/ADT/StringExtras.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000054#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000055#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000056#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000057#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000058#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000059#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000060#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000061#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000062#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000063#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000064#include <cstdlib>
65
Chris Lattner4b009652007-07-25 00:24:17 +000066using namespace clang;
67
68//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000069// Source Location Parser
70//===----------------------------------------------------------------------===//
71
72/// \brief A source location that has been parsed on the command line.
73struct ParsedSourceLocation {
74 std::string FileName;
75 unsigned Line;
76 unsigned Column;
77
78 /// \brief Try to resolve the file name of a parsed source location.
79 ///
80 /// \returns true if there was an error, false otherwise.
81 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
82};
83
84bool
85ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
86 RequestedSourceLocation &Result) {
87 const FileEntry *File = FileMgr.getFile(FileName);
88 if (!File)
89 return true;
90
91 Result.File = File;
92 Result.Line = Line;
93 Result.Column = Column;
94 return false;
95}
96
97namespace llvm {
98 namespace cl {
99 /// \brief Command-line option parser that parses source locations.
100 ///
101 /// Source locations are of the form filename:line:column.
102 template<>
103 class parser<ParsedSourceLocation>
104 : public basic_parser<ParsedSourceLocation> {
105 public:
106 bool parse(Option &O, const char *ArgName,
107 const std::string &ArgValue,
108 ParsedSourceLocation &Val);
109 };
110
111 bool
112 parser<ParsedSourceLocation>::
113 parse(Option &O, const char *ArgName, const std::string &ArgValue,
114 ParsedSourceLocation &Val) {
115 using namespace clang;
116
117 const char *ExpectedFormat
118 = "source location must be of the form filename:line:column";
119 std::string::size_type SecondColon = ArgValue.rfind(':');
120 if (SecondColon == std::string::npos) {
121 std::fprintf(stderr, "%s\n", ExpectedFormat);
122 return true;
123 }
124 char *EndPtr;
125 long Column
126 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
127 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
128 std::fprintf(stderr, "%s\n", ExpectedFormat);
129 return true;
130 }
131
132 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
133 if (SecondColon == std::string::npos) {
134 std::fprintf(stderr, "%s\n", ExpectedFormat);
135 return true;
136 }
137 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
138 if (EndPtr != ArgValue.c_str() + SecondColon) {
139 std::fprintf(stderr, "%s\n", ExpectedFormat);
140 return true;
141 }
142
143 Val.FileName = ArgValue.substr(0, FirstColon);
144 Val.Line = Line;
145 Val.Column = Column;
146 return false;
147 }
148 }
149}
150
151//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000152// Global options.
153//===----------------------------------------------------------------------===//
154
Chris Lattnerefe33382009-02-18 01:51:21 +0000155/// ClangFrontendTimer - The front-end activities should charge time to it with
156/// TimeRegion. The -ftime-report option controls whether this will do
157/// anything.
158llvm::Timer *ClangFrontendTimer = 0;
159
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000160static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000161
Chris Lattner4b009652007-07-25 00:24:17 +0000162static llvm::cl::opt<bool>
163Verbose("v", llvm::cl::desc("Enable verbose output"));
164static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000165Stats("print-stats",
166 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000167static llvm::cl::opt<bool>
168DisableFree("disable-free",
169 llvm::cl::desc("Disable freeing of memory on exit"),
170 llvm::cl::init(false));
Daniel Dunbarbb56def2009-04-27 21:19:07 +0000171static llvm::cl::opt<bool>
172EmptyInputOnly("empty-input-only",
173 llvm::cl::desc("Force running on an empty input file"));
Chris Lattner4b009652007-07-25 00:24:17 +0000174
175enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000176 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000177 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000178 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000179 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000180 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000181 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000182 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000183 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000184 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000185 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000186 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000187 ASTPrint, // Parse ASTs and print them.
188 ASTDump, // Parse ASTs and dump them.
Douglas Gregord7915fd2009-04-26 02:02:08 +0000189 ASTDumpFull, // Parse ASTs and dump them, including the
190 // contents of a PCH file.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000191 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000192 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000193 ParsePrintCallbacks, // Parse and print each callback.
194 ParseSyntaxOnly, // Parse and perform semantic analysis.
195 ParseNoop, // Parse with noop callbacks.
196 RunPreprocessorOnly, // Just lex, no output.
197 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000198 DumpTokens, // Dump out preprocessed tokens.
199 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000200 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000201 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000202 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000203 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000204};
205
206static llvm::cl::opt<ProgActions>
207ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
208 llvm::cl::init(ParseSyntaxOnly),
209 llvm::cl::values(
210 clEnumValN(RunPreprocessorOnly, "Eonly",
211 "Just run preprocessor, no output (for timings)"),
212 clEnumValN(PrintPreprocessedInput, "E",
213 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000214 clEnumValN(DumpRawTokens, "dump-raw-tokens",
215 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000216 clEnumValN(RunAnalysis, "analyze",
217 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000218 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000219 "Run preprocessor, dump internal rep of tokens"),
220 clEnumValN(ParseNoop, "parse-noop",
221 "Run parser with noop callbacks (for timings)"),
222 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
223 "Run parser and perform semantic analysis"),
224 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
225 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000226 clEnumValN(EmitHTML, "emit-html",
227 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000228 clEnumValN(ASTPrint, "ast-print",
229 "Build ASTs and then pretty-print them"),
230 clEnumValN(ASTDump, "ast-dump",
231 "Build ASTs and then debug dump them"),
Douglas Gregord7915fd2009-04-26 02:02:08 +0000232 clEnumValN(ASTDumpFull, "ast-dump-full",
233 "Build ASTs and then debug dump them, including PCH"),
Chris Lattner664dd082007-10-11 00:37:43 +0000234 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000235 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000236 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000237 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000238 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000239 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000240 clEnumValN(GeneratePCH, "emit-pch",
241 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000242 clEnumValN(EmitAssembly, "S",
243 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000244 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000245 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000246 clEnumValN(EmitBC, "emit-llvm-bc",
247 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000248 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
249 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000250 clEnumValN(RewriteTest, "rewrite-test",
251 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000252 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000253 "Rewrite ObjC into C (code rewriter example)"),
254 clEnumValN(RewriteMacros, "rewrite-macros",
255 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000256 clEnumValN(RewriteBlocks, "rewrite-blocks",
257 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000258 clEnumValN(FixIt, "fixit",
259 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000260 clEnumValEnd));
261
Ted Kremenekd01eae62007-12-19 19:47:59 +0000262
263static llvm::cl::opt<std::string>
264OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000265 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000266 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000267
Ted Kremenek57f25b22008-12-02 19:57:31 +0000268
269//===----------------------------------------------------------------------===//
270// PTH.
271//===----------------------------------------------------------------------===//
272
273static llvm::cl::opt<std::string>
274TokenCache("token-cache", llvm::cl::value_desc("path"),
275 llvm::cl::desc("Use specified token cache file"));
276
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000277//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000278// Diagnostic Options
279//===----------------------------------------------------------------------===//
280
Ted Kremenek10389cf2007-09-26 19:42:19 +0000281static llvm::cl::opt<bool>
282VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000283 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000284
Ted Kremenekfd75e312008-03-27 06:17:42 +0000285static llvm::cl::opt<std::string>
286HTMLDiag("html-diags",
287 llvm::cl::desc("Generate HTML to report diagnostics"),
288 llvm::cl::value_desc("HTML directory"));
289
Nico Weber0e13eaa2008-08-05 23:33:20 +0000290static llvm::cl::opt<bool>
291NoShowColumn("fno-show-column",
292 llvm::cl::desc("Do not include column number on diagnostics"));
293
294static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000295NoShowLocation("fno-show-source-location",
296 llvm::cl::desc("Do not include source location information with"
297 " diagnostics"));
298
299static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000300NoCaretDiagnostics("fno-caret-diagnostics",
301 llvm::cl::desc("Do not include source line and caret with"
302 " diagnostics"));
303
Chris Lattner695a4f52009-03-13 01:08:23 +0000304static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000305NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
306 llvm::cl::desc("Do not include fixit information in"
307 " diagnostics"));
308
309static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000310PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
311 llvm::cl::desc("Print source range spans in numeric form"));
312
313static llvm::cl::alias
314PrintSourceRangeInfo2("fprint-source-range-info",
315 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
316 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner695a4f52009-03-13 01:08:23 +0000317
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000318static llvm::cl::opt<bool>
319PrintDiagnosticOption("fdiagnostics-show-option",
320 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000321
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000322static llvm::cl::opt<unsigned>
323MessageLength("fmessage-length",
324 llvm::cl::desc("Format message diagnostics so that they fit "
325 "within N columns or fewer, when possible."),
326 llvm::cl::value_desc("N"));
327
Chris Lattner4b009652007-07-25 00:24:17 +0000328//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000329// C++ Visualization.
330//===----------------------------------------------------------------------===//
331
332static llvm::cl::opt<std::string>
333InheritanceViewCls("cxx-inheritance-view",
334 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000335 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000336
337//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000338// Builtin Options
339//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000340
341static llvm::cl::opt<bool>
342TimeReport("ftime-report",
343 llvm::cl::desc("Print the amount of time each "
344 "phase of compilation takes"));
345
Douglas Gregor23d23262009-02-14 20:49:29 +0000346static llvm::cl::opt<bool>
347Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000348 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000349 "freestanding environment"));
350
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000351static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000352AllowBuiltins("fbuiltin", llvm::cl::init(true),
353 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000354
355
356static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000357MathErrno("fmath-errno", llvm::cl::init(true),
358 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000359
Douglas Gregor23d23262009-02-14 20:49:29 +0000360//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000361// Language Options
362//===----------------------------------------------------------------------===//
363
364enum LangKind {
365 langkind_unspecified,
366 langkind_c,
367 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000368 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000369 langkind_cxx,
370 langkind_cxx_cpp,
371 langkind_objc,
372 langkind_objc_cpp,
373 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000374 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000375};
376
Chris Lattner4b009652007-07-25 00:24:17 +0000377static llvm::cl::opt<LangKind>
378BaseLang("x", llvm::cl::desc("Base language to compile"),
379 llvm::cl::init(langkind_unspecified),
380 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
381 clEnumValN(langkind_cxx, "c++", "C++"),
382 clEnumValN(langkind_objc, "objective-c", "Objective C"),
383 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000384 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000385 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000386 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
387 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000388 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000389 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000390 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
391 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000392 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000393 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000394 clEnumValN(langkind_c, "c-header",
395 "C header"),
396 clEnumValN(langkind_objc, "objective-c-header",
397 "Objective-C header"),
398 clEnumValN(langkind_cxx, "c++-header",
399 "C++ header"),
400 clEnumValN(langkind_objcxx, "objective-c++-header",
401 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000402 clEnumValEnd));
403
404static llvm::cl::opt<bool>
405LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
406 llvm::cl::Hidden);
407static llvm::cl::opt<bool>
408LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
409 llvm::cl::Hidden);
410
Chris Lattnere1be6022009-04-14 23:22:57 +0000411static llvm::cl::opt<bool>
412ObjCExclusiveGC("fobjc-gc-only",
413 llvm::cl::desc("Use GC exclusively for Objective-C related "
414 "memory management"));
415
416static llvm::cl::opt<bool>
417ObjCEnableGC("fobjc-gc",
418 llvm::cl::desc("Enable Objective-C garbage collection"));
419
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000420static llvm::cl::opt<bool>
421ObjCEnableGCBitmapPrint("print-ivar-layout",
422 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
423
Chris Lattnere1be6022009-04-14 23:22:57 +0000424static llvm::cl::opt<LangOptions::VisibilityMode>
425SymbolVisibility("fvisibility",
426 llvm::cl::desc("Set the default symbol visibility:"),
427 llvm::cl::init(LangOptions::Default),
428 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
429 "Use default symbol visibility"),
430 clEnumValN(LangOptions::Hidden, "hidden",
431 "Use hidden symbol visibility"),
432 clEnumValN(LangOptions::Protected,"protected",
433 "Use protected symbol visibility"),
434 clEnumValEnd));
435
436static llvm::cl::opt<bool>
437OverflowChecking("ftrapv",
438 llvm::cl::desc("Trap on integer overflow"),
439 llvm::cl::init(false));
440
441
Ted Kremenek11ad8952007-12-05 23:49:08 +0000442/// InitializeBaseLanguage - Handle the -x foo options.
443static void InitializeBaseLanguage() {
444 if (LangObjC)
445 BaseLang = langkind_objc;
446 else if (LangObjCXX)
447 BaseLang = langkind_objcxx;
448}
449
450static LangKind GetLanguage(const std::string &Filename) {
451 if (BaseLang != langkind_unspecified)
452 return BaseLang;
453
454 std::string::size_type DotPos = Filename.rfind('.');
455
456 if (DotPos == std::string::npos) {
457 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000458 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000459 }
460
Ted Kremenek11ad8952007-12-05 23:49:08 +0000461 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
462 // C header: .h
463 // C++ header: .hh or .H;
464 // assembler no preprocessing: .s
465 // assembler: .S
466 if (Ext == "c")
467 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000468 else if (Ext == "S" ||
469 // If the compiler is run on a .s file, preprocess it as .S
470 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000471 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000472 else if (Ext == "i")
473 return langkind_c_cpp;
474 else if (Ext == "ii")
475 return langkind_cxx_cpp;
476 else if (Ext == "m")
477 return langkind_objc;
478 else if (Ext == "mi")
479 return langkind_objc_cpp;
480 else if (Ext == "mm" || Ext == "M")
481 return langkind_objcxx;
482 else if (Ext == "mii")
483 return langkind_objcxx_cpp;
484 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
485 Ext == "c++" || Ext == "cp" || Ext == "cxx")
486 return langkind_cxx;
487 else
488 return langkind_c;
489}
490
491
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000492static void InitializeCOptions(LangOptions &Options) {
493 // Do nothing.
494}
495
496static void InitializeObjCOptions(LangOptions &Options) {
497 Options.ObjC1 = Options.ObjC2 = 1;
498}
499
500
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000501static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000502 // FIXME: implement -fpreprocessed mode.
503 bool NoPreprocess = false;
504
Ted Kremenek11ad8952007-12-05 23:49:08 +0000505 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000506 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000507 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000508 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000509 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000510 case langkind_c_cpp:
511 NoPreprocess = true;
512 // FALLTHROUGH
513 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000514 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000515 break;
516 case langkind_cxx_cpp:
517 NoPreprocess = true;
518 // FALLTHROUGH
519 case langkind_cxx:
520 Options.CPlusPlus = 1;
521 break;
522 case langkind_objc_cpp:
523 NoPreprocess = true;
524 // FALLTHROUGH
525 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000526 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000527 break;
528 case langkind_objcxx_cpp:
529 NoPreprocess = true;
530 // FALLTHROUGH
531 case langkind_objcxx:
532 Options.ObjC1 = Options.ObjC2 = 1;
533 Options.CPlusPlus = 1;
534 break;
535 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000536
537 if (ObjCExclusiveGC)
538 Options.setGCMode(LangOptions::GCOnly);
539 else if (ObjCEnableGC)
540 Options.setGCMode(LangOptions::HybridGC);
541
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000542 if (ObjCEnableGCBitmapPrint)
543 Options.ObjCGCBitmapPrint = 1;
544
Chris Lattnere1be6022009-04-14 23:22:57 +0000545 Options.setVisibilityMode(SymbolVisibility);
546 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000547}
548
549/// LangStds - Language standards we support.
550enum LangStds {
551 lang_unspecified,
552 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000553 lang_gnu_START,
554 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000555 lang_cxx98, lang_gnucxx98,
556 lang_cxx0x, lang_gnucxx0x
557};
558
559static llvm::cl::opt<LangStds>
560LangStd("std", llvm::cl::desc("Language standard to compile for"),
561 llvm::cl::init(lang_unspecified),
562 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
563 clEnumValN(lang_c89, "c90", "ISO C 1990"),
564 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
565 clEnumValN(lang_c94, "iso9899:199409",
566 "ISO C 1990 with amendment 1"),
567 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000568 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000569 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000570 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000571 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000572 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000573 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000574 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000575 clEnumValN(lang_gnu99, "gnu9x",
576 "ISO C 1999 with GNU extensions"),
577 clEnumValN(lang_cxx98, "c++98",
578 "ISO C++ 1998 with amendments"),
579 clEnumValN(lang_gnucxx98, "gnu++98",
580 "ISO C++ 1998 with amendments and GNU "
581 "extensions (default for C++)"),
582 clEnumValN(lang_cxx0x, "c++0x",
583 "Upcoming ISO C++ 200x with amendments"),
584 clEnumValN(lang_gnucxx0x, "gnu++0x",
585 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000586 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000587 clEnumValEnd));
588
589static llvm::cl::opt<bool>
590NoOperatorNames("fno-operator-names",
591 llvm::cl::desc("Do not treat C++ operator name keywords as "
592 "synonyms for operators"));
593
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000594static llvm::cl::opt<bool>
595PascalStrings("fpascal-strings",
596 llvm::cl::desc("Recognize and construct Pascal-style "
597 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000598
599static llvm::cl::opt<bool>
600MSExtensions("fms-extensions",
601 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000602 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000603
604static llvm::cl::opt<bool>
605WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000606 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000607
608static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000609NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000610 llvm::cl::desc("Disallow implicit conversions between "
611 "vectors with a different number of "
612 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000613
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000614static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000615EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000616
617static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000618EnableHeinousExtensions("fheinous-gnu-extensions",
619 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
620 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
621
622static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000623ObjCNonFragileABI("fobjc-nonfragile-abi",
624 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000625
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000626static llvm::cl::opt<bool>
627EmitAllDecls("femit-all-decls",
628 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000629
Daniel Dunbar91692d92008-08-11 17:36:14 +0000630// FIXME: This (and all GCC -f options) really come in -f... and
631// -fno-... forms, and additionally support automagic behavior when
632// they are not defined. For example, -fexceptions defaults to on or
633// off depending on the language. We should support this behavior in
634// some form (perhaps just add a facility for distinguishing when an
635// has its default value from when it has been set to its default
636// value).
637static llvm::cl::opt<bool>
638Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000639 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000640
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000641static llvm::cl::opt<bool>
642GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000643 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000644 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000645
646static llvm::cl::opt<bool>
647NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000648 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000649 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000650
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000651
652
653static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000654Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000655
Chris Lattner738d3f62009-03-02 22:11:07 +0000656static llvm::cl::list<std::string>
Chris Lattnerf6790a82009-03-03 19:56:18 +0000657TargetFeatures("mattr", llvm::cl::CommaSeparated,
658 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
659
Douglas Gregor375733c2009-03-10 00:06:19 +0000660static llvm::cl::opt<unsigned>
661TemplateDepth("ftemplate-depth", llvm::cl::init(99),
662 llvm::cl::desc("Maximum depth of recursive template "
663 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000664static llvm::cl::opt<bool>
665DollarsInIdents("fdollars-in-identifiers",
666 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000667
Anders Carlssondfd77642009-04-06 17:37:10 +0000668
669static llvm::cl::opt<bool>
670OptSize("Os", llvm::cl::desc("Optimize for size"));
671
672static llvm::cl::opt<bool>
673NoCommon("fno-common",
674 llvm::cl::desc("Compile common globals like normal definitions"),
675 llvm::cl::ValueDisallowed);
676
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000677static llvm::cl::opt<std::string>
678MainFileName("main-file-name",
679 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000680
681// It might be nice to add bounds to the CommandLine library directly.
682struct OptLevelParser : public llvm::cl::parser<unsigned> {
683 bool parse(llvm::cl::Option &O, const char *ArgName,
684 const std::string &Arg, unsigned &Val) {
685 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
686 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000687 if (Val > 3)
688 return O.error(": '" + Arg + "' invalid optimization level!");
689 return false;
690 }
691};
692static llvm::cl::opt<unsigned, false, OptLevelParser>
693OptLevel("O", llvm::cl::Prefix,
694 llvm::cl::desc("Optimization level"),
695 llvm::cl::init(0));
696
Daniel Dunbare079c712009-04-08 03:03:23 +0000697static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000698PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
699
700static llvm::cl::opt<bool>
701StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000702
Daniel Dunbar34542952008-08-23 08:43:39 +0000703static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
704 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000705 // Allow the target to set the default the langauge options as it sees fit.
706 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000707
Chris Lattnerf6790a82009-03-03 19:56:18 +0000708 // If there are any -mattr options, pass them to the target for validation and
709 // processing. The driver should have already consolidated all the
710 // target-feature settings and passed them to us in the -mattr list. The
711 // -mattr list is treated by the code generator as a diff against the -mcpu
712 // setting, but the driver should pass all enabled options as "+" settings.
713 // This means that the target should only look at + settings.
Chris Lattner880d38e2009-04-13 06:33:49 +0000714 if (!TargetFeatures.empty()) {
Chris Lattner738d3f62009-03-02 22:11:07 +0000715 std::string ErrorStr;
Chris Lattnerf6790a82009-03-03 19:56:18 +0000716 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
717 TargetFeatures.size(), ErrorStr);
Chris Lattner738d3f62009-03-02 22:11:07 +0000718 if (Opt != -1) {
719 if (ErrorStr.empty())
Chris Lattnerf6790a82009-03-03 19:56:18 +0000720 fprintf(stderr, "invalid feature '%s'\n",
721 TargetFeatures[Opt].c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000722 else
Chris Lattnerf6790a82009-03-03 19:56:18 +0000723 fprintf(stderr, "feature '%s': %s\n",
724 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner738d3f62009-03-02 22:11:07 +0000725 exit(1);
726 }
727 }
728
Chris Lattner4b009652007-07-25 00:24:17 +0000729 if (LangStd == lang_unspecified) {
730 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000731 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000732 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000733 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000734 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000735 case langkind_c_cpp:
736 case langkind_objc:
737 case langkind_objc_cpp:
738 LangStd = lang_gnu99;
739 break;
740 case langkind_cxx:
741 case langkind_cxx_cpp:
742 case langkind_objcxx:
743 case langkind_objcxx_cpp:
744 LangStd = lang_gnucxx98;
745 break;
746 }
747 }
748
749 switch (LangStd) {
750 default: assert(0 && "Unknown language standard!");
751
752 // Fall through from newer standards to older ones. This isn't really right.
753 // FIXME: Enable specifically the right features based on the language stds.
754 case lang_gnucxx0x:
755 case lang_cxx0x:
756 Options.CPlusPlus0x = 1;
757 // FALL THROUGH
758 case lang_gnucxx98:
759 case lang_cxx98:
760 Options.CPlusPlus = 1;
761 Options.CXXOperatorNames = !NoOperatorNames;
762 // FALL THROUGH.
763 case lang_gnu99:
764 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000765 Options.C99 = 1;
766 Options.HexFloats = 1;
767 // FALL THROUGH.
768 case lang_gnu89:
769 Options.BCPLComment = 1; // Only for C99/C++.
770 // FALL THROUGH.
771 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000772 Options.Digraphs = 1; // C94, C99, C++.
773 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000774 case lang_c89:
775 break;
776 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000777
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000778 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
779 Options.GNUMode = LangStd >= lang_gnu_START;
780
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000781 if (Options.CPlusPlus) {
782 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000783 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000784 }
Chris Lattner4b009652007-07-25 00:24:17 +0000785
Chris Lattner6ab935b2008-04-05 06:32:51 +0000786 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
787 Options.ImplicitInt = 1;
788 else
789 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000790
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000791 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
792 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000793 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000794 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000795 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000796
Chris Lattner58d5ba52008-12-05 00:10:44 +0000797 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
798 // even if they are normally on for the target. In GNU modes (e.g.
799 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000800 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000801 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000802 Options.Blocks = 0;
803
Chris Lattner284784c2009-04-19 07:06:52 +0000804 // Default to not accepting '$' in identifiers when preprocessing assembler,
805 // but do accept when preprocessing C. FIXME: these defaults are right for
806 // darwin, are they right everywhere?
807 Options.DollarIdents = LK != langkind_asm_cpp;
808 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000809 Options.DollarIdents = DollarsInIdents;
810
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000811 if (PascalStrings.getPosition())
812 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000813 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000814 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000815 if (NoLaxVectorConversions.getPosition())
816 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000817 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000818 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000819 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000820
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000821 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000822 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000823 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000824 Options.Freestanding = Options.NoBuiltin = 1;
825
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000826 if (EnableHeinousExtensions)
827 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000828
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000829 Options.MathErrno = MathErrno;
830
Douglas Gregor375733c2009-03-10 00:06:19 +0000831 Options.InstantiationDepth = TemplateDepth;
832
Chris Lattnerddae7102008-12-04 22:54:33 +0000833 // Override the default runtime if the user requested it.
834 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000835 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000836 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000837 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000838
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000839 if (ObjCNonFragileABI)
840 Options.ObjCNonFragileABI = 1;
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000841
842 if (EmitAllDecls)
843 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000844
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000845 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
846 // support.
847 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000848
849 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000850 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000851 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000852
853 assert(PICLevel <= 2 && "Invalid value for -pic-level");
854 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000855
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000856 Options.GNUInline = !Options.C99;
857 // FIXME: This is affected by other options (-fno-inline).
858 Options.NoInline = !OptSize && !OptLevel;
859
860 Options.Static = StaticDefine;
861
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000862 if (MainFileName.getPosition())
863 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000864}
865
866//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000867// Target Triple Processing.
868//===----------------------------------------------------------------------===//
869
870static llvm::cl::opt<std::string>
871TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000872 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000873
Chris Lattnerfc457002008-03-05 01:18:20 +0000874static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000875Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000876
Chris Lattner2b168e02008-09-30 01:13:12 +0000877static llvm::cl::opt<std::string>
878MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000879 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000880
Chris Lattner01de9c82008-09-30 20:16:56 +0000881// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
882// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000883
884// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000885static void HandleMacOSVersionMin(std::string &Triple) {
886 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
887 if (DarwinDashIdx == std::string::npos) {
888 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000889 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000890 exit(1);
891 }
892 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
893
Chris Lattner01de9c82008-09-30 20:16:56 +0000894 // Remove the number.
895 Triple.resize(DarwinNumIdx);
896
897 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
898 bool MacOSVersionMinIsInvalid = false;
899 int VersionNum = 0;
900 if (MacOSVersionMin.size() < 4 ||
901 MacOSVersionMin.substr(0, 3) != "10." ||
902 !isdigit(MacOSVersionMin[3])) {
903 MacOSVersionMinIsInvalid = true;
904 } else {
905 const char *Start = MacOSVersionMin.c_str()+3;
906 char *End = 0;
907 VersionNum = (int)strtol(Start, &End, 10);
908
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000909 // The version number must be in the range 0-9.
910 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
911
Chris Lattner01de9c82008-09-30 20:16:56 +0000912 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
913 Triple += llvm::itostr(VersionNum+4);
914
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000915 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
916 // Add the period piece (.7) to the end of the triple. This gives us
917 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000918 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000919 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
920 MacOSVersionMinIsInvalid = true;
921 }
922 }
923
924 if (MacOSVersionMinIsInvalid) {
925 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000926 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000927 MacOSVersionMin.c_str());
928 exit(1);
929 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000930 else if (VersionNum <= 4 &&
931 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
932 fprintf(stderr,
933 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
934 MacOSVersionMin.c_str());
935 exit(1);
936 }
937
Chris Lattner01de9c82008-09-30 20:16:56 +0000938}
939
Daniel Dunbar93f64532009-04-10 19:52:24 +0000940static llvm::cl::opt<std::string>
941IPhoneOSVersionMin("miphoneos-version-min",
942 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
943
944// If -miphoneos-version-min=2.2 is specified, change the triple from being
945// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
946// 9 as the default major Darwin number, and encode the iPhone OS version
947// number in the minor version and revision.
948
949// FIXME: We should have the driver do this instead.
950static void HandleIPhoneOSVersionMin(std::string &Triple) {
951 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
952 if (DarwinDashIdx == std::string::npos) {
953 fprintf(stderr,
954 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
955 exit(1);
956 }
957 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
958
959 // Remove the number.
960 Triple.resize(DarwinNumIdx);
961
962 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
963 bool IPhoneOSVersionMinIsInvalid = false;
964 int VersionNum = 0;
965 if (IPhoneOSVersionMin.size() < 3 ||
966 !isdigit(IPhoneOSVersionMin[0])) {
967 IPhoneOSVersionMinIsInvalid = true;
968 } else {
969 const char *Start = IPhoneOSVersionMin.c_str();
970 char *End = 0;
971 VersionNum = (int)strtol(Start, &End, 10);
972
973 // The version number must be in the range 0-9.
974 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
975
976 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
977 Triple += "9." + llvm::itostr(VersionNum);
978
979 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
980 // Add the period piece (.2) to the end of the triple. This gives us
981 // something like ...-darwin9.2.2
982 Triple += End;
983 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
984 IPhoneOSVersionMinIsInvalid = true;
985 }
986 }
987
988 if (IPhoneOSVersionMinIsInvalid) {
989 fprintf(stderr,
990 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
991 IPhoneOSVersionMin.c_str());
992 exit(1);
993 }
994}
995
Chris Lattner01de9c82008-09-30 20:16:56 +0000996/// CreateTargetTriple - Process the various options that affect the target
997/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000998static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000999 // Initialize base triple. If a -triple option has been specified, use
1000 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +00001001 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +00001002 if (Triple.empty())
1003 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +00001004
Chris Lattnerf3d79c32008-03-09 01:35:13 +00001005 // If -arch foo was specified, remove the architecture from the triple we have
1006 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +00001007
1008 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +00001009 if (!Arch.empty()) {
1010 // Decompose the base triple into "arch" and suffix.
1011 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +00001012
Chris Lattner2b168e02008-09-30 01:13:12 +00001013 if (FirstDashIdx == std::string::npos) {
1014 fprintf(stderr,
1015 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1016 Triple.c_str());
1017 exit(1);
1018 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +00001019
1020 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1021 if (Arch == "ppc")
1022 Arch = "powerpc";
1023 else if (Arch == "ppc64")
1024 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001025
Chris Lattner2b168e02008-09-30 01:13:12 +00001026 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1027 }
1028
1029 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1030 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001031 if (!MacOSVersionMin.empty())
1032 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001033 else if (!IPhoneOSVersionMin.empty())
1034 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001035
Chris Lattner2b168e02008-09-30 01:13:12 +00001036 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001037}
1038
1039//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001040// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001041//===----------------------------------------------------------------------===//
1042
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001043static bool InitializeSourceManager(Preprocessor &PP,
1044 const std::string &InFile) {
1045 // Figure out where to get and map in the main file.
1046 SourceManager &SourceMgr = PP.getSourceManager();
1047 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001048
1049 if (EmptyInputOnly) {
1050 const char *EmptyStr = "";
1051 llvm::MemoryBuffer *SB =
1052 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1053 SourceMgr.createMainFileIDForMemBuffer(SB);
1054 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001055 const FileEntry *File = FileMgr.getFile(InFile);
1056 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1057 if (SourceMgr.getMainFileID().isInvalid()) {
1058 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1059 << InFile.c_str();
1060 return true;
1061 }
1062 } else {
1063 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1064
1065 // If stdin was empty, SB is null. Cons up an empty memory
1066 // buffer now.
1067 if (!SB) {
1068 const char *EmptyStr = "";
1069 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1070 }
1071
1072 SourceMgr.createMainFileIDForMemBuffer(SB);
1073 if (SourceMgr.getMainFileID().isInvalid()) {
1074 PP.getDiagnostics().Report(FullSourceLoc(),
1075 diag::err_fe_error_reading_stdin);
1076 return true;
1077 }
1078 }
1079
1080 return false;
1081}
1082
Chris Lattner47b6a162008-04-19 23:09:31 +00001083
Chris Lattner94269d72009-04-21 05:40:52 +00001084//===----------------------------------------------------------------------===//
1085// Preprocessor Initialization
1086//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001087
Chris Lattner94269d72009-04-21 05:40:52 +00001088// FIXME: Preprocessor builtins to support.
1089// -A... - Play with #assertions
1090// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001091
Chris Lattner94269d72009-04-21 05:40:52 +00001092static llvm::cl::list<std::string>
1093D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1094 llvm::cl::desc("Predefine the specified macro"));
1095static llvm::cl::list<std::string>
1096U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1097 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001098
Chris Lattner94269d72009-04-21 05:40:52 +00001099static llvm::cl::list<std::string>
1100ImplicitIncludes("include", llvm::cl::value_desc("file"),
1101 llvm::cl::desc("Include file before parsing"));
1102static llvm::cl::list<std::string>
1103ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1104 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001105
Chris Lattner94269d72009-04-21 05:40:52 +00001106static llvm::cl::opt<std::string>
1107ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1108 llvm::cl::desc("Include precompiled header file"));
1109
1110static llvm::cl::opt<std::string>
1111ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1112 llvm::cl::desc("Include file before parsing"));
1113
Chris Lattner4b009652007-07-25 00:24:17 +00001114
1115//===----------------------------------------------------------------------===//
1116// Preprocessor include path information.
1117//===----------------------------------------------------------------------===//
1118
1119// This tool exports a large number of command line options to control how the
1120// preprocessor searches for header files. At root, however, the Preprocessor
1121// object takes a very simple interface: a list of directories to search for
1122//
1123// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001124// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001125//
Chris Lattner4b009652007-07-25 00:24:17 +00001126
1127static llvm::cl::opt<bool>
1128nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1129
1130// Various command line options. These four add directories to each chain.
1131static llvm::cl::list<std::string>
1132F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1133 llvm::cl::desc("Add directory to framework include search path"));
1134static llvm::cl::list<std::string>
1135I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1136 llvm::cl::desc("Add directory to include search path"));
1137static llvm::cl::list<std::string>
1138idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1139 llvm::cl::desc("Add directory to AFTER include search path"));
1140static llvm::cl::list<std::string>
1141iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1142 llvm::cl::desc("Add directory to QUOTE include search path"));
1143static llvm::cl::list<std::string>
1144isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1145 llvm::cl::desc("Add directory to SYSTEM include search path"));
1146
1147// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1148static llvm::cl::list<std::string>
1149iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1150 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1151static llvm::cl::list<std::string>
1152iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1153 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1154static llvm::cl::list<std::string>
1155iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1156 llvm::cl::Prefix,
1157 llvm::cl::desc("Set directory to include search path with prefix"));
1158
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001159static llvm::cl::opt<std::string>
1160isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1161 llvm::cl::desc("Set the system root directory (usually /)"));
1162
Chris Lattner4b009652007-07-25 00:24:17 +00001163// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001164
Chris Lattner4b009652007-07-25 00:24:17 +00001165/// InitializeIncludePaths - Process the -I options and set them in the
1166/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001167void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1168 FileManager &FM, const LangOptions &Lang) {
1169 InitHeaderSearch Init(Headers, Verbose, isysroot);
1170
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001171 // Handle -I... and -F... options, walking the lists in parallel.
1172 unsigned Iidx = 0, Fidx = 0;
1173 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1174 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001175 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001176 ++Iidx;
1177 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001178 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001179 ++Fidx;
1180 }
1181 }
Chris Lattner4b009652007-07-25 00:24:17 +00001182
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001183 // Consume what's left from whatever list was longer.
1184 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001185 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001186 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001187 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001188
1189 // Handle -idirafter... options.
1190 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001191 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1192 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001193
1194 // Handle -iquote... options.
1195 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001196 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001197
1198 // Handle -isystem... options.
1199 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001200 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001201
1202 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1203 // parallel, processing the values in order of occurance to get the right
1204 // prefixes.
1205 {
1206 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1207 unsigned iprefix_idx = 0;
1208 unsigned iwithprefix_idx = 0;
1209 unsigned iwithprefixbefore_idx = 0;
1210 bool iprefix_done = iprefix_vals.empty();
1211 bool iwithprefix_done = iwithprefix_vals.empty();
1212 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1213 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1214 if (!iprefix_done &&
1215 (iwithprefix_done ||
1216 iprefix_vals.getPosition(iprefix_idx) <
1217 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1218 (iwithprefixbefore_done ||
1219 iprefix_vals.getPosition(iprefix_idx) <
1220 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1221 Prefix = iprefix_vals[iprefix_idx];
1222 ++iprefix_idx;
1223 iprefix_done = iprefix_idx == iprefix_vals.size();
1224 } else if (!iwithprefix_done &&
1225 (iwithprefixbefore_done ||
1226 iwithprefix_vals.getPosition(iwithprefix_idx) <
1227 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001228 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1229 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001230 ++iwithprefix_idx;
1231 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1232 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001233 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1234 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001235 ++iwithprefixbefore_idx;
1236 iwithprefixbefore_done =
1237 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1238 }
1239 }
1240 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001241
Nico Weber770e3882008-08-22 09:25:22 +00001242 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001243
Daniel Dunbar4e604292009-02-21 20:52:41 +00001244 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001245 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001246 llvm::sys::Path::GetMainExecutable(Argv0,
1247 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001248 if (!MainExecutablePath.isEmpty()) {
1249 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1250 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001251
1252 // Get foo/lib/clang/1.0/include
1253 //
1254 // FIXME: Don't embed version here.
1255 MainExecutablePath.appendComponent("lib");
1256 MainExecutablePath.appendComponent("clang");
1257 MainExecutablePath.appendComponent("1.0");
1258 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001259
1260 // We pass true to ignore sysroot so that we *always* look for clang headers
1261 // relative to our executable, never relative to -isysroot.
1262 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1263 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001264 }
1265
Nico Weber770e3882008-08-22 09:25:22 +00001266 if (!nostdinc)
1267 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001268
1269 // Now that we have collected all of the include paths, merge them all
1270 // together and tell the preprocessor about them.
1271
Nico Weber770e3882008-08-22 09:25:22 +00001272 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001273}
1274
Chris Lattner94269d72009-04-21 05:40:52 +00001275void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1276{
1277 // Add macros from the command line.
1278 unsigned d = 0, D = D_macros.size();
1279 unsigned u = 0, U = U_macros.size();
1280 while (d < D || u < U) {
1281 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1282 InitOpts.addMacroDef(D_macros[d++]);
1283 else
1284 InitOpts.addMacroUndef(U_macros[u++]);
1285 }
1286
1287 // If -imacros are specified, include them now. These are processed before
1288 // any -include directives.
1289 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1290 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1291
1292 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1293 // We want to add these paths to the predefines buffer in order, make a
1294 // temporary vector to sort by their occurrence.
1295 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1296
1297 if (!ImplicitIncludePTH.empty())
1298 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1299 &ImplicitIncludePTH));
1300 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1301 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1302 &ImplicitIncludes[i]));
1303 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1304
1305
1306 // Now that they are ordered by position, add to the predefines buffer.
1307 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1308 std::string *Ptr = OrderedPaths[i].second;
1309 if (!ImplicitIncludes.empty() &&
1310 Ptr >= &ImplicitIncludes[0] &&
1311 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1312 InitOpts.addInclude(*Ptr, false);
1313 } else {
1314 assert(Ptr == &ImplicitIncludePTH);
1315 InitOpts.addInclude(*Ptr, true);
1316 }
1317 }
1318 }
1319}
1320
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001321//===----------------------------------------------------------------------===//
1322// Driver PreprocessorFactory - For lazily generating preprocessors ...
1323//===----------------------------------------------------------------------===//
1324
1325namespace {
1326class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001327 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001328 Diagnostic &Diags;
1329 const LangOptions &LangInfo;
1330 TargetInfo &Target;
1331 SourceManager &SourceMgr;
1332 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001333
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001334public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001335 DriverPreprocessorFactory(const std::string &infile,
1336 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001337 TargetInfo &target, SourceManager &SM,
1338 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001339 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001340 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001341
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001342
1343 virtual ~DriverPreprocessorFactory() {}
1344
1345 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001346 llvm::OwningPtr<PTHManager> PTHMgr;
1347
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001348 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1349 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1350 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001351 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001352 }
1353
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001354 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001355 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1356 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001357 PTHMgr.reset(PTHManager::Create(x, &Diags,
1358 TokenCache.empty() ? Diagnostic::Error
1359 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001360 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001361
Ted Kremenek6348cc62009-03-22 06:42:39 +00001362 if (Diags.hasErrorOccurred())
1363 exit(1);
1364
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001365 // Create the Preprocessor.
1366 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1367 SourceMgr, HeaderInfo,
1368 PTHMgr.get()));
1369
1370 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1371 // That argument is used as the IdentifierInfoLookup argument to
1372 // IdentifierTable's ctor.
1373 if (PTHMgr) {
1374 PTHMgr->setPreprocessor(PP.get());
1375 PP->setPTHManager(PTHMgr.take());
1376 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001377
Chris Lattner94269d72009-04-21 05:40:52 +00001378 PreprocessorInitOptions InitOpts;
1379 InitializePreprocessorInitOptions(InitOpts);
1380 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001381 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001382
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001383 /// FIXME: PP can only handle one callback
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001384 if (ProgAction != PrintPreprocessedInput) {
1385 std::string ErrStr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001386 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
Daniel Dunbar0bf13eb2009-03-30 00:34:04 +00001387 if (!DFG && !ErrStr.empty()) {
1388 fprintf(stderr, "%s", ErrStr.c_str());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001389 return 0;
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001390 }
1391 }
1392
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001393 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001394 }
1395};
1396}
Chris Lattner4b009652007-07-25 00:24:17 +00001397
Chris Lattner4b009652007-07-25 00:24:17 +00001398//===----------------------------------------------------------------------===//
1399// Basic Parser driver
1400//===----------------------------------------------------------------------===//
1401
Chris Lattner9d818a22008-04-19 23:25:44 +00001402static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001403 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001404 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001405
1406 // Parsing the specified input file.
1407 P.ParseTranslationUnit();
1408 delete PA;
1409}
1410
1411//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001412// Code generation options
1413//===----------------------------------------------------------------------===//
1414
1415static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001416GenerateDebugInfo("g",
1417 llvm::cl::desc("Generate source level debug information"));
1418
Daniel Dunbar9101a632009-02-17 19:47:34 +00001419static llvm::cl::opt<std::string>
1420TargetCPU("mcpu",
1421 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1422
Chris Lattner8a9615c2009-03-16 18:41:18 +00001423static void InitializeCompileOptions(CompileOptions &Opts,
1424 const LangOptions &LangOpts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001425 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001426 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001427 if (OptSize) {
1428 // -Os implies -O2
1429 // FIXME: Diagnose conflicting options.
1430 Opts.OptimizationLevel = 2;
1431 } else {
1432 Opts.OptimizationLevel = OptLevel;
1433 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001434
1435 // FIXME: There are llvm-gcc options to control these selectively.
1436 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1437 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001438 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001439
1440#ifdef NDEBUG
1441 Opts.VerifyModule = 0;
1442#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001443
1444 Opts.CPU = TargetCPU;
1445 Opts.Features.insert(Opts.Features.end(),
1446 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattnere8f70712009-02-18 01:23:44 +00001447
Chris Lattnerf04a7562009-03-26 05:00:52 +00001448 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1449
Chris Lattnere8f70712009-02-18 01:23:44 +00001450 // Handle -ftime-report.
1451 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001452}
1453
1454//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001455// Fix-It Options
1456//===----------------------------------------------------------------------===//
1457static llvm::cl::list<ParsedSourceLocation>
1458FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1459 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1460
1461//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001462// -dump-build-information Stuff
1463//===----------------------------------------------------------------------===//
1464
1465static llvm::cl::opt<std::string>
1466DumpBuildInformation("dump-build-information",
1467 llvm::cl::value_desc("filename"),
1468 llvm::cl::desc("output a dump of some build information to a file"));
1469
1470static llvm::raw_ostream *BuildLogFile = 0;
1471
1472/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1473/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1474namespace {
1475class LoggingDiagnosticClient : public DiagnosticClient {
1476 llvm::OwningPtr<DiagnosticClient> Chain1;
1477 llvm::OwningPtr<DiagnosticClient> Chain2;
1478public:
1479
1480 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1481 // Output diags both where requested...
1482 Chain1.reset(Normal);
1483 // .. and to our log file.
1484 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1485 !NoShowColumn,
1486 !NoCaretDiagnostics,
1487 !NoShowLocation,
1488 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001489 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001490 !NoDiagnosticsFixIt,
1491 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001492 }
1493
1494 virtual void setLangOptions(const LangOptions *LO) {
1495 Chain1->setLangOptions(LO);
1496 Chain2->setLangOptions(LO);
1497 }
1498
1499 virtual bool IncludeInDiagnosticCounts() const {
1500 return Chain1->IncludeInDiagnosticCounts();
1501 }
1502
1503 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1504 const DiagnosticInfo &Info) {
1505 Chain1->HandleDiagnostic(DiagLevel, Info);
1506 Chain2->HandleDiagnostic(DiagLevel, Info);
1507 }
1508};
1509} // end anonymous namespace.
1510
1511static void SetUpBuildDumpLog(unsigned argc, char **argv,
1512 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1513
1514 std::string ErrorInfo;
1515 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1516 ErrorInfo);
1517
1518 if (!ErrorInfo.empty()) {
1519 llvm::errs() << "error opening -dump-build-information file '"
1520 << DumpBuildInformation << "', option ignored!\n";
1521 delete BuildLogFile;
1522 BuildLogFile = 0;
1523 DumpBuildInformation = "";
1524 return;
1525 }
1526
1527 (*BuildLogFile) << "clang-cc command line arguments: ";
1528 for (unsigned i = 0; i != argc; ++i)
1529 (*BuildLogFile) << argv[i] << ' ';
1530 (*BuildLogFile) << '\n';
1531
1532 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1533 // the diagnostic producers and the normal receiver.
1534 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1535}
1536
1537
1538
1539//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001540// Main driver
1541//===----------------------------------------------------------------------===//
1542
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001543/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner9a09eda2009-03-09 22:05:03 +00001544/// action. These consumers can operate on both ASTs that are freshly
1545/// parsed from source files as well as those deserialized from Bitcode.
1546/// Note that PP and PPF may be null here.
Chris Lattner7f902922009-02-18 01:20:05 +00001547static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001548 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001549 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001550 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001551 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001552 switch (ProgAction) {
Chris Lattner7f902922009-02-18 01:20:05 +00001553 default:
1554 return NULL;
1555
1556 case ASTPrint:
1557 return CreateASTPrinter();
1558
1559 case ASTDump:
Douglas Gregord7915fd2009-04-26 02:02:08 +00001560 return CreateASTDumper(false);
1561
1562 case ASTDumpFull:
1563 return CreateASTDumper(true);
Chris Lattner7f902922009-02-18 01:20:05 +00001564
1565 case ASTView:
1566 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001567
Chris Lattner7f902922009-02-18 01:20:05 +00001568 case PrintDeclContext:
1569 return CreateDeclContextPrinter();
1570
1571 case EmitHTML:
1572 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001573
Chris Lattner7f902922009-02-18 01:20:05 +00001574 case InheritanceView:
1575 return CreateInheritanceViewer(InheritanceViewCls);
1576
Chris Lattner7f902922009-02-18 01:20:05 +00001577 case EmitAssembly:
1578 case EmitLLVM:
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001579 case EmitBC:
1580 case EmitLLVMOnly: {
Chris Lattner7f902922009-02-18 01:20:05 +00001581 BackendAction Act;
1582 if (ProgAction == EmitAssembly)
1583 Act = Backend_EmitAssembly;
1584 else if (ProgAction == EmitLLVM)
1585 Act = Backend_EmitLL;
Daniel Dunbard999a8e2009-02-26 22:39:37 +00001586 else if (ProgAction == EmitLLVMOnly)
1587 Act = Backend_EmitNothing;
Chris Lattner7f902922009-02-18 01:20:05 +00001588 else
1589 Act = Backend_EmitBC;
1590
1591 CompileOptions Opts;
Chris Lattner8a9615c2009-03-16 18:41:18 +00001592 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner7f902922009-02-18 01:20:05 +00001593 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001594 InFile, OutputFile);
Chris Lattner7f902922009-02-18 01:20:05 +00001595 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001596
Douglas Gregorc34897d2009-04-09 22:27:44 +00001597 case GeneratePCH:
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001598 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001599
Chris Lattner7f902922009-02-18 01:20:05 +00001600 case RewriteObjC:
1601 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001602
Chris Lattner7f902922009-02-18 01:20:05 +00001603 case RewriteBlocks:
1604 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1605
1606 case RunAnalysis:
1607 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001608 }
1609}
1610
Chris Lattner4b009652007-07-25 00:24:17 +00001611/// ProcessInputFile - Process a single input file with the specified state.
1612///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001613static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001614 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001615 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001616 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001617 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001618 bool CompleteTranslationUnit = true;
Douglas Gregor133d2552009-04-02 01:08:08 +00001619
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001620 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001621 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001622 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1623 PP.getFileManager(), PP.getLangOptions(),
1624 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001625
1626 if (!Consumer) {
1627 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001628 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001629 return;
1630 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001631
Douglas Gregore0d5c562009-04-14 16:27:31 +00001632 if (ProgAction == GeneratePCH)
1633 CompleteTranslationUnit = false;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001634 break;
1635
Chris Lattneraf669fb2008-10-12 05:03:36 +00001636 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001637 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001638 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001639 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001640 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001641 RawLex.SetKeepWhitespaceMode(true);
1642
1643 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001644 RawLex.LexFromRawLexer(RawTok);
1645 while (RawTok.isNot(tok::eof)) {
1646 PP.DumpToken(RawTok, true);
1647 fprintf(stderr, "\n");
1648 RawLex.LexFromRawLexer(RawTok);
1649 }
1650 ClearSourceMgr = true;
1651 break;
1652 }
Chris Lattner4b009652007-07-25 00:24:17 +00001653 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001654 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001655 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001656 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001657 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001658 do {
1659 PP.Lex(Tok);
1660 PP.DumpToken(Tok, true);
1661 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001662 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001663 ClearSourceMgr = true;
1664 break;
1665 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001666 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001667 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001668
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001669 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001670 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001671 CacheTokens(PP, OutputFile);
1672 ClearSourceMgr = true;
1673 break;
1674 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001675
Chris Lattner772a7c12009-04-27 22:02:30 +00001676 case PrintPreprocessedInput:
Chris Lattner4b009652007-07-25 00:24:17 +00001677 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001678
Chris Lattner270d29a2009-04-27 21:45:14 +00001679 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001680 break;
1681
Chris Lattnerefe33382009-02-18 01:51:21 +00001682 case ParsePrintCallbacks: {
1683 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001684 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001685 ClearSourceMgr = true;
1686 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001687 }
1688
1689 case ParseSyntaxOnly: { // -fsyntax-only
1690 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001691 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001692 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001693 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001694
1695 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001696 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001697 ClearSourceMgr = true;
1698 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001699
Chris Lattnerefe33382009-02-18 01:51:21 +00001700 case RewriteTest: {
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001701 DoRewriteTest(PP, InFile, OutputFile);
1702 ClearSourceMgr = true;
1703 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001704 }
Douglas Gregor133d2552009-04-02 01:08:08 +00001705
1706 case FixIt:
1707 llvm::TimeRegion Timer(ClangFrontendTimer);
1708 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001709 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001710 PP.getSourceManager(),
1711 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001712 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001713 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001714
Chris Lattner38a4f182009-04-27 21:25:27 +00001715 if (FixItAtLocations.size() > 0) {
1716 // Even without the "-fixit" flag, with may have some specific
1717 // locations where the user has requested fixes. Process those
1718 // locations now.
1719 if (!FixItRewrite)
1720 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1721 PP.getSourceManager(),
1722 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001723
Chris Lattner38a4f182009-04-27 21:25:27 +00001724 bool AddedFixitLocation = false;
1725 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1726 Idx != Last; ++Idx) {
1727 RequestedSourceLocation Requested;
1728 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1729 Requested)) {
1730 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1731 FixItAtLocations[Idx].FileName.c_str());
1732 } else {
1733 FixItRewrite->addFixItLocation(Requested);
1734 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001735 }
1736 }
1737
Chris Lattner38a4f182009-04-27 21:25:27 +00001738 if (!AddedFixitLocation) {
1739 // All of the fix-it locations were bad. Don't fix anything.
1740 delete FixItRewrite;
1741 FixItRewrite = 0;
1742 }
1743 }
1744
1745 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001746 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001747 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1748 PP.getSourceManager(),
1749 PP.getTargetInfo(),
1750 PP.getIdentifierTable(),
1751 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001752 /* FreeMemory = */ !DisableFree,
1753 /* size_reserve = */0,
1754 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00001755 llvm::OwningPtr<PCHReader> Reader;
1756 llvm::OwningPtr<ExternalASTSource> Source;
1757
Chris Lattner270d29a2009-04-27 21:45:14 +00001758 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001759 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1760
Chris Lattner270d29a2009-04-27 21:45:14 +00001761 // The user has asked us to include a precompiled header. Load
1762 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001763 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1764 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00001765 // Set the predefines buffer as suggested by the PCH
1766 // reader. Typically, the predefines buffer will be empty.
1767 PP.setPredefines(Reader->getSuggestedPredefines());
1768
Chris Lattner270d29a2009-04-27 21:45:14 +00001769 // Attach the PCH reader to the AST context as an external AST
1770 // source, so that declarations will be deserialized from the
1771 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00001772 if (ContextOwner) {
1773 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001774 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00001775 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001776 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001777 }
1778
Chris Lattner270d29a2009-04-27 21:45:14 +00001779 case PCHReader::Failure:
1780 // Unrecoverable failure: don't even try to process the input
1781 // file.
1782 return;
1783
1784 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001785 // No suitable PCH file could be found. Return an error.
1786 return;
1787
1788#if 0
1789 // FIXME: We can recover from failed attempts to load PCH
1790 // files. This code will do so, if we ever want to enable it.
1791
Chris Lattner270d29a2009-04-27 21:45:14 +00001792 // We delayed the initialization of builtins in the hope of
1793 // loading the PCH file. Since the PCH file could not be
1794 // loaded, initialize builtins now.
1795 if (ContextOwner)
1796 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001797#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00001798 }
1799
1800 // Finish preprocessor initialization. We do this now (rather
1801 // than earlier) because this initialization creates new source
1802 // location entries in the source manager, which must come after
1803 // the source location entries for the PCH file.
1804 if (InitializeSourceManager(PP, InFile))
1805 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00001806 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001807
Chris Lattner270d29a2009-04-27 21:45:14 +00001808
1809 // If we have an ASTConsumer, run the parser with it.
1810 if (Consumer)
1811 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1812 CompleteTranslationUnit);
1813
1814 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
1815 llvm::TimeRegion Timer(ClangFrontendTimer);
1816 Token Tok;
1817 // Start parsing the specified input file.
1818 PP.EnterMainSourceFile();
1819 do {
1820 PP.Lex(Tok);
1821 } while (Tok.isNot(tok::eof));
1822 ClearSourceMgr = true;
1823 } else if (PA == ParseNoop) { // -parse-noop
1824 llvm::TimeRegion Timer(ClangFrontendTimer);
1825 ParseFile(PP, new MinimalAction(PP));
1826 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00001827 } else if (PA == PrintPreprocessedInput){ // -E mode.
1828 llvm::TimeRegion Timer(ClangFrontendTimer);
1829 DoPrintPreprocessedInput(PP, OutputFile);
1830 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00001831 }
1832
Chris Lattner38a4f182009-04-27 21:25:27 +00001833 if (FixItRewrite)
1834 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1835
1836 // If in -disable-free mode, don't deallocate ASTContext.
1837 if (DisableFree)
1838 ContextOwner.take();
1839 else
1840 ContextOwner.reset(); // Delete ASTContext
1841
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001842 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001843 if (CheckDiagnostics(PP))
1844 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001845
Chris Lattner4b009652007-07-25 00:24:17 +00001846 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001847 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001848 PP.PrintStats();
1849 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001850 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001851 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001852 fprintf(stderr, "\n");
1853 }
1854
1855 // For a multi-file compilation, some things are ok with nuking the source
1856 // manager tables, other require stable fileid/macroid's across multiple
1857 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001858 if (ClearSourceMgr)
1859 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001860
1861 if (DisableFree)
1862 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001863}
1864
1865static llvm::cl::list<std::string>
1866InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1867
Chris Lattner4b009652007-07-25 00:24:17 +00001868int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00001869 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00001870 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00001871 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00001872 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001873
Chris Lattnerefe33382009-02-18 01:51:21 +00001874 if (TimeReport)
1875 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1876
Chris Lattner4b009652007-07-25 00:24:17 +00001877 // If no input was specified, read from stdin.
1878 if (InputFilenames.empty())
1879 InputFilenames.push_back("-");
Chris Lattner93d4d982009-02-18 01:12:43 +00001880
Ted Kremenekb240e822007-12-11 23:28:38 +00001881 // Create the diagnostic client for reporting errors or for
1882 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00001883 llvm::OwningPtr<DiagnosticClient> DiagClient;
1884 if (VerifyDiagnostics) {
1885 // When checking diagnostics, just buffer them up.
1886 DiagClient.reset(new TextDiagnosticBuffer());
1887 if (InputFilenames.size() != 1) {
1888 fprintf(stderr, "-verify only works on single input files for now.\n");
1889 return 1;
1890 }
1891 if (!HTMLDiag.empty()) {
1892 fprintf(stderr, "-verify and -html-diags don't work together\n");
1893 return 1;
1894 }
1895 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00001896 // Print diagnostics to stderr by default.
Chris Lattner5f7937d2009-04-17 20:40:01 +00001897 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00001898 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00001899 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00001900 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00001901 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001902 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001903 !NoDiagnosticsFixIt,
1904 MessageLength));
Ted Kremenek5c341732008-08-07 17:49:57 +00001905 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00001906 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00001907 }
Chris Lattner94859302009-04-17 21:05:01 +00001908
1909 if (!DumpBuildInformation.empty()) {
1910 if (!HTMLDiag.empty()) {
1911 fprintf(stderr,
1912 "-dump-build-information and -html-diags don't work together\n");
1913 return 1;
1914 }
1915
1916 SetUpBuildDumpLog(argc, argv, DiagClient);
1917 }
1918
Ted Kremenek5c341732008-08-07 17:49:57 +00001919
Chris Lattner4b009652007-07-25 00:24:17 +00001920 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001921 Diagnostic Diags(DiagClient.get());
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001922 if (ProcessWarningOptions(Diags))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00001923 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00001924
Chris Lattner45a56e02007-12-05 23:24:17 +00001925 // -I- is a deprecated GCC feature, scan for it and reject it.
1926 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1927 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001928 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001929 I_dirs.erase(I_dirs.begin()+i);
1930 --i;
1931 }
1932 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001933
1934 // Get information about the target being compiled for.
1935 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001936 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1937
Chris Lattner2c77d852008-03-14 06:12:05 +00001938 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00001939 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1940 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00001941 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00001942 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001943
Daniel Dunbar9c321102009-01-20 23:17:32 +00001944 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001945 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001946
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001947 llvm::OwningPtr<SourceManager> SourceMgr;
1948
Chris Lattnere1be6022009-04-14 23:22:57 +00001949 // Create a file manager object to provide access to and cache the filesystem.
1950 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001951
Chris Lattner4b009652007-07-25 00:24:17 +00001952 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001953 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001954
Chris Lattner2b989562009-03-04 21:40:56 +00001955 /// Create a SourceManager object. This tracks and owns all the file
1956 /// buffers allocated to a translation unit.
1957 if (!SourceMgr)
1958 SourceMgr.reset(new SourceManager());
1959 else
1960 SourceMgr->clearIDTables();
1961
1962 // Initialize language options, inferring file types from input filenames.
1963 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00001964 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00001965
Chris Lattner2b989562009-03-04 21:40:56 +00001966 InitializeBaseLanguage();
1967 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001968 InitializeLangOptions(LangInfo, LK);
Chris Lattner2b989562009-03-04 21:40:56 +00001969 InitializeLanguageStandard(LangInfo, LK, Target.get());
1970
1971 // Process the -I options and set them in the HeaderInfo.
1972 HeaderSearch HeaderInfo(FileMgr);
1973
Chris Lattnere1be6022009-04-14 23:22:57 +00001974
Chris Lattner2b989562009-03-04 21:40:56 +00001975 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
1976
1977 // Set up the preprocessor with these options.
1978 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
1979 *SourceMgr.get(), HeaderInfo);
1980
1981 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1982
1983 if (!PP)
1984 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001985
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001986 if (ImplicitIncludePCH.empty() &&
1987 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00001988 continue;
1989
Chris Lattner5f7937d2009-04-17 20:40:01 +00001990 if (!HTMLDiag.empty())
1991 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00001992
1993 // Process the source file.
Daniel Dunbardb6126e2009-04-01 05:09:09 +00001994 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattner2b989562009-03-04 21:40:56 +00001995
Chris Lattner2961dc52009-04-17 20:16:08 +00001996 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00001997 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00001998 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001999
Mike Stump91d01352009-01-28 02:43:35 +00002000 if (Verbose)
2001 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2002 " hosted on " LLVM_HOSTTRIPLE "\n");
2003
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002004 if (!NoCaretDiagnostics)
2005 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2006 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2007 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002008
2009 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002010 FileMgr.PrintStats();
2011 fprintf(stderr, "\n");
2012 }
Chris Lattner94859302009-04-17 21:05:01 +00002013
2014 delete ClangFrontendTimer;
2015 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002016
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002017 // If verifying diagnostics and we reached here, all is well.
2018 if (VerifyDiagnostics)
2019 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002020
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002021 // Managed static deconstruction. Useful for making things like
2022 // -time-passes usable.
2023 llvm::llvm_shutdown();
2024
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002025 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002026}