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