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