blob: 76cad929d1d333e4bc2ef090bc08f3f9303b4dc7 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek20e97482007-12-12 23:41:08 +000029#include "TranslationUnit.h"
Chris Lattner556beb72007-09-15 22:56:56 +000030#include "clang/Sema/ASTStreamer.h"
31#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Parse/Parser.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/MemoryBuffer.h"
39#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000040#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include <memory>
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// Global options.
46//===----------------------------------------------------------------------===//
47
48static llvm::cl::opt<bool>
49Verbose("v", llvm::cl::desc("Enable verbose output"));
50static llvm::cl::opt<bool>
51Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
52
53enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000054 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000055 EmitLLVM, // Emit a .ll file.
Chris Lattner3b427b32007-10-11 00:18:28 +000056 ASTPrint, // Parse ASTs and print them.
57 ASTDump, // Parse ASTs and dump them.
58 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000059 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000060 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000061 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000062 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000063 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000064 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000065 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000066 ParsePrintCallbacks, // Parse and print each callback.
67 ParseSyntaxOnly, // Parse and perform semantic analysis.
68 ParseNoop, // Parse with noop callbacks.
69 RunPreprocessorOnly, // Just lex, no output.
70 PrintPreprocessedInput, // -E mode.
71 DumpTokens // Token dump mode.
72};
73
74static llvm::cl::opt<ProgActions>
75ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
76 llvm::cl::init(ParseSyntaxOnly),
77 llvm::cl::values(
78 clEnumValN(RunPreprocessorOnly, "Eonly",
79 "Just run preprocessor, no output (for timings)"),
80 clEnumValN(PrintPreprocessedInput, "E",
81 "Run preprocessor, emit preprocessed file"),
82 clEnumValN(DumpTokens, "dumptokens",
83 "Run preprocessor, dump internal rep of tokens"),
84 clEnumValN(ParseNoop, "parse-noop",
85 "Run parser with noop callbacks (for timings)"),
86 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
87 "Run parser and perform semantic analysis"),
88 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
89 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000090 clEnumValN(ASTPrint, "ast-print",
91 "Build ASTs and then pretty-print them"),
92 clEnumValN(ASTDump, "ast-dump",
93 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000094 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000095 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000096 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +000097 "Run parser, then build and print CFGs."),
98 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +000099 "Run parser, then build and view CFGs with Graphviz."),
100 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000101 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000102 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000103 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000104 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000105 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000106 clEnumValN(TestSerialization, "test-pickling",
107 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000109 "Build ASTs then convert to LLVM, emit .ll file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000110 clEnumValN(RewriteTest, "rewrite-test",
111 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 clEnumValEnd));
113
Ted Kremenek41193e42007-09-26 19:42:19 +0000114static llvm::cl::opt<bool>
115VerifyDiagnostics("verify",
116 llvm::cl::desc("Verify emitted diagnostics and warnings."));
117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118//===----------------------------------------------------------------------===//
119// Language Options
120//===----------------------------------------------------------------------===//
121
122enum LangKind {
123 langkind_unspecified,
124 langkind_c,
125 langkind_c_cpp,
126 langkind_cxx,
127 langkind_cxx_cpp,
128 langkind_objc,
129 langkind_objc_cpp,
130 langkind_objcxx,
131 langkind_objcxx_cpp
132};
133
134/* TODO: GCC also accepts:
135 c-header c++-header objective-c-header objective-c++-header
136 assembler assembler-with-cpp
137 ada, f77*, ratfor (!), f95, java, treelang
138 */
139static llvm::cl::opt<LangKind>
140BaseLang("x", llvm::cl::desc("Base language to compile"),
141 llvm::cl::init(langkind_unspecified),
142 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
143 clEnumValN(langkind_cxx, "c++", "C++"),
144 clEnumValN(langkind_objc, "objective-c", "Objective C"),
145 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
146 clEnumValN(langkind_c_cpp, "c-cpp-output",
147 "Preprocessed C"),
148 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
149 "Preprocessed C++"),
150 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
151 "Preprocessed Objective C"),
152 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
153 "Preprocessed Objective C++"),
154 clEnumValEnd));
155
156static llvm::cl::opt<bool>
157LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
158 llvm::cl::Hidden);
159static llvm::cl::opt<bool>
160LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
161 llvm::cl::Hidden);
162
Ted Kremenek8904f152007-12-05 23:49:08 +0000163/// InitializeBaseLanguage - Handle the -x foo options.
164static void InitializeBaseLanguage() {
165 if (LangObjC)
166 BaseLang = langkind_objc;
167 else if (LangObjCXX)
168 BaseLang = langkind_objcxx;
169}
170
171static LangKind GetLanguage(const std::string &Filename) {
172 if (BaseLang != langkind_unspecified)
173 return BaseLang;
174
175 std::string::size_type DotPos = Filename.rfind('.');
176
177 if (DotPos == std::string::npos) {
178 BaseLang = langkind_c; // Default to C if no extension.
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 }
180
Ted Kremenek8904f152007-12-05 23:49:08 +0000181 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
182 // C header: .h
183 // C++ header: .hh or .H;
184 // assembler no preprocessing: .s
185 // assembler: .S
186 if (Ext == "c")
187 return langkind_c;
188 else if (Ext == "i")
189 return langkind_c_cpp;
190 else if (Ext == "ii")
191 return langkind_cxx_cpp;
192 else if (Ext == "m")
193 return langkind_objc;
194 else if (Ext == "mi")
195 return langkind_objc_cpp;
196 else if (Ext == "mm" || Ext == "M")
197 return langkind_objcxx;
198 else if (Ext == "mii")
199 return langkind_objcxx_cpp;
200 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
201 Ext == "c++" || Ext == "cp" || Ext == "cxx")
202 return langkind_cxx;
203 else
204 return langkind_c;
205}
206
207
208static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 // FIXME: implement -fpreprocessed mode.
210 bool NoPreprocess = false;
211
Ted Kremenek8904f152007-12-05 23:49:08 +0000212 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 default: assert(0 && "Unknown language kind!");
214 case langkind_c_cpp:
215 NoPreprocess = true;
216 // FALLTHROUGH
217 case langkind_c:
218 break;
219 case langkind_cxx_cpp:
220 NoPreprocess = true;
221 // FALLTHROUGH
222 case langkind_cxx:
223 Options.CPlusPlus = 1;
224 break;
225 case langkind_objc_cpp:
226 NoPreprocess = true;
227 // FALLTHROUGH
228 case langkind_objc:
229 Options.ObjC1 = Options.ObjC2 = 1;
230 break;
231 case langkind_objcxx_cpp:
232 NoPreprocess = true;
233 // FALLTHROUGH
234 case langkind_objcxx:
235 Options.ObjC1 = Options.ObjC2 = 1;
236 Options.CPlusPlus = 1;
237 break;
238 }
239}
240
241/// LangStds - Language standards we support.
242enum LangStds {
243 lang_unspecified,
244 lang_c89, lang_c94, lang_c99,
245 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000246 lang_cxx98, lang_gnucxx98,
247 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000248};
249
250static llvm::cl::opt<LangStds>
251LangStd("std", llvm::cl::desc("Language standard to compile for"),
252 llvm::cl::init(lang_unspecified),
253 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
254 clEnumValN(lang_c89, "c90", "ISO C 1990"),
255 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
256 clEnumValN(lang_c94, "iso9899:199409",
257 "ISO C 1990 with amendment 1"),
258 clEnumValN(lang_c99, "c99", "ISO C 1999"),
259// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
260 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
261// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
262 clEnumValN(lang_gnu89, "gnu89",
263 "ISO C 1990 with GNU extensions (default for C)"),
264 clEnumValN(lang_gnu99, "gnu99",
265 "ISO C 1999 with GNU extensions"),
266 clEnumValN(lang_gnu99, "gnu9x",
267 "ISO C 1999 with GNU extensions"),
268 clEnumValN(lang_cxx98, "c++98",
269 "ISO C++ 1998 with amendments"),
270 clEnumValN(lang_gnucxx98, "gnu++98",
271 "ISO C++ 1998 with amendments and GNU "
272 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000273 clEnumValN(lang_cxx0x, "c++0x",
274 "Upcoming ISO C++ 200x with amendments"),
275 clEnumValN(lang_gnucxx0x, "gnu++0x",
276 "Upcoming ISO C++ 200x with amendments and GNU "
277 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 clEnumValEnd));
279
280static llvm::cl::opt<bool>
281NoOperatorNames("fno-operator-names",
282 llvm::cl::desc("Do not treat C++ operator name keywords as "
283 "synonyms for operators"));
284
Anders Carlssonee98ac52007-10-15 02:50:23 +0000285static llvm::cl::opt<bool>
286PascalStrings("fpascal-strings",
287 llvm::cl::desc("Recognize and construct Pascal-style "
288 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000289
290static llvm::cl::opt<bool>
291WritableStrings("fwritable-strings",
292 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000293
294static llvm::cl::opt<bool>
295LaxVectorConversions("flax-vector-conversions",
296 llvm::cl::desc("Allow implicit conversions between vectors"
297 " with a different number of elements or "
298 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000299// FIXME: add:
300// -ansi
301// -trigraphs
302// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000303// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000304static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 if (LangStd == lang_unspecified) {
306 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000307 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 default: assert(0 && "Unknown base language");
309 case langkind_c:
310 case langkind_c_cpp:
311 case langkind_objc:
312 case langkind_objc_cpp:
313 LangStd = lang_gnu99;
314 break;
315 case langkind_cxx:
316 case langkind_cxx_cpp:
317 case langkind_objcxx:
318 case langkind_objcxx_cpp:
319 LangStd = lang_gnucxx98;
320 break;
321 }
322 }
323
324 switch (LangStd) {
325 default: assert(0 && "Unknown language standard!");
326
327 // Fall through from newer standards to older ones. This isn't really right.
328 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000329 case lang_gnucxx0x:
330 case lang_cxx0x:
331 Options.CPlusPlus0x = 1;
332 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 case lang_gnucxx98:
334 case lang_cxx98:
335 Options.CPlusPlus = 1;
336 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000337 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 // FALL THROUGH.
339 case lang_gnu99:
340 case lang_c99:
341 Options.Digraphs = 1;
342 Options.C99 = 1;
343 Options.HexFloats = 1;
344 // FALL THROUGH.
345 case lang_gnu89:
346 Options.BCPLComment = 1; // Only for C99/C++.
347 // FALL THROUGH.
348 case lang_c94:
349 case lang_c89:
350 break;
351 }
352
353 Options.Trigraphs = 1; // -trigraphs or -ansi
354 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000355 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000356 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000357 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000358}
359
360//===----------------------------------------------------------------------===//
361// Our DiagnosticClient implementation
362//===----------------------------------------------------------------------===//
363
364// FIXME: Werror should take a list of things, -Werror=foo,bar
365static llvm::cl::opt<bool>
366WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
367
368static llvm::cl::opt<bool>
369WarnOnExtensions("pedantic", llvm::cl::init(false),
370 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
371
372static llvm::cl::opt<bool>
373ErrorOnExtensions("pedantic-errors",
374 llvm::cl::desc("Issue an error on uses of GCC extensions"));
375
376static llvm::cl::opt<bool>
377WarnUnusedMacros("Wunused_macros",
378 llvm::cl::desc("Warn for unused macros in the main translation unit"));
379
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000380static llvm::cl::opt<bool>
381WarnFloatEqual("Wfloat-equal",
382 llvm::cl::desc("Warn about equality comparisons of floating point values."));
383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384/// InitializeDiagnostics - Initialize the diagnostic object, based on the
385/// current command line option settings.
386static void InitializeDiagnostics(Diagnostic &Diags) {
387 Diags.setWarningsAsErrors(WarningsAsErrors);
388 Diags.setWarnOnExtensions(WarnOnExtensions);
389 Diags.setErrorOnExtensions(ErrorOnExtensions);
390
391 // Silence the "macro is not used" warning unless requested.
392 if (!WarnUnusedMacros)
393 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000394
395 // Silence "floating point comparison" warnings unless requested.
396 if (!WarnFloatEqual)
397 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398}
399
400//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000401// Target Triple Processing.
402//===----------------------------------------------------------------------===//
403
404static llvm::cl::opt<std::string>
405TargetTriple("triple",
406 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
407
408static llvm::cl::list<std::string>
409Archs("arch",
410 llvm::cl::desc("Specify target architecture (e.g. i686)."));
411
412namespace {
413 class TripleProcessor {
414 llvm::StringMap<char> TriplesProcessed;
415 std::vector<std::string>& triples;
416 public:
417 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
418
419 void addTriple(const std::string& t) {
420 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
421 TriplesProcessed.end()) {
422 triples.push_back(t);
423 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
424 }
425 }
426 };
427}
428
429static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000430 // Initialize base triple. If a -triple option has been specified, use
431 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000432 std::string Triple = TargetTriple;
433 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000434
435 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000436 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000437
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000438 if (firstDash == std::string::npos) {
439 fprintf(stderr,
440 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000441 Triple.c_str());
442 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000443 }
Ted Kremenekae360762007-12-03 22:06:55 +0000444
Chris Lattner6590d212007-12-12 05:01:48 +0000445 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000446
447 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000448 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
449 Triple.c_str());
450 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000451 }
Ted Kremenekae360762007-12-03 22:06:55 +0000452
453 // Create triple cacher.
454 TripleProcessor tp(triples);
455
456 // Add the primary triple to our set of triples if we are using the
457 // host-triple with no archs or using a specified target triple.
458 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000459 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000460
461 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
462 tp.addTriple(Archs[i] + "-" + suffix);
463}
464
465//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000466// Preprocessor Initialization
467//===----------------------------------------------------------------------===//
468
469// FIXME: Preprocessor builtins to support.
470// -A... - Play with #assertions
471// -undef - Undefine all predefined macros
472
473static llvm::cl::list<std::string>
474D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
475 llvm::cl::desc("Predefine the specified macro"));
476static llvm::cl::list<std::string>
477U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
478 llvm::cl::desc("Undefine the specified macro"));
479
480// Append a #define line to Buf for Macro. Macro should be of the form XXX,
481// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
482// "#define XXX Y z W". To get a #define with no value, use "XXX=".
483static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
484 const char *Command = "#define ") {
485 Buf.insert(Buf.end(), Command, Command+strlen(Command));
486 if (const char *Equal = strchr(Macro, '=')) {
487 // Turn the = into ' '.
488 Buf.insert(Buf.end(), Macro, Equal);
489 Buf.push_back(' ');
490 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
491 } else {
492 // Push "macroname 1".
493 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
494 Buf.push_back(' ');
495 Buf.push_back('1');
496 }
497 Buf.push_back('\n');
498}
499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500
Chris Lattner53b0dab2007-10-09 22:10:18 +0000501/// InitializePreprocessor - Initialize the preprocessor getting it and the
502/// environment ready to process a single file. This returns the file ID for the
503/// input file. If a failure happens, it returns 0.
504///
505static unsigned InitializePreprocessor(Preprocessor &PP,
506 const std::string &InFile,
507 SourceManager &SourceMgr,
508 HeaderSearch &HeaderInfo,
509 const LangOptions &LangInfo,
510 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000511
Chris Lattner53b0dab2007-10-09 22:10:18 +0000512 FileManager &FileMgr = HeaderInfo.getFileMgr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000513
Chris Lattner53b0dab2007-10-09 22:10:18 +0000514 // Figure out where to get and map in the main file.
515 unsigned MainFileID = 0;
516 if (InFile != "-") {
517 const FileEntry *File = FileMgr.getFile(InFile);
518 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
519 if (MainFileID == 0) {
520 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
521 return 0;
522 }
523 } else {
524 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
525 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
526 if (MainFileID == 0) {
527 fprintf(stderr, "Error reading standard input! Empty?\n");
528 return 0;
529 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 }
531
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 // Add macros from the command line.
533 // FIXME: Should traverse the #define/#undef lists in parallel.
534 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000535 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000537 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
538
539 // FIXME: Read any files specified by -imacros or -include.
540
541 // Null terminate PredefinedBuffer and add it.
542 PredefineBuffer.push_back(0);
543 PP.setPredefines(&PredefineBuffer[0]);
544
545 // Once we've read this, we're done.
546 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000547}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000548
549
Reid Spencer5f016e22007-07-11 17:01:13 +0000550
551//===----------------------------------------------------------------------===//
552// Preprocessor include path information.
553//===----------------------------------------------------------------------===//
554
555// This tool exports a large number of command line options to control how the
556// preprocessor searches for header files. At root, however, the Preprocessor
557// object takes a very simple interface: a list of directories to search for
558//
559// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000560// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000561//
562// FIXME: -include,-imacros
563
564static llvm::cl::opt<bool>
565nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
566
567// Various command line options. These four add directories to each chain.
568static llvm::cl::list<std::string>
569F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
570 llvm::cl::desc("Add directory to framework include search path"));
571static llvm::cl::list<std::string>
572I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
573 llvm::cl::desc("Add directory to include search path"));
574static llvm::cl::list<std::string>
575idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
576 llvm::cl::desc("Add directory to AFTER include search path"));
577static llvm::cl::list<std::string>
578iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
579 llvm::cl::desc("Add directory to QUOTE include search path"));
580static llvm::cl::list<std::string>
581isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
582 llvm::cl::desc("Add directory to SYSTEM include search path"));
583
584// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
585static llvm::cl::list<std::string>
586iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
587 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
588static llvm::cl::list<std::string>
589iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
590 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
591static llvm::cl::list<std::string>
592iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
593 llvm::cl::Prefix,
594 llvm::cl::desc("Set directory to include search path with prefix"));
595
Chris Lattner0c946412007-08-26 17:47:35 +0000596static llvm::cl::opt<std::string>
597isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
598 llvm::cl::desc("Set the system root directory (usually /)"));
599
Reid Spencer5f016e22007-07-11 17:01:13 +0000600// Finally, implement the code that groks the options above.
601enum IncludeDirGroup {
602 Quoted = 0,
603 Angled,
604 System,
605 After
606};
607
608static std::vector<DirectoryLookup> IncludeGroup[4];
609
610/// AddPath - Add the specified path to the specified group list.
611///
612static void AddPath(const std::string &Path, IncludeDirGroup Group,
613 bool isCXXAware, bool isUserSupplied,
614 bool isFramework, FileManager &FM) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000615 assert(!Path.empty() && "can't handle empty path here");
616
Chris Lattner0c946412007-08-26 17:47:35 +0000617 const DirectoryEntry *DE;
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000618 if (Group == System) {
619 if (isysroot != "/")
620 DE = FM.getDirectory(isysroot + "/" + Path);
621 else if (Path[0] == '/')
622 DE = FM.getDirectory(Path);
623 else
624 DE = FM.getDirectory("/" + Path);
625 } else
Chris Lattner0c946412007-08-26 17:47:35 +0000626 DE = FM.getDirectory(Path);
627
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 if (DE == 0) {
629 if (Verbose)
630 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
631 Path.c_str());
632 return;
633 }
634
635 DirectoryLookup::DirType Type;
636 if (Group == Quoted || Group == Angled)
637 Type = DirectoryLookup::NormalHeaderDir;
638 else if (isCXXAware)
639 Type = DirectoryLookup::SystemHeaderDir;
640 else
641 Type = DirectoryLookup::ExternCSystemHeaderDir;
642
643 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
644 isFramework));
645}
646
647/// RemoveDuplicates - If there are duplicate directory entries in the specified
648/// search list, remove the later (dead) ones.
649static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
650 std::set<const DirectoryEntry *> SeenDirs;
651 for (unsigned i = 0; i != SearchList.size(); ++i) {
652 // If this isn't the first time we've seen this dir, remove it.
653 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
654 if (Verbose)
655 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
656 SearchList[i].getDir()->getName());
657 SearchList.erase(SearchList.begin()+i);
658 --i;
659 }
660 }
661}
662
663/// InitializeIncludePaths - Process the -I options and set them in the
664/// HeaderSearch object.
665static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000666 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 // Handle -F... options.
668 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
669 AddPath(F_dirs[i], Angled, false, true, true, FM);
670
671 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000672 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
673 AddPath(I_dirs[i], Angled, false, true, false, FM);
Reid Spencer5f016e22007-07-11 17:01:13 +0000674
675 // Handle -idirafter... options.
676 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
677 AddPath(idirafter_dirs[i], After, false, true, false, FM);
678
679 // Handle -iquote... options.
680 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
681 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
682
683 // Handle -isystem... options.
684 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
685 AddPath(isystem_dirs[i], System, false, true, false, FM);
686
687 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
688 // parallel, processing the values in order of occurance to get the right
689 // prefixes.
690 {
691 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
692 unsigned iprefix_idx = 0;
693 unsigned iwithprefix_idx = 0;
694 unsigned iwithprefixbefore_idx = 0;
695 bool iprefix_done = iprefix_vals.empty();
696 bool iwithprefix_done = iwithprefix_vals.empty();
697 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
698 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
699 if (!iprefix_done &&
700 (iwithprefix_done ||
701 iprefix_vals.getPosition(iprefix_idx) <
702 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
703 (iwithprefixbefore_done ||
704 iprefix_vals.getPosition(iprefix_idx) <
705 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
706 Prefix = iprefix_vals[iprefix_idx];
707 ++iprefix_idx;
708 iprefix_done = iprefix_idx == iprefix_vals.size();
709 } else if (!iwithprefix_done &&
710 (iwithprefixbefore_done ||
711 iwithprefix_vals.getPosition(iwithprefix_idx) <
712 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
713 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
714 System, false, false, false, FM);
715 ++iwithprefix_idx;
716 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
717 } else {
718 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
719 Angled, false, false, false, FM);
720 ++iwithprefixbefore_idx;
721 iwithprefixbefore_done =
722 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
723 }
724 }
725 }
726
727 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
728 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
729
730 // FIXME: temporary hack: hard-coded paths.
731 // FIXME: get these from the target?
732 if (!nostdinc) {
733 if (Lang.CPlusPlus) {
734 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
735 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
736 false, FM);
737 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
738 }
739
740 AddPath("/usr/local/include", System, false, false, false, FM);
741 // leopard
742 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
743 false, false, false, FM);
744 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
745 System, false, false, false, FM);
746 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
747 "4.0.1/../../../../powerpc-apple-darwin0/include",
748 System, false, false, false, FM);
749
750 // tiger
751 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
752 false, false, false, FM);
753 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
754 System, false, false, false, FM);
755 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
756 "4.0.1/../../../../powerpc-apple-darwin8/include",
757 System, false, false, false, FM);
758
759 AddPath("/usr/include", System, false, false, false, FM);
760 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
761 AddPath("/Library/Frameworks", System, true, false, true, FM);
762 }
763
764 // Now that we have collected all of the include paths, merge them all
765 // together and tell the preprocessor about them.
766
767 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
768 std::vector<DirectoryLookup> SearchList;
769 SearchList = IncludeGroup[Angled];
770 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
771 IncludeGroup[System].end());
772 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
773 IncludeGroup[After].end());
774 RemoveDuplicates(SearchList);
775 RemoveDuplicates(IncludeGroup[Quoted]);
776
777 // Prepend QUOTED list on the search list.
778 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
779 IncludeGroup[Quoted].end());
780
781
782 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
783 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
784 DontSearchCurDir);
785
786 // If verbose, print the list of directories that will be searched.
787 if (Verbose) {
788 fprintf(stderr, "#include \"...\" search starts here:\n");
789 unsigned QuotedIdx = IncludeGroup[Quoted].size();
790 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
791 if (i == QuotedIdx)
792 fprintf(stderr, "#include <...> search starts here:\n");
793 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
794 }
795 }
796}
797
798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799//===----------------------------------------------------------------------===//
800// Basic Parser driver
801//===----------------------------------------------------------------------===//
802
803static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
804 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000805 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000806
807 // Parsing the specified input file.
808 P.ParseTranslationUnit();
809 delete PA;
810}
811
812//===----------------------------------------------------------------------===//
813// Main driver
814//===----------------------------------------------------------------------===//
815
Ted Kremenekdb094a22007-12-05 18:27:04 +0000816/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
817/// action. These consumers can operate on both ASTs that are freshly
818/// parsed from source files as well as those deserialized from Bitcode.
819static ASTConsumer* CreateASTConsumer(Diagnostic& Diag, FileManager& FileMgr,
820 const LangOptions& LangOpts) {
821 switch (ProgAction) {
822 default:
823 return NULL;
824
825 case ASTPrint:
826 return CreateASTPrinter();
827
828 case ASTDump:
829 return CreateASTDumper();
830
831 case ASTView:
832 return CreateASTViewer();
833
834 case ParseCFGDump:
835 case ParseCFGView:
836 return CreateCFGDumper(ProgAction == ParseCFGView);
837
838 case AnalysisLiveVariables:
839 return CreateLiveVarAnalyzer();
840
841 case WarnDeadStores:
842 return CreateDeadStoreChecker(Diag);
843
844 case WarnUninitVals:
845 return CreateUnitValsChecker(Diag);
846
847 case TestSerialization:
Ted Kremenekacc9f332007-12-05 21:34:36 +0000848 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000849
850 case EmitLLVM:
851 return CreateLLVMEmitter(Diag, LangOpts);
852
853 case RewriteTest:
854 return CreateCodeRewriterTest(Diag);
855 }
856}
857
Reid Spencer5f016e22007-07-11 17:01:13 +0000858/// ProcessInputFile - Process a single input file with the specified state.
859///
860static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
861 const std::string &InFile,
862 SourceManager &SourceMgr,
863 TextDiagnostics &OurDiagnosticClient,
864 HeaderSearch &HeaderInfo,
865 const LangOptions &LangInfo) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000866
867 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000868 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000869
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 switch (ProgAction) {
871 default:
Ted Kremenekdb094a22007-12-05 18:27:04 +0000872 Consumer = CreateASTConsumer(PP.getDiagnostics(), HeaderInfo.getFileMgr(),
873 PP.getLangOptions());
874
875 if (!Consumer) {
876 fprintf(stderr, "Unexpected program action!\n");
877 return;
878 }
879 break;
880
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000882 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000884 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 do {
886 PP.Lex(Tok);
887 PP.DumpToken(Tok, true);
888 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000889 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000890 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 break;
892 }
893 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000894 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000896 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 do {
898 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000899 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000900 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 break;
902 }
903
904 case PrintPreprocessedInput: // -E mode.
905 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000906 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 break;
908
909 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000910 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000911 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 break;
913
914 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +0000915 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
916 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000917 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000919
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000920 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000921 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000922 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000923 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000924
925 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000926 if (VerifyDiagnostics)
Chris Lattner31e6c7d2007-11-03 06:24:16 +0000927 exit(CheckASTConsumer(PP, MainFileID, Consumer));
928
929 // This deletes Consumer.
930 ParseAST(PP, MainFileID, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 }
932
933 if (Stats) {
934 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
935 PP.PrintStats();
936 PP.getIdentifierTable().PrintStats();
937 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000938 if (ClearSourceMgr)
939 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 fprintf(stderr, "\n");
941 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000942
943 // For a multi-file compilation, some things are ok with nuking the source
944 // manager tables, other require stable fileid/macroid's across multiple
945 // files.
946 if (ClearSourceMgr) {
947 SourceMgr.clearIDTables();
948 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000949}
950
Ted Kremenek20e97482007-12-12 23:41:08 +0000951static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
952 FileManager& FileMgr) {
953
954 if (VerifyDiagnostics) {
955 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
956 exit (1);
957 }
958
959 llvm::sys::Path Filename(InFile);
960
961 if (!Filename.isValid()) {
962 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
963 exit (1);
964 }
965
966 TranslationUnit* TU = TranslationUnit::ReadBitcodeFile(Filename,FileMgr);
967 ASTConsumer* Consumer = CreateASTConsumer(Diag,FileMgr,TU->getLangOpts());
968
969 if (!Consumer) {
970 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
971 exit (1);
972 }
973
974 // FIXME: only work on consumers that do not require MainFileID.
975 Consumer->Initialize(*TU->getContext(),0);
976
977 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
978 Consumer->HandleTopLevelDecl(*I);
979
980 delete Consumer;
981}
982
983
Reid Spencer5f016e22007-07-11 17:01:13 +0000984static llvm::cl::list<std::string>
985InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
986
Ted Kremenek20e97482007-12-12 23:41:08 +0000987static bool isSerializedFile(const std::string& InFile) {
988 if (InFile.size() < 4)
989 return false;
990
991 const char* s = InFile.c_str()+InFile.size()-4;
992
993 return s[0] == '.' &&
994 s[1] == 'a' &&
995 s[2] == 's' &&
996 s[3] == 't';
997}
998
Reid Spencer5f016e22007-07-11 17:01:13 +0000999
1000int main(int argc, char **argv) {
1001 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1002 llvm::sys::PrintStackTraceOnErrorSignal();
1003
1004 // If no input was specified, read from stdin.
1005 if (InputFilenames.empty())
1006 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001007
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 // Create a file manager object to provide access to and cache the filesystem.
1009 FileManager FileMgr;
1010
Ted Kremenek31e703b2007-12-11 23:28:38 +00001011 // Create the diagnostic client for reporting errors or for
1012 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001014 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001016 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 } else {
1018 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001019 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001020
1021 if (InputFilenames.size() != 1) {
1022 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001023 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 return 1;
1025 }
1026 }
1027
1028 // Configure our handling of diagnostics.
1029 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001030 InitializeDiagnostics(Diags);
1031
Chris Lattner4f037832007-12-05 23:24:17 +00001032 // -I- is a deprecated GCC feature, scan for it and reject it.
1033 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1034 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001035 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001036 I_dirs.erase(I_dirs.begin()+i);
1037 --i;
1038 }
1039 }
1040
Reid Spencer5f016e22007-07-11 17:01:13 +00001041 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001042 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001043
Ted Kremenek20e97482007-12-12 23:41:08 +00001044 if (isSerializedFile(InFile))
1045 ProcessSerializedFile(InFile,Diags,FileMgr);
1046 else {
1047 /// Create a SourceManager object. This tracks and owns all the file
1048 /// buffers allocated to a translation unit.
1049 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001050
Ted Kremenek20e97482007-12-12 23:41:08 +00001051 // Initialize language options, inferring file types from input filenames.
1052 LangOptions LangInfo;
1053 InitializeBaseLanguage();
1054 LangKind LK = GetLanguage(InFile);
1055 InitializeLangOptions(LangInfo, LK);
1056 InitializeLanguageStandard(LangInfo, LK);
1057
1058 // Process the -I options and set them in the HeaderInfo.
1059 HeaderSearch HeaderInfo(FileMgr);
1060 DiagClient->setHeaderSearch(HeaderInfo);
1061 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1062
1063 // Get information about the targets being compiled for. Note that this
1064 // pointer and the TargetInfoImpl objects are never deleted by this toy
1065 // driver.
1066 TargetInfo *Target;
1067
1068 // Create triples, and create the TargetInfo.
1069 std::vector<std::string> triples;
1070 CreateTargetTriples(triples);
1071 Target = TargetInfo::CreateTargetInfo(&triples[0],
1072 &triples[0]+triples.size(),
1073 &Diags);
1074
1075 if (Target == 0) {
1076 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1077 triples[0].c_str());
1078 fprintf(stderr, "Please use -triple or -arch.\n");
1079 exit(1);
1080 }
1081
1082 // Set up the preprocessor with these options.
1083 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1084
1085 std::vector<char> PredefineBuffer;
1086 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
1087 HeaderInfo, LangInfo,
1088 PredefineBuffer);
1089
1090 if (!MainFileID) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001091
Ted Kremenek20e97482007-12-12 23:41:08 +00001092 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
1093 *DiagClient, HeaderInfo, LangInfo);
1094
1095 HeaderInfo.ClearFileInfo();
1096
1097 if (Stats)
1098 SourceMgr.PrintStats();
1099 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 }
1101
1102 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1103
1104 if (NumDiagnostics)
1105 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1106 (NumDiagnostics == 1 ? "" : "s"));
1107
1108 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 FileMgr.PrintStats();
1110 fprintf(stderr, "\n");
1111 }
1112
Chris Lattner96f1a642007-07-21 05:40:53 +00001113 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001114}