blob: 5897da32a36b520a8e7fe639214b87a5285db48e [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"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#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 {
Chris Lattnerb429ae42007-10-11 00:43:27 +000052 RewriteTest, // Rewriter testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000053 EmitLLVM, // Emit a .ll file.
Chris Lattner4045a8a2007-10-11 00:18:28 +000054 ASTPrint, // Parse ASTs and print them.
55 ASTDump, // Parse ASTs and dump them.
56 ASTView, // Parse ASTs and view them in Graphviz.
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.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000063 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000064 ParsePrintCallbacks, // Parse and print each callback.
65 ParseSyntaxOnly, // Parse and perform semantic analysis.
66 ParseNoop, // Parse with noop callbacks.
67 RunPreprocessorOnly, // Just lex, no output.
68 PrintPreprocessedInput, // -E mode.
69 DumpTokens // Token dump mode.
70};
71
72static llvm::cl::opt<ProgActions>
73ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
74 llvm::cl::init(ParseSyntaxOnly),
75 llvm::cl::values(
76 clEnumValN(RunPreprocessorOnly, "Eonly",
77 "Just run preprocessor, no output (for timings)"),
78 clEnumValN(PrintPreprocessedInput, "E",
79 "Run preprocessor, emit preprocessed file"),
80 clEnumValN(DumpTokens, "dumptokens",
81 "Run preprocessor, dump internal rep of tokens"),
82 clEnumValN(ParseNoop, "parse-noop",
83 "Run parser with noop callbacks (for timings)"),
84 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
85 "Run parser and perform semantic analysis"),
86 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
87 "Run parser and print each callback invoked"),
Chris Lattner4045a8a2007-10-11 00:18:28 +000088 clEnumValN(ASTPrint, "ast-print",
89 "Build ASTs and then pretty-print them"),
90 clEnumValN(ASTDump, "ast-dump",
91 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +000092 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +000093 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +000094 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000095 "Run parser, then build and print CFGs."),
96 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +000097 "Run parser, then build and view CFGs with Graphviz."),
98 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +000099 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000100 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000101 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000102 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000103 "Flag warnings of uses of unitialized variables."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000104 clEnumValN(TestSerialization, "test-pickling",
105 "Run prototype serializtion code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000106 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000107 "Build ASTs then convert to LLVM, emit .ll file"),
Chris Lattnerb429ae42007-10-11 00:43:27 +0000108 clEnumValN(RewriteTest, "rewrite-test",
109 "Playground for the code rewriter"),
Chris Lattner4b009652007-07-25 00:24:17 +0000110 clEnumValEnd));
111
Ted Kremenek10389cf2007-09-26 19:42:19 +0000112static llvm::cl::opt<bool>
113VerifyDiagnostics("verify",
114 llvm::cl::desc("Verify emitted diagnostics and warnings."));
115
Chris Lattner4b009652007-07-25 00:24:17 +0000116//===----------------------------------------------------------------------===//
117// Language Options
118//===----------------------------------------------------------------------===//
119
120enum LangKind {
121 langkind_unspecified,
122 langkind_c,
123 langkind_c_cpp,
124 langkind_cxx,
125 langkind_cxx_cpp,
126 langkind_objc,
127 langkind_objc_cpp,
128 langkind_objcxx,
129 langkind_objcxx_cpp
130};
131
132/* TODO: GCC also accepts:
133 c-header c++-header objective-c-header objective-c++-header
134 assembler assembler-with-cpp
135 ada, f77*, ratfor (!), f95, java, treelang
136 */
137static llvm::cl::opt<LangKind>
138BaseLang("x", llvm::cl::desc("Base language to compile"),
139 llvm::cl::init(langkind_unspecified),
140 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
141 clEnumValN(langkind_cxx, "c++", "C++"),
142 clEnumValN(langkind_objc, "objective-c", "Objective C"),
143 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
144 clEnumValN(langkind_c_cpp, "c-cpp-output",
145 "Preprocessed C"),
146 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
147 "Preprocessed C++"),
148 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
149 "Preprocessed Objective C"),
150 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
151 "Preprocessed Objective C++"),
152 clEnumValEnd));
153
154static llvm::cl::opt<bool>
155LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
156 llvm::cl::Hidden);
157static llvm::cl::opt<bool>
158LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
159 llvm::cl::Hidden);
160
161/// InitializeBaseLanguage - Handle the -x foo options or infer a base language
162/// from the input filename.
163static void InitializeBaseLanguage(LangOptions &Options,
164 const std::string &Filename) {
165 if (BaseLang == langkind_unspecified) {
166 std::string::size_type DotPos = Filename.rfind('.');
167 if (LangObjC) {
168 BaseLang = langkind_objc;
169 } else if (LangObjCXX) {
170 BaseLang = langkind_objcxx;
171 } else if (DotPos == std::string::npos) {
172 BaseLang = langkind_c; // Default to C if no extension.
173 } else {
174 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
175 // C header: .h
176 // C++ header: .hh or .H;
177 // assembler no preprocessing: .s
178 // assembler: .S
179 if (Ext == "c")
180 BaseLang = langkind_c;
181 else if (Ext == "i")
182 BaseLang = langkind_c_cpp;
183 else if (Ext == "ii")
184 BaseLang = langkind_cxx_cpp;
185 else if (Ext == "m")
186 BaseLang = langkind_objc;
187 else if (Ext == "mi")
188 BaseLang = langkind_objc_cpp;
189 else if (Ext == "mm" || Ext == "M")
190 BaseLang = langkind_objcxx;
191 else if (Ext == "mii")
192 BaseLang = langkind_objcxx_cpp;
193 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
194 Ext == "c++" || Ext == "cp" || Ext == "cxx")
195 BaseLang = langkind_cxx;
196 else
197 BaseLang = langkind_c;
198 }
199 }
200
201 // FIXME: implement -fpreprocessed mode.
202 bool NoPreprocess = false;
203
204 switch (BaseLang) {
205 default: assert(0 && "Unknown language kind!");
206 case langkind_c_cpp:
207 NoPreprocess = true;
208 // FALLTHROUGH
209 case langkind_c:
210 break;
211 case langkind_cxx_cpp:
212 NoPreprocess = true;
213 // FALLTHROUGH
214 case langkind_cxx:
215 Options.CPlusPlus = 1;
216 break;
217 case langkind_objc_cpp:
218 NoPreprocess = true;
219 // FALLTHROUGH
220 case langkind_objc:
221 Options.ObjC1 = Options.ObjC2 = 1;
222 break;
223 case langkind_objcxx_cpp:
224 NoPreprocess = true;
225 // FALLTHROUGH
226 case langkind_objcxx:
227 Options.ObjC1 = Options.ObjC2 = 1;
228 Options.CPlusPlus = 1;
229 break;
230 }
231}
232
233/// LangStds - Language standards we support.
234enum LangStds {
235 lang_unspecified,
236 lang_c89, lang_c94, lang_c99,
237 lang_gnu89, lang_gnu99,
238 lang_cxx98, lang_gnucxx98,
239 lang_cxx0x, lang_gnucxx0x
240};
241
242static llvm::cl::opt<LangStds>
243LangStd("std", llvm::cl::desc("Language standard to compile for"),
244 llvm::cl::init(lang_unspecified),
245 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
246 clEnumValN(lang_c89, "c90", "ISO C 1990"),
247 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
248 clEnumValN(lang_c94, "iso9899:199409",
249 "ISO C 1990 with amendment 1"),
250 clEnumValN(lang_c99, "c99", "ISO C 1999"),
251// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
252 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
253// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
254 clEnumValN(lang_gnu89, "gnu89",
255 "ISO C 1990 with GNU extensions (default for C)"),
256 clEnumValN(lang_gnu99, "gnu99",
257 "ISO C 1999 with GNU extensions"),
258 clEnumValN(lang_gnu99, "gnu9x",
259 "ISO C 1999 with GNU extensions"),
260 clEnumValN(lang_cxx98, "c++98",
261 "ISO C++ 1998 with amendments"),
262 clEnumValN(lang_gnucxx98, "gnu++98",
263 "ISO C++ 1998 with amendments and GNU "
264 "extensions (default for C++)"),
265 clEnumValN(lang_cxx0x, "c++0x",
266 "Upcoming ISO C++ 200x with amendments"),
267 clEnumValN(lang_gnucxx0x, "gnu++0x",
268 "Upcoming ISO C++ 200x with amendments and GNU "
269 "extensions (default for C++)"),
270 clEnumValEnd));
271
272static llvm::cl::opt<bool>
273NoOperatorNames("fno-operator-names",
274 llvm::cl::desc("Do not treat C++ operator name keywords as "
275 "synonyms for operators"));
276
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000277static llvm::cl::opt<bool>
278PascalStrings("fpascal-strings",
279 llvm::cl::desc("Recognize and construct Pascal-style "
280 "string literals"));
Chris Lattner4b009652007-07-25 00:24:17 +0000281// FIXME: add:
282// -ansi
283// -trigraphs
284// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000285// -fpascal-strings
Chris Lattner4b009652007-07-25 00:24:17 +0000286static void InitializeLanguageStandard(LangOptions &Options) {
287 if (LangStd == lang_unspecified) {
288 // Based on the base language, pick one.
289 switch (BaseLang) {
290 default: assert(0 && "Unknown base language");
291 case langkind_c:
292 case langkind_c_cpp:
293 case langkind_objc:
294 case langkind_objc_cpp:
295 LangStd = lang_gnu99;
296 break;
297 case langkind_cxx:
298 case langkind_cxx_cpp:
299 case langkind_objcxx:
300 case langkind_objcxx_cpp:
301 LangStd = lang_gnucxx98;
302 break;
303 }
304 }
305
306 switch (LangStd) {
307 default: assert(0 && "Unknown language standard!");
308
309 // Fall through from newer standards to older ones. This isn't really right.
310 // FIXME: Enable specifically the right features based on the language stds.
311 case lang_gnucxx0x:
312 case lang_cxx0x:
313 Options.CPlusPlus0x = 1;
314 // FALL THROUGH
315 case lang_gnucxx98:
316 case lang_cxx98:
317 Options.CPlusPlus = 1;
318 Options.CXXOperatorNames = !NoOperatorNames;
319 // FALL THROUGH.
320 case lang_gnu99:
321 case lang_c99:
322 Options.Digraphs = 1;
323 Options.C99 = 1;
324 Options.HexFloats = 1;
325 // FALL THROUGH.
326 case lang_gnu89:
327 Options.BCPLComment = 1; // Only for C99/C++.
328 // FALL THROUGH.
329 case lang_c94:
330 case lang_c89:
331 break;
332 }
333
334 Options.Trigraphs = 1; // -trigraphs or -ansi
335 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000336 Options.PascalStrings = PascalStrings;
Chris Lattner4b009652007-07-25 00:24:17 +0000337}
338
339//===----------------------------------------------------------------------===//
340// Our DiagnosticClient implementation
341//===----------------------------------------------------------------------===//
342
343// FIXME: Werror should take a list of things, -Werror=foo,bar
344static llvm::cl::opt<bool>
345WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
346
347static llvm::cl::opt<bool>
348WarnOnExtensions("pedantic", llvm::cl::init(false),
349 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
350
351static llvm::cl::opt<bool>
352ErrorOnExtensions("pedantic-errors",
353 llvm::cl::desc("Issue an error on uses of GCC extensions"));
354
355static llvm::cl::opt<bool>
356WarnUnusedMacros("Wunused_macros",
357 llvm::cl::desc("Warn for unused macros in the main translation unit"));
358
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000359static llvm::cl::opt<bool>
360WarnFloatEqual("Wfloat-equal",
361 llvm::cl::desc("Warn about equality comparisons of floating point values."));
362
Chris Lattner4b009652007-07-25 00:24:17 +0000363/// InitializeDiagnostics - Initialize the diagnostic object, based on the
364/// current command line option settings.
365static void InitializeDiagnostics(Diagnostic &Diags) {
366 Diags.setWarningsAsErrors(WarningsAsErrors);
367 Diags.setWarnOnExtensions(WarnOnExtensions);
368 Diags.setErrorOnExtensions(ErrorOnExtensions);
369
370 // Silence the "macro is not used" warning unless requested.
371 if (!WarnUnusedMacros)
372 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000373
374 // Silence "floating point comparison" warnings unless requested.
375 if (!WarnFloatEqual)
376 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000377}
378
379//===----------------------------------------------------------------------===//
380// Preprocessor Initialization
381//===----------------------------------------------------------------------===//
382
383// FIXME: Preprocessor builtins to support.
384// -A... - Play with #assertions
385// -undef - Undefine all predefined macros
386
387static llvm::cl::list<std::string>
388D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
389 llvm::cl::desc("Predefine the specified macro"));
390static llvm::cl::list<std::string>
391U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
392 llvm::cl::desc("Undefine the specified macro"));
393
394// Append a #define line to Buf for Macro. Macro should be of the form XXX,
395// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
396// "#define XXX Y z W". To get a #define with no value, use "XXX=".
397static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
398 const char *Command = "#define ") {
399 Buf.insert(Buf.end(), Command, Command+strlen(Command));
400 if (const char *Equal = strchr(Macro, '=')) {
401 // Turn the = into ' '.
402 Buf.insert(Buf.end(), Macro, Equal);
403 Buf.push_back(' ');
404 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
405 } else {
406 // Push "macroname 1".
407 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
408 Buf.push_back(' ');
409 Buf.push_back('1');
410 }
411 Buf.push_back('\n');
412}
413
Chris Lattner4b009652007-07-25 00:24:17 +0000414
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000415/// InitializePreprocessor - Initialize the preprocessor getting it and the
416/// environment ready to process a single file. This returns the file ID for the
417/// input file. If a failure happens, it returns 0.
418///
419static unsigned InitializePreprocessor(Preprocessor &PP,
420 const std::string &InFile,
421 SourceManager &SourceMgr,
422 HeaderSearch &HeaderInfo,
423 const LangOptions &LangInfo,
424 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000425
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000426 FileManager &FileMgr = HeaderInfo.getFileMgr();
Chris Lattner4b009652007-07-25 00:24:17 +0000427
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000428 // Figure out where to get and map in the main file.
429 unsigned MainFileID = 0;
430 if (InFile != "-") {
431 const FileEntry *File = FileMgr.getFile(InFile);
432 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
433 if (MainFileID == 0) {
434 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
435 return 0;
436 }
437 } else {
438 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
439 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
440 if (MainFileID == 0) {
441 fprintf(stderr, "Error reading standard input! Empty?\n");
442 return 0;
443 }
Chris Lattner4b009652007-07-25 00:24:17 +0000444 }
445
Chris Lattner4b009652007-07-25 00:24:17 +0000446 // Add macros from the command line.
447 // FIXME: Should traverse the #define/#undef lists in parallel.
448 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000449 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000450 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000451 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
452
453 // FIXME: Read any files specified by -imacros or -include.
454
455 // Null terminate PredefinedBuffer and add it.
456 PredefineBuffer.push_back(0);
457 PP.setPredefines(&PredefineBuffer[0]);
458
459 // Once we've read this, we're done.
460 return MainFileID;
Chris Lattner4b009652007-07-25 00:24:17 +0000461}
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000462
463
Chris Lattner4b009652007-07-25 00:24:17 +0000464
465//===----------------------------------------------------------------------===//
466// Preprocessor include path information.
467//===----------------------------------------------------------------------===//
468
469// This tool exports a large number of command line options to control how the
470// preprocessor searches for header files. At root, however, the Preprocessor
471// object takes a very simple interface: a list of directories to search for
472//
473// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000474// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000475//
476// FIXME: -include,-imacros
477
478static llvm::cl::opt<bool>
479nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
480
481// Various command line options. These four add directories to each chain.
482static llvm::cl::list<std::string>
483F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
484 llvm::cl::desc("Add directory to framework include search path"));
485static llvm::cl::list<std::string>
486I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
487 llvm::cl::desc("Add directory to include search path"));
488static llvm::cl::list<std::string>
489idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
490 llvm::cl::desc("Add directory to AFTER include search path"));
491static llvm::cl::list<std::string>
492iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
493 llvm::cl::desc("Add directory to QUOTE include search path"));
494static llvm::cl::list<std::string>
495isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
496 llvm::cl::desc("Add directory to SYSTEM include search path"));
497
498// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
499static llvm::cl::list<std::string>
500iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
501 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
502static llvm::cl::list<std::string>
503iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
504 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
505static llvm::cl::list<std::string>
506iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
507 llvm::cl::Prefix,
508 llvm::cl::desc("Set directory to include search path with prefix"));
509
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000510static llvm::cl::opt<std::string>
511isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
512 llvm::cl::desc("Set the system root directory (usually /)"));
513
Chris Lattner4b009652007-07-25 00:24:17 +0000514// Finally, implement the code that groks the options above.
515enum IncludeDirGroup {
516 Quoted = 0,
517 Angled,
518 System,
519 After
520};
521
522static std::vector<DirectoryLookup> IncludeGroup[4];
523
524/// AddPath - Add the specified path to the specified group list.
525///
526static void AddPath(const std::string &Path, IncludeDirGroup Group,
527 bool isCXXAware, bool isUserSupplied,
528 bool isFramework, FileManager &FM) {
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000529 const DirectoryEntry *DE;
530 if (Group == System)
531 DE = FM.getDirectory(isysroot + "/" + Path);
532 else
533 DE = FM.getDirectory(Path);
534
Chris Lattner4b009652007-07-25 00:24:17 +0000535 if (DE == 0) {
536 if (Verbose)
537 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
538 Path.c_str());
539 return;
540 }
541
542 DirectoryLookup::DirType Type;
543 if (Group == Quoted || Group == Angled)
544 Type = DirectoryLookup::NormalHeaderDir;
545 else if (isCXXAware)
546 Type = DirectoryLookup::SystemHeaderDir;
547 else
548 Type = DirectoryLookup::ExternCSystemHeaderDir;
549
550 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
551 isFramework));
552}
553
554/// RemoveDuplicates - If there are duplicate directory entries in the specified
555/// search list, remove the later (dead) ones.
556static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
557 std::set<const DirectoryEntry *> SeenDirs;
558 for (unsigned i = 0; i != SearchList.size(); ++i) {
559 // If this isn't the first time we've seen this dir, remove it.
560 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
561 if (Verbose)
562 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
563 SearchList[i].getDir()->getName());
564 SearchList.erase(SearchList.begin()+i);
565 --i;
566 }
567 }
568}
569
570/// InitializeIncludePaths - Process the -I options and set them in the
571/// HeaderSearch object.
572static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
573 Diagnostic &Diags, const LangOptions &Lang) {
574 // Handle -F... options.
575 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
576 AddPath(F_dirs[i], Angled, false, true, true, FM);
577
578 // Handle -I... options.
579 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
580 if (I_dirs[i] == "-") {
581 // -I- is a deprecated GCC feature.
582 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
583 } else {
584 AddPath(I_dirs[i], Angled, false, true, false, FM);
585 }
586 }
587
588 // Handle -idirafter... options.
589 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
590 AddPath(idirafter_dirs[i], After, false, true, false, FM);
591
592 // Handle -iquote... options.
593 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
594 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
595
596 // Handle -isystem... options.
597 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
598 AddPath(isystem_dirs[i], System, false, true, false, FM);
599
600 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
601 // parallel, processing the values in order of occurance to get the right
602 // prefixes.
603 {
604 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
605 unsigned iprefix_idx = 0;
606 unsigned iwithprefix_idx = 0;
607 unsigned iwithprefixbefore_idx = 0;
608 bool iprefix_done = iprefix_vals.empty();
609 bool iwithprefix_done = iwithprefix_vals.empty();
610 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
611 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
612 if (!iprefix_done &&
613 (iwithprefix_done ||
614 iprefix_vals.getPosition(iprefix_idx) <
615 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
616 (iwithprefixbefore_done ||
617 iprefix_vals.getPosition(iprefix_idx) <
618 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
619 Prefix = iprefix_vals[iprefix_idx];
620 ++iprefix_idx;
621 iprefix_done = iprefix_idx == iprefix_vals.size();
622 } else if (!iwithprefix_done &&
623 (iwithprefixbefore_done ||
624 iwithprefix_vals.getPosition(iwithprefix_idx) <
625 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
626 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
627 System, false, false, false, FM);
628 ++iwithprefix_idx;
629 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
630 } else {
631 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
632 Angled, false, false, false, FM);
633 ++iwithprefixbefore_idx;
634 iwithprefixbefore_done =
635 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
636 }
637 }
638 }
639
640 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
641 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
642
643 // FIXME: temporary hack: hard-coded paths.
644 // FIXME: get these from the target?
645 if (!nostdinc) {
646 if (Lang.CPlusPlus) {
647 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
648 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
649 false, FM);
650 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
651 }
652
653 AddPath("/usr/local/include", System, false, false, false, FM);
654 // leopard
655 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
656 false, false, false, FM);
657 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
658 System, false, false, false, FM);
659 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
660 "4.0.1/../../../../powerpc-apple-darwin0/include",
661 System, false, false, false, FM);
662
663 // tiger
664 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
665 false, false, false, FM);
666 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
667 System, false, false, false, FM);
668 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
669 "4.0.1/../../../../powerpc-apple-darwin8/include",
670 System, false, false, false, FM);
671
672 AddPath("/usr/include", System, false, false, false, FM);
673 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
674 AddPath("/Library/Frameworks", System, true, false, true, FM);
675 }
676
677 // Now that we have collected all of the include paths, merge them all
678 // together and tell the preprocessor about them.
679
680 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
681 std::vector<DirectoryLookup> SearchList;
682 SearchList = IncludeGroup[Angled];
683 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
684 IncludeGroup[System].end());
685 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
686 IncludeGroup[After].end());
687 RemoveDuplicates(SearchList);
688 RemoveDuplicates(IncludeGroup[Quoted]);
689
690 // Prepend QUOTED list on the search list.
691 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
692 IncludeGroup[Quoted].end());
693
694
695 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
696 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
697 DontSearchCurDir);
698
699 // If verbose, print the list of directories that will be searched.
700 if (Verbose) {
701 fprintf(stderr, "#include \"...\" search starts here:\n");
702 unsigned QuotedIdx = IncludeGroup[Quoted].size();
703 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
704 if (i == QuotedIdx)
705 fprintf(stderr, "#include <...> search starts here:\n");
706 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
707 }
708 }
709}
710
711
Chris Lattner4b009652007-07-25 00:24:17 +0000712//===----------------------------------------------------------------------===//
713// Basic Parser driver
714//===----------------------------------------------------------------------===//
715
716static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
717 Parser P(PP, *PA);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000718 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000719
720 // Parsing the specified input file.
721 P.ParseTranslationUnit();
722 delete PA;
723}
724
725//===----------------------------------------------------------------------===//
726// Main driver
727//===----------------------------------------------------------------------===//
728
Chris Lattner4b009652007-07-25 00:24:17 +0000729/// ProcessInputFile - Process a single input file with the specified state.
730///
731static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
732 const std::string &InFile,
733 SourceManager &SourceMgr,
734 TextDiagnostics &OurDiagnosticClient,
735 HeaderSearch &HeaderInfo,
736 const LangOptions &LangInfo) {
Ted Kremenek6856c632007-09-26 18:39:29 +0000737
738 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +0000739 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +0000740
Chris Lattner4b009652007-07-25 00:24:17 +0000741 switch (ProgAction) {
742 default:
743 fprintf(stderr, "Unexpected program action!\n");
744 return;
745 case DumpTokens: { // Token dump mode.
746 Token Tok;
747 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000748 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000749 do {
750 PP.Lex(Tok);
751 PP.DumpToken(Tok, true);
752 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +0000753 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000754 ClearSourceMgr = true;
755 break;
756 }
757 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
758 Token Tok;
759 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000760 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000761 do {
762 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +0000763 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000764 ClearSourceMgr = true;
765 break;
766 }
767
768 case PrintPreprocessedInput: // -E mode.
769 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
770 ClearSourceMgr = true;
771 break;
772
773 case ParseNoop: // -parse-noop
Steve Naroffebeb4282007-10-31 20:55:39 +0000774 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000775 ClearSourceMgr = true;
776 break;
777
778 case ParsePrintCallbacks:
Steve Naroffebeb4282007-10-31 20:55:39 +0000779 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
780 MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000781 ClearSourceMgr = true;
782 break;
Ted Kremenek0841c702007-09-25 18:37:20 +0000783
Ted Kremenek6856c632007-09-26 18:39:29 +0000784 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +0000785 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000786 break;
Ted Kremenek6856c632007-09-26 18:39:29 +0000787
Chris Lattner4045a8a2007-10-11 00:18:28 +0000788 case ASTPrint:
Ted Kremenek6856c632007-09-26 18:39:29 +0000789 Consumer = CreateASTPrinter();
790 break;
791
Chris Lattner4045a8a2007-10-11 00:18:28 +0000792 case ASTDump:
Ted Kremenek6856c632007-09-26 18:39:29 +0000793 Consumer = CreateASTDumper();
794 break;
795
Chris Lattner4045a8a2007-10-11 00:18:28 +0000796 case ASTView:
Ted Kremenek6856c632007-09-26 18:39:29 +0000797 Consumer = CreateASTViewer();
798 break;
799
800 case ParseCFGDump:
801 case ParseCFGView:
802 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
803 break;
804
805 case AnalysisLiveVariables:
806 Consumer = CreateLiveVarAnalyzer();
807 break;
808
809 case WarnDeadStores:
810 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
811 break;
812
813 case WarnUninitVals:
814 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
815 break;
816
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000817 case TestSerialization:
818 Consumer = CreateSerializationTest();
819 break;
820
Ted Kremenek6856c632007-09-26 18:39:29 +0000821 case EmitLLVM:
822 Consumer = CreateLLVMEmitter(PP.getDiagnostics());
Chris Lattner4b009652007-07-25 00:24:17 +0000823 break;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000824
825 case RewriteTest:
826 Consumer = CreateCodeRewriterTest();
827 break;
Chris Lattner129758d2007-09-16 19:46:59 +0000828 }
Ted Kremenek6856c632007-09-26 18:39:29 +0000829
830 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +0000831 if (VerifyDiagnostics)
Chris Lattner8593cbf2007-11-03 06:24:16 +0000832 exit(CheckASTConsumer(PP, MainFileID, Consumer));
833
834 // This deletes Consumer.
835 ParseAST(PP, MainFileID, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +0000836 }
837
838 if (Stats) {
839 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
840 PP.PrintStats();
841 PP.getIdentifierTable().PrintStats();
842 HeaderInfo.PrintStats();
843 if (ClearSourceMgr)
844 SourceMgr.PrintStats();
845 fprintf(stderr, "\n");
846 }
847
848 // For a multi-file compilation, some things are ok with nuking the source
849 // manager tables, other require stable fileid/macroid's across multiple
850 // files.
851 if (ClearSourceMgr) {
852 SourceMgr.clearIDTables();
853 }
854}
855
856static llvm::cl::list<std::string>
857InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
858
859
860int main(int argc, char **argv) {
861 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
862 llvm::sys::PrintStackTraceOnErrorSignal();
863
864 // If no input was specified, read from stdin.
865 if (InputFilenames.empty())
866 InputFilenames.push_back("-");
867
868 /// Create a SourceManager object. This tracks and owns all the file buffers
869 /// allocated to the program.
870 SourceManager SourceMgr;
871
872 // Create a file manager object to provide access to and cache the filesystem.
873 FileManager FileMgr;
874
875 // Initialize language options, inferring file types from input filenames.
876 // FIXME: This infers info from the first file, we should clump by language
877 // to handle 'x.c y.c a.cpp b.cpp'.
878 LangOptions LangInfo;
879 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
880 InitializeLanguageStandard(LangInfo);
881
882 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +0000883 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +0000884 // Print diagnostics to stderr by default.
885 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
886 } else {
887 // When checking diagnostics, just buffer them up.
888 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
889
890 if (InputFilenames.size() != 1) {
891 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +0000892 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000893 return 1;
894 }
895 }
896
897 // Configure our handling of diagnostics.
898 Diagnostic Diags(*DiagClient);
899 InitializeDiagnostics(Diags);
900
901 // Get information about the targets being compiled for. Note that this
902 // pointer and the TargetInfoImpl objects are never deleted by this toy
903 // driver.
904 TargetInfo *Target = CreateTargetInfo(Diags);
905 if (Target == 0) {
906 fprintf(stderr,
907 "Sorry, don't know what target this is, please use -arch.\n");
908 exit(1);
909 }
910
911 // Process the -I options and set them in the HeaderInfo.
912 HeaderSearch HeaderInfo(FileMgr);
913 DiagClient->setHeaderSearch(HeaderInfo);
914 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
915
916 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
917 // Set up the preprocessor with these options.
918 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
Chris Lattner4b009652007-07-25 00:24:17 +0000919 const std::string &InFile = InputFilenames[i];
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000920 std::vector<char> PredefineBuffer;
Chris Lattner4b009652007-07-25 00:24:17 +0000921 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
922 HeaderInfo, LangInfo,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000923 PredefineBuffer);
Chris Lattner4b009652007-07-25 00:24:17 +0000924
925 if (!MainFileID) continue;
926
927 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
928 *DiagClient, HeaderInfo, LangInfo);
929 HeaderInfo.ClearFileInfo();
930 }
931
932 unsigned NumDiagnostics = Diags.getNumDiagnostics();
933
934 if (NumDiagnostics)
935 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
936 (NumDiagnostics == 1 ? "" : "s"));
937
938 if (Stats) {
939 // Printed from high-to-low level.
940 SourceMgr.PrintStats();
941 FileMgr.PrintStats();
942 fprintf(stderr, "\n");
943 }
944
945 return Diags.getNumErrors() != 0;
946}