blob: b526bb157fd833d8fa479d013adc9871126e4dde [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000029#include "clang/Sema/ASTStreamer.h"
30#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "clang/Parse/Parser.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Basic/FileManager.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/System/Signals.h"
Ted Kremenek40499482007-12-03 22:06:55 +000039#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000040#include <memory>
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44// Global options.
45//===----------------------------------------------------------------------===//
46
47static llvm::cl::opt<bool>
48Verbose("v", llvm::cl::desc("Enable verbose output"));
49static llvm::cl::opt<bool>
50Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
51
52enum ProgActions {
Chris Lattnerb429ae42007-10-11 00:43:27 +000053 RewriteTest, // Rewriter testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000054 EmitLLVM, // Emit a .ll file.
Chris Lattner4045a8a2007-10-11 00:18:28 +000055 ASTPrint, // Parse ASTs and print them.
56 ASTDump, // Parse ASTs and dump them.
57 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek97f75312007-08-21 21:42:03 +000058 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000059 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000060 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000061 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000062 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000063 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000064 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000065 ParsePrintCallbacks, // Parse and print each callback.
66 ParseSyntaxOnly, // Parse and perform semantic analysis.
67 ParseNoop, // Parse with noop callbacks.
68 RunPreprocessorOnly, // Just lex, no output.
69 PrintPreprocessedInput, // -E mode.
70 DumpTokens // Token dump mode.
71};
72
73static llvm::cl::opt<ProgActions>
74ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
75 llvm::cl::init(ParseSyntaxOnly),
76 llvm::cl::values(
77 clEnumValN(RunPreprocessorOnly, "Eonly",
78 "Just run preprocessor, no output (for timings)"),
79 clEnumValN(PrintPreprocessedInput, "E",
80 "Run preprocessor, emit preprocessed file"),
81 clEnumValN(DumpTokens, "dumptokens",
82 "Run preprocessor, dump internal rep of tokens"),
83 clEnumValN(ParseNoop, "parse-noop",
84 "Run parser with noop callbacks (for timings)"),
85 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
86 "Run parser and perform semantic analysis"),
87 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
88 "Run parser and print each callback invoked"),
Chris Lattner4045a8a2007-10-11 00:18:28 +000089 clEnumValN(ASTPrint, "ast-print",
90 "Build ASTs and then pretty-print them"),
91 clEnumValN(ASTDump, "ast-dump",
92 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +000093 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +000094 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +000095 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000096 "Run parser, then build and print CFGs."),
97 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +000098 "Run parser, then build and view CFGs with Graphviz."),
99 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +0000100 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000101 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000102 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000103 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000104 "Flag warnings of uses of unitialized variables."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000105 clEnumValN(TestSerialization, "test-pickling",
106 "Run prototype serializtion code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000107 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000108 "Build ASTs then convert to LLVM, emit .ll file"),
Chris Lattnerb429ae42007-10-11 00:43:27 +0000109 clEnumValN(RewriteTest, "rewrite-test",
110 "Playground for the code rewriter"),
Chris Lattner4b009652007-07-25 00:24:17 +0000111 clEnumValEnd));
112
Ted Kremenek10389cf2007-09-26 19:42:19 +0000113static llvm::cl::opt<bool>
114VerifyDiagnostics("verify",
115 llvm::cl::desc("Verify emitted diagnostics and warnings."));
116
Chris Lattner4b009652007-07-25 00:24:17 +0000117//===----------------------------------------------------------------------===//
118// Language Options
119//===----------------------------------------------------------------------===//
120
121enum LangKind {
122 langkind_unspecified,
123 langkind_c,
124 langkind_c_cpp,
125 langkind_cxx,
126 langkind_cxx_cpp,
127 langkind_objc,
128 langkind_objc_cpp,
129 langkind_objcxx,
130 langkind_objcxx_cpp
131};
132
133/* TODO: GCC also accepts:
134 c-header c++-header objective-c-header objective-c++-header
135 assembler assembler-with-cpp
136 ada, f77*, ratfor (!), f95, java, treelang
137 */
138static llvm::cl::opt<LangKind>
139BaseLang("x", llvm::cl::desc("Base language to compile"),
140 llvm::cl::init(langkind_unspecified),
141 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
142 clEnumValN(langkind_cxx, "c++", "C++"),
143 clEnumValN(langkind_objc, "objective-c", "Objective C"),
144 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
145 clEnumValN(langkind_c_cpp, "c-cpp-output",
146 "Preprocessed C"),
147 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
148 "Preprocessed C++"),
149 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
150 "Preprocessed Objective C"),
151 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
152 "Preprocessed Objective C++"),
153 clEnumValEnd));
154
155static llvm::cl::opt<bool>
156LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
157 llvm::cl::Hidden);
158static llvm::cl::opt<bool>
159LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
160 llvm::cl::Hidden);
161
Ted Kremenek11ad8952007-12-05 23:49:08 +0000162/// InitializeBaseLanguage - Handle the -x foo options.
163static void InitializeBaseLanguage() {
164 if (LangObjC)
165 BaseLang = langkind_objc;
166 else if (LangObjCXX)
167 BaseLang = langkind_objcxx;
168}
169
170static LangKind GetLanguage(const std::string &Filename) {
171 if (BaseLang != langkind_unspecified)
172 return BaseLang;
173
174 std::string::size_type DotPos = Filename.rfind('.');
175
176 if (DotPos == std::string::npos) {
177 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
179
Ted Kremenek11ad8952007-12-05 23:49:08 +0000180 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
181 // C header: .h
182 // C++ header: .hh or .H;
183 // assembler no preprocessing: .s
184 // assembler: .S
185 if (Ext == "c")
186 return langkind_c;
187 else if (Ext == "i")
188 return langkind_c_cpp;
189 else if (Ext == "ii")
190 return langkind_cxx_cpp;
191 else if (Ext == "m")
192 return langkind_objc;
193 else if (Ext == "mi")
194 return langkind_objc_cpp;
195 else if (Ext == "mm" || Ext == "M")
196 return langkind_objcxx;
197 else if (Ext == "mii")
198 return langkind_objcxx_cpp;
199 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
200 Ext == "c++" || Ext == "cp" || Ext == "cxx")
201 return langkind_cxx;
202 else
203 return langkind_c;
204}
205
206
207static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000208 // FIXME: implement -fpreprocessed mode.
209 bool NoPreprocess = false;
210
Ted Kremenek11ad8952007-12-05 23:49:08 +0000211 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000212 default: assert(0 && "Unknown language kind!");
213 case langkind_c_cpp:
214 NoPreprocess = true;
215 // FALLTHROUGH
216 case langkind_c:
217 break;
218 case langkind_cxx_cpp:
219 NoPreprocess = true;
220 // FALLTHROUGH
221 case langkind_cxx:
222 Options.CPlusPlus = 1;
223 break;
224 case langkind_objc_cpp:
225 NoPreprocess = true;
226 // FALLTHROUGH
227 case langkind_objc:
228 Options.ObjC1 = Options.ObjC2 = 1;
229 break;
230 case langkind_objcxx_cpp:
231 NoPreprocess = true;
232 // FALLTHROUGH
233 case langkind_objcxx:
234 Options.ObjC1 = Options.ObjC2 = 1;
235 Options.CPlusPlus = 1;
236 break;
237 }
238}
239
240/// LangStds - Language standards we support.
241enum LangStds {
242 lang_unspecified,
243 lang_c89, lang_c94, lang_c99,
244 lang_gnu89, lang_gnu99,
245 lang_cxx98, lang_gnucxx98,
246 lang_cxx0x, lang_gnucxx0x
247};
248
249static llvm::cl::opt<LangStds>
250LangStd("std", llvm::cl::desc("Language standard to compile for"),
251 llvm::cl::init(lang_unspecified),
252 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
253 clEnumValN(lang_c89, "c90", "ISO C 1990"),
254 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
255 clEnumValN(lang_c94, "iso9899:199409",
256 "ISO C 1990 with amendment 1"),
257 clEnumValN(lang_c99, "c99", "ISO C 1999"),
258// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
259 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
260// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
261 clEnumValN(lang_gnu89, "gnu89",
262 "ISO C 1990 with GNU extensions (default for C)"),
263 clEnumValN(lang_gnu99, "gnu99",
264 "ISO C 1999 with GNU extensions"),
265 clEnumValN(lang_gnu99, "gnu9x",
266 "ISO C 1999 with GNU extensions"),
267 clEnumValN(lang_cxx98, "c++98",
268 "ISO C++ 1998 with amendments"),
269 clEnumValN(lang_gnucxx98, "gnu++98",
270 "ISO C++ 1998 with amendments and GNU "
271 "extensions (default for C++)"),
272 clEnumValN(lang_cxx0x, "c++0x",
273 "Upcoming ISO C++ 200x with amendments"),
274 clEnumValN(lang_gnucxx0x, "gnu++0x",
275 "Upcoming ISO C++ 200x with amendments and GNU "
276 "extensions (default for C++)"),
277 clEnumValEnd));
278
279static llvm::cl::opt<bool>
280NoOperatorNames("fno-operator-names",
281 llvm::cl::desc("Do not treat C++ operator name keywords as "
282 "synonyms for operators"));
283
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000284static llvm::cl::opt<bool>
285PascalStrings("fpascal-strings",
286 llvm::cl::desc("Recognize and construct Pascal-style "
287 "string literals"));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000288
289static llvm::cl::opt<bool>
290WritableStrings("fwritable-strings",
291 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000292
293static llvm::cl::opt<bool>
294LaxVectorConversions("flax-vector-conversions",
295 llvm::cl::desc("Allow implicit conversions between vectors"
296 " with a different number of elements or "
297 "different element types."));
Chris Lattner4b009652007-07-25 00:24:17 +0000298// FIXME: add:
299// -ansi
300// -trigraphs
301// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000302// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000303static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000304 if (LangStd == lang_unspecified) {
305 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000306 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000307 default: assert(0 && "Unknown base language");
308 case langkind_c:
309 case langkind_c_cpp:
310 case langkind_objc:
311 case langkind_objc_cpp:
312 LangStd = lang_gnu99;
313 break;
314 case langkind_cxx:
315 case langkind_cxx_cpp:
316 case langkind_objcxx:
317 case langkind_objcxx_cpp:
318 LangStd = lang_gnucxx98;
319 break;
320 }
321 }
322
323 switch (LangStd) {
324 default: assert(0 && "Unknown language standard!");
325
326 // Fall through from newer standards to older ones. This isn't really right.
327 // FIXME: Enable specifically the right features based on the language stds.
328 case lang_gnucxx0x:
329 case lang_cxx0x:
330 Options.CPlusPlus0x = 1;
331 // FALL THROUGH
332 case lang_gnucxx98:
333 case lang_cxx98:
334 Options.CPlusPlus = 1;
335 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000336 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000337 // FALL THROUGH.
338 case lang_gnu99:
339 case lang_c99:
340 Options.Digraphs = 1;
341 Options.C99 = 1;
342 Options.HexFloats = 1;
343 // FALL THROUGH.
344 case lang_gnu89:
345 Options.BCPLComment = 1; // Only for C99/C++.
346 // FALL THROUGH.
347 case lang_c94:
348 case lang_c89:
349 break;
350 }
351
352 Options.Trigraphs = 1; // -trigraphs or -ansi
353 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000354 Options.PascalStrings = PascalStrings;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000355 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000356 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000357}
358
359//===----------------------------------------------------------------------===//
360// Our DiagnosticClient implementation
361//===----------------------------------------------------------------------===//
362
363// FIXME: Werror should take a list of things, -Werror=foo,bar
364static llvm::cl::opt<bool>
365WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
366
367static llvm::cl::opt<bool>
368WarnOnExtensions("pedantic", llvm::cl::init(false),
369 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
370
371static llvm::cl::opt<bool>
372ErrorOnExtensions("pedantic-errors",
373 llvm::cl::desc("Issue an error on uses of GCC extensions"));
374
375static llvm::cl::opt<bool>
376WarnUnusedMacros("Wunused_macros",
377 llvm::cl::desc("Warn for unused macros in the main translation unit"));
378
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000379static llvm::cl::opt<bool>
380WarnFloatEqual("Wfloat-equal",
381 llvm::cl::desc("Warn about equality comparisons of floating point values."));
382
Chris Lattner4b009652007-07-25 00:24:17 +0000383/// InitializeDiagnostics - Initialize the diagnostic object, based on the
384/// current command line option settings.
385static void InitializeDiagnostics(Diagnostic &Diags) {
386 Diags.setWarningsAsErrors(WarningsAsErrors);
387 Diags.setWarnOnExtensions(WarnOnExtensions);
388 Diags.setErrorOnExtensions(ErrorOnExtensions);
389
390 // Silence the "macro is not used" warning unless requested.
391 if (!WarnUnusedMacros)
392 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000393
394 // Silence "floating point comparison" warnings unless requested.
395 if (!WarnFloatEqual)
396 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000397}
398
399//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000400// Target Triple Processing.
401//===----------------------------------------------------------------------===//
402
403static llvm::cl::opt<std::string>
404TargetTriple("triple",
405 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
406
407static llvm::cl::list<std::string>
408Archs("arch",
409 llvm::cl::desc("Specify target architecture (e.g. i686)."));
410
411namespace {
412 class TripleProcessor {
413 llvm::StringMap<char> TriplesProcessed;
414 std::vector<std::string>& triples;
415 public:
416 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
417
418 void addTriple(const std::string& t) {
419 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
420 TriplesProcessed.end()) {
421 triples.push_back(t);
422 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
423 }
424 }
425 };
426}
427
428static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenek40499482007-12-03 22:06:55 +0000429 // Initialize base triple. If a -triple option has been specified, use
430 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000431 std::string Triple = TargetTriple;
432 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000433
434 // Decompose the base triple into "arch" and suffix.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000435 std::string::size_type firstDash = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000436
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000437 if (firstDash == std::string::npos) {
438 fprintf(stderr,
439 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000440 Triple.c_str());
441 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000442 }
Ted Kremenek40499482007-12-03 22:06:55 +0000443
Chris Lattner210c0cc2007-12-12 05:01:48 +0000444 std::string suffix(Triple, firstDash+1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000445
446 if (suffix.empty()) {
Chris Lattner210c0cc2007-12-12 05:01:48 +0000447 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
448 Triple.c_str());
449 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000450 }
Ted Kremenek40499482007-12-03 22:06:55 +0000451
452 // Create triple cacher.
453 TripleProcessor tp(triples);
454
455 // Add the primary triple to our set of triples if we are using the
456 // host-triple with no archs or using a specified target triple.
457 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner210c0cc2007-12-12 05:01:48 +0000458 tp.addTriple(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000459
460 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
461 tp.addTriple(Archs[i] + "-" + suffix);
462}
463
464//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000465// Preprocessor Initialization
466//===----------------------------------------------------------------------===//
467
468// FIXME: Preprocessor builtins to support.
469// -A... - Play with #assertions
470// -undef - Undefine all predefined macros
471
472static llvm::cl::list<std::string>
473D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
474 llvm::cl::desc("Predefine the specified macro"));
475static llvm::cl::list<std::string>
476U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
477 llvm::cl::desc("Undefine the specified macro"));
478
479// Append a #define line to Buf for Macro. Macro should be of the form XXX,
480// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
481// "#define XXX Y z W". To get a #define with no value, use "XXX=".
482static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
483 const char *Command = "#define ") {
484 Buf.insert(Buf.end(), Command, Command+strlen(Command));
485 if (const char *Equal = strchr(Macro, '=')) {
486 // Turn the = into ' '.
487 Buf.insert(Buf.end(), Macro, Equal);
488 Buf.push_back(' ');
489 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
490 } else {
491 // Push "macroname 1".
492 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
493 Buf.push_back(' ');
494 Buf.push_back('1');
495 }
496 Buf.push_back('\n');
497}
498
Chris Lattner4b009652007-07-25 00:24:17 +0000499
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000500/// InitializePreprocessor - Initialize the preprocessor getting it and the
501/// environment ready to process a single file. This returns the file ID for the
502/// input file. If a failure happens, it returns 0.
503///
504static unsigned InitializePreprocessor(Preprocessor &PP,
505 const std::string &InFile,
506 SourceManager &SourceMgr,
507 HeaderSearch &HeaderInfo,
508 const LangOptions &LangInfo,
509 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000510
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000511 FileManager &FileMgr = HeaderInfo.getFileMgr();
Chris Lattner4b009652007-07-25 00:24:17 +0000512
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000513 // Figure out where to get and map in the main file.
514 unsigned MainFileID = 0;
515 if (InFile != "-") {
516 const FileEntry *File = FileMgr.getFile(InFile);
517 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
518 if (MainFileID == 0) {
519 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
520 return 0;
521 }
522 } else {
523 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
524 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
525 if (MainFileID == 0) {
526 fprintf(stderr, "Error reading standard input! Empty?\n");
527 return 0;
528 }
Chris Lattner4b009652007-07-25 00:24:17 +0000529 }
530
Chris Lattner4b009652007-07-25 00:24:17 +0000531 // Add macros from the command line.
532 // FIXME: Should traverse the #define/#undef lists in parallel.
533 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000534 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000535 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000536 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
537
538 // FIXME: Read any files specified by -imacros or -include.
539
540 // Null terminate PredefinedBuffer and add it.
541 PredefineBuffer.push_back(0);
542 PP.setPredefines(&PredefineBuffer[0]);
543
544 // Once we've read this, we're done.
545 return MainFileID;
Chris Lattner4b009652007-07-25 00:24:17 +0000546}
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000547
548
Chris Lattner4b009652007-07-25 00:24:17 +0000549
550//===----------------------------------------------------------------------===//
551// Preprocessor include path information.
552//===----------------------------------------------------------------------===//
553
554// This tool exports a large number of command line options to control how the
555// preprocessor searches for header files. At root, however, the Preprocessor
556// object takes a very simple interface: a list of directories to search for
557//
558// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000559// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000560//
561// FIXME: -include,-imacros
562
563static llvm::cl::opt<bool>
564nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
565
566// Various command line options. These four add directories to each chain.
567static llvm::cl::list<std::string>
568F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
569 llvm::cl::desc("Add directory to framework include search path"));
570static llvm::cl::list<std::string>
571I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
572 llvm::cl::desc("Add directory to include search path"));
573static llvm::cl::list<std::string>
574idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
575 llvm::cl::desc("Add directory to AFTER include search path"));
576static llvm::cl::list<std::string>
577iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
578 llvm::cl::desc("Add directory to QUOTE include search path"));
579static llvm::cl::list<std::string>
580isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
581 llvm::cl::desc("Add directory to SYSTEM include search path"));
582
583// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
584static llvm::cl::list<std::string>
585iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
586 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
587static llvm::cl::list<std::string>
588iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
589 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
590static llvm::cl::list<std::string>
591iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
592 llvm::cl::Prefix,
593 llvm::cl::desc("Set directory to include search path with prefix"));
594
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000595static llvm::cl::opt<std::string>
596isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
597 llvm::cl::desc("Set the system root directory (usually /)"));
598
Chris Lattner4b009652007-07-25 00:24:17 +0000599// Finally, implement the code that groks the options above.
600enum IncludeDirGroup {
601 Quoted = 0,
602 Angled,
603 System,
604 After
605};
606
607static std::vector<DirectoryLookup> IncludeGroup[4];
608
609/// AddPath - Add the specified path to the specified group list.
610///
611static void AddPath(const std::string &Path, IncludeDirGroup Group,
612 bool isCXXAware, bool isUserSupplied,
613 bool isFramework, FileManager &FM) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000614 assert(!Path.empty() && "can't handle empty path here");
615
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000616 const DirectoryEntry *DE;
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000617 if (Group == System) {
618 if (isysroot != "/")
619 DE = FM.getDirectory(isysroot + "/" + Path);
620 else if (Path[0] == '/')
621 DE = FM.getDirectory(Path);
622 else
623 DE = FM.getDirectory("/" + Path);
624 } else
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000625 DE = FM.getDirectory(Path);
626
Chris Lattner4b009652007-07-25 00:24:17 +0000627 if (DE == 0) {
628 if (Verbose)
629 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
630 Path.c_str());
631 return;
632 }
633
634 DirectoryLookup::DirType Type;
635 if (Group == Quoted || Group == Angled)
636 Type = DirectoryLookup::NormalHeaderDir;
637 else if (isCXXAware)
638 Type = DirectoryLookup::SystemHeaderDir;
639 else
640 Type = DirectoryLookup::ExternCSystemHeaderDir;
641
642 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
643 isFramework));
644}
645
646/// RemoveDuplicates - If there are duplicate directory entries in the specified
647/// search list, remove the later (dead) ones.
648static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
649 std::set<const DirectoryEntry *> SeenDirs;
650 for (unsigned i = 0; i != SearchList.size(); ++i) {
651 // If this isn't the first time we've seen this dir, remove it.
652 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
653 if (Verbose)
654 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
655 SearchList[i].getDir()->getName());
656 SearchList.erase(SearchList.begin()+i);
657 --i;
658 }
659 }
660}
661
662/// InitializeIncludePaths - Process the -I options and set them in the
663/// HeaderSearch object.
664static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner45a56e02007-12-05 23:24:17 +0000665 const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000666 // Handle -F... options.
667 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
668 AddPath(F_dirs[i], Angled, false, true, true, FM);
669
670 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000671 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
672 AddPath(I_dirs[i], Angled, false, true, false, FM);
Chris Lattner4b009652007-07-25 00:24:17 +0000673
674 // Handle -idirafter... options.
675 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
676 AddPath(idirafter_dirs[i], After, false, true, false, FM);
677
678 // Handle -iquote... options.
679 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
680 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
681
682 // Handle -isystem... options.
683 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
684 AddPath(isystem_dirs[i], System, false, true, false, FM);
685
686 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
687 // parallel, processing the values in order of occurance to get the right
688 // prefixes.
689 {
690 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
691 unsigned iprefix_idx = 0;
692 unsigned iwithprefix_idx = 0;
693 unsigned iwithprefixbefore_idx = 0;
694 bool iprefix_done = iprefix_vals.empty();
695 bool iwithprefix_done = iwithprefix_vals.empty();
696 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
697 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
698 if (!iprefix_done &&
699 (iwithprefix_done ||
700 iprefix_vals.getPosition(iprefix_idx) <
701 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
702 (iwithprefixbefore_done ||
703 iprefix_vals.getPosition(iprefix_idx) <
704 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
705 Prefix = iprefix_vals[iprefix_idx];
706 ++iprefix_idx;
707 iprefix_done = iprefix_idx == iprefix_vals.size();
708 } else if (!iwithprefix_done &&
709 (iwithprefixbefore_done ||
710 iwithprefix_vals.getPosition(iwithprefix_idx) <
711 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
712 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
713 System, false, false, false, FM);
714 ++iwithprefix_idx;
715 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
716 } else {
717 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
718 Angled, false, false, false, FM);
719 ++iwithprefixbefore_idx;
720 iwithprefixbefore_done =
721 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
722 }
723 }
724 }
725
726 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
727 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
728
729 // FIXME: temporary hack: hard-coded paths.
730 // FIXME: get these from the target?
731 if (!nostdinc) {
732 if (Lang.CPlusPlus) {
733 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
734 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
735 false, FM);
736 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
737 }
738
739 AddPath("/usr/local/include", System, false, false, false, FM);
740 // leopard
741 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
742 false, false, false, FM);
743 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
744 System, false, false, false, FM);
745 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
746 "4.0.1/../../../../powerpc-apple-darwin0/include",
747 System, false, false, false, FM);
748
749 // tiger
750 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
751 false, false, false, FM);
752 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
753 System, false, false, false, FM);
754 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
755 "4.0.1/../../../../powerpc-apple-darwin8/include",
756 System, false, false, false, FM);
757
758 AddPath("/usr/include", System, false, false, false, FM);
759 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
760 AddPath("/Library/Frameworks", System, true, false, true, FM);
761 }
762
763 // Now that we have collected all of the include paths, merge them all
764 // together and tell the preprocessor about them.
765
766 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
767 std::vector<DirectoryLookup> SearchList;
768 SearchList = IncludeGroup[Angled];
769 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
770 IncludeGroup[System].end());
771 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
772 IncludeGroup[After].end());
773 RemoveDuplicates(SearchList);
774 RemoveDuplicates(IncludeGroup[Quoted]);
775
776 // Prepend QUOTED list on the search list.
777 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
778 IncludeGroup[Quoted].end());
779
780
781 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
782 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
783 DontSearchCurDir);
784
785 // If verbose, print the list of directories that will be searched.
786 if (Verbose) {
787 fprintf(stderr, "#include \"...\" search starts here:\n");
788 unsigned QuotedIdx = IncludeGroup[Quoted].size();
789 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
790 if (i == QuotedIdx)
791 fprintf(stderr, "#include <...> search starts here:\n");
792 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
793 }
794 }
795}
796
797
Chris Lattner4b009652007-07-25 00:24:17 +0000798//===----------------------------------------------------------------------===//
799// Basic Parser driver
800//===----------------------------------------------------------------------===//
801
802static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
803 Parser P(PP, *PA);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000804 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000805
806 // Parsing the specified input file.
807 P.ParseTranslationUnit();
808 delete PA;
809}
810
811//===----------------------------------------------------------------------===//
812// Main driver
813//===----------------------------------------------------------------------===//
814
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000815/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
816/// action. These consumers can operate on both ASTs that are freshly
817/// parsed from source files as well as those deserialized from Bitcode.
818static ASTConsumer* CreateASTConsumer(Diagnostic& Diag, FileManager& FileMgr,
819 const LangOptions& LangOpts) {
820 switch (ProgAction) {
821 default:
822 return NULL;
823
824 case ASTPrint:
825 return CreateASTPrinter();
826
827 case ASTDump:
828 return CreateASTDumper();
829
830 case ASTView:
831 return CreateASTViewer();
832
833 case ParseCFGDump:
834 case ParseCFGView:
835 return CreateCFGDumper(ProgAction == ParseCFGView);
836
837 case AnalysisLiveVariables:
838 return CreateLiveVarAnalyzer();
839
840 case WarnDeadStores:
841 return CreateDeadStoreChecker(Diag);
842
843 case WarnUninitVals:
844 return CreateUnitValsChecker(Diag);
845
846 case TestSerialization:
Ted Kremenek2939b8a2007-12-05 21:34:36 +0000847 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000848
849 case EmitLLVM:
850 return CreateLLVMEmitter(Diag, LangOpts);
851
852 case RewriteTest:
853 return CreateCodeRewriterTest(Diag);
854 }
855}
856
Chris Lattner4b009652007-07-25 00:24:17 +0000857/// ProcessInputFile - Process a single input file with the specified state.
858///
859static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
860 const std::string &InFile,
861 SourceManager &SourceMgr,
862 TextDiagnostics &OurDiagnosticClient,
863 HeaderSearch &HeaderInfo,
864 const LangOptions &LangInfo) {
Ted Kremenek6856c632007-09-26 18:39:29 +0000865
866 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +0000867 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +0000868
Chris Lattner4b009652007-07-25 00:24:17 +0000869 switch (ProgAction) {
870 default:
Ted Kremeneka36aaef2007-12-05 18:27:04 +0000871 Consumer = CreateASTConsumer(PP.getDiagnostics(), HeaderInfo.getFileMgr(),
872 PP.getLangOptions());
873
874 if (!Consumer) {
875 fprintf(stderr, "Unexpected program action!\n");
876 return;
877 }
878 break;
879
Chris Lattner4b009652007-07-25 00:24:17 +0000880 case DumpTokens: { // Token dump mode.
881 Token Tok;
882 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000883 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000884 do {
885 PP.Lex(Tok);
886 PP.DumpToken(Tok, true);
887 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +0000888 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000889 ClearSourceMgr = true;
890 break;
891 }
892 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
893 Token Tok;
894 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000895 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000896 do {
897 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +0000898 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000899 ClearSourceMgr = true;
900 break;
901 }
902
903 case PrintPreprocessedInput: // -E mode.
904 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
905 ClearSourceMgr = true;
906 break;
907
908 case ParseNoop: // -parse-noop
Steve Naroffebeb4282007-10-31 20:55:39 +0000909 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000910 ClearSourceMgr = true;
911 break;
912
913 case ParsePrintCallbacks:
Steve Naroffebeb4282007-10-31 20:55:39 +0000914 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
915 MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000916 ClearSourceMgr = true;
917 break;
Ted Kremenek0841c702007-09-25 18:37:20 +0000918
Ted Kremenek6856c632007-09-26 18:39:29 +0000919 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +0000920 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000921 break;
Chris Lattner129758d2007-09-16 19:46:59 +0000922 }
Ted Kremenek6856c632007-09-26 18:39:29 +0000923
924 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +0000925 if (VerifyDiagnostics)
Chris Lattner8593cbf2007-11-03 06:24:16 +0000926 exit(CheckASTConsumer(PP, MainFileID, Consumer));
927
928 // This deletes Consumer.
929 ParseAST(PP, MainFileID, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +0000930 }
931
932 if (Stats) {
933 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
934 PP.PrintStats();
935 PP.getIdentifierTable().PrintStats();
936 HeaderInfo.PrintStats();
937 if (ClearSourceMgr)
938 SourceMgr.PrintStats();
939 fprintf(stderr, "\n");
940 }
941
942 // For a multi-file compilation, some things are ok with nuking the source
943 // manager tables, other require stable fileid/macroid's across multiple
944 // files.
945 if (ClearSourceMgr) {
946 SourceMgr.clearIDTables();
947 }
948}
949
950static llvm::cl::list<std::string>
951InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
952
953
954int main(int argc, char **argv) {
955 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
956 llvm::sys::PrintStackTraceOnErrorSignal();
957
958 // If no input was specified, read from stdin.
959 if (InputFilenames.empty())
960 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +0000961
Chris Lattner4b009652007-07-25 00:24:17 +0000962 // Create a file manager object to provide access to and cache the filesystem.
963 FileManager FileMgr;
964
Ted Kremenekb240e822007-12-11 23:28:38 +0000965 // Create the diagnostic client for reporting errors or for
966 // implementing -verify.
Chris Lattner4b009652007-07-25 00:24:17 +0000967 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +0000968 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +0000969 // Print diagnostics to stderr by default.
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000970 DiagClient.reset(new TextDiagnosticPrinter());
Chris Lattner4b009652007-07-25 00:24:17 +0000971 } else {
972 // When checking diagnostics, just buffer them up.
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000973 DiagClient.reset(new TextDiagnosticBuffer());
Chris Lattner4b009652007-07-25 00:24:17 +0000974
975 if (InputFilenames.size() != 1) {
976 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +0000977 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000978 return 1;
979 }
980 }
981
982 // Configure our handling of diagnostics.
983 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +0000984 InitializeDiagnostics(Diags);
985
Chris Lattner45a56e02007-12-05 23:24:17 +0000986 // -I- is a deprecated GCC feature, scan for it and reject it.
987 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
988 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +0000989 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +0000990 I_dirs.erase(I_dirs.begin()+i);
991 --i;
992 }
993 }
994
Chris Lattner4b009652007-07-25 00:24:17 +0000995 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +0000996 const std::string &InFile = InputFilenames[i];
997
998 /// Create a SourceManager object. This tracks and owns all the file
999 /// buffers allocated to a translation unit.
1000 SourceManager SourceMgr;
1001
1002 // Initialize language options, inferring file types from input filenames.
1003 LangOptions LangInfo;
1004 InitializeBaseLanguage();
1005 LangKind LK = GetLanguage(InFile);
1006 InitializeLangOptions(LangInfo, LK);
1007 InitializeLanguageStandard(LangInfo, LK);
1008
1009 // Process the -I options and set them in the HeaderInfo.
1010 HeaderSearch HeaderInfo(FileMgr);
1011 DiagClient->setHeaderSearch(HeaderInfo);
1012 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1013
1014 // Get information about the targets being compiled for. Note that this
1015 // pointer and the TargetInfoImpl objects are never deleted by this toy
1016 // driver.
1017 TargetInfo *Target;
1018
1019 // Create triples, and create the TargetInfo.
1020 std::vector<std::string> triples;
1021 CreateTargetTriples(triples);
1022 Target = CreateTargetInfo(SourceMgr,triples,&Diags);
1023
1024 if (Target == 0) {
1025 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1026 triples[0].c_str());
1027 fprintf(stderr, "Please use -triple or -arch.\n");
1028 exit(1);
1029 }
1030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 // Set up the preprocessor with these options.
1032 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
Ted Kremenekb240e822007-12-11 23:28:38 +00001033
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001034 std::vector<char> PredefineBuffer;
Chris Lattner4b009652007-07-25 00:24:17 +00001035 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
1036 HeaderInfo, LangInfo,
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001037 PredefineBuffer);
Chris Lattner4b009652007-07-25 00:24:17 +00001038
1039 if (!MainFileID) continue;
1040
1041 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
1042 *DiagClient, HeaderInfo, LangInfo);
Ted Kremenekb240e822007-12-11 23:28:38 +00001043
Chris Lattner4b009652007-07-25 00:24:17 +00001044 HeaderInfo.ClearFileInfo();
Ted Kremenekb240e822007-12-11 23:28:38 +00001045
1046 if (Stats)
1047 SourceMgr.PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001048 }
1049
1050 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1051
1052 if (NumDiagnostics)
1053 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1054 (NumDiagnostics == 1 ? "" : "s"));
1055
1056 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001057 FileMgr.PrintStats();
1058 fprintf(stderr, "\n");
1059 }
1060
1061 return Diags.getNumErrors() != 0;
1062}