blob: dc435f945a34b0bcd421dfc0cc6a53ee9ddc2251 [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 Kremenek77cda502007-12-18 21:34:28 +000029#include "clang/AST/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"
Chris Lattner8f3dab82007-12-15 23:20:07 +000037#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000041#include "llvm/Config/config.h"
Ted Kremenek63ea8632007-12-19 19:27:38 +000042#include "llvm/ADT/scoped_ptr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include <memory>
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47// Global options.
48//===----------------------------------------------------------------------===//
49
50static llvm::cl::opt<bool>
51Verbose("v", llvm::cl::desc("Enable verbose output"));
52static llvm::cl::opt<bool>
53Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
54
55enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000056 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000057 EmitLLVM, // Emit a .ll file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000058 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000059 ASTPrint, // Parse ASTs and print them.
60 ASTDump, // Parse ASTs and dump them.
61 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000062 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000063 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000064 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000065 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000066 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000067 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000068 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000069 ParsePrintCallbacks, // Parse and print each callback.
70 ParseSyntaxOnly, // Parse and perform semantic analysis.
71 ParseNoop, // Parse with noop callbacks.
72 RunPreprocessorOnly, // Just lex, no output.
73 PrintPreprocessedInput, // -E mode.
74 DumpTokens // Token dump mode.
75};
76
77static llvm::cl::opt<ProgActions>
78ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
79 llvm::cl::init(ParseSyntaxOnly),
80 llvm::cl::values(
81 clEnumValN(RunPreprocessorOnly, "Eonly",
82 "Just run preprocessor, no output (for timings)"),
83 clEnumValN(PrintPreprocessedInput, "E",
84 "Run preprocessor, emit preprocessed file"),
85 clEnumValN(DumpTokens, "dumptokens",
86 "Run preprocessor, dump internal rep of tokens"),
87 clEnumValN(ParseNoop, "parse-noop",
88 "Run parser with noop callbacks (for timings)"),
89 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
90 "Run parser and perform semantic analysis"),
91 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
92 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000093 clEnumValN(ASTPrint, "ast-print",
94 "Build ASTs and then pretty-print them"),
95 clEnumValN(ASTDump, "ast-dump",
96 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000097 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000098 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000099 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000100 "Run parser, then build and print CFGs."),
101 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000102 "Run parser, then build and view CFGs with Graphviz."),
103 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000104 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000105 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000106 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000107 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000108 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000109 clEnumValN(TestSerialization, "test-pickling",
110 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000112 "Build ASTs then convert to LLVM, emit .ll file"),
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000113 clEnumValN(SerializeAST, "serialize-ast",
114 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000115 clEnumValN(RewriteTest, "rewrite-test",
116 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 clEnumValEnd));
118
Ted Kremenek41193e42007-09-26 19:42:19 +0000119static llvm::cl::opt<bool>
120VerifyDiagnostics("verify",
121 llvm::cl::desc("Verify emitted diagnostics and warnings."));
122
Reid Spencer5f016e22007-07-11 17:01:13 +0000123//===----------------------------------------------------------------------===//
124// Language Options
125//===----------------------------------------------------------------------===//
126
127enum LangKind {
128 langkind_unspecified,
129 langkind_c,
130 langkind_c_cpp,
131 langkind_cxx,
132 langkind_cxx_cpp,
133 langkind_objc,
134 langkind_objc_cpp,
135 langkind_objcxx,
136 langkind_objcxx_cpp
137};
138
139/* TODO: GCC also accepts:
140 c-header c++-header objective-c-header objective-c++-header
141 assembler assembler-with-cpp
142 ada, f77*, ratfor (!), f95, java, treelang
143 */
144static llvm::cl::opt<LangKind>
145BaseLang("x", llvm::cl::desc("Base language to compile"),
146 llvm::cl::init(langkind_unspecified),
147 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
148 clEnumValN(langkind_cxx, "c++", "C++"),
149 clEnumValN(langkind_objc, "objective-c", "Objective C"),
150 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
151 clEnumValN(langkind_c_cpp, "c-cpp-output",
152 "Preprocessed C"),
153 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
154 "Preprocessed C++"),
155 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
156 "Preprocessed Objective C"),
157 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
158 "Preprocessed Objective C++"),
159 clEnumValEnd));
160
161static llvm::cl::opt<bool>
162LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
163 llvm::cl::Hidden);
164static llvm::cl::opt<bool>
165LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
166 llvm::cl::Hidden);
167
Ted Kremenek8904f152007-12-05 23:49:08 +0000168/// InitializeBaseLanguage - Handle the -x foo options.
169static void InitializeBaseLanguage() {
170 if (LangObjC)
171 BaseLang = langkind_objc;
172 else if (LangObjCXX)
173 BaseLang = langkind_objcxx;
174}
175
176static LangKind GetLanguage(const std::string &Filename) {
177 if (BaseLang != langkind_unspecified)
178 return BaseLang;
179
180 std::string::size_type DotPos = Filename.rfind('.');
181
182 if (DotPos == std::string::npos) {
183 BaseLang = langkind_c; // Default to C if no extension.
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 }
185
Ted Kremenek8904f152007-12-05 23:49:08 +0000186 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
187 // C header: .h
188 // C++ header: .hh or .H;
189 // assembler no preprocessing: .s
190 // assembler: .S
191 if (Ext == "c")
192 return langkind_c;
193 else if (Ext == "i")
194 return langkind_c_cpp;
195 else if (Ext == "ii")
196 return langkind_cxx_cpp;
197 else if (Ext == "m")
198 return langkind_objc;
199 else if (Ext == "mi")
200 return langkind_objc_cpp;
201 else if (Ext == "mm" || Ext == "M")
202 return langkind_objcxx;
203 else if (Ext == "mii")
204 return langkind_objcxx_cpp;
205 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
206 Ext == "c++" || Ext == "cp" || Ext == "cxx")
207 return langkind_cxx;
208 else
209 return langkind_c;
210}
211
212
213static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // FIXME: implement -fpreprocessed mode.
215 bool NoPreprocess = false;
216
Ted Kremenek8904f152007-12-05 23:49:08 +0000217 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 default: assert(0 && "Unknown language kind!");
219 case langkind_c_cpp:
220 NoPreprocess = true;
221 // FALLTHROUGH
222 case langkind_c:
223 break;
224 case langkind_cxx_cpp:
225 NoPreprocess = true;
226 // FALLTHROUGH
227 case langkind_cxx:
228 Options.CPlusPlus = 1;
229 break;
230 case langkind_objc_cpp:
231 NoPreprocess = true;
232 // FALLTHROUGH
233 case langkind_objc:
234 Options.ObjC1 = Options.ObjC2 = 1;
235 break;
236 case langkind_objcxx_cpp:
237 NoPreprocess = true;
238 // FALLTHROUGH
239 case langkind_objcxx:
240 Options.ObjC1 = Options.ObjC2 = 1;
241 Options.CPlusPlus = 1;
242 break;
243 }
244}
245
246/// LangStds - Language standards we support.
247enum LangStds {
248 lang_unspecified,
249 lang_c89, lang_c94, lang_c99,
250 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000251 lang_cxx98, lang_gnucxx98,
252 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000253};
254
255static llvm::cl::opt<LangStds>
256LangStd("std", llvm::cl::desc("Language standard to compile for"),
257 llvm::cl::init(lang_unspecified),
258 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
259 clEnumValN(lang_c89, "c90", "ISO C 1990"),
260 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
261 clEnumValN(lang_c94, "iso9899:199409",
262 "ISO C 1990 with amendment 1"),
263 clEnumValN(lang_c99, "c99", "ISO C 1999"),
264// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
265 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
266// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
267 clEnumValN(lang_gnu89, "gnu89",
268 "ISO C 1990 with GNU extensions (default for C)"),
269 clEnumValN(lang_gnu99, "gnu99",
270 "ISO C 1999 with GNU extensions"),
271 clEnumValN(lang_gnu99, "gnu9x",
272 "ISO C 1999 with GNU extensions"),
273 clEnumValN(lang_cxx98, "c++98",
274 "ISO C++ 1998 with amendments"),
275 clEnumValN(lang_gnucxx98, "gnu++98",
276 "ISO C++ 1998 with amendments and GNU "
277 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000278 clEnumValN(lang_cxx0x, "c++0x",
279 "Upcoming ISO C++ 200x with amendments"),
280 clEnumValN(lang_gnucxx0x, "gnu++0x",
281 "Upcoming ISO C++ 200x with amendments and GNU "
282 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 clEnumValEnd));
284
285static llvm::cl::opt<bool>
286NoOperatorNames("fno-operator-names",
287 llvm::cl::desc("Do not treat C++ operator name keywords as "
288 "synonyms for operators"));
289
Anders Carlssonee98ac52007-10-15 02:50:23 +0000290static llvm::cl::opt<bool>
291PascalStrings("fpascal-strings",
292 llvm::cl::desc("Recognize and construct Pascal-style "
293 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000294
295static llvm::cl::opt<bool>
296WritableStrings("fwritable-strings",
297 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000298
299static llvm::cl::opt<bool>
300LaxVectorConversions("flax-vector-conversions",
301 llvm::cl::desc("Allow implicit conversions between vectors"
302 " with a different number of elements or "
303 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000304// FIXME: add:
305// -ansi
306// -trigraphs
307// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000308// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000309static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 if (LangStd == lang_unspecified) {
311 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000312 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 default: assert(0 && "Unknown base language");
314 case langkind_c:
315 case langkind_c_cpp:
316 case langkind_objc:
317 case langkind_objc_cpp:
318 LangStd = lang_gnu99;
319 break;
320 case langkind_cxx:
321 case langkind_cxx_cpp:
322 case langkind_objcxx:
323 case langkind_objcxx_cpp:
324 LangStd = lang_gnucxx98;
325 break;
326 }
327 }
328
329 switch (LangStd) {
330 default: assert(0 && "Unknown language standard!");
331
332 // Fall through from newer standards to older ones. This isn't really right.
333 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000334 case lang_gnucxx0x:
335 case lang_cxx0x:
336 Options.CPlusPlus0x = 1;
337 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 case lang_gnucxx98:
339 case lang_cxx98:
340 Options.CPlusPlus = 1;
341 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000342 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 // FALL THROUGH.
344 case lang_gnu99:
345 case lang_c99:
346 Options.Digraphs = 1;
347 Options.C99 = 1;
348 Options.HexFloats = 1;
349 // FALL THROUGH.
350 case lang_gnu89:
351 Options.BCPLComment = 1; // Only for C99/C++.
352 // FALL THROUGH.
353 case lang_c94:
354 case lang_c89:
355 break;
356 }
357
358 Options.Trigraphs = 1; // -trigraphs or -ansi
359 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000360 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000361 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000362 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000363}
364
365//===----------------------------------------------------------------------===//
366// Our DiagnosticClient implementation
367//===----------------------------------------------------------------------===//
368
369// FIXME: Werror should take a list of things, -Werror=foo,bar
370static llvm::cl::opt<bool>
371WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
372
373static llvm::cl::opt<bool>
374WarnOnExtensions("pedantic", llvm::cl::init(false),
375 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
376
377static llvm::cl::opt<bool>
378ErrorOnExtensions("pedantic-errors",
379 llvm::cl::desc("Issue an error on uses of GCC extensions"));
380
381static llvm::cl::opt<bool>
382WarnUnusedMacros("Wunused_macros",
383 llvm::cl::desc("Warn for unused macros in the main translation unit"));
384
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000385static llvm::cl::opt<bool>
386WarnFloatEqual("Wfloat-equal",
387 llvm::cl::desc("Warn about equality comparisons of floating point values."));
388
Ted Kremenek73da5902007-12-17 17:50:07 +0000389static llvm::cl::opt<bool>
390WarnNoFormatNonLiteral("Wno-format-nonliteral",
391 llvm::cl::desc("Do not warn about non-literal format strings."));
392
Reid Spencer5f016e22007-07-11 17:01:13 +0000393/// InitializeDiagnostics - Initialize the diagnostic object, based on the
394/// current command line option settings.
395static void InitializeDiagnostics(Diagnostic &Diags) {
396 Diags.setWarningsAsErrors(WarningsAsErrors);
397 Diags.setWarnOnExtensions(WarnOnExtensions);
398 Diags.setErrorOnExtensions(ErrorOnExtensions);
399
400 // Silence the "macro is not used" warning unless requested.
401 if (!WarnUnusedMacros)
402 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000403
404 // Silence "floating point comparison" warnings unless requested.
405 if (!WarnFloatEqual)
406 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000407
408 // Silence "format string is not a string literal" warnings if requested
409 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000410 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
411 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000412
Reid Spencer5f016e22007-07-11 17:01:13 +0000413}
414
415//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000416// Target Triple Processing.
417//===----------------------------------------------------------------------===//
418
419static llvm::cl::opt<std::string>
420TargetTriple("triple",
421 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
422
423static llvm::cl::list<std::string>
424Archs("arch",
425 llvm::cl::desc("Specify target architecture (e.g. i686)."));
426
427namespace {
428 class TripleProcessor {
429 llvm::StringMap<char> TriplesProcessed;
430 std::vector<std::string>& triples;
431 public:
432 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
433
434 void addTriple(const std::string& t) {
435 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
436 TriplesProcessed.end()) {
437 triples.push_back(t);
438 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
439 }
440 }
441 };
442}
443
444static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000445 // Initialize base triple. If a -triple option has been specified, use
446 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000447 std::string Triple = TargetTriple;
448 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000449
450 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000451 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000452
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000453 if (firstDash == std::string::npos) {
454 fprintf(stderr,
455 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000456 Triple.c_str());
457 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000458 }
Ted Kremenekae360762007-12-03 22:06:55 +0000459
Chris Lattner6590d212007-12-12 05:01:48 +0000460 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000461
462 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000463 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
464 Triple.c_str());
465 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000466 }
Ted Kremenekae360762007-12-03 22:06:55 +0000467
468 // Create triple cacher.
469 TripleProcessor tp(triples);
470
471 // Add the primary triple to our set of triples if we are using the
472 // host-triple with no archs or using a specified target triple.
473 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000474 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000475
476 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
477 tp.addTriple(Archs[i] + "-" + suffix);
478}
479
480//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000481// Preprocessor Initialization
482//===----------------------------------------------------------------------===//
483
484// FIXME: Preprocessor builtins to support.
485// -A... - Play with #assertions
486// -undef - Undefine all predefined macros
487
488static llvm::cl::list<std::string>
489D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
490 llvm::cl::desc("Predefine the specified macro"));
491static llvm::cl::list<std::string>
492U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
493 llvm::cl::desc("Undefine the specified macro"));
494
495// Append a #define line to Buf for Macro. Macro should be of the form XXX,
496// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
497// "#define XXX Y z W". To get a #define with no value, use "XXX=".
498static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
499 const char *Command = "#define ") {
500 Buf.insert(Buf.end(), Command, Command+strlen(Command));
501 if (const char *Equal = strchr(Macro, '=')) {
502 // Turn the = into ' '.
503 Buf.insert(Buf.end(), Macro, Equal);
504 Buf.push_back(' ');
505 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
506 } else {
507 // Push "macroname 1".
508 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
509 Buf.push_back(' ');
510 Buf.push_back('1');
511 }
512 Buf.push_back('\n');
513}
514
Reid Spencer5f016e22007-07-11 17:01:13 +0000515
Chris Lattner53b0dab2007-10-09 22:10:18 +0000516/// InitializePreprocessor - Initialize the preprocessor getting it and the
517/// environment ready to process a single file. This returns the file ID for the
518/// input file. If a failure happens, it returns 0.
519///
520static unsigned InitializePreprocessor(Preprocessor &PP,
521 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000522 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000523
Chris Lattnerdee73592007-12-15 20:48:40 +0000524 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000525
Chris Lattner53b0dab2007-10-09 22:10:18 +0000526 // Figure out where to get and map in the main file.
527 unsigned MainFileID = 0;
Chris Lattnerdee73592007-12-15 20:48:40 +0000528 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000529 if (InFile != "-") {
530 const FileEntry *File = FileMgr.getFile(InFile);
531 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
532 if (MainFileID == 0) {
533 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
534 return 0;
535 }
536 } else {
537 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
538 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
539 if (MainFileID == 0) {
540 fprintf(stderr, "Error reading standard input! Empty?\n");
541 return 0;
542 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 }
544
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 // Add macros from the command line.
546 // FIXME: Should traverse the #define/#undef lists in parallel.
547 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000548 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000550 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
551
552 // FIXME: Read any files specified by -imacros or -include.
553
554 // Null terminate PredefinedBuffer and add it.
555 PredefineBuffer.push_back(0);
556 PP.setPredefines(&PredefineBuffer[0]);
557
558 // Once we've read this, we're done.
559 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000560}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000561
562
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
564//===----------------------------------------------------------------------===//
565// Preprocessor include path information.
566//===----------------------------------------------------------------------===//
567
568// This tool exports a large number of command line options to control how the
569// preprocessor searches for header files. At root, however, the Preprocessor
570// object takes a very simple interface: a list of directories to search for
571//
572// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000573// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000574//
575// FIXME: -include,-imacros
576
577static llvm::cl::opt<bool>
578nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
579
580// Various command line options. These four add directories to each chain.
581static llvm::cl::list<std::string>
582F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
583 llvm::cl::desc("Add directory to framework include search path"));
584static llvm::cl::list<std::string>
585I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
586 llvm::cl::desc("Add directory to include search path"));
587static llvm::cl::list<std::string>
588idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
589 llvm::cl::desc("Add directory to AFTER include search path"));
590static llvm::cl::list<std::string>
591iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
592 llvm::cl::desc("Add directory to QUOTE include search path"));
593static llvm::cl::list<std::string>
594isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
595 llvm::cl::desc("Add directory to SYSTEM include search path"));
596
597// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
598static llvm::cl::list<std::string>
599iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
600 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
601static llvm::cl::list<std::string>
602iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
603 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
604static llvm::cl::list<std::string>
605iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
606 llvm::cl::Prefix,
607 llvm::cl::desc("Set directory to include search path with prefix"));
608
Chris Lattner0c946412007-08-26 17:47:35 +0000609static llvm::cl::opt<std::string>
610isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
611 llvm::cl::desc("Set the system root directory (usually /)"));
612
Reid Spencer5f016e22007-07-11 17:01:13 +0000613// Finally, implement the code that groks the options above.
614enum IncludeDirGroup {
615 Quoted = 0,
616 Angled,
617 System,
618 After
619};
620
621static std::vector<DirectoryLookup> IncludeGroup[4];
622
623/// AddPath - Add the specified path to the specified group list.
624///
625static void AddPath(const std::string &Path, IncludeDirGroup Group,
626 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000627 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000628 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000629 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000630
Chris Lattnerd6655272007-12-17 05:59:27 +0000631 // Compute the actual path, taking into consideration -isysroot.
632 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000633
Chris Lattnerd6655272007-12-17 05:59:27 +0000634 // Handle isysroot.
635 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000636 // FIXME: Portability. This should be a sys::Path interface, this doesn't
637 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000638 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
639 MappedPath.append(isysroot.begin(), isysroot.end());
640 if (Path[0] != '/') // If in the system group, add a /.
641 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 }
643
Chris Lattnerd6655272007-12-17 05:59:27 +0000644 MappedPath.append(Path.begin(), Path.end());
645
646 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 DirectoryLookup::DirType Type;
648 if (Group == Quoted || Group == Angled)
649 Type = DirectoryLookup::NormalHeaderDir;
650 else if (isCXXAware)
651 Type = DirectoryLookup::SystemHeaderDir;
652 else
653 Type = DirectoryLookup::ExternCSystemHeaderDir;
654
Chris Lattnerd6655272007-12-17 05:59:27 +0000655
656 // If the directory exists, add it.
657 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
658 &MappedPath[0]+
659 MappedPath.size())) {
660 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
661 isFramework));
662 return;
663 }
664
Chris Lattnerdf772332007-12-17 07:52:39 +0000665 // Check to see if this is an apple-style headermap (which are not allowed to
666 // be frameworks).
667 if (!isFramework) {
668 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
669 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000670 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
671 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000672 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
673 return;
674 }
Chris Lattner822da612007-12-17 06:36:45 +0000675 }
676 }
677
Chris Lattnerd6655272007-12-17 05:59:27 +0000678 if (Verbose)
679 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000680}
681
682/// RemoveDuplicates - If there are duplicate directory entries in the specified
683/// search list, remove the later (dead) ones.
684static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000685 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000686 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000687 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000689 if (SearchList[i].isNormalDir()) {
690 // If this isn't the first time we've seen this dir, remove it.
691 if (SeenDirs.insert(SearchList[i].getDir()))
692 continue;
693
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 if (Verbose)
695 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
696 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000697 } else if (SearchList[i].isFramework()) {
698 // If this isn't the first time we've seen this framework dir, remove it.
699 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
700 continue;
701
702 if (Verbose)
703 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
704 SearchList[i].getFrameworkDir()->getName());
705
Chris Lattnerb94c7072007-12-17 06:44:29 +0000706 } else {
707 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
708 // If this isn't the first time we've seen this headermap, remove it.
709 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
710 continue;
711
712 if (Verbose)
713 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
714 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000716
717 // This is reached if the current entry is a duplicate.
718 SearchList.erase(SearchList.begin()+i);
719 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 }
721}
722
723/// InitializeIncludePaths - Process the -I options and set them in the
724/// HeaderSearch object.
725static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000726 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 // Handle -F... options.
728 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000729 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000730
731 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000732 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000733 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000734
735 // Handle -idirafter... options.
736 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000737 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000738
739 // Handle -iquote... options.
740 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000741 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000742
743 // Handle -isystem... options.
744 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000745 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000746
747 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
748 // parallel, processing the values in order of occurance to get the right
749 // prefixes.
750 {
751 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
752 unsigned iprefix_idx = 0;
753 unsigned iwithprefix_idx = 0;
754 unsigned iwithprefixbefore_idx = 0;
755 bool iprefix_done = iprefix_vals.empty();
756 bool iwithprefix_done = iwithprefix_vals.empty();
757 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
758 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
759 if (!iprefix_done &&
760 (iwithprefix_done ||
761 iprefix_vals.getPosition(iprefix_idx) <
762 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
763 (iwithprefixbefore_done ||
764 iprefix_vals.getPosition(iprefix_idx) <
765 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
766 Prefix = iprefix_vals[iprefix_idx];
767 ++iprefix_idx;
768 iprefix_done = iprefix_idx == iprefix_vals.size();
769 } else if (!iwithprefix_done &&
770 (iwithprefixbefore_done ||
771 iwithprefix_vals.getPosition(iwithprefix_idx) <
772 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
773 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000774 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 ++iwithprefix_idx;
776 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
777 } else {
778 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000779 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 ++iwithprefixbefore_idx;
781 iwithprefixbefore_done =
782 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
783 }
784 }
785 }
786
787 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
788 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
789
790 // FIXME: temporary hack: hard-coded paths.
791 // FIXME: get these from the target?
792 if (!nostdinc) {
793 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000794 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000796 false, Headers);
797 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
798 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 }
800
Chris Lattner822da612007-12-17 06:36:45 +0000801 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 // leopard
803 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000804 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000806 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
808 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000809 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810
811 // tiger
812 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000813 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000815 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
817 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000818 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000819
Chris Lattner822da612007-12-17 06:36:45 +0000820 AddPath("/usr/include", System, false, false, false, Headers);
821 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
822 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 }
824
825 // Now that we have collected all of the include paths, merge them all
826 // together and tell the preprocessor about them.
827
828 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
829 std::vector<DirectoryLookup> SearchList;
830 SearchList = IncludeGroup[Angled];
831 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
832 IncludeGroup[System].end());
833 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
834 IncludeGroup[After].end());
835 RemoveDuplicates(SearchList);
836 RemoveDuplicates(IncludeGroup[Quoted]);
837
838 // Prepend QUOTED list on the search list.
839 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
840 IncludeGroup[Quoted].end());
841
842
843 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
844 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
845 DontSearchCurDir);
846
847 // If verbose, print the list of directories that will be searched.
848 if (Verbose) {
849 fprintf(stderr, "#include \"...\" search starts here:\n");
850 unsigned QuotedIdx = IncludeGroup[Quoted].size();
851 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
852 if (i == QuotedIdx)
853 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000854 const char *Name = SearchList[i].getName();
855 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000856 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000857 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000858 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000859 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000860 else {
861 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000862 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000863 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000864 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 }
Chris Lattner80e17152007-12-15 23:11:06 +0000866 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 }
868}
869
870
Reid Spencer5f016e22007-07-11 17:01:13 +0000871//===----------------------------------------------------------------------===//
872// Basic Parser driver
873//===----------------------------------------------------------------------===//
874
875static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
876 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000877 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000878
879 // Parsing the specified input file.
880 P.ParseTranslationUnit();
881 delete PA;
882}
883
884//===----------------------------------------------------------------------===//
885// Main driver
886//===----------------------------------------------------------------------===//
887
Ted Kremenekdb094a22007-12-05 18:27:04 +0000888/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
889/// action. These consumers can operate on both ASTs that are freshly
890/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenek63ea8632007-12-19 19:27:38 +0000891static ASTConsumer* CreateASTConsumer(const std::string& SourceFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000892 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000893 const LangOptions& LangOpts) {
894 switch (ProgAction) {
895 default:
896 return NULL;
897
898 case ASTPrint:
899 return CreateASTPrinter();
900
901 case ASTDump:
902 return CreateASTDumper();
903
904 case ASTView:
905 return CreateASTViewer();
906
907 case ParseCFGDump:
908 case ParseCFGView:
909 return CreateCFGDumper(ProgAction == ParseCFGView);
910
911 case AnalysisLiveVariables:
912 return CreateLiveVarAnalyzer();
913
914 case WarnDeadStores:
915 return CreateDeadStoreChecker(Diag);
916
917 case WarnUninitVals:
918 return CreateUnitValsChecker(Diag);
919
920 case TestSerialization:
Ted Kremenek63ea8632007-12-19 19:27:38 +0000921 return CreateSerializationTest(SourceFile, Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000922
923 case EmitLLVM:
924 return CreateLLVMEmitter(Diag, LangOpts);
925
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000926 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000927 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek63ea8632007-12-19 19:27:38 +0000928 return CreateASTSerializer(SourceFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000929
Ted Kremenekdb094a22007-12-05 18:27:04 +0000930 case RewriteTest:
931 return CreateCodeRewriterTest(Diag);
932 }
933}
934
Reid Spencer5f016e22007-07-11 17:01:13 +0000935/// ProcessInputFile - Process a single input file with the specified state.
936///
937static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
Ted Kremenek63ea8632007-12-19 19:27:38 +0000938 const std::string &SourceFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000939 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000940
941 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000942 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000943
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 switch (ProgAction) {
945 default:
Ted Kremenek63ea8632007-12-19 19:27:38 +0000946 Consumer = CreateASTConsumer(SourceFile, PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000947 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000948 PP.getLangOptions());
949
950 if (!Consumer) {
951 fprintf(stderr, "Unexpected program action!\n");
952 return;
953 }
954 break;
955
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000957 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000959 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 do {
961 PP.Lex(Tok);
962 PP.DumpToken(Tok, true);
963 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000964 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000965 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 break;
967 }
968 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000969 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000971 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 do {
973 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000974 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000975 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 break;
977 }
978
979 case PrintPreprocessedInput: // -E mode.
Chris Lattnerdee73592007-12-15 20:48:40 +0000980 DoPrintPreprocessedInput(MainFileID, PP);
Chris Lattnerbd247762007-07-22 06:05:44 +0000981 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000982 break;
983
984 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000985 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000986 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 break;
988
989 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +0000990 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
991 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000992 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000994
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000995 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000996 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000997 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000998 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000999
1000 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001001 if (VerifyDiagnostics)
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001002 exit(CheckASTConsumer(PP, MainFileID, Consumer));
1003
1004 // This deletes Consumer.
1005 ParseAST(PP, MainFileID, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 }
1007
1008 if (Stats) {
Ted Kremenek63ea8632007-12-19 19:27:38 +00001009 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", SourceFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 PP.PrintStats();
1011 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001012 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001013 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001014 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 fprintf(stderr, "\n");
1016 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001017
1018 // For a multi-file compilation, some things are ok with nuking the source
1019 // manager tables, other require stable fileid/macroid's across multiple
1020 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001021 if (ClearSourceMgr)
1022 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001023}
1024
Ted Kremenek20e97482007-12-12 23:41:08 +00001025static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1026 FileManager& FileMgr) {
1027
1028 if (VerifyDiagnostics) {
1029 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1030 exit (1);
1031 }
1032
1033 llvm::sys::Path Filename(InFile);
1034
1035 if (!Filename.isValid()) {
1036 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1037 exit (1);
1038 }
1039
Ted Kremenek63ea8632007-12-19 19:27:38 +00001040 llvm::scoped_ptr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001041
1042 if (!TU) {
1043 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1044 InFile.c_str());
1045 exit (1);
1046 }
1047
Ted Kremenek63ea8632007-12-19 19:27:38 +00001048 // Observe that we use the source file name stored in the deserialized
1049 // translation unit, rather than InFile.
1050 llvm::scoped_ptr<ASTConsumer>
1051 Consumer(CreateASTConsumer(TU->getSourceFile(), Diag, FileMgr,
1052 TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001053
1054 if (!Consumer) {
1055 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1056 exit (1);
1057 }
1058
1059 // FIXME: only work on consumers that do not require MainFileID.
Ted Kremenek63ea8632007-12-19 19:27:38 +00001060 Consumer->Initialize(*TU->getContext(), 0);
Ted Kremenek20e97482007-12-12 23:41:08 +00001061
1062 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1063 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001064}
1065
1066
Reid Spencer5f016e22007-07-11 17:01:13 +00001067static llvm::cl::list<std::string>
1068InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1069
Ted Kremenek20e97482007-12-12 23:41:08 +00001070static bool isSerializedFile(const std::string& InFile) {
1071 if (InFile.size() < 4)
1072 return false;
1073
1074 const char* s = InFile.c_str()+InFile.size()-4;
1075
1076 return s[0] == '.' &&
1077 s[1] == 'a' &&
1078 s[2] == 's' &&
1079 s[3] == 't';
1080}
1081
Reid Spencer5f016e22007-07-11 17:01:13 +00001082
1083int main(int argc, char **argv) {
1084 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1085 llvm::sys::PrintStackTraceOnErrorSignal();
1086
1087 // If no input was specified, read from stdin.
1088 if (InputFilenames.empty())
1089 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001090
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 // Create a file manager object to provide access to and cache the filesystem.
1092 FileManager FileMgr;
1093
Ted Kremenek31e703b2007-12-11 23:28:38 +00001094 // Create the diagnostic client for reporting errors or for
1095 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001097 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001099 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 } else {
1101 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001102 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001103
1104 if (InputFilenames.size() != 1) {
1105 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001106 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 return 1;
1108 }
1109 }
1110
1111 // Configure our handling of diagnostics.
1112 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001113 InitializeDiagnostics(Diags);
1114
Chris Lattner4f037832007-12-05 23:24:17 +00001115 // -I- is a deprecated GCC feature, scan for it and reject it.
1116 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1117 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001118 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001119 I_dirs.erase(I_dirs.begin()+i);
1120 --i;
1121 }
1122 }
1123
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001125 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001126
Ted Kremenek20e97482007-12-12 23:41:08 +00001127 if (isSerializedFile(InFile))
1128 ProcessSerializedFile(InFile,Diags,FileMgr);
1129 else {
1130 /// Create a SourceManager object. This tracks and owns all the file
1131 /// buffers allocated to a translation unit.
1132 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001133
Ted Kremenek20e97482007-12-12 23:41:08 +00001134 // Initialize language options, inferring file types from input filenames.
1135 LangOptions LangInfo;
1136 InitializeBaseLanguage();
1137 LangKind LK = GetLanguage(InFile);
1138 InitializeLangOptions(LangInfo, LK);
1139 InitializeLanguageStandard(LangInfo, LK);
1140
1141 // Process the -I options and set them in the HeaderInfo.
1142 HeaderSearch HeaderInfo(FileMgr);
1143 DiagClient->setHeaderSearch(HeaderInfo);
1144 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1145
1146 // Get information about the targets being compiled for. Note that this
1147 // pointer and the TargetInfoImpl objects are never deleted by this toy
1148 // driver.
1149 TargetInfo *Target;
1150
1151 // Create triples, and create the TargetInfo.
1152 std::vector<std::string> triples;
1153 CreateTargetTriples(triples);
1154 Target = TargetInfo::CreateTargetInfo(&triples[0],
1155 &triples[0]+triples.size(),
1156 &Diags);
1157
1158 if (Target == 0) {
1159 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1160 triples[0].c_str());
1161 fprintf(stderr, "Please use -triple or -arch.\n");
1162 exit(1);
1163 }
1164
1165 // Set up the preprocessor with these options.
1166 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1167
1168 std::vector<char> PredefineBuffer;
Chris Lattnerdee73592007-12-15 20:48:40 +00001169 unsigned MainFileID = InitializePreprocessor(PP, InFile, PredefineBuffer);
Ted Kremenek20e97482007-12-12 23:41:08 +00001170
1171 if (!MainFileID) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001172
Chris Lattnerdee73592007-12-15 20:48:40 +00001173 ProcessInputFile(PP, MainFileID, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001174
1175 HeaderInfo.ClearFileInfo();
1176
1177 if (Stats)
1178 SourceMgr.PrintStats();
1179 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 }
1181
1182 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1183
1184 if (NumDiagnostics)
1185 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1186 (NumDiagnostics == 1 ? "" : "s"));
1187
1188 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 FileMgr.PrintStats();
1190 fprintf(stderr, "\n");
1191 }
1192
Chris Lattner96f1a642007-07-21 05:40:53 +00001193 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001194}