blob: fa1be49c6a4c80e73078f6eee288c2edba4d4cde [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>
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.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000058 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000059 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000060 ASTPrint, // Parse ASTs and print them.
61 ASTDump, // Parse ASTs and dump them.
62 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000063 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000064 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000065 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000066 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000067 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000068 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000069 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000070 ParsePrintCallbacks, // Parse and print each callback.
71 ParseSyntaxOnly, // Parse and perform semantic analysis.
72 ParseNoop, // Parse with noop callbacks.
73 RunPreprocessorOnly, // Just lex, no output.
74 PrintPreprocessedInput, // -E mode.
75 DumpTokens // Token dump mode.
76};
77
78static llvm::cl::opt<ProgActions>
79ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
80 llvm::cl::init(ParseSyntaxOnly),
81 llvm::cl::values(
82 clEnumValN(RunPreprocessorOnly, "Eonly",
83 "Just run preprocessor, no output (for timings)"),
84 clEnumValN(PrintPreprocessedInput, "E",
85 "Run preprocessor, emit preprocessed file"),
86 clEnumValN(DumpTokens, "dumptokens",
87 "Run preprocessor, dump internal rep of tokens"),
88 clEnumValN(ParseNoop, "parse-noop",
89 "Run parser with noop callbacks (for timings)"),
90 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
91 "Run parser and perform semantic analysis"),
92 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
93 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000094 clEnumValN(ASTPrint, "ast-print",
95 "Build ASTs and then pretty-print them"),
96 clEnumValN(ASTDump, "ast-dump",
97 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +000098 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000099 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000100 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000101 "Run parser, then build and print CFGs."),
102 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000103 "Run parser, then build and view CFGs with Graphviz."),
104 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000105 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000106 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000107 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000108 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000109 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000110 clEnumValN(TestSerialization, "test-pickling",
111 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000113 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000114 clEnumValN(EmitBC, "emit-llvm-bc",
115 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000116 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000117 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000118 clEnumValN(RewriteTest, "rewrite-test",
119 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 clEnumValEnd));
121
Ted Kremenekccc76472007-12-19 19:47:59 +0000122
123static llvm::cl::opt<std::string>
124OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000125 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000126 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
127
Ted Kremenek41193e42007-09-26 19:42:19 +0000128static llvm::cl::opt<bool>
129VerifyDiagnostics("verify",
130 llvm::cl::desc("Verify emitted diagnostics and warnings."));
131
Reid Spencer5f016e22007-07-11 17:01:13 +0000132//===----------------------------------------------------------------------===//
133// Language Options
134//===----------------------------------------------------------------------===//
135
136enum LangKind {
137 langkind_unspecified,
138 langkind_c,
139 langkind_c_cpp,
140 langkind_cxx,
141 langkind_cxx_cpp,
142 langkind_objc,
143 langkind_objc_cpp,
144 langkind_objcxx,
145 langkind_objcxx_cpp
146};
147
148/* TODO: GCC also accepts:
149 c-header c++-header objective-c-header objective-c++-header
150 assembler assembler-with-cpp
151 ada, f77*, ratfor (!), f95, java, treelang
152 */
153static llvm::cl::opt<LangKind>
154BaseLang("x", llvm::cl::desc("Base language to compile"),
155 llvm::cl::init(langkind_unspecified),
156 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
157 clEnumValN(langkind_cxx, "c++", "C++"),
158 clEnumValN(langkind_objc, "objective-c", "Objective C"),
159 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
160 clEnumValN(langkind_c_cpp, "c-cpp-output",
161 "Preprocessed C"),
162 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
163 "Preprocessed C++"),
164 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
165 "Preprocessed Objective C"),
166 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
167 "Preprocessed Objective C++"),
168 clEnumValEnd));
169
170static llvm::cl::opt<bool>
171LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
172 llvm::cl::Hidden);
173static llvm::cl::opt<bool>
174LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
175 llvm::cl::Hidden);
176
Ted Kremenek8904f152007-12-05 23:49:08 +0000177/// InitializeBaseLanguage - Handle the -x foo options.
178static void InitializeBaseLanguage() {
179 if (LangObjC)
180 BaseLang = langkind_objc;
181 else if (LangObjCXX)
182 BaseLang = langkind_objcxx;
183}
184
185static LangKind GetLanguage(const std::string &Filename) {
186 if (BaseLang != langkind_unspecified)
187 return BaseLang;
188
189 std::string::size_type DotPos = Filename.rfind('.');
190
191 if (DotPos == std::string::npos) {
192 BaseLang = langkind_c; // Default to C if no extension.
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 }
194
Ted Kremenek8904f152007-12-05 23:49:08 +0000195 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
196 // C header: .h
197 // C++ header: .hh or .H;
198 // assembler no preprocessing: .s
199 // assembler: .S
200 if (Ext == "c")
201 return langkind_c;
202 else if (Ext == "i")
203 return langkind_c_cpp;
204 else if (Ext == "ii")
205 return langkind_cxx_cpp;
206 else if (Ext == "m")
207 return langkind_objc;
208 else if (Ext == "mi")
209 return langkind_objc_cpp;
210 else if (Ext == "mm" || Ext == "M")
211 return langkind_objcxx;
212 else if (Ext == "mii")
213 return langkind_objcxx_cpp;
214 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
215 Ext == "c++" || Ext == "cp" || Ext == "cxx")
216 return langkind_cxx;
217 else
218 return langkind_c;
219}
220
221
222static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 // FIXME: implement -fpreprocessed mode.
224 bool NoPreprocess = false;
225
Ted Kremenek8904f152007-12-05 23:49:08 +0000226 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 default: assert(0 && "Unknown language kind!");
228 case langkind_c_cpp:
229 NoPreprocess = true;
230 // FALLTHROUGH
231 case langkind_c:
232 break;
233 case langkind_cxx_cpp:
234 NoPreprocess = true;
235 // FALLTHROUGH
236 case langkind_cxx:
237 Options.CPlusPlus = 1;
238 break;
239 case langkind_objc_cpp:
240 NoPreprocess = true;
241 // FALLTHROUGH
242 case langkind_objc:
243 Options.ObjC1 = Options.ObjC2 = 1;
244 break;
245 case langkind_objcxx_cpp:
246 NoPreprocess = true;
247 // FALLTHROUGH
248 case langkind_objcxx:
249 Options.ObjC1 = Options.ObjC2 = 1;
250 Options.CPlusPlus = 1;
251 break;
252 }
253}
254
255/// LangStds - Language standards we support.
256enum LangStds {
257 lang_unspecified,
258 lang_c89, lang_c94, lang_c99,
259 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000260 lang_cxx98, lang_gnucxx98,
261 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000262};
263
264static llvm::cl::opt<LangStds>
265LangStd("std", llvm::cl::desc("Language standard to compile for"),
266 llvm::cl::init(lang_unspecified),
267 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
268 clEnumValN(lang_c89, "c90", "ISO C 1990"),
269 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
270 clEnumValN(lang_c94, "iso9899:199409",
271 "ISO C 1990 with amendment 1"),
272 clEnumValN(lang_c99, "c99", "ISO C 1999"),
273// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
274 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
275// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
276 clEnumValN(lang_gnu89, "gnu89",
277 "ISO C 1990 with GNU extensions (default for C)"),
278 clEnumValN(lang_gnu99, "gnu99",
279 "ISO C 1999 with GNU extensions"),
280 clEnumValN(lang_gnu99, "gnu9x",
281 "ISO C 1999 with GNU extensions"),
282 clEnumValN(lang_cxx98, "c++98",
283 "ISO C++ 1998 with amendments"),
284 clEnumValN(lang_gnucxx98, "gnu++98",
285 "ISO C++ 1998 with amendments and GNU "
286 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000287 clEnumValN(lang_cxx0x, "c++0x",
288 "Upcoming ISO C++ 200x with amendments"),
289 clEnumValN(lang_gnucxx0x, "gnu++0x",
290 "Upcoming ISO C++ 200x with amendments and GNU "
291 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 clEnumValEnd));
293
294static llvm::cl::opt<bool>
295NoOperatorNames("fno-operator-names",
296 llvm::cl::desc("Do not treat C++ operator name keywords as "
297 "synonyms for operators"));
298
Anders Carlssonee98ac52007-10-15 02:50:23 +0000299static llvm::cl::opt<bool>
300PascalStrings("fpascal-strings",
301 llvm::cl::desc("Recognize and construct Pascal-style "
302 "string literals"));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000303
304static llvm::cl::opt<bool>
305WritableStrings("fwritable-strings",
306 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000307
308static llvm::cl::opt<bool>
309LaxVectorConversions("flax-vector-conversions",
310 llvm::cl::desc("Allow implicit conversions between vectors"
311 " with a different number of elements or "
312 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000313// FIXME: add:
314// -ansi
315// -trigraphs
316// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000317// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000318static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 if (LangStd == lang_unspecified) {
320 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000321 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 default: assert(0 && "Unknown base language");
323 case langkind_c:
324 case langkind_c_cpp:
325 case langkind_objc:
326 case langkind_objc_cpp:
327 LangStd = lang_gnu99;
328 break;
329 case langkind_cxx:
330 case langkind_cxx_cpp:
331 case langkind_objcxx:
332 case langkind_objcxx_cpp:
333 LangStd = lang_gnucxx98;
334 break;
335 }
336 }
337
338 switch (LangStd) {
339 default: assert(0 && "Unknown language standard!");
340
341 // Fall through from newer standards to older ones. This isn't really right.
342 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000343 case lang_gnucxx0x:
344 case lang_cxx0x:
345 Options.CPlusPlus0x = 1;
346 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 case lang_gnucxx98:
348 case lang_cxx98:
349 Options.CPlusPlus = 1;
350 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000351 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // FALL THROUGH.
353 case lang_gnu99:
354 case lang_c99:
355 Options.Digraphs = 1;
356 Options.C99 = 1;
357 Options.HexFloats = 1;
358 // FALL THROUGH.
359 case lang_gnu89:
360 Options.BCPLComment = 1; // Only for C99/C++.
361 // FALL THROUGH.
362 case lang_c94:
363 case lang_c89:
364 break;
365 }
366
367 Options.Trigraphs = 1; // -trigraphs or -ansi
368 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000369 Options.PascalStrings = PascalStrings;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000370 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000371 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000372}
373
374//===----------------------------------------------------------------------===//
375// Our DiagnosticClient implementation
376//===----------------------------------------------------------------------===//
377
378// FIXME: Werror should take a list of things, -Werror=foo,bar
379static llvm::cl::opt<bool>
380WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
381
382static llvm::cl::opt<bool>
383WarnOnExtensions("pedantic", llvm::cl::init(false),
384 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
385
386static llvm::cl::opt<bool>
387ErrorOnExtensions("pedantic-errors",
388 llvm::cl::desc("Issue an error on uses of GCC extensions"));
389
390static llvm::cl::opt<bool>
391WarnUnusedMacros("Wunused_macros",
392 llvm::cl::desc("Warn for unused macros in the main translation unit"));
393
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000394static llvm::cl::opt<bool>
395WarnFloatEqual("Wfloat-equal",
396 llvm::cl::desc("Warn about equality comparisons of floating point values."));
397
Ted Kremenek73da5902007-12-17 17:50:07 +0000398static llvm::cl::opt<bool>
399WarnNoFormatNonLiteral("Wno-format-nonliteral",
400 llvm::cl::desc("Do not warn about non-literal format strings."));
401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402/// InitializeDiagnostics - Initialize the diagnostic object, based on the
403/// current command line option settings.
404static void InitializeDiagnostics(Diagnostic &Diags) {
405 Diags.setWarningsAsErrors(WarningsAsErrors);
406 Diags.setWarnOnExtensions(WarnOnExtensions);
407 Diags.setErrorOnExtensions(ErrorOnExtensions);
408
409 // Silence the "macro is not used" warning unless requested.
410 if (!WarnUnusedMacros)
411 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000412
413 // Silence "floating point comparison" warnings unless requested.
414 if (!WarnFloatEqual)
415 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000416
417 // Silence "format string is not a string literal" warnings if requested
418 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000419 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
420 diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422}
423
424//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000425// Target Triple Processing.
426//===----------------------------------------------------------------------===//
427
428static llvm::cl::opt<std::string>
429TargetTriple("triple",
430 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
431
432static llvm::cl::list<std::string>
433Archs("arch",
434 llvm::cl::desc("Specify target architecture (e.g. i686)."));
435
436namespace {
437 class TripleProcessor {
438 llvm::StringMap<char> TriplesProcessed;
439 std::vector<std::string>& triples;
440 public:
441 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
442
443 void addTriple(const std::string& t) {
444 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
445 TriplesProcessed.end()) {
446 triples.push_back(t);
447 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
448 }
449 }
450 };
451}
452
453static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000454 // Initialize base triple. If a -triple option has been specified, use
455 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000456 std::string Triple = TargetTriple;
457 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000458
459 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000460 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000461
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000462 if (firstDash == std::string::npos) {
463 fprintf(stderr,
464 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000465 Triple.c_str());
466 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000467 }
Ted Kremenekae360762007-12-03 22:06:55 +0000468
Chris Lattner6590d212007-12-12 05:01:48 +0000469 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000470
471 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000472 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
473 Triple.c_str());
474 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000475 }
Ted Kremenekae360762007-12-03 22:06:55 +0000476
477 // Create triple cacher.
478 TripleProcessor tp(triples);
479
480 // Add the primary triple to our set of triples if we are using the
481 // host-triple with no archs or using a specified target triple.
482 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000483 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000484
485 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
486 tp.addTriple(Archs[i] + "-" + suffix);
487}
488
489//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000490// Preprocessor Initialization
491//===----------------------------------------------------------------------===//
492
493// FIXME: Preprocessor builtins to support.
494// -A... - Play with #assertions
495// -undef - Undefine all predefined macros
496
497static llvm::cl::list<std::string>
498D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
499 llvm::cl::desc("Predefine the specified macro"));
500static llvm::cl::list<std::string>
501U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
502 llvm::cl::desc("Undefine the specified macro"));
503
504// Append a #define line to Buf for Macro. Macro should be of the form XXX,
505// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
506// "#define XXX Y z W". To get a #define with no value, use "XXX=".
507static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
508 const char *Command = "#define ") {
509 Buf.insert(Buf.end(), Command, Command+strlen(Command));
510 if (const char *Equal = strchr(Macro, '=')) {
511 // Turn the = into ' '.
512 Buf.insert(Buf.end(), Macro, Equal);
513 Buf.push_back(' ');
514 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
515 } else {
516 // Push "macroname 1".
517 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
518 Buf.push_back(' ');
519 Buf.push_back('1');
520 }
521 Buf.push_back('\n');
522}
523
Reid Spencer5f016e22007-07-11 17:01:13 +0000524
Chris Lattner53b0dab2007-10-09 22:10:18 +0000525/// InitializePreprocessor - Initialize the preprocessor getting it and the
526/// environment ready to process a single file. This returns the file ID for the
527/// input file. If a failure happens, it returns 0.
528///
529static unsigned InitializePreprocessor(Preprocessor &PP,
530 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000531 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000532
Chris Lattnerdee73592007-12-15 20:48:40 +0000533 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000534
Chris Lattner53b0dab2007-10-09 22:10:18 +0000535 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000536 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000537 if (InFile != "-") {
538 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000539 if (File) SourceMgr.createMainFileID(File, SourceLocation());
540 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000541 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
542 return 0;
543 }
544 } else {
545 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000546 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
547 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000548 fprintf(stderr, "Error reading standard input! Empty?\n");
549 return 0;
550 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 }
552
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 // Add macros from the command line.
554 // FIXME: Should traverse the #define/#undef lists in parallel.
555 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000556 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000558 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
559
560 // FIXME: Read any files specified by -imacros or -include.
561
562 // Null terminate PredefinedBuffer and add it.
563 PredefineBuffer.push_back(0);
564 PP.setPredefines(&PredefineBuffer[0]);
565
566 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000567 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000568}
569
570//===----------------------------------------------------------------------===//
571// Preprocessor include path information.
572//===----------------------------------------------------------------------===//
573
574// This tool exports a large number of command line options to control how the
575// preprocessor searches for header files. At root, however, the Preprocessor
576// object takes a very simple interface: a list of directories to search for
577//
578// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000579// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000580//
581// FIXME: -include,-imacros
582
583static llvm::cl::opt<bool>
584nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
585
586// Various command line options. These four add directories to each chain.
587static llvm::cl::list<std::string>
588F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
589 llvm::cl::desc("Add directory to framework include search path"));
590static llvm::cl::list<std::string>
591I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
592 llvm::cl::desc("Add directory to include search path"));
593static llvm::cl::list<std::string>
594idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
595 llvm::cl::desc("Add directory to AFTER include search path"));
596static llvm::cl::list<std::string>
597iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
598 llvm::cl::desc("Add directory to QUOTE include search path"));
599static llvm::cl::list<std::string>
600isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
601 llvm::cl::desc("Add directory to SYSTEM include search path"));
602
603// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
604static llvm::cl::list<std::string>
605iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
606 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
607static llvm::cl::list<std::string>
608iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
609 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
610static llvm::cl::list<std::string>
611iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
612 llvm::cl::Prefix,
613 llvm::cl::desc("Set directory to include search path with prefix"));
614
Chris Lattner0c946412007-08-26 17:47:35 +0000615static llvm::cl::opt<std::string>
616isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
617 llvm::cl::desc("Set the system root directory (usually /)"));
618
Reid Spencer5f016e22007-07-11 17:01:13 +0000619// Finally, implement the code that groks the options above.
620enum IncludeDirGroup {
621 Quoted = 0,
622 Angled,
623 System,
624 After
625};
626
627static std::vector<DirectoryLookup> IncludeGroup[4];
628
629/// AddPath - Add the specified path to the specified group list.
630///
631static void AddPath(const std::string &Path, IncludeDirGroup Group,
632 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000633 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000634 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000635 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000636
Chris Lattnerd6655272007-12-17 05:59:27 +0000637 // Compute the actual path, taking into consideration -isysroot.
638 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000639
Chris Lattnerd6655272007-12-17 05:59:27 +0000640 // Handle isysroot.
641 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000642 // FIXME: Portability. This should be a sys::Path interface, this doesn't
643 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000644 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
645 MappedPath.append(isysroot.begin(), isysroot.end());
646 if (Path[0] != '/') // If in the system group, add a /.
647 MappedPath.push_back('/');
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 }
649
Chris Lattnerd6655272007-12-17 05:59:27 +0000650 MappedPath.append(Path.begin(), Path.end());
651
652 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 DirectoryLookup::DirType Type;
654 if (Group == Quoted || Group == Angled)
655 Type = DirectoryLookup::NormalHeaderDir;
656 else if (isCXXAware)
657 Type = DirectoryLookup::SystemHeaderDir;
658 else
659 Type = DirectoryLookup::ExternCSystemHeaderDir;
660
Chris Lattnerd6655272007-12-17 05:59:27 +0000661
662 // If the directory exists, add it.
663 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
664 &MappedPath[0]+
665 MappedPath.size())) {
666 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
667 isFramework));
668 return;
669 }
670
Chris Lattnerdf772332007-12-17 07:52:39 +0000671 // Check to see if this is an apple-style headermap (which are not allowed to
672 // be frameworks).
673 if (!isFramework) {
674 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
675 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000676 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
677 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000678 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
679 return;
680 }
Chris Lattner822da612007-12-17 06:36:45 +0000681 }
682 }
683
Chris Lattnerd6655272007-12-17 05:59:27 +0000684 if (Verbose)
685 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000686}
687
688/// RemoveDuplicates - If there are duplicate directory entries in the specified
689/// search list, remove the later (dead) ones.
690static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000691 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000692 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000693 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000695 if (SearchList[i].isNormalDir()) {
696 // If this isn't the first time we've seen this dir, remove it.
697 if (SeenDirs.insert(SearchList[i].getDir()))
698 continue;
699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 if (Verbose)
701 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
702 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000703 } else if (SearchList[i].isFramework()) {
704 // If this isn't the first time we've seen this framework dir, remove it.
705 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
706 continue;
707
708 if (Verbose)
709 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
710 SearchList[i].getFrameworkDir()->getName());
711
Chris Lattnerb94c7072007-12-17 06:44:29 +0000712 } else {
713 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
714 // If this isn't the first time we've seen this headermap, remove it.
715 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
716 continue;
717
718 if (Verbose)
719 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
720 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000722
723 // This is reached if the current entry is a duplicate.
724 SearchList.erase(SearchList.begin()+i);
725 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 }
727}
728
729/// InitializeIncludePaths - Process the -I options and set them in the
730/// HeaderSearch object.
731static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000732 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 // Handle -F... options.
734 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000735 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000736
737 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000738 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000739 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000740
741 // Handle -idirafter... options.
742 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000743 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000744
745 // Handle -iquote... options.
746 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000747 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000748
749 // Handle -isystem... options.
750 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000751 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000752
753 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
754 // parallel, processing the values in order of occurance to get the right
755 // prefixes.
756 {
757 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
758 unsigned iprefix_idx = 0;
759 unsigned iwithprefix_idx = 0;
760 unsigned iwithprefixbefore_idx = 0;
761 bool iprefix_done = iprefix_vals.empty();
762 bool iwithprefix_done = iwithprefix_vals.empty();
763 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
764 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
765 if (!iprefix_done &&
766 (iwithprefix_done ||
767 iprefix_vals.getPosition(iprefix_idx) <
768 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
769 (iwithprefixbefore_done ||
770 iprefix_vals.getPosition(iprefix_idx) <
771 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
772 Prefix = iprefix_vals[iprefix_idx];
773 ++iprefix_idx;
774 iprefix_done = iprefix_idx == iprefix_vals.size();
775 } else if (!iwithprefix_done &&
776 (iwithprefixbefore_done ||
777 iwithprefix_vals.getPosition(iwithprefix_idx) <
778 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
779 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000780 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 ++iwithprefix_idx;
782 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
783 } else {
784 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000785 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 ++iwithprefixbefore_idx;
787 iwithprefixbefore_done =
788 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
789 }
790 }
791 }
792
793 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
794 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
795
796 // FIXME: temporary hack: hard-coded paths.
797 // FIXME: get these from the target?
798 if (!nostdinc) {
799 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000800 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000802 false, Headers);
803 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
804 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 }
806
Chris Lattner822da612007-12-17 06:36:45 +0000807 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 // leopard
809 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000810 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000812 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
814 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000815 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000816
817 // tiger
818 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000819 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000821 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
823 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000824 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000825
Chris Lattner822da612007-12-17 06:36:45 +0000826 AddPath("/usr/include", System, false, false, false, Headers);
827 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
828 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 }
830
831 // Now that we have collected all of the include paths, merge them all
832 // together and tell the preprocessor about them.
833
834 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
835 std::vector<DirectoryLookup> SearchList;
836 SearchList = IncludeGroup[Angled];
837 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
838 IncludeGroup[System].end());
839 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
840 IncludeGroup[After].end());
841 RemoveDuplicates(SearchList);
842 RemoveDuplicates(IncludeGroup[Quoted]);
843
844 // Prepend QUOTED list on the search list.
845 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
846 IncludeGroup[Quoted].end());
847
848
849 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
850 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
851 DontSearchCurDir);
852
853 // If verbose, print the list of directories that will be searched.
854 if (Verbose) {
855 fprintf(stderr, "#include \"...\" search starts here:\n");
856 unsigned QuotedIdx = IncludeGroup[Quoted].size();
857 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
858 if (i == QuotedIdx)
859 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000860 const char *Name = SearchList[i].getName();
861 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000862 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000863 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000864 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000865 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000866 else {
867 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000868 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000869 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000870 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000871 }
Chris Lattner80e17152007-12-15 23:11:06 +0000872 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 }
874}
875
876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877//===----------------------------------------------------------------------===//
878// Basic Parser driver
879//===----------------------------------------------------------------------===//
880
Ted Kremenek95041a22007-12-19 22:51:13 +0000881static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000883 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000884
885 // Parsing the specified input file.
886 P.ParseTranslationUnit();
887 delete PA;
888}
889
890//===----------------------------------------------------------------------===//
891// Main driver
892//===----------------------------------------------------------------------===//
893
Ted Kremenekdb094a22007-12-05 18:27:04 +0000894/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
895/// action. These consumers can operate on both ASTs that are freshly
896/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000897static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000898 Diagnostic& Diag, FileManager& FileMgr,
Ted Kremenekdb094a22007-12-05 18:27:04 +0000899 const LangOptions& LangOpts) {
900 switch (ProgAction) {
901 default:
902 return NULL;
903
904 case ASTPrint:
905 return CreateASTPrinter();
906
907 case ASTDump:
908 return CreateASTDumper();
909
910 case ASTView:
911 return CreateASTViewer();
912
913 case ParseCFGDump:
914 case ParseCFGView:
915 return CreateCFGDumper(ProgAction == ParseCFGView);
916
917 case AnalysisLiveVariables:
918 return CreateLiveVarAnalyzer();
919
920 case WarnDeadStores:
921 return CreateDeadStoreChecker(Diag);
922
923 case WarnUninitVals:
924 return CreateUnitValsChecker(Diag);
925
926 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000927 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000928
929 case EmitLLVM:
930 return CreateLLVMEmitter(Diag, LangOpts);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000931
932 case EmitBC:
933 return CreateBCWriter(InFile, OutputFile, Diag, LangOpts);
934
Ted Kremenek3910c7c2007-12-19 17:25:59 +0000935 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000936 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +0000937 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000938
Ted Kremenekdb094a22007-12-05 18:27:04 +0000939 case RewriteTest:
940 return CreateCodeRewriterTest(Diag);
941 }
942}
943
Reid Spencer5f016e22007-07-11 17:01:13 +0000944/// ProcessInputFile - Process a single input file with the specified state.
945///
Ted Kremenek7dcc9682007-12-19 22:32:34 +0000946static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +0000947 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000948
949 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000950 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000951
Reid Spencer5f016e22007-07-11 17:01:13 +0000952 switch (ProgAction) {
953 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000954 Consumer = CreateASTConsumer(InFile,
955 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +0000956 PP.getFileManager(),
Ted Kremenekdb094a22007-12-05 18:27:04 +0000957 PP.getLangOptions());
958
959 if (!Consumer) {
960 fprintf(stderr, "Unexpected program action!\n");
961 return;
962 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000963
Ted Kremenekdb094a22007-12-05 18:27:04 +0000964 break;
965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000967 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000969 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 do {
971 PP.Lex(Tok);
972 PP.DumpToken(Tok, true);
973 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000974 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000975 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 break;
977 }
978 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000979 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000981 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000982 do {
983 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000984 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000985 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 break;
987 }
988
989 case PrintPreprocessedInput: // -E mode.
Ted Kremenek95041a22007-12-19 22:51:13 +0000990 DoPrintPreprocessedInput(PP);
Chris Lattnerbd247762007-07-22 06:05:44 +0000991 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 break;
993
994 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +0000995 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000996 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 break;
998
999 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001000 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001001 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001003
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001004 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001005 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001006 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001007 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001008
1009 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001010 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001011 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001012
1013 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001014 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 }
1016
1017 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001018 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 PP.PrintStats();
1020 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001021 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001022 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001023 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 fprintf(stderr, "\n");
1025 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001026
1027 // For a multi-file compilation, some things are ok with nuking the source
1028 // manager tables, other require stable fileid/macroid's across multiple
1029 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001030 if (ClearSourceMgr)
1031 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001032}
1033
Ted Kremenek20e97482007-12-12 23:41:08 +00001034static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1035 FileManager& FileMgr) {
1036
1037 if (VerifyDiagnostics) {
1038 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1039 exit (1);
1040 }
1041
1042 llvm::sys::Path Filename(InFile);
1043
1044 if (!Filename.isValid()) {
1045 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1046 exit (1);
1047 }
1048
Ted Kremenekee533642007-12-20 19:47:16 +00001049 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001050
1051 if (!TU) {
1052 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1053 InFile.c_str());
1054 exit (1);
1055 }
1056
Ted Kremenek63ea8632007-12-19 19:27:38 +00001057 // Observe that we use the source file name stored in the deserialized
1058 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001059 llvm::OwningPtr<ASTConsumer>
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001060 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts()));
Ted Kremenek20e97482007-12-12 23:41:08 +00001061
1062 if (!Consumer) {
1063 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1064 exit (1);
1065 }
1066
Ted Kremenek95041a22007-12-19 22:51:13 +00001067 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001068
1069 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1070 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001071}
1072
1073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074static llvm::cl::list<std::string>
1075InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1076
Ted Kremenek20e97482007-12-12 23:41:08 +00001077static bool isSerializedFile(const std::string& InFile) {
1078 if (InFile.size() < 4)
1079 return false;
1080
1081 const char* s = InFile.c_str()+InFile.size()-4;
1082
1083 return s[0] == '.' &&
1084 s[1] == 'a' &&
1085 s[2] == 's' &&
1086 s[3] == 't';
1087}
1088
Reid Spencer5f016e22007-07-11 17:01:13 +00001089
1090int main(int argc, char **argv) {
1091 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1092 llvm::sys::PrintStackTraceOnErrorSignal();
1093
1094 // If no input was specified, read from stdin.
1095 if (InputFilenames.empty())
1096 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001097
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 // Create a file manager object to provide access to and cache the filesystem.
1099 FileManager FileMgr;
1100
Ted Kremenek31e703b2007-12-11 23:28:38 +00001101 // Create the diagnostic client for reporting errors or for
1102 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001104 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001106 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 } else {
1108 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001109 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001110
1111 if (InputFilenames.size() != 1) {
1112 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001113 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 return 1;
1115 }
1116 }
1117
1118 // Configure our handling of diagnostics.
1119 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001120 InitializeDiagnostics(Diags);
1121
Chris Lattner4f037832007-12-05 23:24:17 +00001122 // -I- is a deprecated GCC feature, scan for it and reject it.
1123 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1124 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001125 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001126 I_dirs.erase(I_dirs.begin()+i);
1127 --i;
1128 }
1129 }
1130
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001132 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001133
Ted Kremenek20e97482007-12-12 23:41:08 +00001134 if (isSerializedFile(InFile))
1135 ProcessSerializedFile(InFile,Diags,FileMgr);
1136 else {
1137 /// Create a SourceManager object. This tracks and owns all the file
1138 /// buffers allocated to a translation unit.
1139 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001140
Ted Kremenek20e97482007-12-12 23:41:08 +00001141 // Initialize language options, inferring file types from input filenames.
1142 LangOptions LangInfo;
1143 InitializeBaseLanguage();
1144 LangKind LK = GetLanguage(InFile);
1145 InitializeLangOptions(LangInfo, LK);
1146 InitializeLanguageStandard(LangInfo, LK);
1147
1148 // Process the -I options and set them in the HeaderInfo.
1149 HeaderSearch HeaderInfo(FileMgr);
1150 DiagClient->setHeaderSearch(HeaderInfo);
1151 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1152
1153 // Get information about the targets being compiled for. Note that this
1154 // pointer and the TargetInfoImpl objects are never deleted by this toy
1155 // driver.
1156 TargetInfo *Target;
1157
1158 // Create triples, and create the TargetInfo.
1159 std::vector<std::string> triples;
1160 CreateTargetTriples(triples);
1161 Target = TargetInfo::CreateTargetInfo(&triples[0],
1162 &triples[0]+triples.size(),
1163 &Diags);
1164
1165 if (Target == 0) {
1166 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1167 triples[0].c_str());
1168 fprintf(stderr, "Please use -triple or -arch.\n");
1169 exit(1);
1170 }
1171
1172 // Set up the preprocessor with these options.
1173 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1174
1175 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001176 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001177 continue;
1178
Ted Kremenek1036b682007-12-19 23:48:45 +00001179 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001180 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}