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