clang.cpp 34 KB

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