blob: d284434bedde4b34eff9aedc4e0a2a2e42f8170b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
26#include "ASTStreamers.h"
27#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
29#include "clang/Parse/Parser.h"
30#include "clang/Lex/HeaderSearch.h"
31#include "clang/Basic/FileManager.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/System/Signals.h"
37#include <memory>
38using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Global options.
42//===----------------------------------------------------------------------===//
43
44static llvm::cl::opt<bool>
45Verbose("v", llvm::cl::desc("Enable verbose output"));
46static llvm::cl::opt<bool>
47Stats("stats", llvm::cl::desc("Print performance metrics and statistics"));
48
49enum ProgActions {
50 EmitLLVM, // Emit a .ll file.
51 ParseASTPrint, // Parse ASTs and print them.
Chris Lattner6000dac2007-08-08 22:51:59 +000052 ParseASTDump, // Parse ASTs and dump them.
Reid Spencer5f016e22007-07-11 17:01:13 +000053 ParseASTCheck, // Parse ASTs and check diagnostics.
54 ParseAST, // Parse ASTs.
Ted Kremenekfddd5182007-08-21 21:42:03 +000055 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Reid Spencer5f016e22007-07-11 17:01:13 +000056 ParsePrintCallbacks, // Parse and print each callback.
57 ParseSyntaxOnly, // Parse and perform semantic analysis.
58 ParseNoop, // Parse with noop callbacks.
59 RunPreprocessorOnly, // Just lex, no output.
60 PrintPreprocessedInput, // -E mode.
61 DumpTokens // Token dump mode.
62};
63
64static llvm::cl::opt<ProgActions>
65ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
66 llvm::cl::init(ParseSyntaxOnly),
67 llvm::cl::values(
68 clEnumValN(RunPreprocessorOnly, "Eonly",
69 "Just run preprocessor, no output (for timings)"),
70 clEnumValN(PrintPreprocessedInput, "E",
71 "Run preprocessor, emit preprocessed file"),
72 clEnumValN(DumpTokens, "dumptokens",
73 "Run preprocessor, dump internal rep of tokens"),
74 clEnumValN(ParseNoop, "parse-noop",
75 "Run parser with noop callbacks (for timings)"),
76 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
77 "Run parser and perform semantic analysis"),
78 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
79 "Run parser and print each callback invoked"),
80 clEnumValN(ParseAST, "parse-ast",
81 "Run parser and build ASTs"),
82 clEnumValN(ParseASTPrint, "parse-ast-print",
83 "Run parser, build ASTs, then print ASTs"),
Chris Lattner6000dac2007-08-08 22:51:59 +000084 clEnumValN(ParseASTDump, "parse-ast-dump",
85 "Run parser, build ASTs, then dump them"),
Reid Spencer5f016e22007-07-11 17:01:13 +000086 clEnumValN(ParseASTCheck, "parse-ast-check",
87 "Run parser, build ASTs, then check diagnostics"),
Ted Kremenekfddd5182007-08-21 21:42:03 +000088 clEnumValN(ParseCFGDump, "dump-cfg",
89 "Run parser, build ASTs, then build and print CFGs."),
Reid Spencer5f016e22007-07-11 17:01:13 +000090 clEnumValN(EmitLLVM, "emit-llvm",
91 "Build ASTs then convert to LLVM, emit .ll file"),
92 clEnumValEnd));
93
94//===----------------------------------------------------------------------===//
95// Language Options
96//===----------------------------------------------------------------------===//
97
98enum LangKind {
99 langkind_unspecified,
100 langkind_c,
101 langkind_c_cpp,
102 langkind_cxx,
103 langkind_cxx_cpp,
104 langkind_objc,
105 langkind_objc_cpp,
106 langkind_objcxx,
107 langkind_objcxx_cpp
108};
109
110/* TODO: GCC also accepts:
111 c-header c++-header objective-c-header objective-c++-header
112 assembler assembler-with-cpp
113 ada, f77*, ratfor (!), f95, java, treelang
114 */
115static llvm::cl::opt<LangKind>
116BaseLang("x", llvm::cl::desc("Base language to compile"),
117 llvm::cl::init(langkind_unspecified),
118 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
119 clEnumValN(langkind_cxx, "c++", "C++"),
120 clEnumValN(langkind_objc, "objective-c", "Objective C"),
121 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
122 clEnumValN(langkind_c_cpp, "c-cpp-output",
123 "Preprocessed C"),
124 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
125 "Preprocessed C++"),
126 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
127 "Preprocessed Objective C"),
128 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
129 "Preprocessed Objective C++"),
130 clEnumValEnd));
131
132static llvm::cl::opt<bool>
133LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
134 llvm::cl::Hidden);
135static llvm::cl::opt<bool>
136LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
137 llvm::cl::Hidden);
138
139/// InitializeBaseLanguage - Handle the -x foo options or infer a base language
140/// from the input filename.
141static void InitializeBaseLanguage(LangOptions &Options,
142 const std::string &Filename) {
143 if (BaseLang == langkind_unspecified) {
144 std::string::size_type DotPos = Filename.rfind('.');
145 if (LangObjC) {
146 BaseLang = langkind_objc;
147 } else if (LangObjCXX) {
148 BaseLang = langkind_objcxx;
149 } else if (DotPos == std::string::npos) {
150 BaseLang = langkind_c; // Default to C if no extension.
151 } else {
152 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
153 // C header: .h
154 // C++ header: .hh or .H;
155 // assembler no preprocessing: .s
156 // assembler: .S
157 if (Ext == "c")
158 BaseLang = langkind_c;
159 else if (Ext == "i")
160 BaseLang = langkind_c_cpp;
161 else if (Ext == "ii")
162 BaseLang = langkind_cxx_cpp;
163 else if (Ext == "m")
164 BaseLang = langkind_objc;
165 else if (Ext == "mi")
166 BaseLang = langkind_objc_cpp;
167 else if (Ext == "mm" || Ext == "M")
168 BaseLang = langkind_objcxx;
169 else if (Ext == "mii")
170 BaseLang = langkind_objcxx_cpp;
171 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
172 Ext == "c++" || Ext == "cp" || Ext == "cxx")
173 BaseLang = langkind_cxx;
174 else
175 BaseLang = langkind_c;
176 }
177 }
178
179 // FIXME: implement -fpreprocessed mode.
180 bool NoPreprocess = false;
181
182 switch (BaseLang) {
183 default: assert(0 && "Unknown language kind!");
184 case langkind_c_cpp:
185 NoPreprocess = true;
186 // FALLTHROUGH
187 case langkind_c:
188 break;
189 case langkind_cxx_cpp:
190 NoPreprocess = true;
191 // FALLTHROUGH
192 case langkind_cxx:
193 Options.CPlusPlus = 1;
194 break;
195 case langkind_objc_cpp:
196 NoPreprocess = true;
197 // FALLTHROUGH
198 case langkind_objc:
199 Options.ObjC1 = Options.ObjC2 = 1;
200 break;
201 case langkind_objcxx_cpp:
202 NoPreprocess = true;
203 // FALLTHROUGH
204 case langkind_objcxx:
205 Options.ObjC1 = Options.ObjC2 = 1;
206 Options.CPlusPlus = 1;
207 break;
208 }
209}
210
211/// LangStds - Language standards we support.
212enum LangStds {
213 lang_unspecified,
214 lang_c89, lang_c94, lang_c99,
215 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000216 lang_cxx98, lang_gnucxx98,
217 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000218};
219
220static llvm::cl::opt<LangStds>
221LangStd("std", llvm::cl::desc("Language standard to compile for"),
222 llvm::cl::init(lang_unspecified),
223 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
224 clEnumValN(lang_c89, "c90", "ISO C 1990"),
225 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
226 clEnumValN(lang_c94, "iso9899:199409",
227 "ISO C 1990 with amendment 1"),
228 clEnumValN(lang_c99, "c99", "ISO C 1999"),
229// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
230 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
231// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
232 clEnumValN(lang_gnu89, "gnu89",
233 "ISO C 1990 with GNU extensions (default for C)"),
234 clEnumValN(lang_gnu99, "gnu99",
235 "ISO C 1999 with GNU extensions"),
236 clEnumValN(lang_gnu99, "gnu9x",
237 "ISO C 1999 with GNU extensions"),
238 clEnumValN(lang_cxx98, "c++98",
239 "ISO C++ 1998 with amendments"),
240 clEnumValN(lang_gnucxx98, "gnu++98",
241 "ISO C++ 1998 with amendments and GNU "
242 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000243 clEnumValN(lang_cxx0x, "c++0x",
244 "Upcoming ISO C++ 200x with amendments"),
245 clEnumValN(lang_gnucxx0x, "gnu++0x",
246 "Upcoming ISO C++ 200x with amendments and GNU "
247 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 clEnumValEnd));
249
250static llvm::cl::opt<bool>
251NoOperatorNames("fno-operator-names",
252 llvm::cl::desc("Do not treat C++ operator name keywords as "
253 "synonyms for operators"));
254
255// FIXME: add:
256// -ansi
257// -trigraphs
258// -fdollars-in-identifiers
259static void InitializeLanguageStandard(LangOptions &Options) {
260 if (LangStd == lang_unspecified) {
261 // Based on the base language, pick one.
262 switch (BaseLang) {
263 default: assert(0 && "Unknown base language");
264 case langkind_c:
265 case langkind_c_cpp:
266 case langkind_objc:
267 case langkind_objc_cpp:
268 LangStd = lang_gnu99;
269 break;
270 case langkind_cxx:
271 case langkind_cxx_cpp:
272 case langkind_objcxx:
273 case langkind_objcxx_cpp:
274 LangStd = lang_gnucxx98;
275 break;
276 }
277 }
278
279 switch (LangStd) {
280 default: assert(0 && "Unknown language standard!");
281
282 // Fall through from newer standards to older ones. This isn't really right.
283 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000284 case lang_gnucxx0x:
285 case lang_cxx0x:
286 Options.CPlusPlus0x = 1;
287 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 case lang_gnucxx98:
289 case lang_cxx98:
290 Options.CPlusPlus = 1;
291 Options.CXXOperatorNames = !NoOperatorNames;
292 // FALL THROUGH.
293 case lang_gnu99:
294 case lang_c99:
295 Options.Digraphs = 1;
296 Options.C99 = 1;
297 Options.HexFloats = 1;
298 // FALL THROUGH.
299 case lang_gnu89:
300 Options.BCPLComment = 1; // Only for C99/C++.
301 // FALL THROUGH.
302 case lang_c94:
303 case lang_c89:
304 break;
305 }
306
307 Options.Trigraphs = 1; // -trigraphs or -ansi
308 Options.DollarIdents = 1; // FIXME: Really a target property.
309}
310
311//===----------------------------------------------------------------------===//
312// Our DiagnosticClient implementation
313//===----------------------------------------------------------------------===//
314
315// FIXME: Werror should take a list of things, -Werror=foo,bar
316static llvm::cl::opt<bool>
317WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
318
319static llvm::cl::opt<bool>
320WarnOnExtensions("pedantic", llvm::cl::init(false),
321 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
322
323static llvm::cl::opt<bool>
324ErrorOnExtensions("pedantic-errors",
325 llvm::cl::desc("Issue an error on uses of GCC extensions"));
326
327static llvm::cl::opt<bool>
328WarnUnusedMacros("Wunused_macros",
329 llvm::cl::desc("Warn for unused macros in the main translation unit"));
330
331
332/// InitializeDiagnostics - Initialize the diagnostic object, based on the
333/// current command line option settings.
334static void InitializeDiagnostics(Diagnostic &Diags) {
335 Diags.setWarningsAsErrors(WarningsAsErrors);
336 Diags.setWarnOnExtensions(WarnOnExtensions);
337 Diags.setErrorOnExtensions(ErrorOnExtensions);
338
339 // Silence the "macro is not used" warning unless requested.
340 if (!WarnUnusedMacros)
341 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
342}
343
344//===----------------------------------------------------------------------===//
345// Preprocessor Initialization
346//===----------------------------------------------------------------------===//
347
348// FIXME: Preprocessor builtins to support.
349// -A... - Play with #assertions
350// -undef - Undefine all predefined macros
351
352static llvm::cl::list<std::string>
353D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
354 llvm::cl::desc("Predefine the specified macro"));
355static llvm::cl::list<std::string>
356U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
357 llvm::cl::desc("Undefine the specified macro"));
358
359// Append a #define line to Buf for Macro. Macro should be of the form XXX,
360// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
361// "#define XXX Y z W". To get a #define with no value, use "XXX=".
362static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
363 const char *Command = "#define ") {
364 Buf.insert(Buf.end(), Command, Command+strlen(Command));
365 if (const char *Equal = strchr(Macro, '=')) {
366 // Turn the = into ' '.
367 Buf.insert(Buf.end(), Macro, Equal);
368 Buf.push_back(' ');
369 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
370 } else {
371 // Push "macroname 1".
372 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
373 Buf.push_back(' ');
374 Buf.push_back('1');
375 }
376 Buf.push_back('\n');
377}
378
379static void InitializePredefinedMacros(Preprocessor &PP,
380 std::vector<char> &Buf) {
381 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
382 // and __DATE__ etc.
383#if 0
384 /* __STDC__ has the value 1 under normal circumstances.
385 However, if (a) we are in a system header, (b) the option
386 stdc_0_in_system_headers is true (set by target config), and
387 (c) we are not in strictly conforming mode, then it has the
388 value 0. (b) and (c) are already checked in cpp_init_builtins. */
389 //case BT_STDC:
390 if (cpp_in_system_header (pfile))
391 number = 0;
392 else
393 number = 1;
394 break;
395#endif
396 // These should all be defined in the preprocessor according to the
397 // current language configuration.
398 DefineBuiltinMacro(Buf, "__STDC__=1");
399 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
Chris Lattner94fea5a2007-07-22 22:11:35 +0000400 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
Chris Lattner94fea5a2007-07-22 22:11:35 +0000402 else if (0) // STDC94 ?
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
404
405 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
406 if (PP.getLangOptions().ObjC1)
407 DefineBuiltinMacro(Buf, "__OBJC__=1");
408 if (PP.getLangOptions().ObjC2)
409 DefineBuiltinMacro(Buf, "__OBJC2__=1");
410
411 // Get the target #defines.
412 PP.getTargetInfo().getTargetDefines(Buf);
413
414 // Compiler set macros.
415 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
416 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1030");
417 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
418 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
419 DefineBuiltinMacro(Buf, "__GNUC__=4");
420 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
421 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
422 "build 5250)\"");
423
424 // Build configuration options.
425 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
426 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
427 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
428 DefineBuiltinMacro(Buf, "__PIC__=1");
429
430
431 if (PP.getLangOptions().CPlusPlus) {
432 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
433 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
434 DefineBuiltinMacro(Buf, "__GNUG__=4");
435 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
436 DefineBuiltinMacro(Buf, "__cplusplus=1");
437 DefineBuiltinMacro(Buf, "__private_extern__=extern");
438 }
439
440 // FIXME: Should emit a #line directive here.
441
442 // Add macros from the command line.
443 // FIXME: Should traverse the #define/#undef lists in parallel.
444 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
445 DefineBuiltinMacro(Buf, D_macros[i].c_str());
446 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
447 DefineBuiltinMacro(Buf, U_macros[i].c_str(), "#undef ");
448}
449
450//===----------------------------------------------------------------------===//
451// Preprocessor include path information.
452//===----------------------------------------------------------------------===//
453
454// This tool exports a large number of command line options to control how the
455// preprocessor searches for header files. At root, however, the Preprocessor
456// object takes a very simple interface: a list of directories to search for
457//
458// FIXME: -nostdinc,-nostdinc++
459// FIXME: -isysroot,-imultilib
460//
461// FIXME: -include,-imacros
462
463static llvm::cl::opt<bool>
464nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
465
466// Various command line options. These four add directories to each chain.
467static llvm::cl::list<std::string>
468F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
469 llvm::cl::desc("Add directory to framework include search path"));
470static llvm::cl::list<std::string>
471I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
472 llvm::cl::desc("Add directory to include search path"));
473static llvm::cl::list<std::string>
474idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
475 llvm::cl::desc("Add directory to AFTER include search path"));
476static llvm::cl::list<std::string>
477iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
478 llvm::cl::desc("Add directory to QUOTE include search path"));
479static llvm::cl::list<std::string>
480isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
481 llvm::cl::desc("Add directory to SYSTEM include search path"));
482
483// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
484static llvm::cl::list<std::string>
485iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
486 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
487static llvm::cl::list<std::string>
488iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
489 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
490static llvm::cl::list<std::string>
491iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
492 llvm::cl::Prefix,
493 llvm::cl::desc("Set directory to include search path with prefix"));
494
495// Finally, implement the code that groks the options above.
496enum IncludeDirGroup {
497 Quoted = 0,
498 Angled,
499 System,
500 After
501};
502
503static std::vector<DirectoryLookup> IncludeGroup[4];
504
505/// AddPath - Add the specified path to the specified group list.
506///
507static void AddPath(const std::string &Path, IncludeDirGroup Group,
508 bool isCXXAware, bool isUserSupplied,
509 bool isFramework, FileManager &FM) {
510 const DirectoryEntry *DE = FM.getDirectory(Path);
511 if (DE == 0) {
512 if (Verbose)
513 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
514 Path.c_str());
515 return;
516 }
517
518 DirectoryLookup::DirType Type;
519 if (Group == Quoted || Group == Angled)
520 Type = DirectoryLookup::NormalHeaderDir;
521 else if (isCXXAware)
522 Type = DirectoryLookup::SystemHeaderDir;
523 else
524 Type = DirectoryLookup::ExternCSystemHeaderDir;
525
526 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
527 isFramework));
528}
529
530/// RemoveDuplicates - If there are duplicate directory entries in the specified
531/// search list, remove the later (dead) ones.
532static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
533 std::set<const DirectoryEntry *> SeenDirs;
534 for (unsigned i = 0; i != SearchList.size(); ++i) {
535 // If this isn't the first time we've seen this dir, remove it.
536 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
537 if (Verbose)
538 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
539 SearchList[i].getDir()->getName());
540 SearchList.erase(SearchList.begin()+i);
541 --i;
542 }
543 }
544}
545
546/// InitializeIncludePaths - Process the -I options and set them in the
547/// HeaderSearch object.
548static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
549 Diagnostic &Diags, const LangOptions &Lang) {
550 // Handle -F... options.
551 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
552 AddPath(F_dirs[i], Angled, false, true, true, FM);
553
554 // Handle -I... options.
555 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
556 if (I_dirs[i] == "-") {
557 // -I- is a deprecated GCC feature.
558 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
559 } else {
560 AddPath(I_dirs[i], Angled, false, true, false, FM);
561 }
562 }
563
564 // Handle -idirafter... options.
565 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
566 AddPath(idirafter_dirs[i], After, false, true, false, FM);
567
568 // Handle -iquote... options.
569 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
570 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
571
572 // Handle -isystem... options.
573 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
574 AddPath(isystem_dirs[i], System, false, true, false, FM);
575
576 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
577 // parallel, processing the values in order of occurance to get the right
578 // prefixes.
579 {
580 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
581 unsigned iprefix_idx = 0;
582 unsigned iwithprefix_idx = 0;
583 unsigned iwithprefixbefore_idx = 0;
584 bool iprefix_done = iprefix_vals.empty();
585 bool iwithprefix_done = iwithprefix_vals.empty();
586 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
587 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
588 if (!iprefix_done &&
589 (iwithprefix_done ||
590 iprefix_vals.getPosition(iprefix_idx) <
591 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
592 (iwithprefixbefore_done ||
593 iprefix_vals.getPosition(iprefix_idx) <
594 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
595 Prefix = iprefix_vals[iprefix_idx];
596 ++iprefix_idx;
597 iprefix_done = iprefix_idx == iprefix_vals.size();
598 } else if (!iwithprefix_done &&
599 (iwithprefixbefore_done ||
600 iwithprefix_vals.getPosition(iwithprefix_idx) <
601 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
602 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
603 System, false, false, false, FM);
604 ++iwithprefix_idx;
605 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
606 } else {
607 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
608 Angled, false, false, false, FM);
609 ++iwithprefixbefore_idx;
610 iwithprefixbefore_done =
611 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
612 }
613 }
614 }
615
616 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
617 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
618
619 // FIXME: temporary hack: hard-coded paths.
620 // FIXME: get these from the target?
621 if (!nostdinc) {
622 if (Lang.CPlusPlus) {
623 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
624 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
625 false, FM);
626 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
627 }
628
629 AddPath("/usr/local/include", System, false, false, false, FM);
630 // leopard
631 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
632 false, false, false, FM);
633 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
634 System, false, false, false, FM);
635 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
636 "4.0.1/../../../../powerpc-apple-darwin0/include",
637 System, false, false, false, FM);
638
639 // tiger
640 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
641 false, false, false, FM);
642 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
643 System, false, false, false, FM);
644 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
645 "4.0.1/../../../../powerpc-apple-darwin8/include",
646 System, false, false, false, FM);
647
648 AddPath("/usr/include", System, false, false, false, FM);
649 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
650 AddPath("/Library/Frameworks", System, true, false, true, FM);
651 }
652
653 // Now that we have collected all of the include paths, merge them all
654 // together and tell the preprocessor about them.
655
656 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
657 std::vector<DirectoryLookup> SearchList;
658 SearchList = IncludeGroup[Angled];
659 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
660 IncludeGroup[System].end());
661 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
662 IncludeGroup[After].end());
663 RemoveDuplicates(SearchList);
664 RemoveDuplicates(IncludeGroup[Quoted]);
665
666 // Prepend QUOTED list on the search list.
667 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
668 IncludeGroup[Quoted].end());
669
670
671 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
672 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
673 DontSearchCurDir);
674
675 // If verbose, print the list of directories that will be searched.
676 if (Verbose) {
677 fprintf(stderr, "#include \"...\" search starts here:\n");
678 unsigned QuotedIdx = IncludeGroup[Quoted].size();
679 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
680 if (i == QuotedIdx)
681 fprintf(stderr, "#include <...> search starts here:\n");
682 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
683 }
684 }
685}
686
687
688// Read any files specified by -imacros or -include.
689static void ReadPrologFiles(Preprocessor &PP, std::vector<char> &Buf) {
690 // FIXME: IMPLEMENT
691}
692
693//===----------------------------------------------------------------------===//
694// Basic Parser driver
695//===----------------------------------------------------------------------===//
696
697static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
698 Parser P(PP, *PA);
699 PP.EnterSourceFile(MainFileID, 0, true);
700
701 // Parsing the specified input file.
702 P.ParseTranslationUnit();
703 delete PA;
704}
705
706//===----------------------------------------------------------------------===//
707// Main driver
708//===----------------------------------------------------------------------===//
709
710/// InitializePreprocessor - Initialize the preprocessor getting it and the
711/// environment ready to process a single file. This returns the file ID for the
712/// input file. If a failure happens, it returns 0.
713///
714static unsigned InitializePreprocessor(Preprocessor &PP,
715 const std::string &InFile,
716 SourceManager &SourceMgr,
717 HeaderSearch &HeaderInfo,
718 const LangOptions &LangInfo,
719 std::vector<char> &PrologMacros) {
720 FileManager &FileMgr = HeaderInfo.getFileMgr();
721
722 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
723 InitializePredefinedMacros(PP, PrologMacros);
724
725 // Read any files specified by -imacros or -include.
726 ReadPrologFiles(PP, PrologMacros);
727
728 // Figure out where to get and map in the main file.
729 unsigned MainFileID = 0;
730 if (InFile != "-") {
731 const FileEntry *File = FileMgr.getFile(InFile);
732 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
733 if (MainFileID == 0) {
734 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
735 return 0;
736 }
737 } else {
738 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
739 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
740 if (MainFileID == 0) {
741 fprintf(stderr, "Error reading standard input! Empty?\n");
742 return 0;
743 }
744 }
745
746 // Now that we have emitted the predefined macros, #includes, etc into
747 // PrologMacros, preprocess it to populate the initial preprocessor state.
748
749 // Memory buffer must end with a null byte!
750 PrologMacros.push_back(0);
751
752 llvm::MemoryBuffer *SB =
753 llvm::MemoryBuffer::getMemBuffer(&PrologMacros.front(),&PrologMacros.back(),
754 "<predefines>");
755 assert(SB && "Cannot fail to create predefined source buffer");
756 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
757 assert(FileID && "Could not create FileID for predefines?");
758
759 // Start parsing the predefines.
760 PP.EnterSourceFile(FileID, 0);
761
762 // Lex the file, which will read all the macros.
Chris Lattnerd2177732007-07-20 16:59:19 +0000763 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 PP.Lex(Tok);
765 assert(Tok.getKind() == tok::eof && "Didn't read entire file!");
766
767 // Once we've read this, we're done.
768 return MainFileID;
769}
770
771/// ProcessInputFile - Process a single input file with the specified state.
772///
773static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
774 const std::string &InFile,
775 SourceManager &SourceMgr,
776 TextDiagnostics &OurDiagnosticClient,
777 HeaderSearch &HeaderInfo,
778 const LangOptions &LangInfo) {
Chris Lattnerbd247762007-07-22 06:05:44 +0000779 bool ClearSourceMgr = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 switch (ProgAction) {
781 default:
782 fprintf(stderr, "Unexpected program action!\n");
783 return;
784 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000785 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 // Start parsing the specified input file.
787 PP.EnterSourceFile(MainFileID, 0, true);
788 do {
789 PP.Lex(Tok);
790 PP.DumpToken(Tok, true);
791 fprintf(stderr, "\n");
792 } while (Tok.getKind() != tok::eof);
Chris Lattnerbd247762007-07-22 06:05:44 +0000793 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 break;
795 }
796 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000797 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 // Start parsing the specified input file.
799 PP.EnterSourceFile(MainFileID, 0, true);
800 do {
801 PP.Lex(Tok);
802 } while (Tok.getKind() != tok::eof);
Chris Lattnerbd247762007-07-22 06:05:44 +0000803 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 break;
805 }
806
807 case PrintPreprocessedInput: // -E mode.
808 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000809 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 break;
811
812 case ParseNoop: // -parse-noop
813 ParseFile(PP, new MinimalAction(), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000814 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 break;
816
817 case ParsePrintCallbacks:
818 ParseFile(PP, CreatePrintParserActionsAction(), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000819 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 break;
821 case ParseSyntaxOnly: // -fsyntax-only
822 case ParseAST:
823 BuildASTs(PP, MainFileID, Stats);
824 break;
825 case ParseASTPrint:
826 PrintASTs(PP, MainFileID, Stats);
827 break;
Chris Lattner6000dac2007-08-08 22:51:59 +0000828 case ParseASTDump:
829 DumpASTs(PP, MainFileID, Stats);
830 break;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000831 case ParseCFGDump:
832 DumpCFGs(PP, MainFileID, Stats);
833 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 case EmitLLVM:
835 EmitLLVMFromASTs(PP, MainFileID, Stats);
836 break;
837 case ParseASTCheck:
838 exit(CheckDiagnostics(PP, MainFileID));
839 break;
840 }
841
842 if (Stats) {
843 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
844 PP.PrintStats();
845 PP.getIdentifierTable().PrintStats();
846 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000847 if (ClearSourceMgr)
848 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000849 fprintf(stderr, "\n");
850 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000851
852 // For a multi-file compilation, some things are ok with nuking the source
853 // manager tables, other require stable fileid/macroid's across multiple
854 // files.
855 if (ClearSourceMgr) {
856 SourceMgr.clearIDTables();
857 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000858}
859
860static llvm::cl::list<std::string>
861InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
862
863
864int main(int argc, char **argv) {
865 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
866 llvm::sys::PrintStackTraceOnErrorSignal();
867
868 // If no input was specified, read from stdin.
869 if (InputFilenames.empty())
870 InputFilenames.push_back("-");
871
872 /// Create a SourceManager object. This tracks and owns all the file buffers
873 /// allocated to the program.
874 SourceManager SourceMgr;
875
876 // Create a file manager object to provide access to and cache the filesystem.
877 FileManager FileMgr;
878
879 // Initialize language options, inferring file types from input filenames.
880 // FIXME: This infers info from the first file, we should clump by language
881 // to handle 'x.c y.c a.cpp b.cpp'.
882 LangOptions LangInfo;
883 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
884 InitializeLanguageStandard(LangInfo);
885
886 std::auto_ptr<TextDiagnostics> DiagClient;
887 if (ProgAction != ParseASTCheck) {
888 // Print diagnostics to stderr by default.
889 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
890 } else {
891 // When checking diagnostics, just buffer them up.
892 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
893
894 if (InputFilenames.size() != 1) {
895 fprintf(stderr,
896 "parse-ast-check only works on single input files for now.\n");
897 return 1;
898 }
899 }
900
901 // Configure our handling of diagnostics.
902 Diagnostic Diags(*DiagClient);
903 InitializeDiagnostics(Diags);
904
905 // Get information about the targets being compiled for. Note that this
906 // pointer and the TargetInfoImpl objects are never deleted by this toy
907 // driver.
908 TargetInfo *Target = CreateTargetInfo(Diags);
909 if (Target == 0) {
910 fprintf(stderr,
911 "Sorry, don't know what target this is, please use -arch.\n");
912 exit(1);
913 }
914
915 // Process the -I options and set them in the HeaderInfo.
916 HeaderSearch HeaderInfo(FileMgr);
917 DiagClient->setHeaderSearch(HeaderInfo);
918 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
919
920 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
921 // Set up the preprocessor with these options.
922 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
923 DiagClient->setPreprocessor(PP);
924 const std::string &InFile = InputFilenames[i];
925 std::vector<char> PrologMacros;
926 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
927 HeaderInfo, LangInfo,
928 PrologMacros);
929
930 if (!MainFileID) continue;
931
932 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
933 *DiagClient, HeaderInfo, LangInfo);
934 HeaderInfo.ClearFileInfo();
935 }
936
937 unsigned NumDiagnostics = Diags.getNumDiagnostics();
938
939 if (NumDiagnostics)
940 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
941 (NumDiagnostics == 1 ? "" : "s"));
942
943 if (Stats) {
944 // Printed from high-to-low level.
945 SourceMgr.PrintStats();
946 FileMgr.PrintStats();
947 fprintf(stderr, "\n");
948 }
949
Chris Lattner96f1a642007-07-21 05:40:53 +0000950 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000951}