blob: 139febeda1c8eee369f03b984a86c4720e8d7ade [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
162/// InitializeBaseLanguage - Handle the -x foo options or infer a base language
163/// from the input filename.
164static void InitializeBaseLanguage(LangOptions &Options,
165 const std::string &Filename) {
166 if (BaseLang == langkind_unspecified) {
167 std::string::size_type DotPos = Filename.rfind('.');
168 if (LangObjC) {
169 BaseLang = langkind_objc;
170 } else if (LangObjCXX) {
171 BaseLang = langkind_objcxx;
172 } else if (DotPos == std::string::npos) {
173 BaseLang = langkind_c; // Default to C if no extension.
174 } else {
175 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
176 // C header: .h
177 // C++ header: .hh or .H;
178 // assembler no preprocessing: .s
179 // assembler: .S
180 if (Ext == "c")
181 BaseLang = langkind_c;
182 else if (Ext == "i")
183 BaseLang = langkind_c_cpp;
184 else if (Ext == "ii")
185 BaseLang = langkind_cxx_cpp;
186 else if (Ext == "m")
187 BaseLang = langkind_objc;
188 else if (Ext == "mi")
189 BaseLang = langkind_objc_cpp;
190 else if (Ext == "mm" || Ext == "M")
191 BaseLang = langkind_objcxx;
192 else if (Ext == "mii")
193 BaseLang = langkind_objcxx_cpp;
194 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
195 Ext == "c++" || Ext == "cp" || Ext == "cxx")
196 BaseLang = langkind_cxx;
197 else
198 BaseLang = langkind_c;
199 }
200 }
201
202 // FIXME: implement -fpreprocessed mode.
203 bool NoPreprocess = false;
204
205 switch (BaseLang) {
206 default: assert(0 && "Unknown language kind!");
207 case langkind_c_cpp:
208 NoPreprocess = true;
209 // FALLTHROUGH
210 case langkind_c:
211 break;
212 case langkind_cxx_cpp:
213 NoPreprocess = true;
214 // FALLTHROUGH
215 case langkind_cxx:
216 Options.CPlusPlus = 1;
217 break;
218 case langkind_objc_cpp:
219 NoPreprocess = true;
220 // FALLTHROUGH
221 case langkind_objc:
222 Options.ObjC1 = Options.ObjC2 = 1;
223 break;
224 case langkind_objcxx_cpp:
225 NoPreprocess = true;
226 // FALLTHROUGH
227 case langkind_objcxx:
228 Options.ObjC1 = Options.ObjC2 = 1;
229 Options.CPlusPlus = 1;
230 break;
231 }
232}
233
234/// LangStds - Language standards we support.
235enum LangStds {
236 lang_unspecified,
237 lang_c89, lang_c94, lang_c99,
238 lang_gnu89, lang_gnu99,
239 lang_cxx98, lang_gnucxx98,
240 lang_cxx0x, lang_gnucxx0x
241};
242
243static llvm::cl::opt<LangStds>
244LangStd("std", llvm::cl::desc("Language standard to compile for"),
245 llvm::cl::init(lang_unspecified),
246 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
247 clEnumValN(lang_c89, "c90", "ISO C 1990"),
248 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
249 clEnumValN(lang_c94, "iso9899:199409",
250 "ISO C 1990 with amendment 1"),
251 clEnumValN(lang_c99, "c99", "ISO C 1999"),
252// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
253 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
254// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
255 clEnumValN(lang_gnu89, "gnu89",
256 "ISO C 1990 with GNU extensions (default for C)"),
257 clEnumValN(lang_gnu99, "gnu99",
258 "ISO C 1999 with GNU extensions"),
259 clEnumValN(lang_gnu99, "gnu9x",
260 "ISO C 1999 with GNU extensions"),
261 clEnumValN(lang_cxx98, "c++98",
262 "ISO C++ 1998 with amendments"),
263 clEnumValN(lang_gnucxx98, "gnu++98",
264 "ISO C++ 1998 with amendments and GNU "
265 "extensions (default for C++)"),
266 clEnumValN(lang_cxx0x, "c++0x",
267 "Upcoming ISO C++ 200x with amendments"),
268 clEnumValN(lang_gnucxx0x, "gnu++0x",
269 "Upcoming ISO C++ 200x with amendments and GNU "
270 "extensions (default for C++)"),
271 clEnumValEnd));
272
273static llvm::cl::opt<bool>
274NoOperatorNames("fno-operator-names",
275 llvm::cl::desc("Do not treat C++ operator name keywords as "
276 "synonyms for operators"));
277
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000278static llvm::cl::opt<bool>
279PascalStrings("fpascal-strings",
280 llvm::cl::desc("Recognize and construct Pascal-style "
281 "string literals"));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000282
283static llvm::cl::opt<bool>
284WritableStrings("fwritable-strings",
285 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000286
287static llvm::cl::opt<bool>
288LaxVectorConversions("flax-vector-conversions",
289 llvm::cl::desc("Allow implicit conversions between vectors"
290 " with a different number of elements or "
291 "different element types."));
Chris Lattner4b009652007-07-25 00:24:17 +0000292// FIXME: add:
293// -ansi
294// -trigraphs
295// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000296// -fpascal-strings
Chris Lattner4b009652007-07-25 00:24:17 +0000297static void InitializeLanguageStandard(LangOptions &Options) {
298 if (LangStd == lang_unspecified) {
299 // Based on the base language, pick one.
300 switch (BaseLang) {
301 default: assert(0 && "Unknown base language");
302 case langkind_c:
303 case langkind_c_cpp:
304 case langkind_objc:
305 case langkind_objc_cpp:
306 LangStd = lang_gnu99;
307 break;
308 case langkind_cxx:
309 case langkind_cxx_cpp:
310 case langkind_objcxx:
311 case langkind_objcxx_cpp:
312 LangStd = lang_gnucxx98;
313 break;
314 }
315 }
316
317 switch (LangStd) {
318 default: assert(0 && "Unknown language standard!");
319
320 // Fall through from newer standards to older ones. This isn't really right.
321 // FIXME: Enable specifically the right features based on the language stds.
322 case lang_gnucxx0x:
323 case lang_cxx0x:
324 Options.CPlusPlus0x = 1;
325 // FALL THROUGH
326 case lang_gnucxx98:
327 case lang_cxx98:
328 Options.CPlusPlus = 1;
329 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000330 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000331 // FALL THROUGH.
332 case lang_gnu99:
333 case lang_c99:
334 Options.Digraphs = 1;
335 Options.C99 = 1;
336 Options.HexFloats = 1;
337 // FALL THROUGH.
338 case lang_gnu89:
339 Options.BCPLComment = 1; // Only for C99/C++.
340 // FALL THROUGH.
341 case lang_c94:
342 case lang_c89:
343 break;
344 }
345
346 Options.Trigraphs = 1; // -trigraphs or -ansi
347 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000348 Options.PascalStrings = PascalStrings;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000349 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000350 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000351}
352
353//===----------------------------------------------------------------------===//
354// Our DiagnosticClient implementation
355//===----------------------------------------------------------------------===//
356
357// FIXME: Werror should take a list of things, -Werror=foo,bar
358static llvm::cl::opt<bool>
359WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
360
361static llvm::cl::opt<bool>
362WarnOnExtensions("pedantic", llvm::cl::init(false),
363 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
364
365static llvm::cl::opt<bool>
366ErrorOnExtensions("pedantic-errors",
367 llvm::cl::desc("Issue an error on uses of GCC extensions"));
368
369static llvm::cl::opt<bool>
370WarnUnusedMacros("Wunused_macros",
371 llvm::cl::desc("Warn for unused macros in the main translation unit"));
372
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000373static llvm::cl::opt<bool>
374WarnFloatEqual("Wfloat-equal",
375 llvm::cl::desc("Warn about equality comparisons of floating point values."));
376
Chris Lattner4b009652007-07-25 00:24:17 +0000377/// InitializeDiagnostics - Initialize the diagnostic object, based on the
378/// current command line option settings.
379static void InitializeDiagnostics(Diagnostic &Diags) {
380 Diags.setWarningsAsErrors(WarningsAsErrors);
381 Diags.setWarnOnExtensions(WarnOnExtensions);
382 Diags.setErrorOnExtensions(ErrorOnExtensions);
383
384 // Silence the "macro is not used" warning unless requested.
385 if (!WarnUnusedMacros)
386 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000387
388 // Silence "floating point comparison" warnings unless requested.
389 if (!WarnFloatEqual)
390 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000391}
392
393//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000394// Target Triple Processing.
395//===----------------------------------------------------------------------===//
396
397static llvm::cl::opt<std::string>
398TargetTriple("triple",
399 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
400
401static llvm::cl::list<std::string>
402Archs("arch",
403 llvm::cl::desc("Specify target architecture (e.g. i686)."));
404
405namespace {
406 class TripleProcessor {
407 llvm::StringMap<char> TriplesProcessed;
408 std::vector<std::string>& triples;
409 public:
410 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
411
412 void addTriple(const std::string& t) {
413 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
414 TriplesProcessed.end()) {
415 triples.push_back(t);
416 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
417 }
418 }
419 };
420}
421
422static void CreateTargetTriples(std::vector<std::string>& triples) {
423 std::string base_triple;
424
425 // Initialize base triple. If a -triple option has been specified, use
426 // that triple. Otherwise, default to the host triple.
427 if (TargetTriple.getValue().empty())
428 base_triple = LLVM_HOSTTRIPLE;
429 else
430 base_triple = TargetTriple.getValue();
431
432 // Decompose the base triple into "arch" and suffix.
433 std::string::size_type firstDash = base_triple.find("-");
434
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000435 if (firstDash == std::string::npos) {
436 fprintf(stderr,
437 "Malformed target triple: \"%s\" ('-' could not be found).\n",
438 base_triple.c_str());
439 exit (1);
440 }
Ted Kremenek40499482007-12-03 22:06:55 +0000441
442 std::string suffix(base_triple,firstDash+1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000443
444 if (suffix.empty()) {
445 fprintf(stderr,
446 "Malformed target triple: \"%s\" (no vendor or OS).\n",
447 base_triple.c_str());
448 exit (1);
449 }
Ted Kremenek40499482007-12-03 22:06:55 +0000450
451 // Create triple cacher.
452 TripleProcessor tp(triples);
453
454 // Add the primary triple to our set of triples if we are using the
455 // host-triple with no archs or using a specified target triple.
456 if (!TargetTriple.getValue().empty() || Archs.empty())
457 tp.addTriple(base_triple);
458
459 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
460 tp.addTriple(Archs[i] + "-" + suffix);
461}
462
463//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000464// Preprocessor Initialization
465//===----------------------------------------------------------------------===//
466
467// FIXME: Preprocessor builtins to support.
468// -A... - Play with #assertions
469// -undef - Undefine all predefined macros
470
471static llvm::cl::list<std::string>
472D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
473 llvm::cl::desc("Predefine the specified macro"));
474static llvm::cl::list<std::string>
475U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
476 llvm::cl::desc("Undefine the specified macro"));
477
478// Append a #define line to Buf for Macro. Macro should be of the form XXX,
479// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
480// "#define XXX Y z W". To get a #define with no value, use "XXX=".
481static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
482 const char *Command = "#define ") {
483 Buf.insert(Buf.end(), Command, Command+strlen(Command));
484 if (const char *Equal = strchr(Macro, '=')) {
485 // Turn the = into ' '.
486 Buf.insert(Buf.end(), Macro, Equal);
487 Buf.push_back(' ');
488 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
489 } else {
490 // Push "macroname 1".
491 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
492 Buf.push_back(' ');
493 Buf.push_back('1');
494 }
495 Buf.push_back('\n');
496}
497
Chris Lattner4b009652007-07-25 00:24:17 +0000498
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000499/// InitializePreprocessor - Initialize the preprocessor getting it and the
500/// environment ready to process a single file. This returns the file ID for the
501/// input file. If a failure happens, it returns 0.
502///
503static unsigned InitializePreprocessor(Preprocessor &PP,
504 const std::string &InFile,
505 SourceManager &SourceMgr,
506 HeaderSearch &HeaderInfo,
507 const LangOptions &LangInfo,
508 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000509
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000510 FileManager &FileMgr = HeaderInfo.getFileMgr();
Chris Lattner4b009652007-07-25 00:24:17 +0000511
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000512 // Figure out where to get and map in the main file.
513 unsigned MainFileID = 0;
514 if (InFile != "-") {
515 const FileEntry *File = FileMgr.getFile(InFile);
516 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
517 if (MainFileID == 0) {
518 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
519 return 0;
520 }
521 } else {
522 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
523 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
524 if (MainFileID == 0) {
525 fprintf(stderr, "Error reading standard input! Empty?\n");
526 return 0;
527 }
Chris Lattner4b009652007-07-25 00:24:17 +0000528 }
529
Chris Lattner4b009652007-07-25 00:24:17 +0000530 // Add macros from the command line.
531 // FIXME: Should traverse the #define/#undef lists in parallel.
532 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000533 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000534 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000535 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
536
537 // FIXME: Read any files specified by -imacros or -include.
538
539 // Null terminate PredefinedBuffer and add it.
540 PredefineBuffer.push_back(0);
541 PP.setPredefines(&PredefineBuffer[0]);
542
543 // Once we've read this, we're done.
544 return MainFileID;
Chris Lattner4b009652007-07-25 00:24:17 +0000545}
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000546
547
Chris Lattner4b009652007-07-25 00:24:17 +0000548
549//===----------------------------------------------------------------------===//
550// Preprocessor include path information.
551//===----------------------------------------------------------------------===//
552
553// This tool exports a large number of command line options to control how the
554// preprocessor searches for header files. At root, however, the Preprocessor
555// object takes a very simple interface: a list of directories to search for
556//
557// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000558// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000559//
560// FIXME: -include,-imacros
561
562static llvm::cl::opt<bool>
563nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
564
565// Various command line options. These four add directories to each chain.
566static llvm::cl::list<std::string>
567F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
568 llvm::cl::desc("Add directory to framework include search path"));
569static llvm::cl::list<std::string>
570I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
571 llvm::cl::desc("Add directory to include search path"));
572static llvm::cl::list<std::string>
573idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
574 llvm::cl::desc("Add directory to AFTER include search path"));
575static llvm::cl::list<std::string>
576iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
577 llvm::cl::desc("Add directory to QUOTE include search path"));
578static llvm::cl::list<std::string>
579isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
580 llvm::cl::desc("Add directory to SYSTEM include search path"));
581
582// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
583static llvm::cl::list<std::string>
584iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
585 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
586static llvm::cl::list<std::string>
587iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
588 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
589static llvm::cl::list<std::string>
590iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
591 llvm::cl::Prefix,
592 llvm::cl::desc("Set directory to include search path with prefix"));
593
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000594static llvm::cl::opt<std::string>
595isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
596 llvm::cl::desc("Set the system root directory (usually /)"));
597
Chris Lattner4b009652007-07-25 00:24:17 +0000598// Finally, implement the code that groks the options above.
599enum IncludeDirGroup {
600 Quoted = 0,
601 Angled,
602 System,
603 After
604};
605
606static std::vector<DirectoryLookup> IncludeGroup[4];
607
608/// AddPath - Add the specified path to the specified group list.
609///
610static void AddPath(const std::string &Path, IncludeDirGroup Group,
611 bool isCXXAware, bool isUserSupplied,
612 bool isFramework, FileManager &FM) {
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000613 const DirectoryEntry *DE;
614 if (Group == System)
615 DE = FM.getDirectory(isysroot + "/" + Path);
616 else
617 DE = FM.getDirectory(Path);
618
Chris Lattner4b009652007-07-25 00:24:17 +0000619 if (DE == 0) {
620 if (Verbose)
621 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
622 Path.c_str());
623 return;
624 }
625
626 DirectoryLookup::DirType Type;
627 if (Group == Quoted || Group == Angled)
628 Type = DirectoryLookup::NormalHeaderDir;
629 else if (isCXXAware)
630 Type = DirectoryLookup::SystemHeaderDir;
631 else
632 Type = DirectoryLookup::ExternCSystemHeaderDir;
633
634 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
635 isFramework));
636}
637
638/// RemoveDuplicates - If there are duplicate directory entries in the specified
639/// search list, remove the later (dead) ones.
640static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
641 std::set<const DirectoryEntry *> SeenDirs;
642 for (unsigned i = 0; i != SearchList.size(); ++i) {
643 // If this isn't the first time we've seen this dir, remove it.
644 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
645 if (Verbose)
646 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
647 SearchList[i].getDir()->getName());
648 SearchList.erase(SearchList.begin()+i);
649 --i;
650 }
651 }
652}
653
654/// InitializeIncludePaths - Process the -I options and set them in the
655/// HeaderSearch object.
656static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
657 Diagnostic &Diags, const LangOptions &Lang) {
658 // Handle -F... options.
659 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
660 AddPath(F_dirs[i], Angled, false, true, true, FM);
661
662 // Handle -I... options.
663 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
664 if (I_dirs[i] == "-") {
665 // -I- is a deprecated GCC feature.
666 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
667 } else {
668 AddPath(I_dirs[i], Angled, false, true, false, FM);
669 }
670 }
671
672 // Handle -idirafter... options.
673 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
674 AddPath(idirafter_dirs[i], After, false, true, false, FM);
675
676 // Handle -iquote... options.
677 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
678 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
679
680 // Handle -isystem... options.
681 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
682 AddPath(isystem_dirs[i], System, false, true, false, FM);
683
684 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
685 // parallel, processing the values in order of occurance to get the right
686 // prefixes.
687 {
688 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
689 unsigned iprefix_idx = 0;
690 unsigned iwithprefix_idx = 0;
691 unsigned iwithprefixbefore_idx = 0;
692 bool iprefix_done = iprefix_vals.empty();
693 bool iwithprefix_done = iwithprefix_vals.empty();
694 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
695 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
696 if (!iprefix_done &&
697 (iwithprefix_done ||
698 iprefix_vals.getPosition(iprefix_idx) <
699 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
700 (iwithprefixbefore_done ||
701 iprefix_vals.getPosition(iprefix_idx) <
702 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
703 Prefix = iprefix_vals[iprefix_idx];
704 ++iprefix_idx;
705 iprefix_done = iprefix_idx == iprefix_vals.size();
706 } else if (!iwithprefix_done &&
707 (iwithprefixbefore_done ||
708 iwithprefix_vals.getPosition(iwithprefix_idx) <
709 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
710 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
711 System, false, false, false, FM);
712 ++iwithprefix_idx;
713 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
714 } else {
715 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
716 Angled, false, false, false, FM);
717 ++iwithprefixbefore_idx;
718 iwithprefixbefore_done =
719 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
720 }
721 }
722 }
723
724 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
725 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
726
727 // FIXME: temporary hack: hard-coded paths.
728 // FIXME: get these from the target?
729 if (!nostdinc) {
730 if (Lang.CPlusPlus) {
731 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
732 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
733 false, FM);
734 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
735 }
736
737 AddPath("/usr/local/include", System, false, false, false, FM);
738 // leopard
739 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
740 false, false, false, FM);
741 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
742 System, false, false, false, FM);
743 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
744 "4.0.1/../../../../powerpc-apple-darwin0/include",
745 System, false, false, false, FM);
746
747 // tiger
748 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
749 false, false, false, FM);
750 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
751 System, false, false, false, FM);
752 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
753 "4.0.1/../../../../powerpc-apple-darwin8/include",
754 System, false, false, false, FM);
755
756 AddPath("/usr/include", System, false, false, false, FM);
757 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
758 AddPath("/Library/Frameworks", System, true, false, true, FM);
759 }
760
761 // Now that we have collected all of the include paths, merge them all
762 // together and tell the preprocessor about them.
763
764 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
765 std::vector<DirectoryLookup> SearchList;
766 SearchList = IncludeGroup[Angled];
767 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
768 IncludeGroup[System].end());
769 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
770 IncludeGroup[After].end());
771 RemoveDuplicates(SearchList);
772 RemoveDuplicates(IncludeGroup[Quoted]);
773
774 // Prepend QUOTED list on the search list.
775 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
776 IncludeGroup[Quoted].end());
777
778
779 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
780 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
781 DontSearchCurDir);
782
783 // If verbose, print the list of directories that will be searched.
784 if (Verbose) {
785 fprintf(stderr, "#include \"...\" search starts here:\n");
786 unsigned QuotedIdx = IncludeGroup[Quoted].size();
787 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
788 if (i == QuotedIdx)
789 fprintf(stderr, "#include <...> search starts here:\n");
790 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
791 }
792 }
793}
794
795
Chris Lattner4b009652007-07-25 00:24:17 +0000796//===----------------------------------------------------------------------===//
797// Basic Parser driver
798//===----------------------------------------------------------------------===//
799
800static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
801 Parser P(PP, *PA);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000802 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000803
804 // Parsing the specified input file.
805 P.ParseTranslationUnit();
806 delete PA;
807}
808
809//===----------------------------------------------------------------------===//
810// Main driver
811//===----------------------------------------------------------------------===//
812
Chris Lattner4b009652007-07-25 00:24:17 +0000813/// ProcessInputFile - Process a single input file with the specified state.
814///
815static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
816 const std::string &InFile,
817 SourceManager &SourceMgr,
818 TextDiagnostics &OurDiagnosticClient,
819 HeaderSearch &HeaderInfo,
820 const LangOptions &LangInfo) {
Ted Kremenek6856c632007-09-26 18:39:29 +0000821
822 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +0000823 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +0000824
Chris Lattner4b009652007-07-25 00:24:17 +0000825 switch (ProgAction) {
826 default:
827 fprintf(stderr, "Unexpected program action!\n");
828 return;
829 case DumpTokens: { // Token dump mode.
830 Token Tok;
831 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000832 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000833 do {
834 PP.Lex(Tok);
835 PP.DumpToken(Tok, true);
836 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +0000837 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000838 ClearSourceMgr = true;
839 break;
840 }
841 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
842 Token Tok;
843 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000844 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000845 do {
846 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +0000847 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000848 ClearSourceMgr = true;
849 break;
850 }
851
852 case PrintPreprocessedInput: // -E mode.
853 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
854 ClearSourceMgr = true;
855 break;
856
857 case ParseNoop: // -parse-noop
Steve Naroffebeb4282007-10-31 20:55:39 +0000858 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000859 ClearSourceMgr = true;
860 break;
861
862 case ParsePrintCallbacks:
Steve Naroffebeb4282007-10-31 20:55:39 +0000863 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
864 MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000865 ClearSourceMgr = true;
866 break;
Ted Kremenek0841c702007-09-25 18:37:20 +0000867
Ted Kremenek6856c632007-09-26 18:39:29 +0000868 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +0000869 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000870 break;
Ted Kremenek6856c632007-09-26 18:39:29 +0000871
Chris Lattner4045a8a2007-10-11 00:18:28 +0000872 case ASTPrint:
Ted Kremenek6856c632007-09-26 18:39:29 +0000873 Consumer = CreateASTPrinter();
874 break;
875
Chris Lattner4045a8a2007-10-11 00:18:28 +0000876 case ASTDump:
Ted Kremenek6856c632007-09-26 18:39:29 +0000877 Consumer = CreateASTDumper();
878 break;
879
Chris Lattner4045a8a2007-10-11 00:18:28 +0000880 case ASTView:
Ted Kremenek6856c632007-09-26 18:39:29 +0000881 Consumer = CreateASTViewer();
882 break;
883
884 case ParseCFGDump:
885 case ParseCFGView:
886 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
887 break;
888
889 case AnalysisLiveVariables:
890 Consumer = CreateLiveVarAnalyzer();
891 break;
892
893 case WarnDeadStores:
894 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
895 break;
896
897 case WarnUninitVals:
898 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
899 break;
900
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000901 case TestSerialization:
Ted Kremenek8b61b3b2007-12-03 22:48:14 +0000902 Consumer = CreateSerializationTest(PP.getDiagnostics());
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000903 break;
904
Ted Kremenek6856c632007-09-26 18:39:29 +0000905 case EmitLLVM:
Chris Lattnerdb6be562007-11-28 05:34:05 +0000906 Consumer = CreateLLVMEmitter(PP.getDiagnostics(), PP.getLangOptions());
Chris Lattner4b009652007-07-25 00:24:17 +0000907 break;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000908
909 case RewriteTest:
Chris Lattner258f26c2007-11-30 22:25:36 +0000910 Consumer = CreateCodeRewriterTest(PP.getDiagnostics());
Chris Lattnerb429ae42007-10-11 00:43:27 +0000911 break;
Chris Lattner129758d2007-09-16 19:46:59 +0000912 }
Ted Kremenek6856c632007-09-26 18:39:29 +0000913
914 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +0000915 if (VerifyDiagnostics)
Chris Lattner8593cbf2007-11-03 06:24:16 +0000916 exit(CheckASTConsumer(PP, MainFileID, Consumer));
917
918 // This deletes Consumer.
919 ParseAST(PP, MainFileID, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +0000920 }
921
922 if (Stats) {
923 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
924 PP.PrintStats();
925 PP.getIdentifierTable().PrintStats();
926 HeaderInfo.PrintStats();
927 if (ClearSourceMgr)
928 SourceMgr.PrintStats();
929 fprintf(stderr, "\n");
930 }
931
932 // For a multi-file compilation, some things are ok with nuking the source
933 // manager tables, other require stable fileid/macroid's across multiple
934 // files.
935 if (ClearSourceMgr) {
936 SourceMgr.clearIDTables();
937 }
938}
939
940static llvm::cl::list<std::string>
941InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
942
943
944int main(int argc, char **argv) {
945 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
946 llvm::sys::PrintStackTraceOnErrorSignal();
947
948 // If no input was specified, read from stdin.
949 if (InputFilenames.empty())
950 InputFilenames.push_back("-");
951
952 /// Create a SourceManager object. This tracks and owns all the file buffers
953 /// allocated to the program.
954 SourceManager SourceMgr;
955
956 // Create a file manager object to provide access to and cache the filesystem.
957 FileManager FileMgr;
958
959 // Initialize language options, inferring file types from input filenames.
960 // FIXME: This infers info from the first file, we should clump by language
961 // to handle 'x.c y.c a.cpp b.cpp'.
962 LangOptions LangInfo;
963 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
964 InitializeLanguageStandard(LangInfo);
965
966 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +0000967 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +0000968 // Print diagnostics to stderr by default.
969 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
970 } else {
971 // When checking diagnostics, just buffer them up.
972 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
973
974 if (InputFilenames.size() != 1) {
975 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +0000976 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000977 return 1;
978 }
979 }
980
981 // Configure our handling of diagnostics.
982 Diagnostic Diags(*DiagClient);
983 InitializeDiagnostics(Diags);
984
985 // Get information about the targets being compiled for. Note that this
986 // pointer and the TargetInfoImpl objects are never deleted by this toy
987 // driver.
Ted Kremenek40499482007-12-03 22:06:55 +0000988 TargetInfo *Target;
989
990 { // Create triples, and create the TargetInfo.
991 std::vector<std::string> triples;
992 CreateTargetTriples(triples);
Ted Kremenek40499482007-12-03 22:06:55 +0000993 Target = CreateTargetInfo(triples,Diags);
994 }
995
Chris Lattner4b009652007-07-25 00:24:17 +0000996 if (Target == 0) {
997 fprintf(stderr,
998 "Sorry, don't know what target this is, please use -arch.\n");
999 exit(1);
1000 }
1001
1002 // Process the -I options and set them in the HeaderInfo.
1003 HeaderSearch HeaderInfo(FileMgr);
1004 DiagClient->setHeaderSearch(HeaderInfo);
1005 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
1006
1007 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1008 // Set up the preprocessor with these options.
1009 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
Chris Lattner4b009652007-07-25 00:24:17 +00001010 const std::string &InFile = InputFilenames[i];
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001011 std::vector<char> PredefineBuffer;
Chris Lattner4b009652007-07-25 00:24:17 +00001012 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
1013 HeaderInfo, LangInfo,
Chris Lattnerd1f21e12007-10-09 22:10:18 +00001014 PredefineBuffer);
Chris Lattner4b009652007-07-25 00:24:17 +00001015
1016 if (!MainFileID) continue;
1017
1018 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
1019 *DiagClient, HeaderInfo, LangInfo);
1020 HeaderInfo.ClearFileInfo();
1021 }
1022
1023 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1024
1025 if (NumDiagnostics)
1026 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1027 (NumDiagnostics == 1 ? "" : "s"));
1028
1029 if (Stats) {
1030 // Printed from high-to-low level.
1031 SourceMgr.PrintStats();
1032 FileMgr.PrintStats();
1033 fprintf(stderr, "\n");
1034 }
1035
1036 return Diags.getNumErrors() != 0;
1037}