1 //===--- clang.cpp - C-Language Front-end ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
18 // TODO: Options to support:
23 //===----------------------------------------------------------------------===//
26 #include "ASTConsumers.h"
27 #include "TextDiagnosticBuffer.h"
28 #include "TextDiagnosticPrinter.h"
29 #include "clang/AST/TranslationUnit.h"
30 #include "clang/Sema/ParseAST.h"
31 #include "clang/AST/ASTConsumer.h"
32 #include "clang/Parse/Parser.h"
33 #include "clang/Lex/HeaderSearch.h"
34 #include "clang/Basic/FileManager.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "llvm/Module.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/Bitcode/ReaderWriter.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/System/Signals.h"
43 #include "llvm/Config/config.h"
44 #include "llvm/ADT/OwningPtr.h"
47 using namespace clang;
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
53 static llvm::cl::opt<bool>
54 Verbose("v", llvm::cl::desc("Enable verbose output"));
55 static llvm::cl::opt<bool>
57 llvm::cl::desc("Print performance metrics and statistics"));
60 RewriteTest, // Rewriter testing stuff.
61 EmitLLVM, // Emit a .ll file.
62 EmitBC, // Emit a .bc file.
63 SerializeAST, // Emit a .ast file.
64 ASTPrint, // Parse ASTs and print them.
65 ASTDump, // Parse ASTs and dump them.
66 ASTView, // Parse ASTs and view them in Graphviz.
67 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
68 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
69 AnalysisLiveVariables, // Print results of live-variable analysis.
70 AnalysisGRConstants, // Perform graph-reachability constant prop.
71 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
72 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
73 WarnUninitVals, // Run UnitializedVariables checker.
74 TestSerialization, // Run experimental serialization code.
75 ParsePrintCallbacks, // Parse and print each callback.
76 ParseSyntaxOnly, // Parse and perform semantic analysis.
77 ParseNoop, // Parse with noop callbacks.
78 RunPreprocessorOnly, // Just lex, no output.
79 PrintPreprocessedInput, // -E mode.
80 DumpTokens // Token dump mode.
83 static llvm::cl::opt<ProgActions>
84 ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
85 llvm::cl::init(ParseSyntaxOnly),
87 clEnumValN(RunPreprocessorOnly, "Eonly",
88 "Just run preprocessor, no output (for timings)"),
89 clEnumValN(PrintPreprocessedInput, "E",
90 "Run preprocessor, emit preprocessed file"),
91 clEnumValN(DumpTokens, "dumptokens",
92 "Run preprocessor, dump internal rep of tokens"),
93 clEnumValN(ParseNoop, "parse-noop",
94 "Run parser with noop callbacks (for timings)"),
95 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
96 "Run parser and perform semantic analysis"),
97 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
98 "Run parser and print each callback invoked"),
99 clEnumValN(ASTPrint, "ast-print",
100 "Build ASTs and then pretty-print them"),
101 clEnumValN(ASTDump, "ast-dump",
102 "Build ASTs and then debug dump them"),
103 clEnumValN(ASTView, "ast-view",
104 "Build ASTs and view them with GraphViz."),
105 clEnumValN(ParseCFGDump, "dump-cfg",
106 "Run parser, then build and print CFGs."),
107 clEnumValN(ParseCFGView, "view-cfg",
108 "Run parser, then build and view CFGs with Graphviz."),
109 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
110 "Print results of live variable analysis."),
111 clEnumValN(WarnDeadStores, "warn-dead-stores",
112 "Flag warnings of stores to dead variables."),
113 clEnumValN(WarnUninitVals, "warn-uninit-values",
114 "Flag warnings of uses of unitialized variables."),
115 clEnumValN(AnalysisGRConstants, "grconstants",
116 "Perform path-sensitive constant propagation."),
117 clEnumValN(TestSerialization, "test-pickling",
118 "Run prototype serializtion code."),
119 clEnumValN(EmitLLVM, "emit-llvm",
120 "Build ASTs then convert to LLVM, emit .ll file"),
121 clEnumValN(EmitBC, "emit-llvm-bc",
122 "Build ASTs then convert to LLVM, emit .bc file"),
123 clEnumValN(SerializeAST, "serialize",
124 "Build ASTs and emit .ast file"),
125 clEnumValN(RewriteTest, "rewrite-test",
126 "Playground for the code rewriter"),
130 static llvm::cl::opt<std::string>
132 llvm::cl::value_desc("path"),
133 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
135 static llvm::cl::opt<bool>
136 VerifyDiagnostics("verify",
137 llvm::cl::desc("Verify emitted diagnostics and warnings."));
139 //===----------------------------------------------------------------------===//
141 //===----------------------------------------------------------------------===//
144 langkind_unspecified,
155 /* TODO: GCC also accepts:
156 c-header c++-header objective-c-header objective-c++-header
157 assembler assembler-with-cpp
158 ada, f77*, ratfor (!), f95, java, treelang
160 static llvm::cl::opt<LangKind>
161 BaseLang("x", llvm::cl::desc("Base language to compile"),
162 llvm::cl::init(langkind_unspecified),
163 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
164 clEnumValN(langkind_cxx, "c++", "C++"),
165 clEnumValN(langkind_objc, "objective-c", "Objective C"),
166 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
167 clEnumValN(langkind_c_cpp, "c-cpp-output",
169 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
171 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
172 "Preprocessed Objective C"),
173 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
174 "Preprocessed Objective C++"),
177 static llvm::cl::opt<bool>
178 LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
180 static llvm::cl::opt<bool>
181 LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
184 /// InitializeBaseLanguage - Handle the -x foo options.
185 static void InitializeBaseLanguage() {
187 BaseLang = langkind_objc;
189 BaseLang = langkind_objcxx;
192 static LangKind GetLanguage(const std::string &Filename) {
193 if (BaseLang != langkind_unspecified)
196 std::string::size_type DotPos = Filename.rfind('.');
198 if (DotPos == std::string::npos) {
199 BaseLang = langkind_c; // Default to C if no extension.
203 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
205 // C++ header: .hh or .H;
206 // assembler no preprocessing: .s
211 return langkind_c_cpp;
212 else if (Ext == "ii")
213 return langkind_cxx_cpp;
215 return langkind_objc;
216 else if (Ext == "mi")
217 return langkind_objc_cpp;
218 else if (Ext == "mm" || Ext == "M")
219 return langkind_objcxx;
220 else if (Ext == "mii")
221 return langkind_objcxx_cpp;
222 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
223 Ext == "c++" || Ext == "cp" || Ext == "cxx")
230 static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
231 // FIXME: implement -fpreprocessed mode.
232 bool NoPreprocess = false;
235 default: assert(0 && "Unknown language kind!");
241 case langkind_cxx_cpp:
245 Options.CPlusPlus = 1;
247 case langkind_objc_cpp:
251 Options.ObjC1 = Options.ObjC2 = 1;
253 case langkind_objcxx_cpp:
256 case langkind_objcxx:
257 Options.ObjC1 = Options.ObjC2 = 1;
258 Options.CPlusPlus = 1;
263 /// LangStds - Language standards we support.
266 lang_c89, lang_c94, lang_c99,
267 lang_gnu89, lang_gnu99,
268 lang_cxx98, lang_gnucxx98,
269 lang_cxx0x, lang_gnucxx0x
272 static llvm::cl::opt<LangStds>
273 LangStd("std", llvm::cl::desc("Language standard to compile for"),
274 llvm::cl::init(lang_unspecified),
275 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
276 clEnumValN(lang_c89, "c90", "ISO C 1990"),
277 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
278 clEnumValN(lang_c94, "iso9899:199409",
279 "ISO C 1990 with amendment 1"),
280 clEnumValN(lang_c99, "c99", "ISO C 1999"),
281 // clEnumValN(lang_c99, "c9x", "ISO C 1999"),
282 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
283 // clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
284 clEnumValN(lang_gnu89, "gnu89",
285 "ISO C 1990 with GNU extensions (default for C)"),
286 clEnumValN(lang_gnu99, "gnu99",
287 "ISO C 1999 with GNU extensions"),
288 clEnumValN(lang_gnu99, "gnu9x",
289 "ISO C 1999 with GNU extensions"),
290 clEnumValN(lang_cxx98, "c++98",
291 "ISO C++ 1998 with amendments"),
292 clEnumValN(lang_gnucxx98, "gnu++98",
293 "ISO C++ 1998 with amendments and GNU "
294 "extensions (default for C++)"),
295 clEnumValN(lang_cxx0x, "c++0x",
296 "Upcoming ISO C++ 200x with amendments"),
297 clEnumValN(lang_gnucxx0x, "gnu++0x",
298 "Upcoming ISO C++ 200x with amendments and GNU "
299 "extensions (default for C++)"),
302 static llvm::cl::opt<bool>
303 NoOperatorNames("fno-operator-names",
304 llvm::cl::desc("Do not treat C++ operator name keywords as "
305 "synonyms for operators"));
307 static llvm::cl::opt<bool>
308 PascalStrings("fpascal-strings",
309 llvm::cl::desc("Recognize and construct Pascal-style "
312 static llvm::cl::opt<bool>
313 WritableStrings("fwritable-strings",
314 llvm::cl::desc("Store string literals as writable data."));
316 static llvm::cl::opt<bool>
317 LaxVectorConversions("flax-vector-conversions",
318 llvm::cl::desc("Allow implicit conversions between vectors"
319 " with a different number of elements or "
320 "different element types."));
324 // -fdollars-in-identifiers
326 static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
327 if (LangStd == lang_unspecified) {
328 // Based on the base language, pick one.
330 default: assert(0 && "Unknown base language");
334 case langkind_objc_cpp:
335 LangStd = lang_gnu99;
338 case langkind_cxx_cpp:
339 case langkind_objcxx:
340 case langkind_objcxx_cpp:
341 LangStd = lang_gnucxx98;
347 default: assert(0 && "Unknown language standard!");
349 // Fall through from newer standards to older ones. This isn't really right.
350 // FIXME: Enable specifically the right features based on the language stds.
353 Options.CPlusPlus0x = 1;
357 Options.CPlusPlus = 1;
358 Options.CXXOperatorNames = !NoOperatorNames;
363 Options.Digraphs = 1;
365 Options.HexFloats = 1;
368 Options.BCPLComment = 1; // Only for C99/C++.
375 Options.Trigraphs = 1; // -trigraphs or -ansi
376 Options.DollarIdents = 1; // FIXME: Really a target property.
377 Options.PascalStrings = PascalStrings;
378 Options.WritableStrings = WritableStrings;
379 Options.LaxVectorConversions = LaxVectorConversions;
382 //===----------------------------------------------------------------------===//
383 // Our DiagnosticClient implementation
384 //===----------------------------------------------------------------------===//
386 // FIXME: Werror should take a list of things, -Werror=foo,bar
387 static llvm::cl::opt<bool>
388 WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
390 static llvm::cl::opt<bool>
391 WarnOnExtensions("pedantic", llvm::cl::init(false),
392 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
394 static llvm::cl::opt<bool>
395 ErrorOnExtensions("pedantic-errors",
396 llvm::cl::desc("Issue an error on uses of GCC extensions"));
398 static llvm::cl::opt<bool>
399 WarnUnusedMacros("Wunused_macros",
400 llvm::cl::desc("Warn for unused macros in the main translation unit"));
402 static llvm::cl::opt<bool>
403 WarnFloatEqual("Wfloat-equal",
404 llvm::cl::desc("Warn about equality comparisons of floating point values."));
406 static llvm::cl::opt<bool>
407 WarnNoFormatNonLiteral("Wno-format-nonliteral",
408 llvm::cl::desc("Do not warn about non-literal format strings."));
410 static llvm::cl::opt<bool>
411 WarnUndefMacros("Wundef",
412 llvm::cl::desc("Warn on use of undefined macros in #if's"));
415 /// InitializeDiagnostics - Initialize the diagnostic object, based on the
416 /// current command line option settings.
417 static void InitializeDiagnostics(Diagnostic &Diags) {
418 Diags.setWarningsAsErrors(WarningsAsErrors);
419 Diags.setWarnOnExtensions(WarnOnExtensions);
420 Diags.setErrorOnExtensions(ErrorOnExtensions);
422 // Silence the "macro is not used" warning unless requested.
423 if (!WarnUnusedMacros)
424 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
426 // Silence "floating point comparison" warnings unless requested.
428 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
430 // Silence "format string is not a string literal" warnings if requested
431 if (WarnNoFormatNonLiteral)
432 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
434 if (!WarnUndefMacros)
435 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
438 //===----------------------------------------------------------------------===//
439 // Target Triple Processing.
440 //===----------------------------------------------------------------------===//
442 static llvm::cl::opt<std::string>
443 TargetTriple("triple",
444 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
446 static llvm::cl::list<std::string>
448 llvm::cl::desc("Specify target architecture (e.g. i686)."));
451 class TripleProcessor {
452 llvm::StringMap<char> TriplesProcessed;
453 std::vector<std::string>& triples;
455 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
457 void addTriple(const std::string& t) {
458 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
459 TriplesProcessed.end()) {
460 triples.push_back(t);
461 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
467 static void CreateTargetTriples(std::vector<std::string>& triples) {
468 // Initialize base triple. If a -triple option has been specified, use
469 // that triple. Otherwise, default to the host triple.
470 std::string Triple = TargetTriple;
471 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
473 // Decompose the base triple into "arch" and suffix.
474 std::string::size_type firstDash = Triple.find("-");
476 if (firstDash == std::string::npos) {
478 "Malformed target triple: \"%s\" ('-' could not be found).\n",
483 std::string suffix(Triple, firstDash+1);
485 if (suffix.empty()) {
486 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
491 // Create triple cacher.
492 TripleProcessor tp(triples);
494 // Add the primary triple to our set of triples if we are using the
495 // host-triple with no archs or using a specified target triple.
496 if (!TargetTriple.getValue().empty() || Archs.empty())
497 tp.addTriple(Triple);
499 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
500 tp.addTriple(Archs[i] + "-" + suffix);
503 //===----------------------------------------------------------------------===//
504 // Preprocessor Initialization
505 //===----------------------------------------------------------------------===//
507 // FIXME: Preprocessor builtins to support.
508 // -A... - Play with #assertions
509 // -undef - Undefine all predefined macros
511 static llvm::cl::list<std::string>
512 D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
513 llvm::cl::desc("Predefine the specified macro"));
514 static llvm::cl::list<std::string>
515 U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
516 llvm::cl::desc("Undefine the specified macro"));
518 static llvm::cl::list<std::string>
519 ImplicitIncludes("include", llvm::cl::value_desc("file"),
520 llvm::cl::desc("Include file before parsing"));
523 // Append a #define line to Buf for Macro. Macro should be of the form XXX,
524 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
525 // "#define XXX Y z W". To get a #define with no value, use "XXX=".
526 static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
527 const char *Command = "#define ") {
528 Buf.insert(Buf.end(), Command, Command+strlen(Command));
529 if (const char *Equal = strchr(Macro, '=')) {
530 // Turn the = into ' '.
531 Buf.insert(Buf.end(), Macro, Equal);
533 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
535 // Push "macroname 1".
536 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
543 /// AddImplicitInclude - Add an implicit #include of the specified file to the
544 /// predefines buffer.
545 static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
546 const char *Inc = "#include \"";
547 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
548 Buf.insert(Buf.end(), File.begin(), File.end());
554 /// InitializePreprocessor - Initialize the preprocessor getting it and the
555 /// environment ready to process a single file. This returns the file ID for the
556 /// input file. If a failure happens, it returns 0.
558 static unsigned InitializePreprocessor(Preprocessor &PP,
559 const std::string &InFile,
560 std::vector<char> &PredefineBuffer) {
562 FileManager &FileMgr = PP.getFileManager();
564 // Figure out where to get and map in the main file.
565 SourceManager &SourceMgr = PP.getSourceManager();
567 const FileEntry *File = FileMgr.getFile(InFile);
568 if (File) SourceMgr.createMainFileID(File, SourceLocation());
569 if (SourceMgr.getMainFileID() == 0) {
570 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
574 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
575 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
576 if (SourceMgr.getMainFileID() == 0) {
577 fprintf(stderr, "Error reading standard input! Empty?\n");
582 // Add macros from the command line.
583 // FIXME: Should traverse the #define/#undef lists in parallel.
584 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
585 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
586 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
587 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
589 // FIXME: Read any files specified by -imacros.
591 // Add implicit #includes from -include.
592 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
593 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
595 // Null terminate PredefinedBuffer and add it.
596 PredefineBuffer.push_back(0);
597 PP.setPredefines(&PredefineBuffer[0]);
599 // Once we've read this, we're done.
600 return SourceMgr.getMainFileID();
603 //===----------------------------------------------------------------------===//
604 // Preprocessor include path information.
605 //===----------------------------------------------------------------------===//
607 // This tool exports a large number of command line options to control how the
608 // preprocessor searches for header files. At root, however, the Preprocessor
609 // object takes a very simple interface: a list of directories to search for
611 // FIXME: -nostdinc,-nostdinc++
616 static llvm::cl::opt<bool>
617 nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
619 // Various command line options. These four add directories to each chain.
620 static llvm::cl::list<std::string>
621 F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
622 llvm::cl::desc("Add directory to framework include search path"));
623 static llvm::cl::list<std::string>
624 I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
625 llvm::cl::desc("Add directory to include search path"));
626 static llvm::cl::list<std::string>
627 idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
628 llvm::cl::desc("Add directory to AFTER include search path"));
629 static llvm::cl::list<std::string>
630 iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
631 llvm::cl::desc("Add directory to QUOTE include search path"));
632 static llvm::cl::list<std::string>
633 isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
634 llvm::cl::desc("Add directory to SYSTEM include search path"));
636 // These handle -iprefix/-iwithprefix/-iwithprefixbefore.
637 static llvm::cl::list<std::string>
638 iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
639 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
640 static llvm::cl::list<std::string>
641 iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
642 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
643 static llvm::cl::list<std::string>
644 iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
646 llvm::cl::desc("Set directory to include search path with prefix"));
648 static llvm::cl::opt<std::string>
649 isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
650 llvm::cl::desc("Set the system root directory (usually /)"));
652 // Finally, implement the code that groks the options above.
653 enum IncludeDirGroup {
660 static std::vector<DirectoryLookup> IncludeGroup[4];
662 /// AddPath - Add the specified path to the specified group list.
664 static void AddPath(const std::string &Path, IncludeDirGroup Group,
665 bool isCXXAware, bool isUserSupplied,
666 bool isFramework, HeaderSearch &HS) {
667 assert(!Path.empty() && "can't handle empty path here");
668 FileManager &FM = HS.getFileMgr();
670 // Compute the actual path, taking into consideration -isysroot.
671 llvm::SmallString<256> MappedPath;
674 if (Group == System) {
675 // FIXME: Portability. This should be a sys::Path interface, this doesn't
676 // handle things like C:\ right, nor win32 \\network\device\blah.
677 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
678 MappedPath.append(isysroot.begin(), isysroot.end());
679 if (Path[0] != '/') // If in the system group, add a /.
680 MappedPath.push_back('/');
683 MappedPath.append(Path.begin(), Path.end());
685 // Compute the DirectoryLookup type.
686 DirectoryLookup::DirType Type;
687 if (Group == Quoted || Group == Angled)
688 Type = DirectoryLookup::NormalHeaderDir;
690 Type = DirectoryLookup::SystemHeaderDir;
692 Type = DirectoryLookup::ExternCSystemHeaderDir;
695 // If the directory exists, add it.
696 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
698 MappedPath.size())) {
699 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
704 // Check to see if this is an apple-style headermap (which are not allowed to
707 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
708 &MappedPath[0]+MappedPath.size())) {
709 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
710 // It is a headermap, add it to the search path.
711 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
718 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
721 /// RemoveDuplicates - If there are duplicate directory entries in the specified
722 /// search list, remove the later (dead) ones.
723 static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
724 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
725 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
726 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
727 for (unsigned i = 0; i != SearchList.size(); ++i) {
728 if (SearchList[i].isNormalDir()) {
729 // If this isn't the first time we've seen this dir, remove it.
730 if (SeenDirs.insert(SearchList[i].getDir()))
734 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
735 SearchList[i].getDir()->getName());
736 } else if (SearchList[i].isFramework()) {
737 // If this isn't the first time we've seen this framework dir, remove it.
738 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
742 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
743 SearchList[i].getFrameworkDir()->getName());
746 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
747 // If this isn't the first time we've seen this headermap, remove it.
748 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
752 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
753 SearchList[i].getDir()->getName());
756 // This is reached if the current entry is a duplicate.
757 SearchList.erase(SearchList.begin()+i);
762 /// InitializeIncludePaths - Process the -I options and set them in the
763 /// HeaderSearch object.
764 static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
765 const LangOptions &Lang) {
766 // Handle -F... options.
767 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
768 AddPath(F_dirs[i], Angled, false, true, true, Headers);
770 // Handle -I... options.
771 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
772 AddPath(I_dirs[i], Angled, false, true, false, Headers);
774 // Handle -idirafter... options.
775 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
776 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
778 // Handle -iquote... options.
779 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
780 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
782 // Handle -isystem... options.
783 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
784 AddPath(isystem_dirs[i], System, false, true, false, Headers);
786 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
787 // parallel, processing the values in order of occurance to get the right
790 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
791 unsigned iprefix_idx = 0;
792 unsigned iwithprefix_idx = 0;
793 unsigned iwithprefixbefore_idx = 0;
794 bool iprefix_done = iprefix_vals.empty();
795 bool iwithprefix_done = iwithprefix_vals.empty();
796 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
797 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
800 iprefix_vals.getPosition(iprefix_idx) <
801 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
802 (iwithprefixbefore_done ||
803 iprefix_vals.getPosition(iprefix_idx) <
804 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
805 Prefix = iprefix_vals[iprefix_idx];
807 iprefix_done = iprefix_idx == iprefix_vals.size();
808 } else if (!iwithprefix_done &&
809 (iwithprefixbefore_done ||
810 iwithprefix_vals.getPosition(iwithprefix_idx) <
811 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
812 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
813 System, false, false, false, Headers);
815 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
817 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
818 Angled, false, false, false, Headers);
819 ++iwithprefixbefore_idx;
820 iwithprefixbefore_done =
821 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
826 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
827 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
829 // FIXME: temporary hack: hard-coded paths.
830 // FIXME: get these from the target?
832 if (Lang.CPlusPlus) {
833 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
834 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
836 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
840 AddPath("/usr/local/include", System, false, false, false, Headers);
842 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
843 false, false, false, Headers);
844 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
845 System, false, false, false, Headers);
846 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
847 "4.0.1/../../../../powerpc-apple-darwin0/include",
848 System, false, false, false, Headers);
851 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
852 false, false, false, Headers);
853 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
854 System, false, false, false, Headers);
855 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
856 "4.0.1/../../../../powerpc-apple-darwin8/include",
857 System, false, false, false, Headers);
859 // Ubuntu 7.10 - Gutsy Gibbon
860 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
861 false, false, false, Headers);
863 AddPath("/usr/include", System, false, false, false, Headers);
864 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
865 AddPath("/Library/Frameworks", System, true, false, true, Headers);
868 // Now that we have collected all of the include paths, merge them all
869 // together and tell the preprocessor about them.
871 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
872 std::vector<DirectoryLookup> SearchList;
873 SearchList = IncludeGroup[Angled];
874 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
875 IncludeGroup[System].end());
876 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
877 IncludeGroup[After].end());
878 RemoveDuplicates(SearchList);
879 RemoveDuplicates(IncludeGroup[Quoted]);
881 // Prepend QUOTED list on the search list.
882 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
883 IncludeGroup[Quoted].end());
886 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
887 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
890 // If verbose, print the list of directories that will be searched.
892 fprintf(stderr, "#include \"...\" search starts here:\n");
893 unsigned QuotedIdx = IncludeGroup[Quoted].size();
894 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
896 fprintf(stderr, "#include <...> search starts here:\n");
897 const char *Name = SearchList[i].getName();
899 if (SearchList[i].isNormalDir())
901 else if (SearchList[i].isFramework())
902 Suffix = " (framework directory)";
904 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
905 Suffix = " (headermap)";
907 fprintf(stderr, " %s%s\n", Name, Suffix);
909 fprintf(stderr, "End of search list.\n");
914 //===----------------------------------------------------------------------===//
915 // Basic Parser driver
916 //===----------------------------------------------------------------------===//
918 static void ParseFile(Preprocessor &PP, MinimalAction *PA){
920 PP.EnterMainSourceFile();
922 // Parsing the specified input file.
923 P.ParseTranslationUnit();
927 //===----------------------------------------------------------------------===//
929 //===----------------------------------------------------------------------===//
931 /// CreateASTConsumer - Create the ASTConsumer for the corresponding program
932 /// action. These consumers can operate on both ASTs that are freshly
933 /// parsed from source files as well as those deserialized from Bitcode.
934 static ASTConsumer* CreateASTConsumer(const std::string& InFile,
935 Diagnostic& Diag, FileManager& FileMgr,
936 const LangOptions& LangOpts,
937 llvm::Module *&DestModule) {
938 switch (ProgAction) {
943 return CreateASTPrinter();
946 return CreateASTDumper();
949 return CreateASTViewer();
953 return CreateCFGDumper(ProgAction == ParseCFGView);
955 case AnalysisLiveVariables:
956 return CreateLiveVarAnalyzer();
959 return CreateDeadStoreChecker(Diag);
962 return CreateUnitValsChecker(Diag);
964 case AnalysisGRConstants:
965 return CreateGRConstants();
967 case TestSerialization:
968 return CreateSerializationTest(Diag, FileMgr, LangOpts);
972 DestModule = new llvm::Module(InFile);
973 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
976 // FIXME: Allow user to tailor where the file is written.
977 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
980 return CreateCodeRewriterTest(InFile, Diag);
984 /// ProcessInputFile - Process a single input file with the specified state.
986 static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
987 TextDiagnostics &OurDiagnosticClient) {
989 ASTConsumer* Consumer = NULL;
990 bool ClearSourceMgr = false;
991 llvm::Module *CodeGenModule = 0;
993 switch (ProgAction) {
995 Consumer = CreateASTConsumer(InFile,
1002 fprintf(stderr, "Unexpected program action!\n");
1008 case DumpTokens: { // Token dump mode.
1010 // Start parsing the specified input file.
1011 PP.EnterMainSourceFile();
1014 PP.DumpToken(Tok, true);
1015 fprintf(stderr, "\n");
1016 } while (Tok.isNot(tok::eof));
1017 ClearSourceMgr = true;
1020 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1022 // Start parsing the specified input file.
1023 PP.EnterMainSourceFile();
1026 } while (Tok.isNot(tok::eof));
1027 ClearSourceMgr = true;
1031 case PrintPreprocessedInput: // -E mode.
1032 DoPrintPreprocessedInput(PP, OutputFile);
1033 ClearSourceMgr = true;
1036 case ParseNoop: // -parse-noop
1037 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
1038 ClearSourceMgr = true;
1041 case ParsePrintCallbacks:
1042 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
1043 ClearSourceMgr = true;
1046 case ParseSyntaxOnly: // -fsyntax-only
1047 Consumer = new ASTConsumer();
1052 if (VerifyDiagnostics)
1053 exit(CheckASTConsumer(PP, Consumer));
1055 // This deletes Consumer.
1056 ParseAST(PP, Consumer, Stats);
1059 // If running the code generator, finish up now.
1060 if (CodeGenModule) {
1062 if (OutputFile == "-") {
1063 Out = llvm::cout.stream();
1064 } else if (!OutputFile.empty()) {
1065 Out = new std::ofstream(OutputFile.c_str(),
1066 std::ios_base::binary|std::ios_base::out);
1067 } else if (InFile == "-") {
1068 Out = llvm::cout.stream();
1070 llvm::sys::Path Path(InFile);
1072 if (ProgAction == EmitLLVM)
1073 Path.appendSuffix("ll");
1074 else if (ProgAction == EmitBC)
1075 Path.appendSuffix("bc");
1077 assert(0 && "Unknown action");
1078 Out = new std::ofstream(Path.toString().c_str(),
1079 std::ios_base::binary|std::ios_base::out);
1082 if (ProgAction == EmitLLVM) {
1083 CodeGenModule->print(*Out);
1085 assert(ProgAction == EmitBC);
1086 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1089 if (Out != llvm::cout.stream())
1091 delete CodeGenModule;
1095 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
1097 PP.getIdentifierTable().PrintStats();
1098 PP.getHeaderSearchInfo().PrintStats();
1100 PP.getSourceManager().PrintStats();
1101 fprintf(stderr, "\n");
1104 // For a multi-file compilation, some things are ok with nuking the source
1105 // manager tables, other require stable fileid/macroid's across multiple
1108 PP.getSourceManager().clearIDTables();
1111 static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1112 FileManager& FileMgr) {
1114 if (VerifyDiagnostics) {
1115 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1119 llvm::sys::Path Filename(InFile);
1121 if (!Filename.isValid()) {
1122 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1126 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
1129 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1134 // Observe that we use the source file name stored in the deserialized
1135 // translation unit, rather than InFile.
1136 llvm::Module *DestModule;
1137 llvm::OwningPtr<ASTConsumer>
1138 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1142 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1146 Consumer->Initialize(*TU->getContext());
1148 // FIXME: We need to inform Consumer about completed TagDecls as well.
1149 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1150 Consumer->HandleTopLevelDecl(*I);
1154 static llvm::cl::list<std::string>
1155 InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1157 static bool isSerializedFile(const std::string& InFile) {
1158 if (InFile.size() < 4)
1161 const char* s = InFile.c_str()+InFile.size()-4;
1163 return s[0] == '.' &&
1170 int main(int argc, char **argv) {
1171 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1172 llvm::sys::PrintStackTraceOnErrorSignal();
1174 // If no input was specified, read from stdin.
1175 if (InputFilenames.empty())
1176 InputFilenames.push_back("-");
1178 // Create a file manager object to provide access to and cache the filesystem.
1179 FileManager FileMgr;
1181 // Create the diagnostic client for reporting errors or for
1182 // implementing -verify.
1183 std::auto_ptr<TextDiagnostics> DiagClient;
1184 if (!VerifyDiagnostics) {
1185 // Print diagnostics to stderr by default.
1186 DiagClient.reset(new TextDiagnosticPrinter());
1188 // When checking diagnostics, just buffer them up.
1189 DiagClient.reset(new TextDiagnosticBuffer());
1191 if (InputFilenames.size() != 1) {
1193 "-verify only works on single input files for now.\n");
1198 // Configure our handling of diagnostics.
1199 Diagnostic Diags(*DiagClient);
1200 InitializeDiagnostics(Diags);
1202 // -I- is a deprecated GCC feature, scan for it and reject it.
1203 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1204 if (I_dirs[i] == "-") {
1205 Diags.Report(diag::err_pp_I_dash_not_supported);
1206 I_dirs.erase(I_dirs.begin()+i);
1211 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1212 const std::string &InFile = InputFilenames[i];
1214 if (isSerializedFile(InFile))
1215 ProcessSerializedFile(InFile,Diags,FileMgr);
1217 /// Create a SourceManager object. This tracks and owns all the file
1218 /// buffers allocated to a translation unit.
1219 SourceManager SourceMgr;
1221 // Initialize language options, inferring file types from input filenames.
1222 LangOptions LangInfo;
1223 InitializeBaseLanguage();
1224 LangKind LK = GetLanguage(InFile);
1225 InitializeLangOptions(LangInfo, LK);
1226 InitializeLanguageStandard(LangInfo, LK);
1228 // Process the -I options and set them in the HeaderInfo.
1229 HeaderSearch HeaderInfo(FileMgr);
1230 DiagClient->setHeaderSearch(HeaderInfo);
1231 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1233 // Get information about the targets being compiled for. Note that this
1234 // pointer and the TargetInfoImpl objects are never deleted by this toy
1238 // Create triples, and create the TargetInfo.
1239 std::vector<std::string> triples;
1240 CreateTargetTriples(triples);
1241 Target = TargetInfo::CreateTargetInfo(&triples[0],
1242 &triples[0]+triples.size(),
1246 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1247 triples[0].c_str());
1248 fprintf(stderr, "Please use -triple or -arch.\n");
1252 // Set up the preprocessor with these options.
1253 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1255 std::vector<char> PredefineBuffer;
1256 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
1259 ProcessInputFile(PP, InFile, *DiagClient);
1260 HeaderInfo.ClearFileInfo();
1263 SourceMgr.PrintStats();
1267 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1270 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1271 (NumDiagnostics == 1 ? "" : "s"));
1274 FileMgr.PrintStats();
1275 fprintf(stderr, "\n");
1278 return Diags.getNumErrors() != 0;