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