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