blob: a8836887a70e7a4a46d275f8102cdebb4b10c638 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Ted Kremenekc2542b62009-03-31 18:58:14 +000025#include "clang-cc.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000036#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000037#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000038#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000039#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000040#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000041#include "clang/AST/ASTContext.h"
42#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000043#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044#include "clang/Parse/Parser.h"
45#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000046#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include "clang/Basic/FileManager.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000050#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000051#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/StringExtras.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000055#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000056#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000057#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000058#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000059#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000060#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000061#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000062#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000063#include "llvm/System/Process.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000064#include "llvm/System/Signals.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000065#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000066#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000067# include <sys/types.h>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000068# include <sys/ioctl.h>
Douglas Gregor68a0d782009-05-02 00:03:46 +000069#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000070
Reid Spencer5f016e22007-07-11 17:01:13 +000071using namespace clang;
72
73//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000074// Source Location Parser
75//===----------------------------------------------------------------------===//
76
77/// \brief A source location that has been parsed on the command line.
78struct ParsedSourceLocation {
79 std::string FileName;
80 unsigned Line;
81 unsigned Column;
82
83 /// \brief Try to resolve the file name of a parsed source location.
84 ///
85 /// \returns true if there was an error, false otherwise.
86 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
87};
88
89bool
90ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
91 RequestedSourceLocation &Result) {
92 const FileEntry *File = FileMgr.getFile(FileName);
93 if (!File)
94 return true;
95
96 Result.File = File;
97 Result.Line = Line;
98 Result.Column = Column;
99 return false;
100}
101
102namespace llvm {
103 namespace cl {
104 /// \brief Command-line option parser that parses source locations.
105 ///
106 /// Source locations are of the form filename:line:column.
107 template<>
108 class parser<ParsedSourceLocation>
109 : public basic_parser<ParsedSourceLocation> {
110 public:
111 bool parse(Option &O, const char *ArgName,
112 const std::string &ArgValue,
113 ParsedSourceLocation &Val);
114 };
115
116 bool
117 parser<ParsedSourceLocation>::
118 parse(Option &O, const char *ArgName, const std::string &ArgValue,
119 ParsedSourceLocation &Val) {
120 using namespace clang;
121
122 const char *ExpectedFormat
123 = "source location must be of the form filename:line:column";
124 std::string::size_type SecondColon = ArgValue.rfind(':');
125 if (SecondColon == std::string::npos) {
126 std::fprintf(stderr, "%s\n", ExpectedFormat);
127 return true;
128 }
129 char *EndPtr;
130 long Column
131 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
132 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
133 std::fprintf(stderr, "%s\n", ExpectedFormat);
134 return true;
135 }
136
137 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
138 if (SecondColon == std::string::npos) {
139 std::fprintf(stderr, "%s\n", ExpectedFormat);
140 return true;
141 }
142 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
143 if (EndPtr != ArgValue.c_str() + SecondColon) {
144 std::fprintf(stderr, "%s\n", ExpectedFormat);
145 return true;
146 }
147
148 Val.FileName = ArgValue.substr(0, FirstColon);
149 Val.Line = Line;
150 Val.Column = Column;
151 return false;
152 }
153 }
154}
155
156//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000157// Global options.
158//===----------------------------------------------------------------------===//
159
Chris Lattner47099742009-02-18 01:51:21 +0000160/// ClangFrontendTimer - The front-end activities should charge time to it with
161/// TimeRegion. The -ftime-report option controls whether this will do
162/// anything.
163llvm::Timer *ClangFrontendTimer = 0;
164
Daniel Dunbard3db4012008-10-16 16:54:18 +0000165static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000166
Reid Spencer5f016e22007-07-11 17:01:13 +0000167static llvm::cl::opt<bool>
168Verbose("v", llvm::cl::desc("Enable verbose output"));
169static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000170Stats("print-stats",
171 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000172static llvm::cl::opt<bool>
173DisableFree("disable-free",
174 llvm::cl::desc("Disable freeing of memory on exit"),
175 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000176static llvm::cl::opt<bool>
177EmptyInputOnly("empty-input-only",
178 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000179
180enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000181 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000182 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000183 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000184 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000185 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000186 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000187 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000189 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000190 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000191 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000192 ASTPrint, // Parse ASTs and print them.
193 ASTDump, // Parse ASTs and dump them.
Douglas Gregor609e72f2009-04-26 02:02:08 +0000194 ASTDumpFull, // Parse ASTs and dump them, including the
195 // contents of a PCH file.
Chris Lattner3b427b32007-10-11 00:18:28 +0000196 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000197 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 ParsePrintCallbacks, // Parse and print each callback.
199 ParseSyntaxOnly, // Parse and perform semantic analysis.
200 ParseNoop, // Parse with noop callbacks.
201 RunPreprocessorOnly, // Just lex, no output.
202 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000203 DumpTokens, // Dump out preprocessed tokens.
204 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000205 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000206 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000207 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000208 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000209};
210
211static llvm::cl::opt<ProgActions>
212ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
213 llvm::cl::init(ParseSyntaxOnly),
214 llvm::cl::values(
215 clEnumValN(RunPreprocessorOnly, "Eonly",
216 "Just run preprocessor, no output (for timings)"),
217 clEnumValN(PrintPreprocessedInput, "E",
218 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000219 clEnumValN(DumpRawTokens, "dump-raw-tokens",
220 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000221 clEnumValN(RunAnalysis, "analyze",
222 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000223 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 "Run preprocessor, dump internal rep of tokens"),
225 clEnumValN(ParseNoop, "parse-noop",
226 "Run parser with noop callbacks (for timings)"),
227 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
228 "Run parser and perform semantic analysis"),
229 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
230 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000231 clEnumValN(EmitHTML, "emit-html",
232 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000233 clEnumValN(ASTPrint, "ast-print",
234 "Build ASTs and then pretty-print them"),
235 clEnumValN(ASTDump, "ast-dump",
236 "Build ASTs and then debug dump them"),
Douglas Gregor609e72f2009-04-26 02:02:08 +0000237 clEnumValN(ASTDumpFull, "ast-dump-full",
238 "Build ASTs and then debug dump them, including PCH"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000239 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000240 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000241 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000242 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000243 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000244 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000245 clEnumValN(GeneratePCH, "emit-pch",
246 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000247 clEnumValN(EmitAssembly, "S",
248 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000250 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000251 clEnumValN(EmitBC, "emit-llvm-bc",
252 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000253 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
254 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000255 clEnumValN(RewriteTest, "rewrite-test",
256 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000257 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000258 "Rewrite ObjC into C (code rewriter example)"),
259 clEnumValN(RewriteMacros, "rewrite-macros",
260 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000261 clEnumValN(RewriteBlocks, "rewrite-blocks",
262 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000263 clEnumValN(FixIt, "fixit",
264 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000265 clEnumValEnd));
266
Ted Kremenekccc76472007-12-19 19:47:59 +0000267
268static llvm::cl::opt<std::string>
269OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000270 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000271 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000272
Ted Kremenekc2e72992008-12-02 19:57:31 +0000273
274//===----------------------------------------------------------------------===//
275// PTH.
276//===----------------------------------------------------------------------===//
277
278static llvm::cl::opt<std::string>
279TokenCache("token-cache", llvm::cl::value_desc("path"),
280 llvm::cl::desc("Use specified token cache file"));
281
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000282//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000283// Diagnostic Options
284//===----------------------------------------------------------------------===//
285
Ted Kremenek41193e42007-09-26 19:42:19 +0000286static llvm::cl::opt<bool>
287VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000288 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000289
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000290static llvm::cl::opt<std::string>
291HTMLDiag("html-diags",
292 llvm::cl::desc("Generate HTML to report diagnostics"),
293 llvm::cl::value_desc("HTML directory"));
294
Nico Weberfd54ebc2008-08-05 23:33:20 +0000295static llvm::cl::opt<bool>
296NoShowColumn("fno-show-column",
297 llvm::cl::desc("Do not include column number on diagnostics"));
298
299static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000300NoShowLocation("fno-show-source-location",
301 llvm::cl::desc("Do not include source location information with"
302 " diagnostics"));
303
304static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000305NoCaretDiagnostics("fno-caret-diagnostics",
306 llvm::cl::desc("Do not include source line and caret with"
307 " diagnostics"));
308
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000309static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000310NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
311 llvm::cl::desc("Do not include fixit information in"
312 " diagnostics"));
313
314static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000315PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
316 llvm::cl::desc("Print source range spans in numeric form"));
317
318static llvm::cl::alias
319PrintSourceRangeInfo2("fprint-source-range-info",
320 llvm::cl::desc("Print source range spans in numeric form [deprecated]"),
321 llvm::cl::aliasopt(PrintSourceRangeInfo));
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000322
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000323static llvm::cl::opt<bool>
324PrintDiagnosticOption("fdiagnostics-show-option",
325 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000326
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000327static llvm::cl::opt<unsigned>
328MessageLength("fmessage-length",
329 llvm::cl::desc("Format message diagnostics so that they fit "
330 "within N columns or fewer, when possible."),
331 llvm::cl::value_desc("N"));
332
Reid Spencer5f016e22007-07-11 17:01:13 +0000333//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000334// C++ Visualization.
335//===----------------------------------------------------------------------===//
336
337static llvm::cl::opt<std::string>
338InheritanceViewCls("cxx-inheritance-view",
339 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000340 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000341
342//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000343// Builtin Options
344//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000345
346static llvm::cl::opt<bool>
347TimeReport("ftime-report",
348 llvm::cl::desc("Print the amount of time each "
349 "phase of compilation takes"));
350
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000351static llvm::cl::opt<bool>
352Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000353 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000354 "freestanding environment"));
355
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000356static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000357AllowBuiltins("fbuiltin", llvm::cl::init(true),
358 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000359
360
361static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000362MathErrno("fmath-errno", llvm::cl::init(true),
363 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000364
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000365//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000366// Language Options
367//===----------------------------------------------------------------------===//
368
369enum LangKind {
370 langkind_unspecified,
371 langkind_c,
372 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000373 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 langkind_cxx,
375 langkind_cxx_cpp,
376 langkind_objc,
377 langkind_objc_cpp,
378 langkind_objcxx,
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000379 langkind_objcxx_cpp
Reid Spencer5f016e22007-07-11 17:01:13 +0000380};
381
Reid Spencer5f016e22007-07-11 17:01:13 +0000382static llvm::cl::opt<LangKind>
383BaseLang("x", llvm::cl::desc("Base language to compile"),
384 llvm::cl::init(langkind_unspecified),
385 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
386 clEnumValN(langkind_cxx, "c++", "C++"),
387 clEnumValN(langkind_objc, "objective-c", "Objective C"),
388 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000389 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000391 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
392 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000394 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
396 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000397 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000399 clEnumValN(langkind_c, "c-header",
400 "C header"),
401 clEnumValN(langkind_objc, "objective-c-header",
402 "Objective-C header"),
403 clEnumValN(langkind_cxx, "c++-header",
404 "C++ header"),
405 clEnumValN(langkind_objcxx, "objective-c++-header",
406 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 clEnumValEnd));
408
409static llvm::cl::opt<bool>
410LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
411 llvm::cl::Hidden);
412static llvm::cl::opt<bool>
413LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
414 llvm::cl::Hidden);
415
Chris Lattner2c78b872009-04-14 23:22:57 +0000416static llvm::cl::opt<bool>
417ObjCExclusiveGC("fobjc-gc-only",
418 llvm::cl::desc("Use GC exclusively for Objective-C related "
419 "memory management"));
420
421static llvm::cl::opt<bool>
422ObjCEnableGC("fobjc-gc",
423 llvm::cl::desc("Enable Objective-C garbage collection"));
424
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000425static llvm::cl::opt<bool>
426ObjCEnableGCBitmapPrint("print-ivar-layout",
427 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
428
Chris Lattner2c78b872009-04-14 23:22:57 +0000429static llvm::cl::opt<LangOptions::VisibilityMode>
430SymbolVisibility("fvisibility",
431 llvm::cl::desc("Set the default symbol visibility:"),
432 llvm::cl::init(LangOptions::Default),
433 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
434 "Use default symbol visibility"),
435 clEnumValN(LangOptions::Hidden, "hidden",
436 "Use hidden symbol visibility"),
437 clEnumValN(LangOptions::Protected,"protected",
438 "Use protected symbol visibility"),
439 clEnumValEnd));
440
441static llvm::cl::opt<bool>
442OverflowChecking("ftrapv",
443 llvm::cl::desc("Trap on integer overflow"),
444 llvm::cl::init(false));
445
446
Ted Kremenek8904f152007-12-05 23:49:08 +0000447/// InitializeBaseLanguage - Handle the -x foo options.
448static void InitializeBaseLanguage() {
449 if (LangObjC)
450 BaseLang = langkind_objc;
451 else if (LangObjCXX)
452 BaseLang = langkind_objcxx;
453}
454
455static LangKind GetLanguage(const std::string &Filename) {
456 if (BaseLang != langkind_unspecified)
457 return BaseLang;
458
459 std::string::size_type DotPos = Filename.rfind('.');
460
461 if (DotPos == std::string::npos) {
462 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000463 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 }
465
Ted Kremenek8904f152007-12-05 23:49:08 +0000466 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
467 // C header: .h
468 // C++ header: .hh or .H;
469 // assembler no preprocessing: .s
470 // assembler: .S
471 if (Ext == "c")
472 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000473 else if (Ext == "S" ||
474 // If the compiler is run on a .s file, preprocess it as .S
475 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000476 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000477 else if (Ext == "i")
478 return langkind_c_cpp;
479 else if (Ext == "ii")
480 return langkind_cxx_cpp;
481 else if (Ext == "m")
482 return langkind_objc;
483 else if (Ext == "mi")
484 return langkind_objc_cpp;
485 else if (Ext == "mm" || Ext == "M")
486 return langkind_objcxx;
487 else if (Ext == "mii")
488 return langkind_objcxx_cpp;
489 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
490 Ext == "c++" || Ext == "cp" || Ext == "cxx")
491 return langkind_cxx;
492 else
493 return langkind_c;
494}
495
496
Ted Kremenek85888962008-10-21 00:54:44 +0000497static void InitializeCOptions(LangOptions &Options) {
498 // Do nothing.
499}
500
501static void InitializeObjCOptions(LangOptions &Options) {
502 Options.ObjC1 = Options.ObjC2 = 1;
503}
504
505
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000506static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 // FIXME: implement -fpreprocessed mode.
508 bool NoPreprocess = false;
509
Ted Kremenek8904f152007-12-05 23:49:08 +0000510 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000512 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000513 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000514 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 case langkind_c_cpp:
516 NoPreprocess = true;
517 // FALLTHROUGH
518 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000519 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 break;
521 case langkind_cxx_cpp:
522 NoPreprocess = true;
523 // FALLTHROUGH
524 case langkind_cxx:
525 Options.CPlusPlus = 1;
526 break;
527 case langkind_objc_cpp:
528 NoPreprocess = true;
529 // FALLTHROUGH
530 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000531 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 break;
533 case langkind_objcxx_cpp:
534 NoPreprocess = true;
535 // FALLTHROUGH
536 case langkind_objcxx:
537 Options.ObjC1 = Options.ObjC2 = 1;
538 Options.CPlusPlus = 1;
539 break;
540 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000541
542 if (ObjCExclusiveGC)
543 Options.setGCMode(LangOptions::GCOnly);
544 else if (ObjCEnableGC)
545 Options.setGCMode(LangOptions::HybridGC);
546
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000547 if (ObjCEnableGCBitmapPrint)
548 Options.ObjCGCBitmapPrint = 1;
549
Chris Lattner2c78b872009-04-14 23:22:57 +0000550 Options.setVisibilityMode(SymbolVisibility);
551 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000552}
553
554/// LangStds - Language standards we support.
555enum LangStds {
556 lang_unspecified,
557 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000558 lang_gnu_START,
559 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000560 lang_cxx98, lang_gnucxx98,
561 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000562};
563
564static llvm::cl::opt<LangStds>
565LangStd("std", llvm::cl::desc("Language standard to compile for"),
566 llvm::cl::init(lang_unspecified),
567 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
568 clEnumValN(lang_c89, "c90", "ISO C 1990"),
569 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
570 clEnumValN(lang_c94, "iso9899:199409",
571 "ISO C 1990 with amendment 1"),
572 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000573 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000575 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000577 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000579 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 clEnumValN(lang_gnu99, "gnu9x",
581 "ISO C 1999 with GNU extensions"),
582 clEnumValN(lang_cxx98, "c++98",
583 "ISO C++ 1998 with amendments"),
584 clEnumValN(lang_gnucxx98, "gnu++98",
585 "ISO C++ 1998 with amendments and GNU "
586 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000587 clEnumValN(lang_cxx0x, "c++0x",
588 "Upcoming ISO C++ 200x with amendments"),
589 clEnumValN(lang_gnucxx0x, "gnu++0x",
590 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000591 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 clEnumValEnd));
593
594static llvm::cl::opt<bool>
595NoOperatorNames("fno-operator-names",
596 llvm::cl::desc("Do not treat C++ operator name keywords as "
597 "synonyms for operators"));
598
Anders Carlssonee98ac52007-10-15 02:50:23 +0000599static llvm::cl::opt<bool>
600PascalStrings("fpascal-strings",
601 llvm::cl::desc("Recognize and construct Pascal-style "
602 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000603
604static llvm::cl::opt<bool>
605MSExtensions("fms-extensions",
606 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000607 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000608
609static llvm::cl::opt<bool>
610WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000611 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000612
613static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000614NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000615 llvm::cl::desc("Disallow implicit conversions between "
616 "vectors with a different number of "
617 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000618
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000619static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000620EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000621
622static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000623EnableHeinousExtensions("fheinous-gnu-extensions",
624 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
625 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
626
627static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000628ObjCNonFragileABI("fobjc-nonfragile-abi",
629 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000630
Daniel Dunbard604c402009-02-04 21:19:06 +0000631static llvm::cl::opt<bool>
632EmitAllDecls("femit-all-decls",
633 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000634
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000635// FIXME: This (and all GCC -f options) really come in -f... and
636// -fno-... forms, and additionally support automagic behavior when
637// they are not defined. For example, -fexceptions defaults to on or
638// off depending on the language. We should support this behavior in
639// some form (perhaps just add a facility for distinguishing when an
640// has its default value from when it has been set to its default
641// value).
642static llvm::cl::opt<bool>
643Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000644 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000645
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000646static llvm::cl::opt<bool>
647GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000648 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000649 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000650
651static llvm::cl::opt<bool>
652NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000653 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000654 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000655
Ted Kremenekea644d82008-09-03 21:22:16 +0000656
657
658static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000659Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000660
Chris Lattner16167a62009-03-02 22:11:07 +0000661static llvm::cl::list<std::string>
Chris Lattner6328cc32009-03-03 19:56:18 +0000662TargetFeatures("mattr", llvm::cl::CommaSeparated,
663 llvm::cl::desc("Target specific attributes (-mattr=help for details)"));
664
Douglas Gregor26dce442009-03-10 00:06:19 +0000665static llvm::cl::opt<unsigned>
666TemplateDepth("ftemplate-depth", llvm::cl::init(99),
667 llvm::cl::desc("Maximum depth of recursive template "
668 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000669static llvm::cl::opt<bool>
670DollarsInIdents("fdollars-in-identifiers",
671 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000672
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000673
674static llvm::cl::opt<bool>
675OptSize("Os", llvm::cl::desc("Optimize for size"));
676
677static llvm::cl::opt<bool>
678NoCommon("fno-common",
679 llvm::cl::desc("Compile common globals like normal definitions"),
680 llvm::cl::ValueDisallowed);
681
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000682static llvm::cl::opt<std::string>
683MainFileName("main-file-name",
684 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000685
686// It might be nice to add bounds to the CommandLine library directly.
687struct OptLevelParser : public llvm::cl::parser<unsigned> {
688 bool parse(llvm::cl::Option &O, const char *ArgName,
689 const std::string &Arg, unsigned &Val) {
690 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
691 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000692 if (Val > 3)
693 return O.error(": '" + Arg + "' invalid optimization level!");
694 return false;
695 }
696};
697static llvm::cl::opt<unsigned, false, OptLevelParser>
698OptLevel("O", llvm::cl::Prefix,
699 llvm::cl::desc("Optimization level"),
700 llvm::cl::init(0));
701
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000702static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000703PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
704
705static llvm::cl::opt<bool>
706StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000707
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000708static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
709 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000710 // Allow the target to set the default the langauge options as it sees fit.
711 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000712
Chris Lattner6328cc32009-03-03 19:56:18 +0000713 // If there are any -mattr options, pass them to the target for validation and
714 // processing. The driver should have already consolidated all the
715 // target-feature settings and passed them to us in the -mattr list. The
716 // -mattr list is treated by the code generator as a diff against the -mcpu
717 // setting, but the driver should pass all enabled options as "+" settings.
718 // This means that the target should only look at + settings.
Chris Lattner4d417652009-04-13 06:33:49 +0000719 if (!TargetFeatures.empty()) {
Chris Lattner16167a62009-03-02 22:11:07 +0000720 std::string ErrorStr;
Chris Lattner6328cc32009-03-03 19:56:18 +0000721 int Opt = Target->HandleTargetFeatures(&TargetFeatures[0],
722 TargetFeatures.size(), ErrorStr);
Chris Lattner16167a62009-03-02 22:11:07 +0000723 if (Opt != -1) {
724 if (ErrorStr.empty())
Chris Lattner6328cc32009-03-03 19:56:18 +0000725 fprintf(stderr, "invalid feature '%s'\n",
726 TargetFeatures[Opt].c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000727 else
Chris Lattner6328cc32009-03-03 19:56:18 +0000728 fprintf(stderr, "feature '%s': %s\n",
729 TargetFeatures[Opt].c_str(), ErrorStr.c_str());
Chris Lattner16167a62009-03-02 22:11:07 +0000730 exit(1);
731 }
732 }
733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 if (LangStd == lang_unspecified) {
735 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000736 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000737 case lang_unspecified: assert(0 && "Unknown base language");
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000739 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 case langkind_c_cpp:
741 case langkind_objc:
742 case langkind_objc_cpp:
743 LangStd = lang_gnu99;
744 break;
745 case langkind_cxx:
746 case langkind_cxx_cpp:
747 case langkind_objcxx:
748 case langkind_objcxx_cpp:
749 LangStd = lang_gnucxx98;
750 break;
751 }
752 }
753
754 switch (LangStd) {
755 default: assert(0 && "Unknown language standard!");
756
757 // Fall through from newer standards to older ones. This isn't really right.
758 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000759 case lang_gnucxx0x:
760 case lang_cxx0x:
761 Options.CPlusPlus0x = 1;
762 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 case lang_gnucxx98:
764 case lang_cxx98:
765 Options.CPlusPlus = 1;
766 Options.CXXOperatorNames = !NoOperatorNames;
767 // FALL THROUGH.
768 case lang_gnu99:
769 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 Options.C99 = 1;
771 Options.HexFloats = 1;
772 // FALL THROUGH.
773 case lang_gnu89:
774 Options.BCPLComment = 1; // Only for C99/C++.
775 // FALL THROUGH.
776 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000777 Options.Digraphs = 1; // C94, C99, C++.
778 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 case lang_c89:
780 break;
781 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000782
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000783 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
784 Options.GNUMode = LangStd >= lang_gnu_START;
785
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000786 if (Options.CPlusPlus) {
787 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000788 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000789 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000790
Chris Lattnerd658b562008-04-05 06:32:51 +0000791 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
792 Options.ImplicitInt = 1;
793 else
794 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000795
Daniel Dunbard573d262009-04-07 22:13:21 +0000796 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
797 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000798 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000799 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000800 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000801
Chris Lattner802db9b2008-12-05 00:10:44 +0000802 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
803 // even if they are normally on for the target. In GNU modes (e.g.
804 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000805 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000806 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000807 Options.Blocks = 0;
808
Chris Lattner01638a62009-04-19 07:06:52 +0000809 // Default to not accepting '$' in identifiers when preprocessing assembler,
810 // but do accept when preprocessing C. FIXME: these defaults are right for
811 // darwin, are they right everywhere?
812 Options.DollarIdents = LK != langkind_asm_cpp;
813 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000814 Options.DollarIdents = DollarsInIdents;
815
Chris Lattnerae0ee032008-12-04 23:20:07 +0000816 if (PascalStrings.getPosition())
817 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000818 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000819 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000820 if (NoLaxVectorConversions.getPosition())
821 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000822 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000823 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000824 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000825
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000826 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000827 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000828 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000829 Options.Freestanding = Options.NoBuiltin = 1;
830
Chris Lattner810f6d52009-03-13 17:38:01 +0000831 if (EnableHeinousExtensions)
832 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000833
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000834 Options.MathErrno = MathErrno;
835
Douglas Gregor26dce442009-03-10 00:06:19 +0000836 Options.InstantiationDepth = TemplateDepth;
837
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000838 // Override the default runtime if the user requested it.
839 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000840 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000841 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000842 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000843
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000844 if (ObjCNonFragileABI)
845 Options.ObjCNonFragileABI = 1;
Daniel Dunbard604c402009-02-04 21:19:06 +0000846
847 if (EmitAllDecls)
848 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000849
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000850 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
851 // support.
852 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000853
854 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000855 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000856 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000857
858 assert(PICLevel <= 2 && "Invalid value for -pic-level");
859 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000860
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000861 Options.GNUInline = !Options.C99;
862 // FIXME: This is affected by other options (-fno-inline).
863 Options.NoInline = !OptSize && !OptLevel;
864
865 Options.Static = StaticDefine;
866
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000867 if (MainFileName.getPosition())
868 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000869}
870
871//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000872// Target Triple Processing.
873//===----------------------------------------------------------------------===//
874
875static llvm::cl::opt<std::string>
876TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000877 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000878
Chris Lattner42e67372008-03-05 01:18:20 +0000879static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000880Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000881
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000882static llvm::cl::opt<std::string>
883MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000884 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000885
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000886// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
887// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000888
889// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000890static void HandleMacOSVersionMin(std::string &Triple) {
891 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
892 if (DarwinDashIdx == std::string::npos) {
893 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000894 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000895 exit(1);
896 }
897 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
898
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000899 // Remove the number.
900 Triple.resize(DarwinNumIdx);
901
902 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
903 bool MacOSVersionMinIsInvalid = false;
904 int VersionNum = 0;
905 if (MacOSVersionMin.size() < 4 ||
906 MacOSVersionMin.substr(0, 3) != "10." ||
907 !isdigit(MacOSVersionMin[3])) {
908 MacOSVersionMinIsInvalid = true;
909 } else {
910 const char *Start = MacOSVersionMin.c_str()+3;
911 char *End = 0;
912 VersionNum = (int)strtol(Start, &End, 10);
913
Chris Lattner079f2c462008-09-30 20:30:12 +0000914 // The version number must be in the range 0-9.
915 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
916
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000917 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
918 Triple += llvm::itostr(VersionNum+4);
919
Chris Lattner079f2c462008-09-30 20:30:12 +0000920 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
921 // Add the period piece (.7) to the end of the triple. This gives us
922 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000923 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000924 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
925 MacOSVersionMinIsInvalid = true;
926 }
927 }
928
929 if (MacOSVersionMinIsInvalid) {
930 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000931 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000932 MacOSVersionMin.c_str());
933 exit(1);
934 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000935 else if (VersionNum <= 4 &&
936 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
937 fprintf(stderr,
938 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
939 MacOSVersionMin.c_str());
940 exit(1);
941 }
942
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000943}
944
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000945static llvm::cl::opt<std::string>
946IPhoneOSVersionMin("miphoneos-version-min",
947 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
948
949// If -miphoneos-version-min=2.2 is specified, change the triple from being
950// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
951// 9 as the default major Darwin number, and encode the iPhone OS version
952// number in the minor version and revision.
953
954// FIXME: We should have the driver do this instead.
955static void HandleIPhoneOSVersionMin(std::string &Triple) {
956 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
957 if (DarwinDashIdx == std::string::npos) {
958 fprintf(stderr,
959 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
960 exit(1);
961 }
962 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
963
964 // Remove the number.
965 Triple.resize(DarwinNumIdx);
966
967 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
968 bool IPhoneOSVersionMinIsInvalid = false;
969 int VersionNum = 0;
970 if (IPhoneOSVersionMin.size() < 3 ||
971 !isdigit(IPhoneOSVersionMin[0])) {
972 IPhoneOSVersionMinIsInvalid = true;
973 } else {
974 const char *Start = IPhoneOSVersionMin.c_str();
975 char *End = 0;
976 VersionNum = (int)strtol(Start, &End, 10);
977
978 // The version number must be in the range 0-9.
979 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
980
981 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
982 Triple += "9." + llvm::itostr(VersionNum);
983
984 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
985 // Add the period piece (.2) to the end of the triple. This gives us
986 // something like ...-darwin9.2.2
987 Triple += End;
988 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
989 IPhoneOSVersionMinIsInvalid = true;
990 }
991 }
992
993 if (IPhoneOSVersionMinIsInvalid) {
994 fprintf(stderr,
995 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
996 IPhoneOSVersionMin.c_str());
997 exit(1);
998 }
999}
1000
Chris Lattnerba0f25f2008-09-30 20:16:56 +00001001/// CreateTargetTriple - Process the various options that affect the target
1002/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001003static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +00001004 // Initialize base triple. If a -triple option has been specified, use
1005 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +00001006 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +00001007 if (Triple.empty())
1008 Triple = llvm::sys::getHostTriple();
Ted Kremenekae360762007-12-03 22:06:55 +00001009
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001010 // If -arch foo was specified, remove the architecture from the triple we have
1011 // so far and replace it with the specified one.
Daniel Dunbar64ffc142009-03-31 20:10:05 +00001012
1013 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001014 if (!Arch.empty()) {
1015 // Decompose the base triple into "arch" and suffix.
1016 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001017
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001018 if (FirstDashIdx == std::string::npos) {
1019 fprintf(stderr,
1020 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1021 Triple.c_str());
1022 exit(1);
1023 }
Chris Lattner37e217c2009-03-24 16:18:41 +00001024
1025 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1026 if (Arch == "ppc")
1027 Arch = "powerpc";
1028 else if (Arch == "ppc64")
1029 Arch = "powerpc64";
Ted Kremenekae360762007-12-03 22:06:55 +00001030
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001031 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1032 }
1033
1034 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1035 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +00001036 if (!MacOSVersionMin.empty())
1037 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +00001038 else if (!IPhoneOSVersionMin.empty())
1039 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +00001040
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001041 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +00001042}
1043
1044//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +00001045// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001046//===----------------------------------------------------------------------===//
1047
Douglas Gregore1d918e2009-04-10 23:10:45 +00001048static bool InitializeSourceManager(Preprocessor &PP,
1049 const std::string &InFile) {
1050 // Figure out where to get and map in the main file.
1051 SourceManager &SourceMgr = PP.getSourceManager();
1052 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001053
1054 if (EmptyInputOnly) {
1055 const char *EmptyStr = "";
1056 llvm::MemoryBuffer *SB =
1057 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1058 SourceMgr.createMainFileIDForMemBuffer(SB);
1059 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001060 const FileEntry *File = FileMgr.getFile(InFile);
1061 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1062 if (SourceMgr.getMainFileID().isInvalid()) {
1063 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1064 << InFile.c_str();
1065 return true;
1066 }
1067 } else {
1068 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1069
1070 // If stdin was empty, SB is null. Cons up an empty memory
1071 // buffer now.
1072 if (!SB) {
1073 const char *EmptyStr = "";
1074 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1075 }
1076
1077 SourceMgr.createMainFileIDForMemBuffer(SB);
1078 if (SourceMgr.getMainFileID().isInvalid()) {
1079 PP.getDiagnostics().Report(FullSourceLoc(),
1080 diag::err_fe_error_reading_stdin);
1081 return true;
1082 }
1083 }
1084
1085 return false;
1086}
1087
Chris Lattneraa391972008-04-19 23:09:31 +00001088
Chris Lattnere116ccf2009-04-21 05:40:52 +00001089//===----------------------------------------------------------------------===//
1090// Preprocessor Initialization
1091//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001092
Chris Lattnere116ccf2009-04-21 05:40:52 +00001093// FIXME: Preprocessor builtins to support.
1094// -A... - Play with #assertions
1095// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001096
Chris Lattnere116ccf2009-04-21 05:40:52 +00001097static llvm::cl::list<std::string>
1098D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1099 llvm::cl::desc("Predefine the specified macro"));
1100static llvm::cl::list<std::string>
1101U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1102 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001103
Chris Lattnere116ccf2009-04-21 05:40:52 +00001104static llvm::cl::list<std::string>
1105ImplicitIncludes("include", llvm::cl::value_desc("file"),
1106 llvm::cl::desc("Include file before parsing"));
1107static llvm::cl::list<std::string>
1108ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1109 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001110
Chris Lattnere116ccf2009-04-21 05:40:52 +00001111static llvm::cl::opt<std::string>
1112ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1113 llvm::cl::desc("Include precompiled header file"));
1114
1115static llvm::cl::opt<std::string>
1116ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1117 llvm::cl::desc("Include file before parsing"));
1118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119
1120//===----------------------------------------------------------------------===//
1121// Preprocessor include path information.
1122//===----------------------------------------------------------------------===//
1123
1124// This tool exports a large number of command line options to control how the
1125// preprocessor searches for header files. At root, however, the Preprocessor
1126// object takes a very simple interface: a list of directories to search for
1127//
1128// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001129// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001130//
Reid Spencer5f016e22007-07-11 17:01:13 +00001131
1132static llvm::cl::opt<bool>
1133nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1134
1135// Various command line options. These four add directories to each chain.
1136static llvm::cl::list<std::string>
1137F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1138 llvm::cl::desc("Add directory to framework include search path"));
1139static llvm::cl::list<std::string>
1140I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1141 llvm::cl::desc("Add directory to include search path"));
1142static llvm::cl::list<std::string>
1143idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1144 llvm::cl::desc("Add directory to AFTER include search path"));
1145static llvm::cl::list<std::string>
1146iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1147 llvm::cl::desc("Add directory to QUOTE include search path"));
1148static llvm::cl::list<std::string>
1149isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1150 llvm::cl::desc("Add directory to SYSTEM include search path"));
1151
1152// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1153static llvm::cl::list<std::string>
1154iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1155 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1156static llvm::cl::list<std::string>
1157iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1158 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1159static llvm::cl::list<std::string>
1160iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1161 llvm::cl::Prefix,
1162 llvm::cl::desc("Set directory to include search path with prefix"));
1163
Chris Lattner0c946412007-08-26 17:47:35 +00001164static llvm::cl::opt<std::string>
1165isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1166 llvm::cl::desc("Set the system root directory (usually /)"));
1167
Reid Spencer5f016e22007-07-11 17:01:13 +00001168// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001169
Reid Spencer5f016e22007-07-11 17:01:13 +00001170/// InitializeIncludePaths - Process the -I options and set them in the
1171/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001172void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1173 FileManager &FM, const LangOptions &Lang) {
1174 InitHeaderSearch Init(Headers, Verbose, isysroot);
1175
Ted Kremenekf3721112008-05-31 00:27:00 +00001176 // Handle -I... and -F... options, walking the lists in parallel.
1177 unsigned Iidx = 0, Fidx = 0;
1178 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1179 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001180 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001181 ++Iidx;
1182 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001183 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001184 ++Fidx;
1185 }
1186 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001187
Ted Kremenekf3721112008-05-31 00:27:00 +00001188 // Consume what's left from whatever list was longer.
1189 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001190 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001191 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001192 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001193
1194 // Handle -idirafter... options.
1195 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001196 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1197 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001198
1199 // Handle -iquote... options.
1200 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001201 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001202
1203 // Handle -isystem... options.
1204 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001205 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001206
1207 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1208 // parallel, processing the values in order of occurance to get the right
1209 // prefixes.
1210 {
1211 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1212 unsigned iprefix_idx = 0;
1213 unsigned iwithprefix_idx = 0;
1214 unsigned iwithprefixbefore_idx = 0;
1215 bool iprefix_done = iprefix_vals.empty();
1216 bool iwithprefix_done = iwithprefix_vals.empty();
1217 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1218 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1219 if (!iprefix_done &&
1220 (iwithprefix_done ||
1221 iprefix_vals.getPosition(iprefix_idx) <
1222 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1223 (iwithprefixbefore_done ||
1224 iprefix_vals.getPosition(iprefix_idx) <
1225 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1226 Prefix = iprefix_vals[iprefix_idx];
1227 ++iprefix_idx;
1228 iprefix_done = iprefix_idx == iprefix_vals.size();
1229 } else if (!iwithprefix_done &&
1230 (iwithprefixbefore_done ||
1231 iwithprefix_vals.getPosition(iwithprefix_idx) <
1232 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001233 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1234 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 ++iwithprefix_idx;
1236 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1237 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001238 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1239 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 ++iwithprefixbefore_idx;
1241 iwithprefixbefore_done =
1242 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1243 }
1244 }
1245 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001246
Nico Weber0fca0222008-08-22 09:25:22 +00001247 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001248
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001249 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001250 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001251 llvm::sys::Path::GetMainExecutable(Argv0,
1252 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001253 if (!MainExecutablePath.isEmpty()) {
1254 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1255 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001256
1257 // Get foo/lib/clang/1.0/include
1258 //
1259 // FIXME: Don't embed version here.
1260 MainExecutablePath.appendComponent("lib");
1261 MainExecutablePath.appendComponent("clang");
1262 MainExecutablePath.appendComponent("1.0");
1263 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001264
1265 // We pass true to ignore sysroot so that we *always* look for clang headers
1266 // relative to our executable, never relative to -isysroot.
1267 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1268 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001269 }
1270
Nico Weber0fca0222008-08-22 09:25:22 +00001271 if (!nostdinc)
1272 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001273
1274 // Now that we have collected all of the include paths, merge them all
1275 // together and tell the preprocessor about them.
1276
Nico Weber0fca0222008-08-22 09:25:22 +00001277 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001278}
1279
Chris Lattnere116ccf2009-04-21 05:40:52 +00001280void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1281{
1282 // Add macros from the command line.
1283 unsigned d = 0, D = D_macros.size();
1284 unsigned u = 0, U = U_macros.size();
1285 while (d < D || u < U) {
1286 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1287 InitOpts.addMacroDef(D_macros[d++]);
1288 else
1289 InitOpts.addMacroUndef(U_macros[u++]);
1290 }
1291
1292 // If -imacros are specified, include them now. These are processed before
1293 // any -include directives.
1294 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1295 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1296
1297 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty()) {
1298 // We want to add these paths to the predefines buffer in order, make a
1299 // temporary vector to sort by their occurrence.
1300 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1301
1302 if (!ImplicitIncludePTH.empty())
1303 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1304 &ImplicitIncludePTH));
1305 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1306 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1307 &ImplicitIncludes[i]));
1308 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1309
1310
1311 // Now that they are ordered by position, add to the predefines buffer.
1312 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1313 std::string *Ptr = OrderedPaths[i].second;
1314 if (!ImplicitIncludes.empty() &&
1315 Ptr >= &ImplicitIncludes[0] &&
1316 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1317 InitOpts.addInclude(*Ptr, false);
1318 } else {
1319 assert(Ptr == &ImplicitIncludePTH);
1320 InitOpts.addInclude(*Ptr, true);
1321 }
1322 }
1323 }
1324}
1325
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001326//===----------------------------------------------------------------------===//
1327// Driver PreprocessorFactory - For lazily generating preprocessors ...
1328//===----------------------------------------------------------------------===//
1329
1330namespace {
1331class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001332 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001333 Diagnostic &Diags;
1334 const LangOptions &LangInfo;
1335 TargetInfo &Target;
1336 SourceManager &SourceMgr;
1337 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001338
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001339public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001340 DriverPreprocessorFactory(const std::string &infile,
1341 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001342 TargetInfo &target, SourceManager &SM,
1343 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001344 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001345 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001346
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001347
1348 virtual ~DriverPreprocessorFactory() {}
1349
1350 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001351 llvm::OwningPtr<PTHManager> PTHMgr;
1352
Ted Kremenek748d5d62009-03-20 00:26:38 +00001353 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1354 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1355 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001356 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001357 }
1358
Ted Kremenek72b1b152009-01-15 18:47:46 +00001359 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001360 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1361 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001362 PTHMgr.reset(PTHManager::Create(x, &Diags,
1363 TokenCache.empty() ? Diagnostic::Error
1364 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001365 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001366
Ted Kremenek22f0d092009-03-22 06:42:39 +00001367 if (Diags.hasErrorOccurred())
1368 exit(1);
1369
Ted Kremenek72b1b152009-01-15 18:47:46 +00001370 // Create the Preprocessor.
1371 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1372 SourceMgr, HeaderInfo,
1373 PTHMgr.get()));
1374
1375 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1376 // That argument is used as the IdentifierInfoLookup argument to
1377 // IdentifierTable's ctor.
1378 if (PTHMgr) {
1379 PTHMgr->setPreprocessor(PP.get());
1380 PP->setPTHManager(PTHMgr.take());
1381 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001382
Chris Lattnere116ccf2009-04-21 05:40:52 +00001383 PreprocessorInitOptions InitOpts;
1384 InitializePreprocessorInitOptions(InitOpts);
1385 if (InitializePreprocessor(*PP, InFile, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001386 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001387
Daniel Dunbar0a70c642009-05-03 09:35:25 +00001388 std::string ErrStr;
1389 bool DFG = CreateDependencyFileGen(PP.get(), ErrStr);
1390 if (!DFG && !ErrStr.empty()) {
1391 fprintf(stderr, "%s", ErrStr.c_str());
1392 return 0;
Daniel Dunbar750c3582008-10-24 22:12:41 +00001393 }
1394
Douglas Gregore1d918e2009-04-10 23:10:45 +00001395 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001396 }
1397};
1398}
Reid Spencer5f016e22007-07-11 17:01:13 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400//===----------------------------------------------------------------------===//
1401// Basic Parser driver
1402//===----------------------------------------------------------------------===//
1403
Chris Lattner51574ea2008-04-19 23:25:44 +00001404static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001406 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001407
1408 // Parsing the specified input file.
1409 P.ParseTranslationUnit();
1410 delete PA;
1411}
1412
1413//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001414// Code generation options
1415//===----------------------------------------------------------------------===//
1416
1417static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001418GenerateDebugInfo("g",
1419 llvm::cl::desc("Generate source level debug information"));
1420
Daniel Dunbara034ba82009-02-17 19:47:34 +00001421static llvm::cl::opt<std::string>
1422TargetCPU("mcpu",
1423 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1424
Chris Lattner7afae712009-03-16 18:41:18 +00001425static void InitializeCompileOptions(CompileOptions &Opts,
1426 const LangOptions &LangOpts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001427 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001428 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001429 if (OptSize) {
1430 // -Os implies -O2
1431 // FIXME: Diagnose conflicting options.
1432 Opts.OptimizationLevel = 2;
1433 } else {
1434 Opts.OptimizationLevel = OptLevel;
1435 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001436
1437 // FIXME: There are llvm-gcc options to control these selectively.
1438 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1439 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001440 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001441
1442#ifdef NDEBUG
1443 Opts.VerifyModule = 0;
1444#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001445
1446 Opts.CPU = TargetCPU;
1447 Opts.Features.insert(Opts.Features.end(),
1448 TargetFeatures.begin(), TargetFeatures.end());
Chris Lattner44502662009-02-18 01:23:44 +00001449
Chris Lattnerbd360642009-03-26 05:00:52 +00001450 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1451
Chris Lattner44502662009-02-18 01:23:44 +00001452 // Handle -ftime-report.
1453 Opts.TimePasses = TimeReport;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001454}
1455
1456//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001457// Fix-It Options
1458//===----------------------------------------------------------------------===//
1459static llvm::cl::list<ParsedSourceLocation>
1460FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1461 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1462
1463//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001464// -dump-build-information Stuff
1465//===----------------------------------------------------------------------===//
1466
1467static llvm::cl::opt<std::string>
1468DumpBuildInformation("dump-build-information",
1469 llvm::cl::value_desc("filename"),
1470 llvm::cl::desc("output a dump of some build information to a file"));
1471
1472static llvm::raw_ostream *BuildLogFile = 0;
1473
1474/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1475/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1476namespace {
1477class LoggingDiagnosticClient : public DiagnosticClient {
1478 llvm::OwningPtr<DiagnosticClient> Chain1;
1479 llvm::OwningPtr<DiagnosticClient> Chain2;
1480public:
1481
1482 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1483 // Output diags both where requested...
1484 Chain1.reset(Normal);
1485 // .. and to our log file.
1486 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1487 !NoShowColumn,
1488 !NoCaretDiagnostics,
1489 !NoShowLocation,
1490 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001491 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001492 !NoDiagnosticsFixIt,
1493 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001494 }
1495
1496 virtual void setLangOptions(const LangOptions *LO) {
1497 Chain1->setLangOptions(LO);
1498 Chain2->setLangOptions(LO);
1499 }
1500
1501 virtual bool IncludeInDiagnosticCounts() const {
1502 return Chain1->IncludeInDiagnosticCounts();
1503 }
1504
1505 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1506 const DiagnosticInfo &Info) {
1507 Chain1->HandleDiagnostic(DiagLevel, Info);
1508 Chain2->HandleDiagnostic(DiagLevel, Info);
1509 }
1510};
1511} // end anonymous namespace.
1512
1513static void SetUpBuildDumpLog(unsigned argc, char **argv,
1514 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1515
1516 std::string ErrorInfo;
1517 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1518 ErrorInfo);
1519
1520 if (!ErrorInfo.empty()) {
1521 llvm::errs() << "error opening -dump-build-information file '"
1522 << DumpBuildInformation << "', option ignored!\n";
1523 delete BuildLogFile;
1524 BuildLogFile = 0;
1525 DumpBuildInformation = "";
1526 return;
1527 }
1528
1529 (*BuildLogFile) << "clang-cc command line arguments: ";
1530 for (unsigned i = 0; i != argc; ++i)
1531 (*BuildLogFile) << argv[i] << ' ';
1532 (*BuildLogFile) << '\n';
1533
1534 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1535 // the diagnostic producers and the normal receiver.
1536 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1537}
1538
1539
1540
1541//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001542// Main driver
1543//===----------------------------------------------------------------------===//
1544
Ted Kremenekdb094a22007-12-05 18:27:04 +00001545/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
Chris Lattner15104882009-03-09 22:05:03 +00001546/// action. These consumers can operate on both ASTs that are freshly
1547/// parsed from source files as well as those deserialized from Bitcode.
1548/// Note that PP and PPF may be null here.
Chris Lattner8a5c8092009-02-18 01:20:05 +00001549static ASTConsumer *CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001550 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001551 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001552 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001553 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001554 switch (ProgAction) {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001555 default:
1556 return NULL;
1557
1558 case ASTPrint:
1559 return CreateASTPrinter();
1560
1561 case ASTDump:
Douglas Gregor609e72f2009-04-26 02:02:08 +00001562 return CreateASTDumper(false);
1563
1564 case ASTDumpFull:
1565 return CreateASTDumper(true);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001566
1567 case ASTView:
1568 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001569
Chris Lattner8a5c8092009-02-18 01:20:05 +00001570 case PrintDeclContext:
1571 return CreateDeclContextPrinter();
1572
1573 case EmitHTML:
1574 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001575
Chris Lattner8a5c8092009-02-18 01:20:05 +00001576 case InheritanceView:
1577 return CreateInheritanceViewer(InheritanceViewCls);
1578
Chris Lattner8a5c8092009-02-18 01:20:05 +00001579 case EmitAssembly:
1580 case EmitLLVM:
Daniel Dunbare8e26002009-02-26 22:39:37 +00001581 case EmitBC:
1582 case EmitLLVMOnly: {
Chris Lattner8a5c8092009-02-18 01:20:05 +00001583 BackendAction Act;
1584 if (ProgAction == EmitAssembly)
1585 Act = Backend_EmitAssembly;
1586 else if (ProgAction == EmitLLVM)
1587 Act = Backend_EmitLL;
Daniel Dunbare8e26002009-02-26 22:39:37 +00001588 else if (ProgAction == EmitLLVMOnly)
1589 Act = Backend_EmitNothing;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001590 else
1591 Act = Backend_EmitBC;
1592
1593 CompileOptions Opts;
Chris Lattner7afae712009-03-16 18:41:18 +00001594 InitializeCompileOptions(Opts, LangOpts);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001595 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Chris Lattner20126042009-03-09 22:00:34 +00001596 InFile, OutputFile);
Chris Lattner8a5c8092009-02-18 01:20:05 +00001597 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001598
Douglas Gregor2cf26342009-04-09 22:27:44 +00001599 case GeneratePCH:
Chris Lattner0b1fb982009-04-10 17:15:23 +00001600 return CreatePCHGenerator(*PP, OutputFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001601
Chris Lattner8a5c8092009-02-18 01:20:05 +00001602 case RewriteObjC:
1603 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001604
Chris Lattner8a5c8092009-02-18 01:20:05 +00001605 case RewriteBlocks:
1606 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
1607
1608 case RunAnalysis:
1609 return CreateAnalysisConsumer(Diag, PP, PPF, LangOpts, OutputFile);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001610 }
1611}
1612
Reid Spencer5f016e22007-07-11 17:01:13 +00001613/// ProcessInputFile - Process a single input file with the specified state.
1614///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001615static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001616 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001617 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001618 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001619 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001620 bool CompleteTranslationUnit = true;
Douglas Gregor558cb562009-04-02 01:08:08 +00001621
Ted Kremenek85888962008-10-21 00:54:44 +00001622 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001624 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1625 PP.getFileManager(), PP.getLangOptions(),
1626 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001627
1628 if (!Consumer) {
1629 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001630 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001631 return;
1632 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001633
Douglas Gregorf807fe02009-04-14 16:27:31 +00001634 if (ProgAction == GeneratePCH)
1635 CompleteTranslationUnit = false;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001636 break;
1637
Chris Lattnerc106c102008-10-12 05:03:36 +00001638 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001639 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001640 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001641 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001642 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001643 RawLex.SetKeepWhitespaceMode(true);
1644
1645 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001646 RawLex.LexFromRawLexer(RawTok);
1647 while (RawTok.isNot(tok::eof)) {
1648 PP.DumpToken(RawTok, true);
1649 fprintf(stderr, "\n");
1650 RawLex.LexFromRawLexer(RawTok);
1651 }
1652 ClearSourceMgr = true;
1653 break;
1654 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001656 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001657 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001658 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001659 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 do {
1661 PP.Lex(Tok);
1662 PP.DumpToken(Tok, true);
1663 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001664 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001665 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 break;
1667 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001668 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 break;
Ted Kremenek85888962008-10-21 00:54:44 +00001670
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001671 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001672 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek85888962008-10-21 00:54:44 +00001673 CacheTokens(PP, OutputFile);
1674 ClearSourceMgr = true;
1675 break;
1676 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001677
Chris Lattnercc7dea82009-04-27 22:02:30 +00001678 case PrintPreprocessedInput:
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001680
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001681 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 break;
1683
Chris Lattner47099742009-02-18 01:51:21 +00001684 case ParsePrintCallbacks: {
1685 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001686 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001687 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 break;
Chris Lattner47099742009-02-18 01:51:21 +00001689 }
1690
1691 case ParseSyntaxOnly: { // -fsyntax-only
1692 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001693 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001694 break;
Chris Lattner47099742009-02-18 01:51:21 +00001695 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001696
1697 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001698 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001699 ClearSourceMgr = true;
1700 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001701
Chris Lattner47099742009-02-18 01:51:21 +00001702 case RewriteTest: {
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001703 DoRewriteTest(PP, InFile, OutputFile);
1704 ClearSourceMgr = true;
1705 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001706 }
Douglas Gregor558cb562009-04-02 01:08:08 +00001707
1708 case FixIt:
1709 llvm::TimeRegion Timer(ClangFrontendTimer);
1710 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001711 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001712 PP.getSourceManager(),
1713 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001714 break;
Chris Lattner47099742009-02-18 01:51:21 +00001715 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001716
Chris Lattner1aee61a2009-04-27 21:25:27 +00001717 if (FixItAtLocations.size() > 0) {
1718 // Even without the "-fixit" flag, with may have some specific
1719 // locations where the user has requested fixes. Process those
1720 // locations now.
1721 if (!FixItRewrite)
1722 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1723 PP.getSourceManager(),
1724 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001725
Chris Lattner1aee61a2009-04-27 21:25:27 +00001726 bool AddedFixitLocation = false;
1727 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1728 Idx != Last; ++Idx) {
1729 RequestedSourceLocation Requested;
1730 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1731 Requested)) {
1732 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1733 FixItAtLocations[Idx].FileName.c_str());
1734 } else {
1735 FixItRewrite->addFixItLocation(Requested);
1736 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001737 }
1738 }
1739
Chris Lattner1aee61a2009-04-27 21:25:27 +00001740 if (!AddedFixitLocation) {
1741 // All of the fix-it locations were bad. Don't fix anything.
1742 delete FixItRewrite;
1743 FixItRewrite = 0;
1744 }
1745 }
1746
1747 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001748 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001749 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1750 PP.getSourceManager(),
1751 PP.getTargetInfo(),
1752 PP.getIdentifierTable(),
1753 PP.getSelectorTable(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001754 /* FreeMemory = */ !DisableFree,
1755 /* size_reserve = */0,
1756 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattnercc7dea82009-04-27 22:02:30 +00001757 llvm::OwningPtr<PCHReader> Reader;
1758 llvm::OwningPtr<ExternalASTSource> Source;
1759
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001760 if (!ImplicitIncludePCH.empty()) {
Chris Lattnercc7dea82009-04-27 22:02:30 +00001761 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1762
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001763 // The user has asked us to include a precompiled header. Load
1764 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001765 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1766 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001767 // Set the predefines buffer as suggested by the PCH
1768 // reader. Typically, the predefines buffer will be empty.
1769 PP.setPredefines(Reader->getSuggestedPredefines());
1770
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001771 // Attach the PCH reader to the AST context as an external AST
1772 // source, so that declarations will be deserialized from the
1773 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001774 if (ContextOwner) {
1775 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001776 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001777 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001778 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001779 }
1780
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001781 case PCHReader::Failure:
1782 // Unrecoverable failure: don't even try to process the input
1783 // file.
1784 return;
1785
1786 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001787 // No suitable PCH file could be found. Return an error.
1788 return;
1789
1790#if 0
1791 // FIXME: We can recover from failed attempts to load PCH
1792 // files. This code will do so, if we ever want to enable it.
1793
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001794 // We delayed the initialization of builtins in the hope of
1795 // loading the PCH file. Since the PCH file could not be
1796 // loaded, initialize builtins now.
1797 if (ContextOwner)
1798 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001799#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001800 }
1801
1802 // Finish preprocessor initialization. We do this now (rather
1803 // than earlier) because this initialization creates new source
1804 // location entries in the source manager, which must come after
1805 // the source location entries for the PCH file.
1806 if (InitializeSourceManager(PP, InFile))
1807 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001808 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001809
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001810
1811 // If we have an ASTConsumer, run the parser with it.
1812 if (Consumer)
1813 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
1814 CompleteTranslationUnit);
1815
1816 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
1817 llvm::TimeRegion Timer(ClangFrontendTimer);
1818 Token Tok;
1819 // Start parsing the specified input file.
1820 PP.EnterMainSourceFile();
1821 do {
1822 PP.Lex(Tok);
1823 } while (Tok.isNot(tok::eof));
1824 ClearSourceMgr = true;
1825 } else if (PA == ParseNoop) { // -parse-noop
1826 llvm::TimeRegion Timer(ClangFrontendTimer);
1827 ParseFile(PP, new MinimalAction(PP));
1828 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00001829 } else if (PA == PrintPreprocessedInput){ // -E mode.
1830 llvm::TimeRegion Timer(ClangFrontendTimer);
1831 DoPrintPreprocessedInput(PP, OutputFile);
1832 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001833 }
1834
Chris Lattner1aee61a2009-04-27 21:25:27 +00001835 if (FixItRewrite)
1836 FixItRewrite->WriteFixedFile(InFile, OutputFile);
1837
1838 // If in -disable-free mode, don't deallocate ASTContext.
1839 if (DisableFree)
1840 ContextOwner.take();
1841 else
1842 ContextOwner.reset(); // Delete ASTContext
1843
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001844 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001845 if (CheckDiagnostics(PP))
1846 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001847
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001849 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 PP.PrintStats();
1851 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001852 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001853 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 fprintf(stderr, "\n");
1855 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001856
1857 // For a multi-file compilation, some things are ok with nuking the source
1858 // manager tables, other require stable fileid/macroid's across multiple
1859 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001860 if (ClearSourceMgr)
1861 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001862
1863 if (DisableFree)
1864 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001865}
1866
1867static llvm::cl::list<std::string>
1868InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1869
Douglas Gregor68a0d782009-05-02 00:03:46 +00001870/// \brief Determine the width of the terminal we'll be printing to,
1871/// if any.
1872///
1873/// \returns the width of the terminal (in characters), if there is a
1874/// terminal. If there is no terminal, returns 0.
1875static unsigned getTerminalWidth() {
Douglas Gregor44cf08e2009-05-03 03:52:38 +00001876 // If COLUMNS is defined in the environment, wrap to that many columns.
1877 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
1878 int Columns = atoi(ColumnsStr);
1879 if (Columns > 0)
1880 return Columns;
1881 }
1882
Douglas Gregor68a0d782009-05-02 00:03:46 +00001883 // Is this a terminal? If not, don't wrap by default.
Douglas Gregor44cf08e2009-05-03 03:52:38 +00001884 if (!llvm::sys::Process::StandardErrIsDisplayed())
Douglas Gregor68a0d782009-05-02 00:03:46 +00001885 return 0;
1886
Douglas Gregor44cf08e2009-05-03 03:52:38 +00001887#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +00001888 // Try to determine the width of the terminal.
1889 struct winsize ws;
1890 unsigned Columns = 80; // A guess, in case the ioctl fails.
1891 if (ioctl(2, TIOCGWINSZ, &ws) == 0)
1892 Columns = ws.ws_col;
1893
1894 // Give ourselves just a little extra room, since printing to the
1895 // end of the terminal will make it wrap when we don't want it to.
1896 if (Columns)
1897 --Columns;
1898 return Columns;
1899#endif
1900
1901 return 0;
1902}
1903
Reid Spencer5f016e22007-07-11 17:01:13 +00001904int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001906 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00001907 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00001908 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001909
Chris Lattner47099742009-02-18 01:51:21 +00001910 if (TimeReport)
1911 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1912
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 // If no input was specified, read from stdin.
1914 if (InputFilenames.empty())
1915 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001916
Ted Kremenek31e703b2007-12-11 23:28:38 +00001917 // Create the diagnostic client for reporting errors or for
1918 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001919 llvm::OwningPtr<DiagnosticClient> DiagClient;
1920 if (VerifyDiagnostics) {
1921 // When checking diagnostics, just buffer them up.
1922 DiagClient.reset(new TextDiagnosticBuffer());
1923 if (InputFilenames.size() != 1) {
1924 fprintf(stderr, "-verify only works on single input files for now.\n");
1925 return 1;
1926 }
1927 if (!HTMLDiag.empty()) {
1928 fprintf(stderr, "-verify and -html-diags don't work together\n");
1929 return 1;
1930 }
1931 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001932 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00001933
1934 // If -fmessage-length=N was not specified, determine whether this
1935 // is a terminal and, if so, implicitly define -fmessage-length
1936 // appropriately.
1937 if (MessageLength.getNumOccurrences() == 0)
1938 MessageLength.setValue(getTerminalWidth());
1939
Chris Lattner409d4e72009-04-17 20:40:01 +00001940 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00001941 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001942 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001943 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00001944 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001945 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001946 !NoDiagnosticsFixIt,
1947 MessageLength));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001948 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00001949 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001951
1952 if (!DumpBuildInformation.empty()) {
1953 if (!HTMLDiag.empty()) {
1954 fprintf(stderr,
1955 "-dump-build-information and -html-diags don't work together\n");
1956 return 1;
1957 }
1958
1959 SetUpBuildDumpLog(argc, argv, DiagClient);
1960 }
1961
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001962
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001964 Diagnostic Diags(DiagClient.get());
Sebastian Redlc5613db2009-03-07 12:09:25 +00001965 if (ProcessWarningOptions(Diags))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001966 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001967
Chris Lattner4f037832007-12-05 23:24:17 +00001968 // -I- is a deprecated GCC feature, scan for it and reject it.
1969 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1970 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001971 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001972 I_dirs.erase(I_dirs.begin()+i);
1973 --i;
1974 }
1975 }
Chris Lattner11215192008-03-14 06:12:05 +00001976
1977 // Get information about the target being compiled for.
1978 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001979 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1980
Chris Lattner11215192008-03-14 06:12:05 +00001981 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00001982 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
1983 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001984 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001985 }
Chris Lattner4f037832007-12-05 23:24:17 +00001986
Daniel Dunbard4270232009-01-20 23:17:32 +00001987 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001988 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001989
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001990 llvm::OwningPtr<SourceManager> SourceMgr;
1991
Chris Lattner2c78b872009-04-14 23:22:57 +00001992 // Create a file manager object to provide access to and cache the filesystem.
1993 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001994
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001996 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001997
Chris Lattnerf63aea32009-03-04 21:40:56 +00001998 /// Create a SourceManager object. This tracks and owns all the file
1999 /// buffers allocated to a translation unit.
2000 if (!SourceMgr)
2001 SourceMgr.reset(new SourceManager());
2002 else
2003 SourceMgr->clearIDTables();
2004
2005 // Initialize language options, inferring file types from input filenames.
2006 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002007 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00002008
Chris Lattnerf63aea32009-03-04 21:40:56 +00002009 InitializeBaseLanguage();
2010 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002011 InitializeLangOptions(LangInfo, LK);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002012 InitializeLanguageStandard(LangInfo, LK, Target.get());
2013
2014 // Process the -I options and set them in the HeaderInfo.
2015 HeaderSearch HeaderInfo(FileMgr);
2016
Chris Lattner2c78b872009-04-14 23:22:57 +00002017
Chris Lattnerf63aea32009-03-04 21:40:56 +00002018 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2019
2020 // Set up the preprocessor with these options.
2021 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
2022 *SourceMgr.get(), HeaderInfo);
2023
2024 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2025
2026 if (!PP)
2027 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002028
Douglas Gregore1d918e2009-04-10 23:10:45 +00002029 if (ImplicitIncludePCH.empty() &&
2030 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregor14f79002009-04-10 03:52:48 +00002031 continue;
2032
Chris Lattner409d4e72009-04-17 20:40:01 +00002033 if (!HTMLDiag.empty())
2034 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002035
2036 // Process the source file.
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002037 ProcessInputFile(*PP, PPFactory, InFile, ProgAction);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002038
Chris Lattner40469652009-04-17 20:16:08 +00002039 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002040 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002041 }
Chris Lattner11215192008-03-14 06:12:05 +00002042
Mike Stump007f2a92009-01-28 02:43:35 +00002043 if (Verbose)
2044 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2045 " hosted on " LLVM_HOSTTRIPLE "\n");
2046
Mike Stumpfc0fed32009-04-28 01:19:10 +00002047 if (!NoCaretDiagnostics)
2048 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2049 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2050 (NumDiagnostics == 1 ? "" : "s"));
Reid Spencer5f016e22007-07-11 17:01:13 +00002051
2052 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 FileMgr.PrintStats();
2054 fprintf(stderr, "\n");
2055 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002056
2057 delete ClangFrontendTimer;
2058 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00002059
Daniel Dunbar276373d2008-10-27 22:10:13 +00002060 // If verifying diagnostics and we reached here, all is well.
2061 if (VerifyDiagnostics)
2062 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00002063
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002064 // Managed static deconstruction. Useful for making things like
2065 // -time-passes usable.
2066 llvm::llvm_shutdown();
2067
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002068 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002069}