blob: c2ebfb38a846db5b1465879a0b513c0084d8096b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
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 Kremenekee533642007-12-20 19:47:16 +000042#include "llvm/ADT/OwningPtr.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>
Nate Begemanaabbb122007-12-30 01:38:50 +000053Stats("print-stats",
54 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000055
56enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000057 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000058 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000059 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000060 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000061 ASTPrint, // Parse ASTs and print them.
62 ASTDump, // Parse ASTs and dump them.
63 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000064 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000065 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000066 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremeneke603df42008-01-08 18:04:06 +000067 AnalysisGRConstProp, // Perform graph-reachability constant prop.
Ted Kremenek055c2752007-09-06 23:00:42 +000068 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000069 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000070 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000071 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000072 ParsePrintCallbacks, // Parse and print each callback.
73 ParseSyntaxOnly, // Parse and perform semantic analysis.
74 ParseNoop, // Parse with noop callbacks.
75 RunPreprocessorOnly, // Just lex, no output.
76 PrintPreprocessedInput, // -E mode.
77 DumpTokens // Token dump mode.
78};
79
80static llvm::cl::opt<ProgActions>
81ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
82 llvm::cl::init(ParseSyntaxOnly),
83 llvm::cl::values(
84 clEnumValN(RunPreprocessorOnly, "Eonly",
85 "Just run preprocessor, no output (for timings)"),
86 clEnumValN(PrintPreprocessedInput, "E",
87 "Run preprocessor, emit preprocessed file"),
88 clEnumValN(DumpTokens, "dumptokens",
89 "Run preprocessor, dump internal rep of tokens"),
90 clEnumValN(ParseNoop, "parse-noop",
91 "Run parser with noop callbacks (for timings)"),
92 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
93 "Run parser and perform semantic analysis"),
94 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
95 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000096 clEnumValN(ASTPrint, "ast-print",
97 "Build ASTs and then pretty-print them"),
98 clEnumValN(ASTDump, "ast-dump",
99 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000100 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000101 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000102 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000103 "Run parser, then build and print CFGs."),
104 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000105 "Run parser, then build and view CFGs with Graphviz."),
106 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000107 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000108 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000109 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000110 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000111 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke603df42008-01-08 18:04:06 +0000112 clEnumValN(AnalysisGRConstProp, "gr-const-prop",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000113 "Perform path-sensitive constant propagation."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000114 clEnumValN(TestSerialization, "test-pickling",
115 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000117 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000118 clEnumValN(EmitBC, "emit-llvm-bc",
119 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000120 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000121 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000122 clEnumValN(RewriteTest, "rewrite-test",
123 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 clEnumValEnd));
125
Ted Kremenekccc76472007-12-19 19:47:59 +0000126
127static llvm::cl::opt<std::string>
128OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000129 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000130 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
131
Ted Kremenek41193e42007-09-26 19:42:19 +0000132static llvm::cl::opt<bool>
133VerifyDiagnostics("verify",
134 llvm::cl::desc("Verify emitted diagnostics and warnings."));
135
Reid Spencer5f016e22007-07-11 17:01:13 +0000136//===----------------------------------------------------------------------===//
137// Language Options
138//===----------------------------------------------------------------------===//
139
140enum LangKind {
141 langkind_unspecified,
142 langkind_c,
143 langkind_c_cpp,
144 langkind_cxx,
145 langkind_cxx_cpp,
146 langkind_objc,
147 langkind_objc_cpp,
148 langkind_objcxx,
149 langkind_objcxx_cpp
150};
151
152/* TODO: GCC also accepts:
153 c-header c++-header objective-c-header objective-c++-header
154 assembler assembler-with-cpp
155 ada, f77*, ratfor (!), f95, java, treelang
156 */
157static llvm::cl::opt<LangKind>
158BaseLang("x", llvm::cl::desc("Base language to compile"),
159 llvm::cl::init(langkind_unspecified),
160 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
161 clEnumValN(langkind_cxx, "c++", "C++"),
162 clEnumValN(langkind_objc, "objective-c", "Objective C"),
163 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
164 clEnumValN(langkind_c_cpp, "c-cpp-output",
165 "Preprocessed C"),
166 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
167 "Preprocessed C++"),
168 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
169 "Preprocessed Objective C"),
170 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
171 "Preprocessed Objective C++"),
172 clEnumValEnd));
173
174static llvm::cl::opt<bool>
175LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
176 llvm::cl::Hidden);
177static llvm::cl::opt<bool>
178LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
179 llvm::cl::Hidden);
180
Ted Kremenek8904f152007-12-05 23:49:08 +0000181/// InitializeBaseLanguage - Handle the -x foo options.
182static void InitializeBaseLanguage() {
183 if (LangObjC)
184 BaseLang = langkind_objc;
185 else if (LangObjCXX)
186 BaseLang = langkind_objcxx;
187}
188
189static LangKind GetLanguage(const std::string &Filename) {
190 if (BaseLang != langkind_unspecified)
191 return BaseLang;
192
193 std::string::size_type DotPos = Filename.rfind('.');
194
195 if (DotPos == std::string::npos) {
196 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000197 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 }
199
Ted Kremenek8904f152007-12-05 23:49:08 +0000200 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
201 // C header: .h
202 // C++ header: .hh or .H;
203 // assembler no preprocessing: .s
204 // assembler: .S
205 if (Ext == "c")
206 return langkind_c;
207 else if (Ext == "i")
208 return langkind_c_cpp;
209 else if (Ext == "ii")
210 return langkind_cxx_cpp;
211 else if (Ext == "m")
212 return langkind_objc;
213 else if (Ext == "mi")
214 return langkind_objc_cpp;
215 else if (Ext == "mm" || Ext == "M")
216 return langkind_objcxx;
217 else if (Ext == "mii")
218 return langkind_objcxx_cpp;
219 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
220 Ext == "c++" || Ext == "cp" || Ext == "cxx")
221 return langkind_cxx;
222 else
223 return langkind_c;
224}
225
226
227static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 // FIXME: implement -fpreprocessed mode.
229 bool NoPreprocess = false;
230
Ted Kremenek8904f152007-12-05 23:49:08 +0000231 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 default: assert(0 && "Unknown language kind!");
233 case langkind_c_cpp:
234 NoPreprocess = true;
235 // FALLTHROUGH
236 case langkind_c:
237 break;
238 case langkind_cxx_cpp:
239 NoPreprocess = true;
240 // FALLTHROUGH
241 case langkind_cxx:
242 Options.CPlusPlus = 1;
243 break;
244 case langkind_objc_cpp:
245 NoPreprocess = true;
246 // FALLTHROUGH
247 case langkind_objc:
248 Options.ObjC1 = Options.ObjC2 = 1;
249 break;
250 case langkind_objcxx_cpp:
251 NoPreprocess = true;
252 // FALLTHROUGH
253 case langkind_objcxx:
254 Options.ObjC1 = Options.ObjC2 = 1;
255 Options.CPlusPlus = 1;
256 break;
257 }
258}
259
260/// LangStds - Language standards we support.
261enum LangStds {
262 lang_unspecified,
263 lang_c89, lang_c94, lang_c99,
264 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000265 lang_cxx98, lang_gnucxx98,
266 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000267};
268
269static llvm::cl::opt<LangStds>
270LangStd("std", llvm::cl::desc("Language standard to compile for"),
271 llvm::cl::init(lang_unspecified),
272 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
273 clEnumValN(lang_c89, "c90", "ISO C 1990"),
274 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
275 clEnumValN(lang_c94, "iso9899:199409",
276 "ISO C 1990 with amendment 1"),
277 clEnumValN(lang_c99, "c99", "ISO C 1999"),
278// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
279 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
280// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
281 clEnumValN(lang_gnu89, "gnu89",
282 "ISO C 1990 with GNU extensions (default for C)"),
283 clEnumValN(lang_gnu99, "gnu99",
284 "ISO C 1999 with GNU extensions"),
285 clEnumValN(lang_gnu99, "gnu9x",
286 "ISO C 1999 with GNU extensions"),
287 clEnumValN(lang_cxx98, "c++98",
288 "ISO C++ 1998 with amendments"),
289 clEnumValN(lang_gnucxx98, "gnu++98",
290 "ISO C++ 1998 with amendments and GNU "
291 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000292 clEnumValN(lang_cxx0x, "c++0x",
293 "Upcoming ISO C++ 200x with amendments"),
294 clEnumValN(lang_gnucxx0x, "gnu++0x",
295 "Upcoming ISO C++ 200x with amendments and GNU "
296 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 clEnumValEnd));
298
299static llvm::cl::opt<bool>
300NoOperatorNames("fno-operator-names",
301 llvm::cl::desc("Do not treat C++ operator name keywords as "
302 "synonyms for operators"));
303
Anders Carlssonee98ac52007-10-15 02:50:23 +0000304static llvm::cl::opt<bool>
305PascalStrings("fpascal-strings",
306 llvm::cl::desc("Recognize and construct Pascal-style "
307 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000308
309static llvm::cl::opt<bool>
310WritableStrings("fwritable-strings",
311 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000312
313static llvm::cl::opt<bool>
314LaxVectorConversions("flax-vector-conversions",
315 llvm::cl::desc("Allow implicit conversions between vectors"
316 " with a different number of elements or "
317 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000318// FIXME: add:
319// -ansi
320// -trigraphs
321// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000322// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000323static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 if (LangStd == lang_unspecified) {
325 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000326 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 default: assert(0 && "Unknown base language");
328 case langkind_c:
329 case langkind_c_cpp:
330 case langkind_objc:
331 case langkind_objc_cpp:
332 LangStd = lang_gnu99;
333 break;
334 case langkind_cxx:
335 case langkind_cxx_cpp:
336 case langkind_objcxx:
337 case langkind_objcxx_cpp:
338 LangStd = lang_gnucxx98;
339 break;
340 }
341 }
342
343 switch (LangStd) {
344 default: assert(0 && "Unknown language standard!");
345
346 // Fall through from newer standards to older ones. This isn't really right.
347 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000348 case lang_gnucxx0x:
349 case lang_cxx0x:
350 Options.CPlusPlus0x = 1;
351 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 case lang_gnucxx98:
353 case lang_cxx98:
354 Options.CPlusPlus = 1;
355 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000356 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // FALL THROUGH.
358 case lang_gnu99:
359 case lang_c99:
360 Options.Digraphs = 1;
361 Options.C99 = 1;
362 Options.HexFloats = 1;
363 // FALL THROUGH.
364 case lang_gnu89:
365 Options.BCPLComment = 1; // Only for C99/C++.
366 // FALL THROUGH.
367 case lang_c94:
368 case lang_c89:
369 break;
370 }
371
372 Options.Trigraphs = 1; // -trigraphs or -ansi
373 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000374 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000375 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000376 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000377}
378
379//===----------------------------------------------------------------------===//
380// Our DiagnosticClient implementation
381//===----------------------------------------------------------------------===//
382
383// FIXME: Werror should take a list of things, -Werror=foo,bar
384static llvm::cl::opt<bool>
385WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
386
387static llvm::cl::opt<bool>
388WarnOnExtensions("pedantic", llvm::cl::init(false),
389 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
390
391static llvm::cl::opt<bool>
392ErrorOnExtensions("pedantic-errors",
393 llvm::cl::desc("Issue an error on uses of GCC extensions"));
394
395static llvm::cl::opt<bool>
396WarnUnusedMacros("Wunused_macros",
397 llvm::cl::desc("Warn for unused macros in the main translation unit"));
398
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000399static llvm::cl::opt<bool>
400WarnFloatEqual("Wfloat-equal",
401 llvm::cl::desc("Warn about equality comparisons of floating point values."));
402
Ted Kremenek73da5902007-12-17 17:50:07 +0000403static llvm::cl::opt<bool>
404WarnNoFormatNonLiteral("Wno-format-nonliteral",
405 llvm::cl::desc("Do not warn about non-literal format strings."));
406
Reid Spencer5f016e22007-07-11 17:01:13 +0000407/// InitializeDiagnostics - Initialize the diagnostic object, based on the
408/// current command line option settings.
409static void InitializeDiagnostics(Diagnostic &Diags) {
410 Diags.setWarningsAsErrors(WarningsAsErrors);
411 Diags.setWarnOnExtensions(WarnOnExtensions);
412 Diags.setErrorOnExtensions(ErrorOnExtensions);
413
414 // Silence the "macro is not used" warning unless requested.
415 if (!WarnUnusedMacros)
416 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000417
418 // Silence "floating point comparison" warnings unless requested.
419 if (!WarnFloatEqual)
420 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000421
422 // Silence "format string is not a string literal" warnings if requested
423 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000424 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
425 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000426
Reid Spencer5f016e22007-07-11 17:01:13 +0000427}
428
429//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000430// Target Triple Processing.
431//===----------------------------------------------------------------------===//
432
433static llvm::cl::opt<std::string>
434TargetTriple("triple",
435 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
436
437static llvm::cl::list<std::string>
438Archs("arch",
439 llvm::cl::desc("Specify target architecture (e.g. i686)."));
440
441namespace {
442 class TripleProcessor {
443 llvm::StringMap<char> TriplesProcessed;
444 std::vector<std::string>& triples;
445 public:
446 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
447
448 void addTriple(const std::string& t) {
449 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
450 TriplesProcessed.end()) {
451 triples.push_back(t);
452 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
453 }
454 }
455 };
456}
457
458static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000459 // Initialize base triple. If a -triple option has been specified, use
460 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000461 std::string Triple = TargetTriple;
462 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000463
464 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000465 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000466
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000467 if (firstDash == std::string::npos) {
468 fprintf(stderr,
469 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000470 Triple.c_str());
471 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000472 }
Ted Kremenekae360762007-12-03 22:06:55 +0000473
Chris Lattner6590d212007-12-12 05:01:48 +0000474 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000475
476 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000477 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
478 Triple.c_str());
479 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000480 }
Ted Kremenekae360762007-12-03 22:06:55 +0000481
482 // Create triple cacher.
483 TripleProcessor tp(triples);
484
485 // Add the primary triple to our set of triples if we are using the
486 // host-triple with no archs or using a specified target triple.
487 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000488 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000489
490 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
491 tp.addTriple(Archs[i] + "-" + suffix);
492}
493
494//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000495// Preprocessor Initialization
496//===----------------------------------------------------------------------===//
497
498// FIXME: Preprocessor builtins to support.
499// -A... - Play with #assertions
500// -undef - Undefine all predefined macros
501
502static llvm::cl::list<std::string>
503D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
504 llvm::cl::desc("Predefine the specified macro"));
505static llvm::cl::list<std::string>
506U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
507 llvm::cl::desc("Undefine the specified macro"));
508
509// Append a #define line to Buf for Macro. Macro should be of the form XXX,
510// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
511// "#define XXX Y z W". To get a #define with no value, use "XXX=".
512static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
513 const char *Command = "#define ") {
514 Buf.insert(Buf.end(), Command, Command+strlen(Command));
515 if (const char *Equal = strchr(Macro, '=')) {
516 // Turn the = into ' '.
517 Buf.insert(Buf.end(), Macro, Equal);
518 Buf.push_back(' ');
519 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
520 } else {
521 // Push "macroname 1".
522 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
523 Buf.push_back(' ');
524 Buf.push_back('1');
525 }
526 Buf.push_back('\n');
527}
528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529
Chris Lattner53b0dab2007-10-09 22:10:18 +0000530/// InitializePreprocessor - Initialize the preprocessor getting it and the
531/// environment ready to process a single file. This returns the file ID for the
532/// input file. If a failure happens, it returns 0.
533///
534static unsigned InitializePreprocessor(Preprocessor &PP,
535 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000536 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000537
Chris Lattnerdee73592007-12-15 20:48:40 +0000538 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000539
Chris Lattner53b0dab2007-10-09 22:10:18 +0000540 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000541 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000542 if (InFile != "-") {
543 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000544 if (File) SourceMgr.createMainFileID(File, SourceLocation());
545 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000546 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
547 return 0;
548 }
549 } else {
550 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000551 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
552 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000553 fprintf(stderr, "Error reading standard input! Empty?\n");
554 return 0;
555 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 }
557
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 // Add macros from the command line.
559 // FIXME: Should traverse the #define/#undef lists in parallel.
560 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000561 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000563 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
564
565 // FIXME: Read any files specified by -imacros or -include.
566
567 // Null terminate PredefinedBuffer and add it.
568 PredefineBuffer.push_back(0);
569 PP.setPredefines(&PredefineBuffer[0]);
570
571 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000572 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000573}
574
575//===----------------------------------------------------------------------===//
576// Preprocessor include path information.
577//===----------------------------------------------------------------------===//
578
579// This tool exports a large number of command line options to control how the
580// preprocessor searches for header files. At root, however, the Preprocessor
581// object takes a very simple interface: a list of directories to search for
582//
583// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000584// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000585//
586// FIXME: -include,-imacros
587
588static llvm::cl::opt<bool>
589nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
590
591// Various command line options. These four add directories to each chain.
592static llvm::cl::list<std::string>
593F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
594 llvm::cl::desc("Add directory to framework include search path"));
595static llvm::cl::list<std::string>
596I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
597 llvm::cl::desc("Add directory to include search path"));
598static llvm::cl::list<std::string>
599idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
600 llvm::cl::desc("Add directory to AFTER include search path"));
601static llvm::cl::list<std::string>
602iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
603 llvm::cl::desc("Add directory to QUOTE include search path"));
604static llvm::cl::list<std::string>
605isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
606 llvm::cl::desc("Add directory to SYSTEM include search path"));
607
608// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
609static llvm::cl::list<std::string>
610iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
611 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
612static llvm::cl::list<std::string>
613iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
614 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
615static llvm::cl::list<std::string>
616iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
617 llvm::cl::Prefix,
618 llvm::cl::desc("Set directory to include search path with prefix"));
619
Chris Lattner0c946412007-08-26 17:47:35 +0000620static llvm::cl::opt<std::string>
621isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
622 llvm::cl::desc("Set the system root directory (usually /)"));
623
Reid Spencer5f016e22007-07-11 17:01:13 +0000624// Finally, implement the code that groks the options above.
625enum IncludeDirGroup {
626 Quoted = 0,
627 Angled,
628 System,
629 After
630};
631
632static std::vector<DirectoryLookup> IncludeGroup[4];
633
634/// AddPath - Add the specified path to the specified group list.
635///
636static void AddPath(const std::string &Path, IncludeDirGroup Group,
637 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000638 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000639 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000640 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000641
Chris Lattnerd6655272007-12-17 05:59:27 +0000642 // Compute the actual path, taking into consideration -isysroot.
643 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000644
Chris Lattnerd6655272007-12-17 05:59:27 +0000645 // Handle isysroot.
646 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000647 // FIXME: Portability. This should be a sys::Path interface, this doesn't
648 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000649 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
650 MappedPath.append(isysroot.begin(), isysroot.end());
651 if (Path[0] != '/') // If in the system group, add a /.
652 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 }
654
Chris Lattnerd6655272007-12-17 05:59:27 +0000655 MappedPath.append(Path.begin(), Path.end());
656
657 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 DirectoryLookup::DirType Type;
659 if (Group == Quoted || Group == Angled)
660 Type = DirectoryLookup::NormalHeaderDir;
661 else if (isCXXAware)
662 Type = DirectoryLookup::SystemHeaderDir;
663 else
664 Type = DirectoryLookup::ExternCSystemHeaderDir;
665
Chris Lattnerd6655272007-12-17 05:59:27 +0000666
667 // If the directory exists, add it.
668 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
669 &MappedPath[0]+
670 MappedPath.size())) {
671 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
672 isFramework));
673 return;
674 }
675
Chris Lattnerdf772332007-12-17 07:52:39 +0000676 // Check to see if this is an apple-style headermap (which are not allowed to
677 // be frameworks).
678 if (!isFramework) {
679 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
680 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000681 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
682 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000683 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
684 return;
685 }
Chris Lattner822da612007-12-17 06:36:45 +0000686 }
687 }
688
Chris Lattnerd6655272007-12-17 05:59:27 +0000689 if (Verbose)
690 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000691}
692
693/// RemoveDuplicates - If there are duplicate directory entries in the specified
694/// search list, remove the later (dead) ones.
695static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000696 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000697 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000698 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000700 if (SearchList[i].isNormalDir()) {
701 // If this isn't the first time we've seen this dir, remove it.
702 if (SeenDirs.insert(SearchList[i].getDir()))
703 continue;
704
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 if (Verbose)
706 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
707 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000708 } else if (SearchList[i].isFramework()) {
709 // If this isn't the first time we've seen this framework dir, remove it.
710 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
711 continue;
712
713 if (Verbose)
714 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
715 SearchList[i].getFrameworkDir()->getName());
716
Chris Lattnerb94c7072007-12-17 06:44:29 +0000717 } else {
718 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
719 // If this isn't the first time we've seen this headermap, remove it.
720 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
721 continue;
722
723 if (Verbose)
724 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
725 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000727
728 // This is reached if the current entry is a duplicate.
729 SearchList.erase(SearchList.begin()+i);
730 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 }
732}
733
734/// InitializeIncludePaths - Process the -I options and set them in the
735/// HeaderSearch object.
736static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000737 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 // Handle -F... options.
739 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000740 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000741
742 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000743 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000744 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000745
746 // Handle -idirafter... options.
747 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000748 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000749
750 // Handle -iquote... options.
751 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000752 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000753
754 // Handle -isystem... options.
755 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000756 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000757
758 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
759 // parallel, processing the values in order of occurance to get the right
760 // prefixes.
761 {
762 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
763 unsigned iprefix_idx = 0;
764 unsigned iwithprefix_idx = 0;
765 unsigned iwithprefixbefore_idx = 0;
766 bool iprefix_done = iprefix_vals.empty();
767 bool iwithprefix_done = iwithprefix_vals.empty();
768 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
769 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
770 if (!iprefix_done &&
771 (iwithprefix_done ||
772 iprefix_vals.getPosition(iprefix_idx) <
773 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
774 (iwithprefixbefore_done ||
775 iprefix_vals.getPosition(iprefix_idx) <
776 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
777 Prefix = iprefix_vals[iprefix_idx];
778 ++iprefix_idx;
779 iprefix_done = iprefix_idx == iprefix_vals.size();
780 } else if (!iwithprefix_done &&
781 (iwithprefixbefore_done ||
782 iwithprefix_vals.getPosition(iwithprefix_idx) <
783 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
784 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000785 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 ++iwithprefix_idx;
787 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
788 } else {
789 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000790 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 ++iwithprefixbefore_idx;
792 iwithprefixbefore_done =
793 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
794 }
795 }
796 }
797
798 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
799 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
800
801 // FIXME: temporary hack: hard-coded paths.
802 // FIXME: get these from the target?
803 if (!nostdinc) {
804 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000805 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000807 false, Headers);
808 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
809 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 }
811
Chris Lattner822da612007-12-17 06:36:45 +0000812 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 // leopard
814 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000815 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000817 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
819 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000820 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000821
822 // tiger
823 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000824 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000826 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
828 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000829 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000830
Chris Lattner822da612007-12-17 06:36:45 +0000831 AddPath("/usr/include", System, false, false, false, Headers);
832 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
833 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 }
835
836 // Now that we have collected all of the include paths, merge them all
837 // together and tell the preprocessor about them.
838
839 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
840 std::vector<DirectoryLookup> SearchList;
841 SearchList = IncludeGroup[Angled];
842 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
843 IncludeGroup[System].end());
844 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
845 IncludeGroup[After].end());
846 RemoveDuplicates(SearchList);
847 RemoveDuplicates(IncludeGroup[Quoted]);
848
849 // Prepend QUOTED list on the search list.
850 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
851 IncludeGroup[Quoted].end());
852
853
854 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
855 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
856 DontSearchCurDir);
857
858 // If verbose, print the list of directories that will be searched.
859 if (Verbose) {
860 fprintf(stderr, "#include \"...\" search starts here:\n");
861 unsigned QuotedIdx = IncludeGroup[Quoted].size();
862 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
863 if (i == QuotedIdx)
864 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000865 const char *Name = SearchList[i].getName();
866 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000867 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000868 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000869 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000870 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000871 else {
872 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000873 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000874 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000875 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 }
Chris Lattner80e17152007-12-15 23:11:06 +0000877 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 }
879}
880
881
Reid Spencer5f016e22007-07-11 17:01:13 +0000882//===----------------------------------------------------------------------===//
883// Basic Parser driver
884//===----------------------------------------------------------------------===//
885
Ted Kremenek95041a22007-12-19 22:51:13 +0000886static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000887 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000888 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000889
890 // Parsing the specified input file.
891 P.ParseTranslationUnit();
892 delete PA;
893}
894
895//===----------------------------------------------------------------------===//
896// Main driver
897//===----------------------------------------------------------------------===//
898
Ted Kremenekdb094a22007-12-05 18:27:04 +0000899/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
900/// action. These consumers can operate on both ASTs that are freshly
901/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000902static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000903 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000904 const LangOptions& LangOpts) {
905 switch (ProgAction) {
906 default:
907 return NULL;
908
909 case ASTPrint:
910 return CreateASTPrinter();
911
912 case ASTDump:
913 return CreateASTDumper();
914
915 case ASTView:
916 return CreateASTViewer();
917
918 case ParseCFGDump:
919 case ParseCFGView:
920 return CreateCFGDumper(ProgAction == ParseCFGView);
921
922 case AnalysisLiveVariables:
923 return CreateLiveVarAnalyzer();
924
925 case WarnDeadStores:
926 return CreateDeadStoreChecker(Diag);
927
928 case WarnUninitVals:
929 return CreateUnitValsChecker(Diag);
930
Ted Kremeneke603df42008-01-08 18:04:06 +0000931 case AnalysisGRConstProp:
932 return CreateGRConstProp();
933
Ted Kremenekdb094a22007-12-05 18:27:04 +0000934 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000935 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000936
937 case EmitLLVM:
938 return CreateLLVMEmitter(Diag, LangOpts);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000939
940 case EmitBC:
941 return CreateBCWriter(InFile, OutputFile, Diag, LangOpts);
942
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000943 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000944 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +0000945 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000946
Ted Kremenekdb094a22007-12-05 18:27:04 +0000947 case RewriteTest:
948 return CreateCodeRewriterTest(Diag);
949 }
950}
951
Reid Spencer5f016e22007-07-11 17:01:13 +0000952/// ProcessInputFile - Process a single input file with the specified state.
953///
Ted Kremenek7dcc9682007-12-19 22:32:34 +0000954static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000955 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000956
957 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000958 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000959
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 switch (ProgAction) {
961 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000962 Consumer = CreateASTConsumer(InFile,
963 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000964 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000965 PP.getLangOptions());
966
967 if (!Consumer) {
968 fprintf(stderr, "Unexpected program action!\n");
969 return;
970 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000971
Ted Kremenekdb094a22007-12-05 18:27:04 +0000972 break;
973
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000975 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000977 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 do {
979 PP.Lex(Tok);
980 PP.DumpToken(Tok, true);
981 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000982 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000983 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 break;
985 }
986 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000987 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000989 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 do {
991 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000992 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000993 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 break;
995 }
996
997 case PrintPreprocessedInput: // -E mode.
Ted Kremenek95041a22007-12-19 22:51:13 +0000998 DoPrintPreprocessedInput(PP);
Chris Lattnerbd247762007-07-22 06:05:44 +0000999 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 break;
1001
1002 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001003 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001004 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 break;
1006
1007 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001008 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001009 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001011
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001012 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001013 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001014 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001015 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001016
1017 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001018 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001019 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001020
1021 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001022 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 }
1024
1025 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001026 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 PP.PrintStats();
1028 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001029 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001030 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001031 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 fprintf(stderr, "\n");
1033 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001034
1035 // For a multi-file compilation, some things are ok with nuking the source
1036 // manager tables, other require stable fileid/macroid's across multiple
1037 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001038 if (ClearSourceMgr)
1039 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001040}
1041
Ted Kremenek20e97482007-12-12 23:41:08 +00001042static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1043 FileManager& FileMgr) {
1044
1045 if (VerifyDiagnostics) {
1046 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1047 exit (1);
1048 }
1049
1050 llvm::sys::Path Filename(InFile);
1051
1052 if (!Filename.isValid()) {
1053 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1054 exit (1);
1055 }
1056
Ted Kremenekee533642007-12-20 19:47:16 +00001057 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001058
1059 if (!TU) {
1060 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1061 InFile.c_str());
1062 exit (1);
1063 }
1064
Ted Kremenek63ea8632007-12-19 19:27:38 +00001065 // Observe that we use the source file name stored in the deserialized
1066 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001067 llvm::OwningPtr<ASTConsumer>
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001068 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001069
1070 if (!Consumer) {
1071 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1072 exit (1);
1073 }
1074
Ted Kremenek95041a22007-12-19 22:51:13 +00001075 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001076
1077 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1078 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001079}
1080
1081
Reid Spencer5f016e22007-07-11 17:01:13 +00001082static llvm::cl::list<std::string>
1083InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1084
Ted Kremenek20e97482007-12-12 23:41:08 +00001085static bool isSerializedFile(const std::string& InFile) {
1086 if (InFile.size() < 4)
1087 return false;
1088
1089 const char* s = InFile.c_str()+InFile.size()-4;
1090
1091 return s[0] == '.' &&
1092 s[1] == 'a' &&
1093 s[2] == 's' &&
1094 s[3] == 't';
1095}
1096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097
1098int main(int argc, char **argv) {
1099 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1100 llvm::sys::PrintStackTraceOnErrorSignal();
1101
1102 // If no input was specified, read from stdin.
1103 if (InputFilenames.empty())
1104 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001105
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 // Create a file manager object to provide access to and cache the filesystem.
1107 FileManager FileMgr;
1108
Ted Kremenek31e703b2007-12-11 23:28:38 +00001109 // Create the diagnostic client for reporting errors or for
1110 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001112 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001114 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 } else {
1116 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001117 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001118
1119 if (InputFilenames.size() != 1) {
1120 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001121 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 return 1;
1123 }
1124 }
1125
1126 // Configure our handling of diagnostics.
1127 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001128 InitializeDiagnostics(Diags);
1129
Chris Lattner4f037832007-12-05 23:24:17 +00001130 // -I- is a deprecated GCC feature, scan for it and reject it.
1131 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1132 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001133 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001134 I_dirs.erase(I_dirs.begin()+i);
1135 --i;
1136 }
1137 }
1138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001140 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001141
Ted Kremenek20e97482007-12-12 23:41:08 +00001142 if (isSerializedFile(InFile))
1143 ProcessSerializedFile(InFile,Diags,FileMgr);
1144 else {
1145 /// Create a SourceManager object. This tracks and owns all the file
1146 /// buffers allocated to a translation unit.
1147 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001148
Ted Kremenek20e97482007-12-12 23:41:08 +00001149 // Initialize language options, inferring file types from input filenames.
1150 LangOptions LangInfo;
1151 InitializeBaseLanguage();
1152 LangKind LK = GetLanguage(InFile);
1153 InitializeLangOptions(LangInfo, LK);
1154 InitializeLanguageStandard(LangInfo, LK);
1155
1156 // Process the -I options and set them in the HeaderInfo.
1157 HeaderSearch HeaderInfo(FileMgr);
1158 DiagClient->setHeaderSearch(HeaderInfo);
1159 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1160
1161 // Get information about the targets being compiled for. Note that this
1162 // pointer and the TargetInfoImpl objects are never deleted by this toy
1163 // driver.
1164 TargetInfo *Target;
1165
1166 // Create triples, and create the TargetInfo.
1167 std::vector<std::string> triples;
1168 CreateTargetTriples(triples);
1169 Target = TargetInfo::CreateTargetInfo(&triples[0],
1170 &triples[0]+triples.size(),
1171 &Diags);
1172
1173 if (Target == 0) {
1174 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1175 triples[0].c_str());
1176 fprintf(stderr, "Please use -triple or -arch.\n");
1177 exit(1);
1178 }
1179
1180 // Set up the preprocessor with these options.
1181 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1182
1183 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001184 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001185 continue;
1186
Ted Kremenek1036b682007-12-19 23:48:45 +00001187 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001188 HeaderInfo.ClearFileInfo();
1189
1190 if (Stats)
1191 SourceMgr.PrintStats();
1192 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 }
1194
1195 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1196
1197 if (NumDiagnostics)
1198 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1199 (NumDiagnostics == 1 ? "" : "s"));
1200
1201 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 FileMgr.PrintStats();
1203 fprintf(stderr, "\n");
1204 }
1205
Chris Lattner96f1a642007-07-21 05:40:53 +00001206 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001207}