blob: 77779f7e80e78c02a757d04be56d6274e4c47b1b [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 {
Chris Lattner77cd2a02007-10-11 00:43:27 +000052 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000053 EmitLLVM, // Emit a .ll file.
Chris Lattner3b427b32007-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 Kremenekfddd5182007-08-21 21:42:03 +000057 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000058 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000059 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000060 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000061 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000062 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000063 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner3b427b32007-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 Lattnerea254db2007-10-11 00:37:43 +000092 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +000093 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +000094 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +000095 "Run parser, then build and print CFGs."),
96 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +000097 "Run parser, then build and view CFGs with Graphviz."),
98 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +000099 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000100 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000101 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000102 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000103 "Flag warnings of uses of unitialized variables."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000104 clEnumValN(TestSerialization, "test-pickling",
105 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000107 "Build ASTs then convert to LLVM, emit .ll file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000108 clEnumValN(RewriteTest, "rewrite-test",
109 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 clEnumValEnd));
111
Ted Kremenek41193e42007-09-26 19:42:19 +0000112static llvm::cl::opt<bool>
113VerifyDiagnostics("verify",
114 llvm::cl::desc("Verify emitted diagnostics and warnings."));
115
Reid Spencer5f016e22007-07-11 17:01:13 +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,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000238 lang_cxx98, lang_gnucxx98,
239 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000240};
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++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000265 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++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 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 Carlssonee98ac52007-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"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000281// FIXME: add:
282// -ansi
283// -trigraphs
284// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000285// -fpascal-strings
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000311 case lang_gnucxx0x:
312 case lang_cxx0x:
313 Options.CPlusPlus0x = 1;
314 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 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 Carlssonee98ac52007-10-15 02:50:23 +0000336 Options.PascalStrings = PascalStrings;
Reid Spencer5f016e22007-07-11 17:01:13 +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
Reid Spencer5f016e22007-07-11 17:01:13 +0000359/// InitializeDiagnostics - Initialize the diagnostic object, based on the
360/// current command line option settings.
361static void InitializeDiagnostics(Diagnostic &Diags) {
362 Diags.setWarningsAsErrors(WarningsAsErrors);
363 Diags.setWarnOnExtensions(WarnOnExtensions);
364 Diags.setErrorOnExtensions(ErrorOnExtensions);
365
366 // Silence the "macro is not used" warning unless requested.
367 if (!WarnUnusedMacros)
368 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
369}
370
371//===----------------------------------------------------------------------===//
372// Preprocessor Initialization
373//===----------------------------------------------------------------------===//
374
375// FIXME: Preprocessor builtins to support.
376// -A... - Play with #assertions
377// -undef - Undefine all predefined macros
378
379static llvm::cl::list<std::string>
380D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
381 llvm::cl::desc("Predefine the specified macro"));
382static llvm::cl::list<std::string>
383U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
384 llvm::cl::desc("Undefine the specified macro"));
385
386// Append a #define line to Buf for Macro. Macro should be of the form XXX,
387// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
388// "#define XXX Y z W". To get a #define with no value, use "XXX=".
389static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
390 const char *Command = "#define ") {
391 Buf.insert(Buf.end(), Command, Command+strlen(Command));
392 if (const char *Equal = strchr(Macro, '=')) {
393 // Turn the = into ' '.
394 Buf.insert(Buf.end(), Macro, Equal);
395 Buf.push_back(' ');
396 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
397 } else {
398 // Push "macroname 1".
399 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
400 Buf.push_back(' ');
401 Buf.push_back('1');
402 }
403 Buf.push_back('\n');
404}
405
Reid Spencer5f016e22007-07-11 17:01:13 +0000406
Chris Lattner53b0dab2007-10-09 22:10:18 +0000407/// InitializePreprocessor - Initialize the preprocessor getting it and the
408/// environment ready to process a single file. This returns the file ID for the
409/// input file. If a failure happens, it returns 0.
410///
411static unsigned InitializePreprocessor(Preprocessor &PP,
412 const std::string &InFile,
413 SourceManager &SourceMgr,
414 HeaderSearch &HeaderInfo,
415 const LangOptions &LangInfo,
416 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000417
Chris Lattner53b0dab2007-10-09 22:10:18 +0000418 FileManager &FileMgr = HeaderInfo.getFileMgr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000419
Chris Lattner53b0dab2007-10-09 22:10:18 +0000420 // Figure out where to get and map in the main file.
421 unsigned MainFileID = 0;
422 if (InFile != "-") {
423 const FileEntry *File = FileMgr.getFile(InFile);
424 if (File) MainFileID = SourceMgr.createFileID(File, SourceLocation());
425 if (MainFileID == 0) {
426 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
427 return 0;
428 }
429 } else {
430 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
431 if (SB) MainFileID = SourceMgr.createFileIDForMemBuffer(SB);
432 if (MainFileID == 0) {
433 fprintf(stderr, "Error reading standard input! Empty?\n");
434 return 0;
435 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 }
437
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 // Add macros from the command line.
439 // FIXME: Should traverse the #define/#undef lists in parallel.
440 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000441 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000443 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
444
445 // FIXME: Read any files specified by -imacros or -include.
446
447 // Null terminate PredefinedBuffer and add it.
448 PredefineBuffer.push_back(0);
449 PP.setPredefines(&PredefineBuffer[0]);
450
451 // Once we've read this, we're done.
452 return MainFileID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000453}
Chris Lattner53b0dab2007-10-09 22:10:18 +0000454
455
Reid Spencer5f016e22007-07-11 17:01:13 +0000456
457//===----------------------------------------------------------------------===//
458// Preprocessor include path information.
459//===----------------------------------------------------------------------===//
460
461// This tool exports a large number of command line options to control how the
462// preprocessor searches for header files. At root, however, the Preprocessor
463// object takes a very simple interface: a list of directories to search for
464//
465// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000466// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000467//
468// FIXME: -include,-imacros
469
470static llvm::cl::opt<bool>
471nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
472
473// Various command line options. These four add directories to each chain.
474static llvm::cl::list<std::string>
475F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
476 llvm::cl::desc("Add directory to framework include search path"));
477static llvm::cl::list<std::string>
478I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
479 llvm::cl::desc("Add directory to include search path"));
480static llvm::cl::list<std::string>
481idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
482 llvm::cl::desc("Add directory to AFTER include search path"));
483static llvm::cl::list<std::string>
484iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
485 llvm::cl::desc("Add directory to QUOTE include search path"));
486static llvm::cl::list<std::string>
487isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
488 llvm::cl::desc("Add directory to SYSTEM include search path"));
489
490// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
491static llvm::cl::list<std::string>
492iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
493 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
494static llvm::cl::list<std::string>
495iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
496 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
497static llvm::cl::list<std::string>
498iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
499 llvm::cl::Prefix,
500 llvm::cl::desc("Set directory to include search path with prefix"));
501
Chris Lattner0c946412007-08-26 17:47:35 +0000502static llvm::cl::opt<std::string>
503isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
504 llvm::cl::desc("Set the system root directory (usually /)"));
505
Reid Spencer5f016e22007-07-11 17:01:13 +0000506// Finally, implement the code that groks the options above.
507enum IncludeDirGroup {
508 Quoted = 0,
509 Angled,
510 System,
511 After
512};
513
514static std::vector<DirectoryLookup> IncludeGroup[4];
515
516/// AddPath - Add the specified path to the specified group list.
517///
518static void AddPath(const std::string &Path, IncludeDirGroup Group,
519 bool isCXXAware, bool isUserSupplied,
520 bool isFramework, FileManager &FM) {
Chris Lattner0c946412007-08-26 17:47:35 +0000521 const DirectoryEntry *DE;
522 if (Group == System)
523 DE = FM.getDirectory(isysroot + "/" + Path);
524 else
525 DE = FM.getDirectory(Path);
526
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 if (DE == 0) {
528 if (Verbose)
529 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n",
530 Path.c_str());
531 return;
532 }
533
534 DirectoryLookup::DirType Type;
535 if (Group == Quoted || Group == Angled)
536 Type = DirectoryLookup::NormalHeaderDir;
537 else if (isCXXAware)
538 Type = DirectoryLookup::SystemHeaderDir;
539 else
540 Type = DirectoryLookup::ExternCSystemHeaderDir;
541
542 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
543 isFramework));
544}
545
546/// RemoveDuplicates - If there are duplicate directory entries in the specified
547/// search list, remove the later (dead) ones.
548static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
549 std::set<const DirectoryEntry *> SeenDirs;
550 for (unsigned i = 0; i != SearchList.size(); ++i) {
551 // If this isn't the first time we've seen this dir, remove it.
552 if (!SeenDirs.insert(SearchList[i].getDir()).second) {
553 if (Verbose)
554 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
555 SearchList[i].getDir()->getName());
556 SearchList.erase(SearchList.begin()+i);
557 --i;
558 }
559 }
560}
561
562/// InitializeIncludePaths - Process the -I options and set them in the
563/// HeaderSearch object.
564static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
565 Diagnostic &Diags, const LangOptions &Lang) {
566 // Handle -F... options.
567 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
568 AddPath(F_dirs[i], Angled, false, true, true, FM);
569
570 // Handle -I... options.
571 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
572 if (I_dirs[i] == "-") {
573 // -I- is a deprecated GCC feature.
574 Diags.Report(SourceLocation(), diag::err_pp_I_dash_not_supported);
575 } else {
576 AddPath(I_dirs[i], Angled, false, true, false, FM);
577 }
578 }
579
580 // Handle -idirafter... options.
581 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
582 AddPath(idirafter_dirs[i], After, false, true, false, FM);
583
584 // Handle -iquote... options.
585 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
586 AddPath(iquote_dirs[i], Quoted, false, true, false, FM);
587
588 // Handle -isystem... options.
589 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
590 AddPath(isystem_dirs[i], System, false, true, false, FM);
591
592 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
593 // parallel, processing the values in order of occurance to get the right
594 // prefixes.
595 {
596 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
597 unsigned iprefix_idx = 0;
598 unsigned iwithprefix_idx = 0;
599 unsigned iwithprefixbefore_idx = 0;
600 bool iprefix_done = iprefix_vals.empty();
601 bool iwithprefix_done = iwithprefix_vals.empty();
602 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
603 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
604 if (!iprefix_done &&
605 (iwithprefix_done ||
606 iprefix_vals.getPosition(iprefix_idx) <
607 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
608 (iwithprefixbefore_done ||
609 iprefix_vals.getPosition(iprefix_idx) <
610 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
611 Prefix = iprefix_vals[iprefix_idx];
612 ++iprefix_idx;
613 iprefix_done = iprefix_idx == iprefix_vals.size();
614 } else if (!iwithprefix_done &&
615 (iwithprefixbefore_done ||
616 iwithprefix_vals.getPosition(iwithprefix_idx) <
617 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
618 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
619 System, false, false, false, FM);
620 ++iwithprefix_idx;
621 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
622 } else {
623 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
624 Angled, false, false, false, FM);
625 ++iwithprefixbefore_idx;
626 iwithprefixbefore_done =
627 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
628 }
629 }
630 }
631
632 // FIXME: Add contents of the CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH,
633 // OBJC_INCLUDE_PATH, OBJCPLUS_INCLUDE_PATH environment variables.
634
635 // FIXME: temporary hack: hard-coded paths.
636 // FIXME: get these from the target?
637 if (!nostdinc) {
638 if (Lang.CPlusPlus) {
639 AddPath("/usr/include/c++/4.0.0", System, true, false, false, FM);
640 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
641 false, FM);
642 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,FM);
643 }
644
645 AddPath("/usr/local/include", System, false, false, false, FM);
646 // leopard
647 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
648 false, false, false, FM);
649 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
650 System, false, false, false, FM);
651 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
652 "4.0.1/../../../../powerpc-apple-darwin0/include",
653 System, false, false, false, FM);
654
655 // tiger
656 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
657 false, false, false, FM);
658 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
659 System, false, false, false, FM);
660 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
661 "4.0.1/../../../../powerpc-apple-darwin8/include",
662 System, false, false, false, FM);
663
664 AddPath("/usr/include", System, false, false, false, FM);
665 AddPath("/System/Library/Frameworks", System, true, false, true, FM);
666 AddPath("/Library/Frameworks", System, true, false, true, FM);
667 }
668
669 // Now that we have collected all of the include paths, merge them all
670 // together and tell the preprocessor about them.
671
672 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
673 std::vector<DirectoryLookup> SearchList;
674 SearchList = IncludeGroup[Angled];
675 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
676 IncludeGroup[System].end());
677 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
678 IncludeGroup[After].end());
679 RemoveDuplicates(SearchList);
680 RemoveDuplicates(IncludeGroup[Quoted]);
681
682 // Prepend QUOTED list on the search list.
683 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
684 IncludeGroup[Quoted].end());
685
686
687 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
688 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
689 DontSearchCurDir);
690
691 // If verbose, print the list of directories that will be searched.
692 if (Verbose) {
693 fprintf(stderr, "#include \"...\" search starts here:\n");
694 unsigned QuotedIdx = IncludeGroup[Quoted].size();
695 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
696 if (i == QuotedIdx)
697 fprintf(stderr, "#include <...> search starts here:\n");
698 fprintf(stderr, " %s\n", SearchList[i].getDir()->getName());
699 }
700 }
701}
702
703
Reid Spencer5f016e22007-07-11 17:01:13 +0000704//===----------------------------------------------------------------------===//
705// Basic Parser driver
706//===----------------------------------------------------------------------===//
707
708static void ParseFile(Preprocessor &PP, MinimalAction *PA, unsigned MainFileID){
709 Parser P(PP, *PA);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000710 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000711
712 // Parsing the specified input file.
713 P.ParseTranslationUnit();
714 delete PA;
715}
716
717//===----------------------------------------------------------------------===//
718// Main driver
719//===----------------------------------------------------------------------===//
720
Reid Spencer5f016e22007-07-11 17:01:13 +0000721/// ProcessInputFile - Process a single input file with the specified state.
722///
723static void ProcessInputFile(Preprocessor &PP, unsigned MainFileID,
724 const std::string &InFile,
725 SourceManager &SourceMgr,
726 TextDiagnostics &OurDiagnosticClient,
727 HeaderSearch &HeaderInfo,
728 const LangOptions &LangInfo) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000729
730 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +0000731 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000732
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 switch (ProgAction) {
734 default:
735 fprintf(stderr, "Unexpected program action!\n");
736 return;
737 case DumpTokens: { // Token dump mode.
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);
743 PP.DumpToken(Tok, true);
744 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000745 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000746 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 break;
748 }
749 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +0000750 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 // Start parsing the specified input file.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000752 PP.EnterMainSourceFile(MainFileID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 do {
754 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +0000755 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000756 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 break;
758 }
759
760 case PrintPreprocessedInput: // -E mode.
761 DoPrintPreprocessedInput(MainFileID, PP, LangInfo);
Chris Lattnerbd247762007-07-22 06:05:44 +0000762 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 break;
764
765 case ParseNoop: // -parse-noop
Steve Naroffb4292f22007-10-31 20:55:39 +0000766 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()), MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000767 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000768 break;
769
770 case ParsePrintCallbacks:
Steve Naroffb4292f22007-10-31 20:55:39 +0000771 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()),
772 MainFileID);
Chris Lattnerbd247762007-07-22 06:05:44 +0000773 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 break;
Ted Kremenek44579782007-09-25 18:37:20 +0000775
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000776 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000777 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +0000778 break;
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000779
Chris Lattner3b427b32007-10-11 00:18:28 +0000780 case ASTPrint:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000781 Consumer = CreateASTPrinter();
782 break;
783
Chris Lattner3b427b32007-10-11 00:18:28 +0000784 case ASTDump:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000785 Consumer = CreateASTDumper();
786 break;
787
Chris Lattner3b427b32007-10-11 00:18:28 +0000788 case ASTView:
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000789 Consumer = CreateASTViewer();
790 break;
791
792 case ParseCFGDump:
793 case ParseCFGView:
794 Consumer = CreateCFGDumper(ProgAction == ParseCFGView);
795 break;
796
797 case AnalysisLiveVariables:
798 Consumer = CreateLiveVarAnalyzer();
799 break;
800
801 case WarnDeadStores:
802 Consumer = CreateDeadStoreChecker(PP.getDiagnostics());
803 break;
804
805 case WarnUninitVals:
806 Consumer = CreateUnitValsChecker(PP.getDiagnostics());
807 break;
808
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000809 case TestSerialization:
810 Consumer = CreateSerializationTest();
811 break;
812
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000813 case EmitLLVM:
814 Consumer = CreateLLVMEmitter(PP.getDiagnostics());
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 break;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000816
817 case RewriteTest:
818 Consumer = CreateCodeRewriterTest();
819 break;
Chris Lattner580980b2007-09-16 19:46:59 +0000820 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000821
822 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000823 if (VerifyDiagnostics)
Ted Kremenekd39bcd82007-09-26 18:39:29 +0000824 exit (CheckASTConsumer(PP, MainFileID, Consumer));
825 else
826 ParseAST(PP, MainFileID, *Consumer, Stats);
827
828 delete Consumer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 }
830
831 if (Stats) {
832 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
833 PP.PrintStats();
834 PP.getIdentifierTable().PrintStats();
835 HeaderInfo.PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +0000836 if (ClearSourceMgr)
837 SourceMgr.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 fprintf(stderr, "\n");
839 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000840
841 // For a multi-file compilation, some things are ok with nuking the source
842 // manager tables, other require stable fileid/macroid's across multiple
843 // files.
844 if (ClearSourceMgr) {
845 SourceMgr.clearIDTables();
846 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000847}
848
849static llvm::cl::list<std::string>
850InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
851
852
853int main(int argc, char **argv) {
854 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
855 llvm::sys::PrintStackTraceOnErrorSignal();
856
857 // If no input was specified, read from stdin.
858 if (InputFilenames.empty())
859 InputFilenames.push_back("-");
860
861 /// Create a SourceManager object. This tracks and owns all the file buffers
862 /// allocated to the program.
863 SourceManager SourceMgr;
864
865 // Create a file manager object to provide access to and cache the filesystem.
866 FileManager FileMgr;
867
868 // Initialize language options, inferring file types from input filenames.
869 // FIXME: This infers info from the first file, we should clump by language
870 // to handle 'x.c y.c a.cpp b.cpp'.
871 LangOptions LangInfo;
872 InitializeBaseLanguage(LangInfo, InputFilenames[0]);
873 InitializeLanguageStandard(LangInfo);
874
875 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000876 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // Print diagnostics to stderr by default.
878 DiagClient.reset(new TextDiagnosticPrinter(SourceMgr));
879 } else {
880 // When checking diagnostics, just buffer them up.
881 DiagClient.reset(new TextDiagnosticBuffer(SourceMgr));
882
883 if (InputFilenames.size() != 1) {
884 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +0000885 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 return 1;
887 }
888 }
889
890 // Configure our handling of diagnostics.
891 Diagnostic Diags(*DiagClient);
892 InitializeDiagnostics(Diags);
893
894 // Get information about the targets being compiled for. Note that this
895 // pointer and the TargetInfoImpl objects are never deleted by this toy
896 // driver.
897 TargetInfo *Target = CreateTargetInfo(Diags);
898 if (Target == 0) {
899 fprintf(stderr,
900 "Sorry, don't know what target this is, please use -arch.\n");
901 exit(1);
902 }
903
904 // Process the -I options and set them in the HeaderInfo.
905 HeaderSearch HeaderInfo(FileMgr);
906 DiagClient->setHeaderSearch(HeaderInfo);
907 InitializeIncludePaths(HeaderInfo, FileMgr, Diags, LangInfo);
908
909 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
910 // Set up the preprocessor with these options.
911 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 const std::string &InFile = InputFilenames[i];
Chris Lattner53b0dab2007-10-09 22:10:18 +0000913 std::vector<char> PredefineBuffer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 unsigned MainFileID = InitializePreprocessor(PP, InFile, SourceMgr,
915 HeaderInfo, LangInfo,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000916 PredefineBuffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000917
918 if (!MainFileID) continue;
919
920 ProcessInputFile(PP, MainFileID, InFile, SourceMgr,
921 *DiagClient, HeaderInfo, LangInfo);
922 HeaderInfo.ClearFileInfo();
923 }
924
925 unsigned NumDiagnostics = Diags.getNumDiagnostics();
926
927 if (NumDiagnostics)
928 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
929 (NumDiagnostics == 1 ? "" : "s"));
930
931 if (Stats) {
932 // Printed from high-to-low level.
933 SourceMgr.PrintStats();
934 FileMgr.PrintStats();
935 fprintf(stderr, "\n");
936 }
937
Chris Lattner96f1a642007-07-21 05:40:53 +0000938 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000939}