blob: ac3a04ab2e92c6226e8336bd41f103cb8bef32a4 [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 Lattnerdb6be562007-11-28 05:34:05 +0000281
282static llvm::cl::opt<bool>
283WritableStrings("fwritable-strings",
284 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000285
286static llvm::cl::opt<bool>
287LaxVectorConversions("flax-vector-conversions",
288 llvm::cl::desc("Allow implicit conversions between vectors"
289 " with a different number of elements or "
290 "different element types."));
Chris Lattner4b009652007-07-25 00:24:17 +0000291// FIXME: add:
292// -ansi
293// -trigraphs
294// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000295// -fpascal-strings
Chris Lattner4b009652007-07-25 00:24:17 +0000296static void InitializeLanguageStandard(LangOptions &Options) {
297 if (LangStd == lang_unspecified) {
298 // Based on the base language, pick one.
299 switch (BaseLang) {
300 default: assert(0 && "Unknown base language");
301 case langkind_c:
302 case langkind_c_cpp:
303 case langkind_objc:
304 case langkind_objc_cpp:
305 LangStd = lang_gnu99;
306 break;
307 case langkind_cxx:
308 case langkind_cxx_cpp:
309 case langkind_objcxx:
310 case langkind_objcxx_cpp:
311 LangStd = lang_gnucxx98;
312 break;
313 }
314 }
315
316 switch (LangStd) {
317 default: assert(0 && "Unknown language standard!");
318
319 // Fall through from newer standards to older ones. This isn't really right.
320 // FIXME: Enable specifically the right features based on the language stds.
321 case lang_gnucxx0x:
322 case lang_cxx0x:
323 Options.CPlusPlus0x = 1;
324 // FALL THROUGH
325 case lang_gnucxx98:
326 case lang_cxx98:
327 Options.CPlusPlus = 1;
328 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000329 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000330 // FALL THROUGH.
331 case lang_gnu99:
332 case lang_c99:
333 Options.Digraphs = 1;
334 Options.C99 = 1;
335 Options.HexFloats = 1;
336 // FALL THROUGH.
337 case lang_gnu89:
338 Options.BCPLComment = 1; // Only for C99/C++.
339 // FALL THROUGH.
340 case lang_c94:
341 case lang_c89:
342 break;
343 }
344
345 Options.Trigraphs = 1; // -trigraphs or -ansi
346 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000347 Options.PascalStrings = PascalStrings;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000348 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000349 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000350}
351
352//===----------------------------------------------------------------------===//
353// Our DiagnosticClient implementation
354//===----------------------------------------------------------------------===//
355
356// FIXME: Werror should take a list of things, -Werror=foo,bar
357static llvm::cl::opt<bool>
358WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
359
360static llvm::cl::opt<bool>
361WarnOnExtensions("pedantic", llvm::cl::init(false),
362 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
363
364static llvm::cl::opt<bool>
365ErrorOnExtensions("pedantic-errors",
366 llvm::cl::desc("Issue an error on uses of GCC extensions"));
367
368static llvm::cl::opt<bool>
369WarnUnusedMacros("Wunused_macros",
370 llvm::cl::desc("Warn for unused macros in the main translation unit"));
371
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000372static llvm::cl::opt<bool>
373WarnFloatEqual("Wfloat-equal",
374 llvm::cl::desc("Warn about equality comparisons of floating point values."));
375
Chris Lattner4b009652007-07-25 00:24:17 +0000376/// InitializeDiagnostics - Initialize the diagnostic object, based on the
377/// current command line option settings.
378static void InitializeDiagnostics(Diagnostic &Diags) {
379 Diags.setWarningsAsErrors(WarningsAsErrors);
380 Diags.setWarnOnExtensions(WarnOnExtensions);
381 Diags.setErrorOnExtensions(ErrorOnExtensions);
382
383 // Silence the "macro is not used" warning unless requested.
384 if (!WarnUnusedMacros)
385 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000386
387 // Silence "floating point comparison" warnings unless requested.
388 if (!WarnFloatEqual)
389 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000390}
391
392//===----------------------------------------------------------------------===//
393// Preprocessor Initialization
394//===----------------------------------------------------------------------===//
395
396// FIXME: Preprocessor builtins to support.
397// -A... - Play with #assertions
398// -undef - Undefine all predefined macros
399
400static llvm::cl::list<std::string>
401D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
402 llvm::cl::desc("Predefine the specified macro"));
403static llvm::cl::list<std::string>
404U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
405 llvm::cl::desc("Undefine the specified macro"));
406
407// Append a #define line to Buf for Macro. Macro should be of the form XXX,
408// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
409// "#define XXX Y z W". To get a #define with no value, use "XXX=".
410static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
411 const char *Command = "#define ") {
412 Buf.insert(Buf.end(), Command, Command+strlen(Command));
413 if (const char *Equal = strchr(Macro, '=')) {
414 // Turn the = into ' '.
415 Buf.insert(Buf.end(), Macro, Equal);
416 Buf.push_back(' ');
417 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
418 } else {
419 // Push "macroname 1".
420 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
421 Buf.push_back(' ');
422 Buf.push_back('1');
423 }
424 Buf.push_back('\n');
425}
426
Chris Lattner4b009652007-07-25 00:24:17 +0000427
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000428/// InitializePreprocessor - Initialize the preprocessor getting it and the
429/// environment ready to process a single file. This returns the file ID for the
430/// input file. If a failure happens, it returns 0.
431///
432static unsigned InitializePreprocessor(Preprocessor &PP,
433 const std::string &InFile,
434 SourceManager &SourceMgr,
435 HeaderSearch &HeaderInfo,
436 const LangOptions &LangInfo,
437 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000438
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000439 FileManager &FileMgr = HeaderInfo.getFileMgr();
Chris Lattner4b009652007-07-25 00:24:17 +0000440
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000441 // Figure out where to get and map in the main file.
442 unsigned MainFileID = 0;
443 if (InFile != "-") {
444 const FileEntry *File = FileMgr.getFile(InFile);
445 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
446 if (MainFileID == 0) {
447 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
448 return 0;
449 }
450 } else {
451 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
452 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
453 if (MainFileID == 0) {
454 fprintf(stderr, "Error reading standard input! Empty?\n");
455 return 0;
456 }
Chris Lattner4b009652007-07-25 00:24:17 +0000457 }
458
Chris Lattner4b009652007-07-25 00:24:17 +0000459 // Add macros from the command line.
460 // FIXME: Should traverse the #define/#undef lists in parallel.
461 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000462 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000463 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000464 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
465
466 // FIXME: Read any files specified by -imacros or -include.
467
468 // Null terminate PredefinedBuffer and add it.
469 PredefineBuffer.push_back(0);
470 PP.setPredefines(&PredefineBuffer[0]);
471
472 // Once we've read this, we're done.
473 return MainFileID;
Chris Lattner4b009652007-07-25 00:24:17 +0000474}
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000475
476
Chris Lattner4b009652007-07-25 00:24:17 +0000477
478//===----------------------------------------------------------------------===//
479// Preprocessor include path information.
480//===----------------------------------------------------------------------===//
481
482// This tool exports a large number of command line options to control how the
483// preprocessor searches for header files. At root, however, the Preprocessor
484// object takes a very simple interface: a list of directories to search for
485//
486// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000487// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000488//
489// FIXME: -include,-imacros
490
491static llvm::cl::opt<bool>
492nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
493
494// Various command line options. These four add directories to each chain.
495static llvm::cl::list<std::string>
496F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
497 llvm::cl::desc("Add directory to framework include search path"));
498static llvm::cl::list<std::string>
499I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
500 llvm::cl::desc("Add directory to include search path"));
501static llvm::cl::list<std::string>
502idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
503 llvm::cl::desc("Add directory to AFTER include search path"));
504static llvm::cl::list<std::string>
505iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
506 llvm::cl::desc("Add directory to QUOTE include search path"));
507static llvm::cl::list<std::string>
508isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
509 llvm::cl::desc("Add directory to SYSTEM include search path"));
510
511// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
512static llvm::cl::list<std::string>
513iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
514 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
515static llvm::cl::list<std::string>
516iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
517 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
518static llvm::cl::list<std::string>
519iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
520 llvm::cl::Prefix,
521 llvm::cl::desc("Set directory to include search path with prefix"));
522
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000523static llvm::cl::opt<std::string>
524isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
525 llvm::cl::desc("Set the system root directory (usually /)"));
526
Chris Lattner4b009652007-07-25 00:24:17 +0000527// Finally, implement the code that groks the options above.
528enum IncludeDirGroup {
529 Quoted = 0,
530 Angled,
531 System,
532 After
533};
534
535static std::vector<DirectoryLookup> IncludeGroup[4];
536
537/// AddPath - Add the specified path to the specified group list.
538///
539static void AddPath(const std::string &Path, IncludeDirGroup Group,
540 bool isCXXAware, bool isUserSupplied,
541 bool isFramework, FileManager &FM) {
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000542 const DirectoryEntry *DE;
543 if (Group == System)
544 DE = FM.getDirectory(isysroot + "/" + Path);
545 else
546 DE = FM.getDirectory(Path);
547
Chris Lattner4b009652007-07-25 00:24:17 +0000548 if (DE == 0) {
549 if (Verbose)
550 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
551 Path.c_str());
552 return;
553 }
554
555 DirectoryLookup::DirType Type;
556 if (Group == Quoted || Group == Angled)
557 Type = DirectoryLookup::NormalHeaderDir;
558 else if (isCXXAware)
559 Type = DirectoryLookup::SystemHeaderDir;
560 else
561 Type = DirectoryLookup::ExternCSystemHeaderDir;
562
563 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
564 isFramework));
565}
566
567/// RemoveDuplicates - If there are duplicate directory entries in the specified
568/// search list, remove the later (dead) ones.
569static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
570 std::set<const DirectoryEntry *> SeenDirs;
571 for (unsigned i = 0; i != SearchList.size(); ++i) {
572 // If this isn't the first time we've seen this dir, remove it.
573 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
574 if (Verbose)
575 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
576 SearchList[i].getDir()->getName());
577 SearchList.erase(SearchList.begin()+i);
578 --i;
579 }
580 }
581}
582
583/// InitializeIncludePaths - Process the -I options and set them in the
584/// HeaderSearch object.
585static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
586 Diagnostic &Diags, const LangOptions &Lang) {
587 // Handle -F... options.
588 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
589 AddPath(F_dirs[i], Angled, false, true, true, FM);
590
591 // Handle -I... options.
592 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
593 if (I_dirs[i] == "-") {
594 // -I- is a deprecated GCC feature.
595 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
596 } else {
597 AddPath(I_dirs[i], Angled, false, true, false, FM);
598 }
599 }
600
601 // Handle -idirafter... options.
602 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
603 AddPath(idirafter_dirs[i], After, false, true, false, FM);
604
605 // Handle -iquote... options.
606 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
607 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
608
609 // Handle -isystem... options.
610 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
611 AddPath(isystem_dirs[i], System, false, true, false, FM);
612
613 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
614 // parallel, processing the values in order of occurance to get the right
615 // prefixes.
616 {
617 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
618 unsigned iprefix_idx = 0;
619 unsigned iwithprefix_idx = 0;
620 unsigned iwithprefixbefore_idx = 0;
621 bool iprefix_done = iprefix_vals.empty();
622 bool iwithprefix_done = iwithprefix_vals.empty();
623 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
624 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
625 if (!iprefix_done &&
626 (iwithprefix_done ||
627 iprefix_vals.getPosition(iprefix_idx) <
628 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
629 (iwithprefixbefore_done ||
630 iprefix_vals.getPosition(iprefix_idx) <
631 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
632 Prefix = iprefix_vals[iprefix_idx];
633 ++iprefix_idx;
634 iprefix_done = iprefix_idx == iprefix_vals.size();
635 } else if (!iwithprefix_done &&
636 (iwithprefixbefore_done ||
637 iwithprefix_vals.getPosition(iwithprefix_idx) <
638 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
639 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
640 System, false, false, false, FM);
641 ++iwithprefix_idx;
642 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
643 } else {
644 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
645 Angled, false, false, false, FM);
646 ++iwithprefixbefore_idx;
647 iwithprefixbefore_done =
648 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
649 }
650 }
651 }
652
653 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
654 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
655
656 // FIXME: temporary hack: hard-coded paths.
657 // FIXME: get these from the target?
658 if (!nostdinc) {
659 if (Lang.CPlusPlus) {
660 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
661 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
662 false, FM);
663 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
664 }
665
666 AddPath("/usr/local/include", System, false, false, false, FM);
667 // leopard
668 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
669 false, false, false, FM);
670 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
671 System, false, false, false, FM);
672 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
673 "4.0.1/../../../../powerpc-apple-darwin0/include",
674 System, false, false, false, FM);
675
676 // tiger
677 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
678 false, false, false, FM);
679 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
680 System, false, false, false, FM);
681 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
682 "4.0.1/../../../../powerpc-apple-darwin8/include",
683 System, false, false, false, FM);
684
685 AddPath("/usr/include", System, false, false, false, FM);
686 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
687 AddPath("/Library/Frameworks", System, true, false, true, FM);
688 }
689
690 // Now that we have collected all of the include paths, merge them all
691 // together and tell the preprocessor about them.
692
693 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
694 std::vector<DirectoryLookup> SearchList;
695 SearchList = IncludeGroup[Angled];
696 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
697 IncludeGroup[System].end());
698 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
699 IncludeGroup[After].end());
700 RemoveDuplicates(SearchList);
701 RemoveDuplicates(IncludeGroup[Quoted]);
702
703 // Prepend QUOTED list on the search list.
704 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
705 IncludeGroup[Quoted].end());
706
707
708 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
709 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
710 DontSearchCurDir);
711
712 // If verbose, print the list of directories that will be searched.
713 if (Verbose) {
714 fprintf(stderr, "#include \"...\" search starts here:\n");
715 unsigned QuotedIdx = IncludeGroup[Quoted].size();
716 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
717 if (i == QuotedIdx)
718 fprintf(stderr, "#include <...> search starts here:\n");
719 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
720 }
721 }
722}
723
724
Chris Lattner4b009652007-07-25 00:24:17 +0000725//===----------------------------------------------------------------------===//
726// Basic Parser driver
727//===----------------------------------------------------------------------===//
728
729static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
730 Parser P(PP, *PA);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000731 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000732
733 // Parsing the specified input file.
734 P.ParseTranslationUnit();
735 delete PA;
736}
737
738//===----------------------------------------------------------------------===//
739// Main driver
740//===----------------------------------------------------------------------===//
741
Chris Lattner4b009652007-07-25 00:24:17 +0000742/// ProcessInputFile - Process a single input file with the specified state.
743///
744static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
745 const std::string &InFile,
746 SourceManager &SourceMgr,
747 TextDiagnostics &OurDiagnosticClient,
748 HeaderSearch &HeaderInfo,
749 const LangOptions &LangInfo) {
Ted Kremenek6856c632007-09-26 18:39:29 +0000750
751 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +0000752 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +0000753
Chris Lattner4b009652007-07-25 00:24:17 +0000754 switch (ProgAction) {
755 default:
756 fprintf(stderr, "Unexpected program action!\n");
757 return;
758 case DumpTokens: { // Token dump mode.
759 Token Tok;
760 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000761 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000762 do {
763 PP.Lex(Tok);
764 PP.DumpToken(Tok, true);
765 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +0000766 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000767 ClearSourceMgr = true;
768 break;
769 }
770 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
771 Token Tok;
772 // Start parsing the specified input file.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000773 PP.EnterMainSourceFile(MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000774 do {
775 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +0000776 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +0000777 ClearSourceMgr = true;
778 break;
779 }
780
781 case PrintPreprocessedInput: // -E mode.
782 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
783 ClearSourceMgr = true;
784 break;
785
786 case ParseNoop: // -parse-noop
Steve Naroffebeb4282007-10-31 20:55:39 +0000787 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000788 ClearSourceMgr = true;
789 break;
790
791 case ParsePrintCallbacks:
Steve Naroffebeb4282007-10-31 20:55:39 +0000792 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
793 MainFileID);
Chris Lattner4b009652007-07-25 00:24:17 +0000794 ClearSourceMgr = true;
795 break;
Ted Kremenek0841c702007-09-25 18:37:20 +0000796
Ted Kremenek6856c632007-09-26 18:39:29 +0000797 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +0000798 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000799 break;
Ted Kremenek6856c632007-09-26 18:39:29 +0000800
Chris Lattner4045a8a2007-10-11 00:18:28 +0000801 case ASTPrint:
Ted Kremenek6856c632007-09-26 18:39:29 +0000802 Consumer = CreateASTPrinter();
803 break;
804
Chris Lattner4045a8a2007-10-11 00:18:28 +0000805 case ASTDump:
Ted Kremenek6856c632007-09-26 18:39:29 +0000806 Consumer = CreateASTDumper();
807 break;
808
Chris Lattner4045a8a2007-10-11 00:18:28 +0000809 case ASTView:
Ted Kremenek6856c632007-09-26 18:39:29 +0000810 Consumer = CreateASTViewer();
811 break;
812
813 case ParseCFGDump:
814 case ParseCFGView:
815 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
816 break;
817
818 case AnalysisLiveVariables:
819 Consumer = CreateLiveVarAnalyzer();
820 break;
821
822 case WarnDeadStores:
823 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
824 break;
825
826 case WarnUninitVals:
827 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
828 break;
829
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000830 case TestSerialization:
831 Consumer = CreateSerializationTest();
832 break;
833
Ted Kremenek6856c632007-09-26 18:39:29 +0000834 case EmitLLVM:
Chris Lattnerdb6be562007-11-28 05:34:05 +0000835 Consumer = CreateLLVMEmitter(PP.getDiagnostics(), PP.getLangOptions());
Chris Lattner4b009652007-07-25 00:24:17 +0000836 break;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000837
838 case RewriteTest:
839 Consumer = CreateCodeRewriterTest();
840 break;
Chris Lattner129758d2007-09-16 19:46:59 +0000841 }
Ted Kremenek6856c632007-09-26 18:39:29 +0000842
843 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +0000844 if (VerifyDiagnostics)
Chris Lattner8593cbf2007-11-03 06:24:16 +0000845 exit(CheckASTConsumer(PP, MainFileID, Consumer));
846
847 // This deletes Consumer.
848 ParseAST(PP, MainFileID, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +0000849 }
850
851 if (Stats) {
852 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
853 PP.PrintStats();
854 PP.getIdentifierTable().PrintStats();
855 HeaderInfo.PrintStats();
856 if (ClearSourceMgr)
857 SourceMgr.PrintStats();
858 fprintf(stderr, "\n");
859 }
860
861 // For a multi-file compilation, some things are ok with nuking the source
862 // manager tables, other require stable fileid/macroid's across multiple
863 // files.
864 if (ClearSourceMgr) {
865 SourceMgr.clearIDTables();
866 }
867}
868
869static llvm::cl::list<std::string>
870InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
871
872
873int main(int argc, char **argv) {
874 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
875 llvm::sys::PrintStackTraceOnErrorSignal();
876
877 // If no input was specified, read from stdin.
878 if (InputFilenames.empty())
879 InputFilenames.push_back("-");
880
881 /// Create a SourceManager object. This tracks and owns all the file buffers
882 /// allocated to the program.
883 SourceManager SourceMgr;
884
885 // Create a file manager object to provide access to and cache the filesystem.
886 FileManager FileMgr;
887
888 // Initialize language options, inferring file types from input filenames.
889 // FIXME: This infers info from the first file, we should clump by language
890 // to handle 'x.c y.c a.cpp b.cpp'.
891 LangOptions LangInfo;
892 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
893 InitializeLanguageStandard(LangInfo);
894
895 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek56b70862007-09-26 20:14:22 +0000896 if (!VerifyDiagnostics) {
Chris Lattner4b009652007-07-25 00:24:17 +0000897 // Print diagnostics to stderr by default.
898 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
899 } else {
900 // When checking diagnostics, just buffer them up.
901 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
902
903 if (InputFilenames.size() != 1) {
904 fprintf(stderr,
Ted Kremenek56b70862007-09-26 20:14:22 +0000905 "-verify only works on single input files for now.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000906 return 1;
907 }
908 }
909
910 // Configure our handling of diagnostics.
911 Diagnostic Diags(*DiagClient);
912 InitializeDiagnostics(Diags);
913
914 // Get information about the targets being compiled for. Note that this
915 // pointer and the TargetInfoImpl objects are never deleted by this toy
916 // driver.
917 TargetInfo *Target = CreateTargetInfo(Diags);
918 if (Target == 0) {
919 fprintf(stderr,
920 "Sorry, don't know what target this is, please use -arch.\n");
921 exit(1);
922 }
923
924 // Process the -I options and set them in the HeaderInfo.
925 HeaderSearch HeaderInfo(FileMgr);
926 DiagClient->setHeaderSearch(HeaderInfo);
927 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
928
929 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
930 // Set up the preprocessor with these options.
931 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
Chris Lattner4b009652007-07-25 00:24:17 +0000932 const std::string &InFile = InputFilenames[i];
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000933 std::vector<char> PredefineBuffer;
Chris Lattner4b009652007-07-25 00:24:17 +0000934 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
935 HeaderInfo, LangInfo,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000936 PredefineBuffer);
Chris Lattner4b009652007-07-25 00:24:17 +0000937
938 if (!MainFileID) continue;
939
940 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
941 *DiagClient, HeaderInfo, LangInfo);
942 HeaderInfo.ClearFileInfo();
943 }
944
945 unsigned NumDiagnostics = Diags.getNumDiagnostics();
946
947 if (NumDiagnostics)
948 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
949 (NumDiagnostics == 1 ? "" : "s"));
950
951 if (Stats) {
952 // Printed from high-to-low level.
953 SourceMgr.PrintStats();
954 FileMgr.PrintStats();
955 fprintf(stderr, "\n");
956 }
957
958 return Diags.getNumErrors() != 0;
959}