blob: 9727e1113533c5ccff3ff807c2ee74c9dc36982a [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 Kremenekccc76472007-12-19 19:47:59 +0000113 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000114 "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 Kremenekccc76472007-12-19 19:47:59 +0000119
120static llvm::cl::opt<std::string>
121OutputFile("o",
122 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
123
Ted Kremenek41193e42007-09-26 19:42:19 +0000124static llvm::cl::opt<bool>
125VerifyDiagnostics("verify",
126 llvm::cl::desc("Verify emitted diagnostics and warnings."));
127
Reid Spencer5f016e22007-07-11 17:01:13 +0000128//===----------------------------------------------------------------------===//
129// Language Options
130//===----------------------------------------------------------------------===//
131
132enum LangKind {
133 langkind_unspecified,
134 langkind_c,
135 langkind_c_cpp,
136 langkind_cxx,
137 langkind_cxx_cpp,
138 langkind_objc,
139 langkind_objc_cpp,
140 langkind_objcxx,
141 langkind_objcxx_cpp
142};
143
144/* TODO: GCC also accepts:
145 c-header c++-header objective-c-header objective-c++-header
146 assembler assembler-with-cpp
147 ada, f77*, ratfor (!), f95, java, treelang
148 */
149static llvm::cl::opt<LangKind>
150BaseLang("x", llvm::cl::desc("Base language to compile"),
151 llvm::cl::init(langkind_unspecified),
152 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
153 clEnumValN(langkind_cxx, "c++", "C++"),
154 clEnumValN(langkind_objc, "objective-c", "Objective C"),
155 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
156 clEnumValN(langkind_c_cpp, "c-cpp-output",
157 "Preprocessed C"),
158 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
159 "Preprocessed C++"),
160 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
161 "Preprocessed Objective C"),
162 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
163 "Preprocessed Objective C++"),
164 clEnumValEnd));
165
166static llvm::cl::opt<bool>
167LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
168 llvm::cl::Hidden);
169static llvm::cl::opt<bool>
170LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
171 llvm::cl::Hidden);
172
Ted Kremenek8904f152007-12-05 23:49:08 +0000173/// InitializeBaseLanguage - Handle the -x foo options.
174static void InitializeBaseLanguage() {
175 if (LangObjC)
176 BaseLang = langkind_objc;
177 else if (LangObjCXX)
178 BaseLang = langkind_objcxx;
179}
180
181static LangKind GetLanguage(const std::string &Filename) {
182 if (BaseLang != langkind_unspecified)
183 return BaseLang;
184
185 std::string::size_type DotPos = Filename.rfind('.');
186
187 if (DotPos == std::string::npos) {
188 BaseLang = langkind_c; // Default to C if no extension.
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 }
190
Ted Kremenek8904f152007-12-05 23:49:08 +0000191 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
192 // C header: .h
193 // C++ header: .hh or .H;
194 // assembler no preprocessing: .s
195 // assembler: .S
196 if (Ext == "c")
197 return langkind_c;
198 else if (Ext == "i")
199 return langkind_c_cpp;
200 else if (Ext == "ii")
201 return langkind_cxx_cpp;
202 else if (Ext == "m")
203 return langkind_objc;
204 else if (Ext == "mi")
205 return langkind_objc_cpp;
206 else if (Ext == "mm" || Ext == "M")
207 return langkind_objcxx;
208 else if (Ext == "mii")
209 return langkind_objcxx_cpp;
210 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
211 Ext == "c++" || Ext == "cp" || Ext == "cxx")
212 return langkind_cxx;
213 else
214 return langkind_c;
215}
216
217
218static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 // FIXME: implement -fpreprocessed mode.
220 bool NoPreprocess = false;
221
Ted Kremenek8904f152007-12-05 23:49:08 +0000222 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 default: assert(0 && "Unknown language kind!");
224 case langkind_c_cpp:
225 NoPreprocess = true;
226 // FALLTHROUGH
227 case langkind_c:
228 break;
229 case langkind_cxx_cpp:
230 NoPreprocess = true;
231 // FALLTHROUGH
232 case langkind_cxx:
233 Options.CPlusPlus = 1;
234 break;
235 case langkind_objc_cpp:
236 NoPreprocess = true;
237 // FALLTHROUGH
238 case langkind_objc:
239 Options.ObjC1 = Options.ObjC2 = 1;
240 break;
241 case langkind_objcxx_cpp:
242 NoPreprocess = true;
243 // FALLTHROUGH
244 case langkind_objcxx:
245 Options.ObjC1 = Options.ObjC2 = 1;
246 Options.CPlusPlus = 1;
247 break;
248 }
249}
250
251/// LangStds - Language standards we support.
252enum LangStds {
253 lang_unspecified,
254 lang_c89, lang_c94, lang_c99,
255 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000256 lang_cxx98, lang_gnucxx98,
257 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000258};
259
260static llvm::cl::opt<LangStds>
261LangStd("std", llvm::cl::desc("Language standard to compile for"),
262 llvm::cl::init(lang_unspecified),
263 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
264 clEnumValN(lang_c89, "c90", "ISO C 1990"),
265 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
266 clEnumValN(lang_c94, "iso9899:199409",
267 "ISO C 1990 with amendment 1"),
268 clEnumValN(lang_c99, "c99", "ISO C 1999"),
269// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
270 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
271// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
272 clEnumValN(lang_gnu89, "gnu89",
273 "ISO C 1990 with GNU extensions (default for C)"),
274 clEnumValN(lang_gnu99, "gnu99",
275 "ISO C 1999 with GNU extensions"),
276 clEnumValN(lang_gnu99, "gnu9x",
277 "ISO C 1999 with GNU extensions"),
278 clEnumValN(lang_cxx98, "c++98",
279 "ISO C++ 1998 with amendments"),
280 clEnumValN(lang_gnucxx98, "gnu++98",
281 "ISO C++ 1998 with amendments and GNU "
282 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000283 clEnumValN(lang_cxx0x, "c++0x",
284 "Upcoming ISO C++ 200x with amendments"),
285 clEnumValN(lang_gnucxx0x, "gnu++0x",
286 "Upcoming ISO C++ 200x with amendments and GNU "
287 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 clEnumValEnd));
289
290static llvm::cl::opt<bool>
291NoOperatorNames("fno-operator-names",
292 llvm::cl::desc("Do not treat C++ operator name keywords as "
293 "synonyms for operators"));
294
Anders Carlssonee98ac52007-10-15 02:50:23 +0000295static llvm::cl::opt<bool>
296PascalStrings("fpascal-strings",
297 llvm::cl::desc("Recognize and construct Pascal-style "
298 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000299
300static llvm::cl::opt<bool>
301WritableStrings("fwritable-strings",
302 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000303
304static llvm::cl::opt<bool>
305LaxVectorConversions("flax-vector-conversions",
306 llvm::cl::desc("Allow implicit conversions between vectors"
307 " with a different number of elements or "
308 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000309// FIXME: add:
310// -ansi
311// -trigraphs
312// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000313// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000314static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 if (LangStd == lang_unspecified) {
316 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000317 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 default: assert(0 && "Unknown base language");
319 case langkind_c:
320 case langkind_c_cpp:
321 case langkind_objc:
322 case langkind_objc_cpp:
323 LangStd = lang_gnu99;
324 break;
325 case langkind_cxx:
326 case langkind_cxx_cpp:
327 case langkind_objcxx:
328 case langkind_objcxx_cpp:
329 LangStd = lang_gnucxx98;
330 break;
331 }
332 }
333
334 switch (LangStd) {
335 default: assert(0 && "Unknown language standard!");
336
337 // Fall through from newer standards to older ones. This isn't really right.
338 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000339 case lang_gnucxx0x:
340 case lang_cxx0x:
341 Options.CPlusPlus0x = 1;
342 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 case lang_gnucxx98:
344 case lang_cxx98:
345 Options.CPlusPlus = 1;
346 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000347 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // FALL THROUGH.
349 case lang_gnu99:
350 case lang_c99:
351 Options.Digraphs = 1;
352 Options.C99 = 1;
353 Options.HexFloats = 1;
354 // FALL THROUGH.
355 case lang_gnu89:
356 Options.BCPLComment = 1; // Only for C99/C++.
357 // FALL THROUGH.
358 case lang_c94:
359 case lang_c89:
360 break;
361 }
362
363 Options.Trigraphs = 1; // -trigraphs or -ansi
364 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000365 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000366 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000367 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000368}
369
370//===----------------------------------------------------------------------===//
371// Our DiagnosticClient implementation
372//===----------------------------------------------------------------------===//
373
374// FIXME: Werror should take a list of things, -Werror=foo,bar
375static llvm::cl::opt<bool>
376WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
377
378static llvm::cl::opt<bool>
379WarnOnExtensions("pedantic", llvm::cl::init(false),
380 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
381
382static llvm::cl::opt<bool>
383ErrorOnExtensions("pedantic-errors",
384 llvm::cl::desc("Issue an error on uses of GCC extensions"));
385
386static llvm::cl::opt<bool>
387WarnUnusedMacros("Wunused_macros",
388 llvm::cl::desc("Warn for unused macros in the main translation unit"));
389
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000390static llvm::cl::opt<bool>
391WarnFloatEqual("Wfloat-equal",
392 llvm::cl::desc("Warn about equality comparisons of floating point values."));
393
Ted Kremenek73da5902007-12-17 17:50:07 +0000394static llvm::cl::opt<bool>
395WarnNoFormatNonLiteral("Wno-format-nonliteral",
396 llvm::cl::desc("Do not warn about non-literal format strings."));
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398/// InitializeDiagnostics - Initialize the diagnostic object, based on the
399/// current command line option settings.
400static void InitializeDiagnostics(Diagnostic &Diags) {
401 Diags.setWarningsAsErrors(WarningsAsErrors);
402 Diags.setWarnOnExtensions(WarnOnExtensions);
403 Diags.setErrorOnExtensions(ErrorOnExtensions);
404
405 // Silence the "macro is not used" warning unless requested.
406 if (!WarnUnusedMacros)
407 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000408
409 // Silence "floating point comparison" warnings unless requested.
410 if (!WarnFloatEqual)
411 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000412
413 // Silence "format string is not a string literal" warnings if requested
414 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000415 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
416 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000417
Reid Spencer5f016e22007-07-11 17:01:13 +0000418}
419
420//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000421// Target Triple Processing.
422//===----------------------------------------------------------------------===//
423
424static llvm::cl::opt<std::string>
425TargetTriple("triple",
426 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
427
428static llvm::cl::list<std::string>
429Archs("arch",
430 llvm::cl::desc("Specify target architecture (e.g. i686)."));
431
432namespace {
433 class TripleProcessor {
434 llvm::StringMap<char> TriplesProcessed;
435 std::vector<std::string>& triples;
436 public:
437 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
438
439 void addTriple(const std::string& t) {
440 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
441 TriplesProcessed.end()) {
442 triples.push_back(t);
443 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
444 }
445 }
446 };
447}
448
449static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000450 // Initialize base triple. If a -triple option has been specified, use
451 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000452 std::string Triple = TargetTriple;
453 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000454
455 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000456 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000457
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000458 if (firstDash == std::string::npos) {
459 fprintf(stderr,
460 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000461 Triple.c_str());
462 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000463 }
Ted Kremenekae360762007-12-03 22:06:55 +0000464
Chris Lattner6590d212007-12-12 05:01:48 +0000465 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000466
467 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000468 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
469 Triple.c_str());
470 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000471 }
Ted Kremenekae360762007-12-03 22:06:55 +0000472
473 // Create triple cacher.
474 TripleProcessor tp(triples);
475
476 // Add the primary triple to our set of triples if we are using the
477 // host-triple with no archs or using a specified target triple.
478 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000479 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000480
481 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
482 tp.addTriple(Archs[i] + "-" + suffix);
483}
484
485//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000486// Preprocessor Initialization
487//===----------------------------------------------------------------------===//
488
489// FIXME: Preprocessor builtins to support.
490// -A... - Play with #assertions
491// -undef - Undefine all predefined macros
492
493static llvm::cl::list<std::string>
494D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
495 llvm::cl::desc("Predefine the specified macro"));
496static llvm::cl::list<std::string>
497U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
498 llvm::cl::desc("Undefine the specified macro"));
499
500// Append a #define line to Buf for Macro. Macro should be of the form XXX,
501// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
502// "#define XXX Y z W". To get a #define with no value, use "XXX=".
503static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
504 const char *Command = "#define ") {
505 Buf.insert(Buf.end(), Command, Command+strlen(Command));
506 if (const char *Equal = strchr(Macro, '=')) {
507 // Turn the = into ' '.
508 Buf.insert(Buf.end(), Macro, Equal);
509 Buf.push_back(' ');
510 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
511 } else {
512 // Push "macroname 1".
513 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
514 Buf.push_back(' ');
515 Buf.push_back('1');
516 }
517 Buf.push_back('\n');
518}
519
Reid Spencer5f016e22007-07-11 17:01:13 +0000520
Chris Lattner53b0dab2007-10-09 22:10:18 +0000521/// InitializePreprocessor - Initialize the preprocessor getting it and the
522/// environment ready to process a single file. This returns the file ID for the
523/// input file. If a failure happens, it returns 0.
524///
525static unsigned InitializePreprocessor(Preprocessor &PP,
526 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000527 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000528
Chris Lattnerdee73592007-12-15 20:48:40 +0000529 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000530
Chris Lattner53b0dab2007-10-09 22:10:18 +0000531 // Figure out where to get and map in the main file.
532 unsigned MainFileID = 0;
Chris Lattnerdee73592007-12-15 20:48:40 +0000533 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000534 if (InFile != "-") {
535 const FileEntry *File = FileMgr.getFile(InFile);
536 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
537 if (MainFileID == 0) {
538 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
539 return 0;
540 }
541 } else {
542 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
543 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
544 if (MainFileID == 0) {
545 fprintf(stderr, "Error reading standard input! Empty?\n");
546 return 0;
547 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 }
549
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 // Add macros from the command line.
551 // FIXME: Should traverse the #define/#undef lists in parallel.
552 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000553 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000555 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
556
557 // FIXME: Read any files specified by -imacros or -include.
558
559 // Null terminate PredefinedBuffer and add it.
560 PredefineBuffer.push_back(0);
561 PP.setPredefines(&PredefineBuffer[0]);
562
563 // Once we've read this, we're done.
564 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000565}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000566
567
Reid Spencer5f016e22007-07-11 17:01:13 +0000568
569//===----------------------------------------------------------------------===//
570// Preprocessor include path information.
571//===----------------------------------------------------------------------===//
572
573// This tool exports a large number of command line options to control how the
574// preprocessor searches for header files. At root, however, the Preprocessor
575// object takes a very simple interface: a list of directories to search for
576//
577// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000578// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000579//
580// FIXME: -include,-imacros
581
582static llvm::cl::opt<bool>
583nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
584
585// Various command line options. These four add directories to each chain.
586static llvm::cl::list<std::string>
587F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
588 llvm::cl::desc("Add directory to framework include search path"));
589static llvm::cl::list<std::string>
590I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
591 llvm::cl::desc("Add directory to include search path"));
592static llvm::cl::list<std::string>
593idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
594 llvm::cl::desc("Add directory to AFTER include search path"));
595static llvm::cl::list<std::string>
596iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
597 llvm::cl::desc("Add directory to QUOTE include search path"));
598static llvm::cl::list<std::string>
599isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
600 llvm::cl::desc("Add directory to SYSTEM include search path"));
601
602// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
603static llvm::cl::list<std::string>
604iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
605 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
606static llvm::cl::list<std::string>
607iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
608 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
609static llvm::cl::list<std::string>
610iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
611 llvm::cl::Prefix,
612 llvm::cl::desc("Set directory to include search path with prefix"));
613
Chris Lattner0c946412007-08-26 17:47:35 +0000614static llvm::cl::opt<std::string>
615isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
616 llvm::cl::desc("Set the system root directory (usually /)"));
617
Reid Spencer5f016e22007-07-11 17:01:13 +0000618// Finally, implement the code that groks the options above.
619enum IncludeDirGroup {
620 Quoted = 0,
621 Angled,
622 System,
623 After
624};
625
626static std::vector<DirectoryLookup> IncludeGroup[4];
627
628/// AddPath - Add the specified path to the specified group list.
629///
630static void AddPath(const std::string &Path, IncludeDirGroup Group,
631 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000632 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000633 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000634 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000635
Chris Lattnerd6655272007-12-17 05:59:27 +0000636 // Compute the actual path, taking into consideration -isysroot.
637 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000638
Chris Lattnerd6655272007-12-17 05:59:27 +0000639 // Handle isysroot.
640 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000641 // FIXME: Portability. This should be a sys::Path interface, this doesn't
642 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000643 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
644 MappedPath.append(isysroot.begin(), isysroot.end());
645 if (Path[0] != '/') // If in the system group, add a /.
646 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 }
648
Chris Lattnerd6655272007-12-17 05:59:27 +0000649 MappedPath.append(Path.begin(), Path.end());
650
651 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 DirectoryLookup::DirType Type;
653 if (Group == Quoted || Group == Angled)
654 Type = DirectoryLookup::NormalHeaderDir;
655 else if (isCXXAware)
656 Type = DirectoryLookup::SystemHeaderDir;
657 else
658 Type = DirectoryLookup::ExternCSystemHeaderDir;
659
Chris Lattnerd6655272007-12-17 05:59:27 +0000660
661 // If the directory exists, add it.
662 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
663 &MappedPath[0]+
664 MappedPath.size())) {
665 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
666 isFramework));
667 return;
668 }
669
Chris Lattnerdf772332007-12-17 07:52:39 +0000670 // Check to see if this is an apple-style headermap (which are not allowed to
671 // be frameworks).
672 if (!isFramework) {
673 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
674 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000675 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
676 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000677 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
678 return;
679 }
Chris Lattner822da612007-12-17 06:36:45 +0000680 }
681 }
682
Chris Lattnerd6655272007-12-17 05:59:27 +0000683 if (Verbose)
684 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000685}
686
687/// RemoveDuplicates - If there are duplicate directory entries in the specified
688/// search list, remove the later (dead) ones.
689static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000690 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000691 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000692 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000693 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000694 if (SearchList[i].isNormalDir()) {
695 // If this isn't the first time we've seen this dir, remove it.
696 if (SeenDirs.insert(SearchList[i].getDir()))
697 continue;
698
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 if (Verbose)
700 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
701 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000702 } else if (SearchList[i].isFramework()) {
703 // If this isn't the first time we've seen this framework dir, remove it.
704 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
705 continue;
706
707 if (Verbose)
708 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
709 SearchList[i].getFrameworkDir()->getName());
710
Chris Lattnerb94c7072007-12-17 06:44:29 +0000711 } else {
712 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
713 // If this isn't the first time we've seen this headermap, remove it.
714 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
715 continue;
716
717 if (Verbose)
718 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
719 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000721
722 // This is reached if the current entry is a duplicate.
723 SearchList.erase(SearchList.begin()+i);
724 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 }
726}
727
728/// InitializeIncludePaths - Process the -I options and set them in the
729/// HeaderSearch object.
730static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000731 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 // Handle -F... options.
733 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000734 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000735
736 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000737 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000738 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000739
740 // Handle -idirafter... options.
741 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000742 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000743
744 // Handle -iquote... options.
745 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000746 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000747
748 // Handle -isystem... options.
749 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000750 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000751
752 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
753 // parallel, processing the values in order of occurance to get the right
754 // prefixes.
755 {
756 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
757 unsigned iprefix_idx = 0;
758 unsigned iwithprefix_idx = 0;
759 unsigned iwithprefixbefore_idx = 0;
760 bool iprefix_done = iprefix_vals.empty();
761 bool iwithprefix_done = iwithprefix_vals.empty();
762 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
763 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
764 if (!iprefix_done &&
765 (iwithprefix_done ||
766 iprefix_vals.getPosition(iprefix_idx) <
767 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
768 (iwithprefixbefore_done ||
769 iprefix_vals.getPosition(iprefix_idx) <
770 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
771 Prefix = iprefix_vals[iprefix_idx];
772 ++iprefix_idx;
773 iprefix_done = iprefix_idx == iprefix_vals.size();
774 } else if (!iwithprefix_done &&
775 (iwithprefixbefore_done ||
776 iwithprefix_vals.getPosition(iwithprefix_idx) <
777 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
778 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000779 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 ++iwithprefix_idx;
781 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
782 } else {
783 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000784 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 ++iwithprefixbefore_idx;
786 iwithprefixbefore_done =
787 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
788 }
789 }
790 }
791
792 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
793 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
794
795 // FIXME: temporary hack: hard-coded paths.
796 // FIXME: get these from the target?
797 if (!nostdinc) {
798 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000799 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000801 false, Headers);
802 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
803 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 }
805
Chris Lattner822da612007-12-17 06:36:45 +0000806 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 // leopard
808 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000809 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000811 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
813 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000814 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000815
816 // tiger
817 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000818 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000820 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
822 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000823 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000824
Chris Lattner822da612007-12-17 06:36:45 +0000825 AddPath("/usr/include", System, false, false, false, Headers);
826 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
827 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000828 }
829
830 // Now that we have collected all of the include paths, merge them all
831 // together and tell the preprocessor about them.
832
833 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
834 std::vector<DirectoryLookup> SearchList;
835 SearchList = IncludeGroup[Angled];
836 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
837 IncludeGroup[System].end());
838 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
839 IncludeGroup[After].end());
840 RemoveDuplicates(SearchList);
841 RemoveDuplicates(IncludeGroup[Quoted]);
842
843 // Prepend QUOTED list on the search list.
844 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
845 IncludeGroup[Quoted].end());
846
847
848 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
849 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
850 DontSearchCurDir);
851
852 // If verbose, print the list of directories that will be searched.
853 if (Verbose) {
854 fprintf(stderr, "#include \"...\" search starts here:\n");
855 unsigned QuotedIdx = IncludeGroup[Quoted].size();
856 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
857 if (i == QuotedIdx)
858 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000859 const char *Name = SearchList[i].getName();
860 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000861 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000862 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000863 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000864 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000865 else {
866 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000867 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000868 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000869 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 }
Chris Lattner80e17152007-12-15 23:11:06 +0000871 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 }
873}
874
875
Reid Spencer5f016e22007-07-11 17:01:13 +0000876//===----------------------------------------------------------------------===//
877// Basic Parser driver
878//===----------------------------------------------------------------------===//
879
880static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
881 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000882 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000883
884 // Parsing the specified input file.
885 P.ParseTranslationUnit();
886 delete PA;
887}
888
889//===----------------------------------------------------------------------===//
890// Main driver
891//===----------------------------------------------------------------------===//
892
Ted Kremenekdb094a22007-12-05 18:27:04 +0000893/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
894/// action. These consumers can operate on both ASTs that are freshly
895/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenek63ea8632007-12-19 19:27:38 +0000896static ASTConsumer* CreateASTConsumer(const std::string& SourceFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000897 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000898 const LangOptions& LangOpts) {
899 switch (ProgAction) {
900 default:
901 return NULL;
902
903 case ASTPrint:
904 return CreateASTPrinter();
905
906 case ASTDump:
907 return CreateASTDumper();
908
909 case ASTView:
910 return CreateASTViewer();
911
912 case ParseCFGDump:
913 case ParseCFGView:
914 return CreateCFGDumper(ProgAction == ParseCFGView);
915
916 case AnalysisLiveVariables:
917 return CreateLiveVarAnalyzer();
918
919 case WarnDeadStores:
920 return CreateDeadStoreChecker(Diag);
921
922 case WarnUninitVals:
923 return CreateUnitValsChecker(Diag);
924
925 case TestSerialization:
Ted Kremenek63ea8632007-12-19 19:27:38 +0000926 return CreateSerializationTest(SourceFile, Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000927
928 case EmitLLVM:
929 return CreateLLVMEmitter(Diag, LangOpts);
930
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000931 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000932 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek63ea8632007-12-19 19:27:38 +0000933 return CreateASTSerializer(SourceFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000934
Ted Kremenekdb094a22007-12-05 18:27:04 +0000935 case RewriteTest:
936 return CreateCodeRewriterTest(Diag);
937 }
938}
939
Reid Spencer5f016e22007-07-11 17:01:13 +0000940/// ProcessInputFile - Process a single input file with the specified state.
941///
942static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
Ted Kremenek63ea8632007-12-19 19:27:38 +0000943 const std::string &SourceFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000944 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000945
946 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000947 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000948
Reid Spencer5f016e22007-07-11 17:01:13 +0000949 switch (ProgAction) {
950 default:
Ted Kremenek63ea8632007-12-19 19:27:38 +0000951 Consumer = CreateASTConsumer(SourceFile, PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000952 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000953 PP.getLangOptions());
954
955 if (!Consumer) {
956 fprintf(stderr, "Unexpected program action!\n");
957 return;
958 }
959 break;
960
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000962 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000963 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000964 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 do {
966 PP.Lex(Tok);
967 PP.DumpToken(Tok, true);
968 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000969 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000970 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 break;
972 }
973 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000974 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000976 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 do {
978 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000979 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000980 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 break;
982 }
983
984 case PrintPreprocessedInput: // -E mode.
Chris Lattnerdee73592007-12-15 20:48:40 +0000985 DoPrintPreprocessedInput(MainFileID, PP);
Chris Lattnerbd247762007-07-22 06:05:44 +0000986 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 break;
988
989 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000990 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000991 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 break;
993
994 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +0000995 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
996 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000997 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000998 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000999
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001000 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001001 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001002 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001003 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001004
1005 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001006 if (VerifyDiagnostics)
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001007 exit(CheckASTConsumer(PP, MainFileID, Consumer));
1008
1009 // This deletes Consumer.
1010 ParseAST(PP, MainFileID, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 }
1012
1013 if (Stats) {
Ted Kremenek63ea8632007-12-19 19:27:38 +00001014 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", SourceFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 PP.PrintStats();
1016 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001017 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001018 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001019 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 fprintf(stderr, "\n");
1021 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001022
1023 // For a multi-file compilation, some things are ok with nuking the source
1024 // manager tables, other require stable fileid/macroid's across multiple
1025 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001026 if (ClearSourceMgr)
1027 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001028}
1029
Ted Kremenek20e97482007-12-12 23:41:08 +00001030static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1031 FileManager& FileMgr) {
1032
1033 if (VerifyDiagnostics) {
1034 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1035 exit (1);
1036 }
1037
1038 llvm::sys::Path Filename(InFile);
1039
1040 if (!Filename.isValid()) {
1041 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1042 exit (1);
1043 }
1044
Ted Kremenek63ea8632007-12-19 19:27:38 +00001045 llvm::scoped_ptr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001046
1047 if (!TU) {
1048 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1049 InFile.c_str());
1050 exit (1);
1051 }
1052
Ted Kremenek63ea8632007-12-19 19:27:38 +00001053 // Observe that we use the source file name stored in the deserialized
1054 // translation unit, rather than InFile.
1055 llvm::scoped_ptr<ASTConsumer>
1056 Consumer(CreateASTConsumer(TU->getSourceFile(), Diag, FileMgr,
1057 TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001058
1059 if (!Consumer) {
1060 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1061 exit (1);
1062 }
1063
1064 // FIXME: only work on consumers that do not require MainFileID.
Ted Kremenek63ea8632007-12-19 19:27:38 +00001065 Consumer->Initialize(*TU->getContext(), 0);
Ted Kremenek20e97482007-12-12 23:41:08 +00001066
1067 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1068 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001069}
1070
1071
Reid Spencer5f016e22007-07-11 17:01:13 +00001072static llvm::cl::list<std::string>
1073InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1074
Ted Kremenek20e97482007-12-12 23:41:08 +00001075static bool isSerializedFile(const std::string& InFile) {
1076 if (InFile.size() < 4)
1077 return false;
1078
1079 const char* s = InFile.c_str()+InFile.size()-4;
1080
1081 return s[0] == '.' &&
1082 s[1] == 'a' &&
1083 s[2] == 's' &&
1084 s[3] == 't';
1085}
1086
Reid Spencer5f016e22007-07-11 17:01:13 +00001087
1088int main(int argc, char **argv) {
1089 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1090 llvm::sys::PrintStackTraceOnErrorSignal();
1091
1092 // If no input was specified, read from stdin.
1093 if (InputFilenames.empty())
1094 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001095
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 // Create a file manager object to provide access to and cache the filesystem.
1097 FileManager FileMgr;
1098
Ted Kremenek31e703b2007-12-11 23:28:38 +00001099 // Create the diagnostic client for reporting errors or for
1100 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001102 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001104 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 } else {
1106 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001107 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001108
1109 if (InputFilenames.size() != 1) {
1110 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001111 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 return 1;
1113 }
1114 }
1115
1116 // Configure our handling of diagnostics.
1117 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001118 InitializeDiagnostics(Diags);
1119
Chris Lattner4f037832007-12-05 23:24:17 +00001120 // -I- is a deprecated GCC feature, scan for it and reject it.
1121 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1122 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001123 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001124 I_dirs.erase(I_dirs.begin()+i);
1125 --i;
1126 }
1127 }
1128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001130 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001131
Ted Kremenek20e97482007-12-12 23:41:08 +00001132 if (isSerializedFile(InFile))
1133 ProcessSerializedFile(InFile,Diags,FileMgr);
1134 else {
1135 /// Create a SourceManager object. This tracks and owns all the file
1136 /// buffers allocated to a translation unit.
1137 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001138
Ted Kremenek20e97482007-12-12 23:41:08 +00001139 // Initialize language options, inferring file types from input filenames.
1140 LangOptions LangInfo;
1141 InitializeBaseLanguage();
1142 LangKind LK = GetLanguage(InFile);
1143 InitializeLangOptions(LangInfo, LK);
1144 InitializeLanguageStandard(LangInfo, LK);
1145
1146 // Process the -I options and set them in the HeaderInfo.
1147 HeaderSearch HeaderInfo(FileMgr);
1148 DiagClient->setHeaderSearch(HeaderInfo);
1149 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1150
1151 // Get information about the targets being compiled for. Note that this
1152 // pointer and the TargetInfoImpl objects are never deleted by this toy
1153 // driver.
1154 TargetInfo *Target;
1155
1156 // Create triples, and create the TargetInfo.
1157 std::vector<std::string> triples;
1158 CreateTargetTriples(triples);
1159 Target = TargetInfo::CreateTargetInfo(&triples[0],
1160 &triples[0]+triples.size(),
1161 &Diags);
1162
1163 if (Target == 0) {
1164 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1165 triples[0].c_str());
1166 fprintf(stderr, "Please use -triple or -arch.\n");
1167 exit(1);
1168 }
1169
1170 // Set up the preprocessor with these options.
1171 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1172
1173 std::vector<char> PredefineBuffer;
Chris Lattnerdee73592007-12-15 20:48:40 +00001174 unsigned MainFileID = InitializePreprocessor(PP, InFile, PredefineBuffer);
Ted Kremenek20e97482007-12-12 23:41:08 +00001175
1176 if (!MainFileID) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001177
Chris Lattnerdee73592007-12-15 20:48:40 +00001178 ProcessInputFile(PP, MainFileID, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001179
1180 HeaderInfo.ClearFileInfo();
1181
1182 if (Stats)
1183 SourceMgr.PrintStats();
1184 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 }
1186
1187 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1188
1189 if (NumDiagnostics)
1190 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1191 (NumDiagnostics == 1 ? "" : "s"));
1192
1193 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 FileMgr.PrintStats();
1195 fprintf(stderr, "\n");
1196 }
1197
Chris Lattner96f1a642007-07-21 05:40:53 +00001198 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001199}