blob: e5185d04985c1a8da86fb04e77076f7e381c34b3 [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"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#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.
Chris Lattner3b427b32007-10-11 00:18:28 +000053 ASTPrint, // Parse ASTs and print them.
54 ASTDump, // Parse ASTs and dump them.
55 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000056 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000057 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000058 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000059 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000060 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000061 WarnUninitVals, // Run UnitializedVariables checker.
Reid Spencer5f016e22007-07-11 17:01:13 +000062 ParsePrintCallbacks, // Parse and print each callback.
63 ParseSyntaxOnly, // Parse and perform semantic analysis.
64 ParseNoop, // Parse with noop callbacks.
65 RunPreprocessorOnly, // Just lex, no output.
66 PrintPreprocessedInput, // -E mode.
67 DumpTokens // Token dump mode.
68};
69
70static llvm::cl::opt<ProgActions>
71ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
72 llvm::cl::init(ParseSyntaxOnly),
73 llvm::cl::values(
74 clEnumValN(RunPreprocessorOnly, "Eonly",
75 "Just run preprocessor, no output (for timings)"),
76 clEnumValN(PrintPreprocessedInput, "E",
77 "Run preprocessor, emit preprocessed file"),
78 clEnumValN(DumpTokens, "dumptokens",
79 "Run preprocessor, dump internal rep of tokens"),
80 clEnumValN(ParseNoop, "parse-noop",
81 "Run parser with noop callbacks (for timings)"),
82 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
83 "Run parser and perform semantic analysis"),
84 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
85 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +000086 clEnumValN(ASTPrint, "ast-print",
87 "Build ASTs and then pretty-print them"),
88 clEnumValN(ASTDump, "ast-dump",
89 "Build ASTs and then debug dump them"),
90 clEnumValN(ASTView, "parse-ast-view",
91 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000092 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +000093 "Run parser, then build and print CFGs."),
94 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +000095 "Run parser, then build and view CFGs with Graphviz."),
96 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +000097 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +000098 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +000099 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000100 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000101 "Flag warnings of uses of unitialized variables."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000103 "Build ASTs then convert to LLVM, emit .ll file"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 clEnumValEnd));
105
Ted Kremenek41193e42007-09-26 19:42:19 +0000106static llvm::cl::opt<bool>
107VerifyDiagnostics("verify",
108 llvm::cl::desc("Verify emitted diagnostics and warnings."));
109
Reid Spencer5f016e22007-07-11 17:01:13 +0000110//===----------------------------------------------------------------------===//
111// Language Options
112//===----------------------------------------------------------------------===//
113
114enum LangKind {
115 langkind_unspecified,
116 langkind_c,
117 langkind_c_cpp,
118 langkind_cxx,
119 langkind_cxx_cpp,
120 langkind_objc,
121 langkind_objc_cpp,
122 langkind_objcxx,
123 langkind_objcxx_cpp
124};
125
126/* TODO: GCC also accepts:
127 c-header c++-header objective-c-header objective-c++-header
128 assembler assembler-with-cpp
129 ada, f77*, ratfor (!), f95, java, treelang
130 */
131static llvm::cl::opt<LangKind>
132BaseLang("x", llvm::cl::desc("Base language to compile"),
133 llvm::cl::init(langkind_unspecified),
134 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
135 clEnumValN(langkind_cxx, "c++", "C++"),
136 clEnumValN(langkind_objc, "objective-c", "Objective C"),
137 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
138 clEnumValN(langkind_c_cpp, "c-cpp-output",
139 "Preprocessed C"),
140 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
141 "Preprocessed C++"),
142 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
143 "Preprocessed Objective C"),
144 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
145 "Preprocessed Objective C++"),
146 clEnumValEnd));
147
148static llvm::cl::opt<bool>
149LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
150 llvm::cl::Hidden);
151static llvm::cl::opt<bool>
152LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
153 llvm::cl::Hidden);
154
155/// InitializeBaseLanguage - Handle the -x foo options or infer a base language
156/// from the input filename.
157static void InitializeBaseLanguage(LangOptions &Options,
158 const std::string &Filename) {
159 if (BaseLang == langkind_unspecified) {
160 std::string::size_type DotPos = Filename.rfind('.');
161 if (LangObjC) {
162 BaseLang = langkind_objc;
163 } else if (LangObjCXX) {
164 BaseLang = langkind_objcxx;
165 } else if (DotPos == std::string::npos) {
166 BaseLang = langkind_c; // Default to C if no extension.
167 } else {
168 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
169 // C header: .h
170 // C++ header: .hh or .H;
171 // assembler no preprocessing: .s
172 // assembler: .S
173 if (Ext == "c")
174 BaseLang = langkind_c;
175 else if (Ext == "i")
176 BaseLang = langkind_c_cpp;
177 else if (Ext == "ii")
178 BaseLang = langkind_cxx_cpp;
179 else if (Ext == "m")
180 BaseLang = langkind_objc;
181 else if (Ext == "mi")
182 BaseLang = langkind_objc_cpp;
183 else if (Ext == "mm" || Ext == "M")
184 BaseLang = langkind_objcxx;
185 else if (Ext == "mii")
186 BaseLang = langkind_objcxx_cpp;
187 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
188 Ext == "c++" || Ext == "cp" || Ext == "cxx")
189 BaseLang = langkind_cxx;
190 else
191 BaseLang = langkind_c;
192 }
193 }
194
195 // FIXME: implement -fpreprocessed mode.
196 bool NoPreprocess = false;
197
198 switch (BaseLang) {
199 default: assert(0 && "Unknown language kind!");
200 case langkind_c_cpp:
201 NoPreprocess = true;
202 // FALLTHROUGH
203 case langkind_c:
204 break;
205 case langkind_cxx_cpp:
206 NoPreprocess = true;
207 // FALLTHROUGH
208 case langkind_cxx:
209 Options.CPlusPlus = 1;
210 break;
211 case langkind_objc_cpp:
212 NoPreprocess = true;
213 // FALLTHROUGH
214 case langkind_objc:
215 Options.ObjC1 = Options.ObjC2 = 1;
216 break;
217 case langkind_objcxx_cpp:
218 NoPreprocess = true;
219 // FALLTHROUGH
220 case langkind_objcxx:
221 Options.ObjC1 = Options.ObjC2 = 1;
222 Options.CPlusPlus = 1;
223 break;
224 }
225}
226
227/// LangStds - Language standards we support.
228enum LangStds {
229 lang_unspecified,
230 lang_c89, lang_c94, lang_c99,
231 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000232 lang_cxx98, lang_gnucxx98,
233 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000234};
235
236static llvm::cl::opt<LangStds>
237LangStd("std", llvm::cl::desc("Language standard to compile for"),
238 llvm::cl::init(lang_unspecified),
239 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
240 clEnumValN(lang_c89, "c90", "ISO C 1990"),
241 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
242 clEnumValN(lang_c94, "iso9899:199409",
243 "ISO C 1990 with amendment 1"),
244 clEnumValN(lang_c99, "c99", "ISO C 1999"),
245// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
246 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
247// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
248 clEnumValN(lang_gnu89, "gnu89",
249 "ISO C 1990 with GNU extensions (default for C)"),
250 clEnumValN(lang_gnu99, "gnu99",
251 "ISO C 1999 with GNU extensions"),
252 clEnumValN(lang_gnu99, "gnu9x",
253 "ISO C 1999 with GNU extensions"),
254 clEnumValN(lang_cxx98, "c++98",
255 "ISO C++ 1998 with amendments"),
256 clEnumValN(lang_gnucxx98, "gnu++98",
257 "ISO C++ 1998 with amendments and GNU "
258 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000259 clEnumValN(lang_cxx0x, "c++0x",
260 "Upcoming ISO C++ 200x with amendments"),
261 clEnumValN(lang_gnucxx0x, "gnu++0x",
262 "Upcoming ISO C++ 200x with amendments and GNU "
263 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 clEnumValEnd));
265
266static llvm::cl::opt<bool>
267NoOperatorNames("fno-operator-names",
268 llvm::cl::desc("Do not treat C++ operator name keywords as "
269 "synonyms for operators"));
270
271// FIXME: add:
272// -ansi
273// -trigraphs
274// -fdollars-in-identifiers
275static void InitializeLanguageStandard(LangOptions &Options) {
276 if (LangStd == lang_unspecified) {
277 // Based on the base language, pick one.
278 switch (BaseLang) {
279 default: assert(0 && "Unknown base language");
280 case langkind_c:
281 case langkind_c_cpp:
282 case langkind_objc:
283 case langkind_objc_cpp:
284 LangStd = lang_gnu99;
285 break;
286 case langkind_cxx:
287 case langkind_cxx_cpp:
288 case langkind_objcxx:
289 case langkind_objcxx_cpp:
290 LangStd = lang_gnucxx98;
291 break;
292 }
293 }
294
295 switch (LangStd) {
296 default: assert(0 && "Unknown language standard!");
297
298 // Fall through from newer standards to older ones. This isn't really right.
299 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000300 case lang_gnucxx0x:
301 case lang_cxx0x:
302 Options.CPlusPlus0x = 1;
303 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 case lang_gnucxx98:
305 case lang_cxx98:
306 Options.CPlusPlus = 1;
307 Options.CXXOperatorNames = !NoOperatorNames;
308 // FALL THROUGH.
309 case lang_gnu99:
310 case lang_c99:
311 Options.Digraphs = 1;
312 Options.C99 = 1;
313 Options.HexFloats = 1;
314 // FALL THROUGH.
315 case lang_gnu89:
316 Options.BCPLComment = 1; // Only for C99/C++.
317 // FALL THROUGH.
318 case lang_c94:
319 case lang_c89:
320 break;
321 }
322
323 Options.Trigraphs = 1; // -trigraphs or -ansi
324 Options.DollarIdents = 1; // FIXME: Really a target property.
325}
326
327//===----------------------------------------------------------------------===//
328// Our DiagnosticClient implementation
329//===----------------------------------------------------------------------===//
330
331// FIXME: Werror should take a list of things, -Werror=foo,bar
332static llvm::cl::opt<bool>
333WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
334
335static llvm::cl::opt<bool>
336WarnOnExtensions("pedantic", llvm::cl::init(false),
337 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
338
339static llvm::cl::opt<bool>
340ErrorOnExtensions("pedantic-errors",
341 llvm::cl::desc("Issue an error on uses of GCC extensions"));
342
343static llvm::cl::opt<bool>
344WarnUnusedMacros("Wunused_macros",
345 llvm::cl::desc("Warn for unused macros in the main translation unit"));
346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347/// InitializeDiagnostics - Initialize the diagnostic object, based on the
348/// current command line option settings.
349static void InitializeDiagnostics(Diagnostic &Diags) {
350 Diags.setWarningsAsErrors(WarningsAsErrors);
351 Diags.setWarnOnExtensions(WarnOnExtensions);
352 Diags.setErrorOnExtensions(ErrorOnExtensions);
353
354 // Silence the "macro is not used" warning unless requested.
355 if (!WarnUnusedMacros)
356 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
357}
358
359//===----------------------------------------------------------------------===//
360// Preprocessor Initialization
361//===----------------------------------------------------------------------===//
362
363// FIXME: Preprocessor builtins to support.
364// -A... - Play with #assertions
365// -undef - Undefine all predefined macros
366
367static llvm::cl::list<std::string>
368D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
369 llvm::cl::desc("Predefine the specified macro"));
370static llvm::cl::list<std::string>
371U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
372 llvm::cl::desc("Undefine the specified macro"));
373
374// Append a #define line to Buf for Macro. Macro should be of the form XXX,
375// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
376// "#define XXX Y z W". To get a #define with no value, use "XXX=".
377static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
378 const char *Command = "#define ") {
379 Buf.insert(Buf.end(), Command, Command+strlen(Command));
380 if (const char *Equal = strchr(Macro, '=')) {
381 // Turn the = into ' '.
382 Buf.insert(Buf.end(), Macro, Equal);
383 Buf.push_back(' ');
384 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
385 } else {
386 // Push "macroname 1".
387 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
388 Buf.push_back(' ');
389 Buf.push_back('1');
390 }
391 Buf.push_back('\n');
392}
393
Reid Spencer5f016e22007-07-11 17:01:13 +0000394
Chris Lattner53b0dab2007-10-09 22:10:18 +0000395/// InitializePreprocessor - Initialize the preprocessor getting it and the
396/// environment ready to process a single file. This returns the file ID for the
397/// input file. If a failure happens, it returns 0.
398///
399static unsigned InitializePreprocessor(Preprocessor &PP,
400 const std::string &InFile,
401 SourceManager &SourceMgr,
402 HeaderSearch &HeaderInfo,
403 const LangOptions &LangInfo,
404 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000405
Chris Lattner53b0dab2007-10-09 22:10:18 +0000406 FileManager &FileMgr = HeaderInfo.getFileMgr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000407
Chris Lattner53b0dab2007-10-09 22:10:18 +0000408 // Figure out where to get and map in the main file.
409 unsigned MainFileID = 0;
410 if (InFile != "-") {
411 const FileEntry *File = FileMgr.getFile(InFile);
412 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
413 if (MainFileID == 0) {
414 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
415 return 0;
416 }
417 } else {
418 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
419 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
420 if (MainFileID == 0) {
421 fprintf(stderr, "Error reading standard input! Empty?\n");
422 return 0;
423 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 }
425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // Add macros from the command line.
427 // FIXME: Should traverse the #define/#undef lists in parallel.
428 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000429 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000431 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
432
433 // FIXME: Read any files specified by -imacros or -include.
434
435 // Null terminate PredefinedBuffer and add it.
436 PredefineBuffer.push_back(0);
437 PP.setPredefines(&PredefineBuffer[0]);
438
439 // Once we've read this, we're done.
440 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000441}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000442
443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444
445//===----------------------------------------------------------------------===//
446// Preprocessor include path information.
447//===----------------------------------------------------------------------===//
448
449// This tool exports a large number of command line options to control how the
450// preprocessor searches for header files. At root, however, the Preprocessor
451// object takes a very simple interface: a list of directories to search for
452//
453// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000454// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000455//
456// FIXME: -include,-imacros
457
458static llvm::cl::opt<bool>
459nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
460
461// Various command line options. These four add directories to each chain.
462static llvm::cl::list<std::string>
463F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
464 llvm::cl::desc("Add directory to framework include search path"));
465static llvm::cl::list<std::string>
466I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
467 llvm::cl::desc("Add directory to include search path"));
468static llvm::cl::list<std::string>
469idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
470 llvm::cl::desc("Add directory to AFTER include search path"));
471static llvm::cl::list<std::string>
472iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
473 llvm::cl::desc("Add directory to QUOTE include search path"));
474static llvm::cl::list<std::string>
475isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
476 llvm::cl::desc("Add directory to SYSTEM include search path"));
477
478// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
479static llvm::cl::list<std::string>
480iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
481 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
482static llvm::cl::list<std::string>
483iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
484 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
485static llvm::cl::list<std::string>
486iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
487 llvm::cl::Prefix,
488 llvm::cl::desc("Set directory to include search path with prefix"));
489
Chris Lattner0c946412007-08-26 17:47:35 +0000490static llvm::cl::opt<std::string>
491isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
492 llvm::cl::desc("Set the system root directory (usually /)"));
493
Reid Spencer5f016e22007-07-11 17:01:13 +0000494// Finally, implement the code that groks the options above.
495enum IncludeDirGroup {
496 Quoted = 0,
497 Angled,
498 System,
499 After
500};
501
502static std::vector<DirectoryLookup> IncludeGroup[4];
503
504/// AddPath - Add the specified path to the specified group list.
505///
506static void AddPath(const std::string &Path, IncludeDirGroup Group,
507 bool isCXXAware, bool isUserSupplied,
508 bool isFramework, FileManager &FM) {
Chris Lattner0c946412007-08-26 17:47:35 +0000509 const DirectoryEntry *DE;
510 if (Group == System)
511 DE = FM.getDirectory(isysroot + "/" + Path);
512 else
513 DE = FM.getDirectory(Path);
514
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 if (DE == 0) {
516 if (Verbose)
517 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
518 Path.c_str());
519 return;
520 }
521
522 DirectoryLookup::DirType Type;
523 if (Group == Quoted || Group == Angled)
524 Type = DirectoryLookup::NormalHeaderDir;
525 else if (isCXXAware)
526 Type = DirectoryLookup::SystemHeaderDir;
527 else
528 Type = DirectoryLookup::ExternCSystemHeaderDir;
529
530 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
531 isFramework));
532}
533
534/// RemoveDuplicates - If there are duplicate directory entries in the specified
535/// search list, remove the later (dead) ones.
536static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
537 std::set<const DirectoryEntry *> SeenDirs;
538 for (unsigned i = 0; i != SearchList.size(); ++i) {
539 // If this isn't the first time we've seen this dir, remove it.
540 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
541 if (Verbose)
542 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
543 SearchList[i].getDir()->getName());
544 SearchList.erase(SearchList.begin()+i);
545 --i;
546 }
547 }
548}
549
550/// InitializeIncludePaths - Process the -I options and set them in the
551/// HeaderSearch object.
552static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
553 Diagnostic &Diags, const LangOptions &Lang) {
554 // Handle -F... options.
555 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
556 AddPath(F_dirs[i], Angled, false, true, true, FM);
557
558 // Handle -I... options.
559 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
560 if (I_dirs[i] == "-") {
561 // -I- is a deprecated GCC feature.
562 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
563 } else {
564 AddPath(I_dirs[i], Angled, false, true, false, FM);
565 }
566 }
567
568 // Handle -idirafter... options.
569 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
570 AddPath(idirafter_dirs[i], After, false, true, false, FM);
571
572 // Handle -iquote... options.
573 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
574 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
575
576 // Handle -isystem... options.
577 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
578 AddPath(isystem_dirs[i], System, false, true, false, FM);
579
580 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
581 // parallel, processing the values in order of occurance to get the right
582 // prefixes.
583 {
584 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
585 unsigned iprefix_idx = 0;
586 unsigned iwithprefix_idx = 0;
587 unsigned iwithprefixbefore_idx = 0;
588 bool iprefix_done = iprefix_vals.empty();
589 bool iwithprefix_done = iwithprefix_vals.empty();
590 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
591 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
592 if (!iprefix_done &&
593 (iwithprefix_done ||
594 iprefix_vals.getPosition(iprefix_idx) <
595 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
596 (iwithprefixbefore_done ||
597 iprefix_vals.getPosition(iprefix_idx) <
598 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
599 Prefix = iprefix_vals[iprefix_idx];
600 ++iprefix_idx;
601 iprefix_done = iprefix_idx == iprefix_vals.size();
602 } else if (!iwithprefix_done &&
603 (iwithprefixbefore_done ||
604 iwithprefix_vals.getPosition(iwithprefix_idx) <
605 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
606 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
607 System, false, false, false, FM);
608 ++iwithprefix_idx;
609 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
610 } else {
611 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
612 Angled, false, false, false, FM);
613 ++iwithprefixbefore_idx;
614 iwithprefixbefore_done =
615 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
616 }
617 }
618 }
619
620 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
621 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
622
623 // FIXME: temporary hack: hard-coded paths.
624 // FIXME: get these from the target?
625 if (!nostdinc) {
626 if (Lang.CPlusPlus) {
627 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
628 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
629 false, FM);
630 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
631 }
632
633 AddPath("/usr/local/include", System, false, false, false, FM);
634 // leopard
635 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
636 false, false, false, FM);
637 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
638 System, false, false, false, FM);
639 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
640 "4.0.1/../../../../powerpc-apple-darwin0/include",
641 System, false, false, false, FM);
642
643 // tiger
644 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
645 false, false, false, FM);
646 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
647 System, false, false, false, FM);
648 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
649 "4.0.1/../../../../powerpc-apple-darwin8/include",
650 System, false, false, false, FM);
651
652 AddPath("/usr/include", System, false, false, false, FM);
653 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
654 AddPath("/Library/Frameworks", System, true, false, true, FM);
655 }
656
657 // Now that we have collected all of the include paths, merge them all
658 // together and tell the preprocessor about them.
659
660 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
661 std::vector<DirectoryLookup> SearchList;
662 SearchList = IncludeGroup[Angled];
663 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
664 IncludeGroup[System].end());
665 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
666 IncludeGroup[After].end());
667 RemoveDuplicates(SearchList);
668 RemoveDuplicates(IncludeGroup[Quoted]);
669
670 // Prepend QUOTED list on the search list.
671 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
672 IncludeGroup[Quoted].end());
673
674
675 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
676 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
677 DontSearchCurDir);
678
679 // If verbose, print the list of directories that will be searched.
680 if (Verbose) {
681 fprintf(stderr, "#include \"...\" search starts here:\n");
682 unsigned QuotedIdx = IncludeGroup[Quoted].size();
683 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
684 if (i == QuotedIdx)
685 fprintf(stderr, "#include <...> search starts here:\n");
686 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
687 }
688 }
689}
690
691
Reid Spencer5f016e22007-07-11 17:01:13 +0000692//===----------------------------------------------------------------------===//
693// Basic Parser driver
694//===----------------------------------------------------------------------===//
695
696static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
697 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000698 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699
700 // Parsing the specified input file.
701 P.ParseTranslationUnit();
702 delete PA;
703}
704
705//===----------------------------------------------------------------------===//
706// Main driver
707//===----------------------------------------------------------------------===//
708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709/// ProcessInputFile - Process a single input file with the specified state.
710///
711static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
712 const std::string &InFile,
713 SourceManager &SourceMgr,
714 TextDiagnostics &OurDiagnosticClient,
715 HeaderSearch &HeaderInfo,
716 const LangOptions &LangInfo) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000717
718 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000719 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000720
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 switch (ProgAction) {
722 default:
723 fprintf(stderr, "Unexpected program action!\n");
724 return;
725 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +0000726 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000728 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 do {
730 PP.Lex(Tok);
731 PP.DumpToken(Tok, true);
732 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000733 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000734 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 break;
736 }
737 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000738 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000740 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 do {
742 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000743 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000744 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 break;
746 }
747
748 case PrintPreprocessedInput: // -E mode.
749 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000750 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 break;
752
753 case ParseNoop: // -parse-noop
754 ParseFile(PP, new MinimalAction(), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000755 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 break;
757
758 case ParsePrintCallbacks:
759 ParseFile(PP, CreatePrintParserActionsAction(), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000760 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000762
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000763 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000764 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000765 break;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000766
Chris Lattner3b427b32007-10-11 00:18:28 +0000767 case ASTPrint:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000768 Consumer = CreateASTPrinter();
769 break;
770
Chris Lattner3b427b32007-10-11 00:18:28 +0000771 case ASTDump:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000772 Consumer = CreateASTDumper();
773 break;
774
Chris Lattner3b427b32007-10-11 00:18:28 +0000775 case ASTView:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000776 Consumer = CreateASTViewer();
777 break;
778
779 case ParseCFGDump:
780 case ParseCFGView:
781 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
782 break;
783
784 case AnalysisLiveVariables:
785 Consumer = CreateLiveVarAnalyzer();
786 break;
787
788 case WarnDeadStores:
789 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
790 break;
791
792 case WarnUninitVals:
793 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
794 break;
795
796 case EmitLLVM:
797 Consumer = CreateLLVMEmitter(PP.getDiagnostics());
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000799 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000800
801 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000802 if (VerifyDiagnostics)
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000803 exit (CheckASTConsumer(PP, MainFileID, Consumer));
804 else
805 ParseAST(PP, MainFileID, *Consumer, Stats);
806
807 delete Consumer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 }
809
810 if (Stats) {
811 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
812 PP.PrintStats();
813 PP.getIdentifierTable().PrintStats();
814 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000815 if (ClearSourceMgr)
816 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 fprintf(stderr, "\n");
818 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000819
820 // For a multi-file compilation, some things are ok with nuking the source
821 // manager tables, other require stable fileid/macroid's across multiple
822 // files.
823 if (ClearSourceMgr) {
824 SourceMgr.clearIDTables();
825 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000826}
827
828static llvm::cl::list<std::string>
829InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
830
831
832int main(int argc, char **argv) {
833 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
834 llvm::sys::PrintStackTraceOnErrorSignal();
835
836 // If no input was specified, read from stdin.
837 if (InputFilenames.empty())
838 InputFilenames.push_back("-");
839
840 /// Create a SourceManager object. This tracks and owns all the file buffers
841 /// allocated to the program.
842 SourceManager SourceMgr;
843
844 // Create a file manager object to provide access to and cache the filesystem.
845 FileManager FileMgr;
846
847 // Initialize language options, inferring file types from input filenames.
848 // FIXME: This infers info from the first file, we should clump by language
849 // to handle 'x.c y.c a.cpp b.cpp'.
850 LangOptions LangInfo;
851 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
852 InitializeLanguageStandard(LangInfo);
853
854 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000855 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 // Print diagnostics to stderr by default.
857 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
858 } else {
859 // When checking diagnostics, just buffer them up.
860 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
861
862 if (InputFilenames.size() != 1) {
863 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000864 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 return 1;
866 }
867 }
868
869 // Configure our handling of diagnostics.
870 Diagnostic Diags(*DiagClient);
871 InitializeDiagnostics(Diags);
872
873 // Get information about the targets being compiled for. Note that this
874 // pointer and the TargetInfoImpl objects are never deleted by this toy
875 // driver.
876 TargetInfo *Target = CreateTargetInfo(Diags);
877 if (Target == 0) {
878 fprintf(stderr,
879 "Sorry, don't know what target this is, please use -arch.\n");
880 exit(1);
881 }
882
883 // Process the -I options and set them in the HeaderInfo.
884 HeaderSearch HeaderInfo(FileMgr);
885 DiagClient->setHeaderSearch(HeaderInfo);
886 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
887
888 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
889 // Set up the preprocessor with these options.
890 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
891 DiagClient->setPreprocessor(PP);
892 const std::string &InFile = InputFilenames[i];
Chris Lattner53b0dab2007-10-09 22:10:18 +0000893 std::vector<char> PredefineBuffer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
895 HeaderInfo, LangInfo,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000896 PredefineBuffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000897
898 if (!MainFileID) continue;
899
900 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
901 *DiagClient, HeaderInfo, LangInfo);
902 HeaderInfo.ClearFileInfo();
903 }
904
905 unsigned NumDiagnostics = Diags.getNumDiagnostics();
906
907 if (NumDiagnostics)
908 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
909 (NumDiagnostics == 1 ? "" : "s"));
910
911 if (Stats) {
912 // Printed from high-to-low level.
913 SourceMgr.PrintStats();
914 FileMgr.PrintStats();
915 fprintf(stderr, "\n");
916 }
917
Chris Lattner96f1a642007-07-21 05:40:53 +0000918 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000919}