blob: 2bf99f8eafb35ed546bf407fe3f180f785f81444 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenekac881932007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000035#include "clang/Parse/Parser.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Basic/FileManager.h"
38#include "clang/Basic/SourceManager.h"
39#include "clang/Basic/TargetInfo.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner4b009652007-07-25 00:24:17 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenek40499482007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include <memory>
Chris Lattner8d72ee02008-02-06 01:42:25 +000050#include <fstream>
Chris Lattner4b009652007-07-25 00:24:17 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Global options.
55//===----------------------------------------------------------------------===//
56
57static llvm::cl::opt<bool>
58Verbose("v", llvm::cl::desc("Enable verbose output"));
59static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000060Stats("print-stats",
61 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000062
63enum ProgActions {
Chris Lattnerb429ae42007-10-11 00:43:27 +000064 RewriteTest, // Rewriter testing stuff.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000065 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000066 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000067 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000068 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000069 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000070 ASTPrint, // Parse ASTs and print them.
71 ASTDump, // Parse ASTs and dump them.
72 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek97f75312007-08-21 21:42:03 +000073 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000074 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000075 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek1da5b142008-02-15 00:35:38 +000076 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
77 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek827f93b2008-03-06 00:08:09 +000078 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000079 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000080 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000081 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000082 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000083 ParsePrintCallbacks, // Parse and print each callback.
84 ParseSyntaxOnly, // Parse and perform semantic analysis.
85 ParseNoop, // Parse with noop callbacks.
86 RunPreprocessorOnly, // Just lex, no output.
87 PrintPreprocessedInput, // -E mode.
88 DumpTokens // Token dump mode.
89};
90
91static llvm::cl::opt<ProgActions>
92ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
93 llvm::cl::init(ParseSyntaxOnly),
94 llvm::cl::values(
95 clEnumValN(RunPreprocessorOnly, "Eonly",
96 "Just run preprocessor, no output (for timings)"),
97 clEnumValN(PrintPreprocessedInput, "E",
98 "Run preprocessor, emit preprocessed file"),
99 clEnumValN(DumpTokens, "dumptokens",
100 "Run preprocessor, dump internal rep of tokens"),
101 clEnumValN(ParseNoop, "parse-noop",
102 "Run parser with noop callbacks (for timings)"),
103 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
104 "Run parser and perform semantic analysis"),
105 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
106 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000107 clEnumValN(EmitHTML, "emit-html",
108 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000109 clEnumValN(ASTPrint, "ast-print",
110 "Build ASTs and then pretty-print them"),
111 clEnumValN(ASTDump, "ast-dump",
112 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000113 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +0000114 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +0000115 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000116 "Run parser, then build and print CFGs."),
117 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +0000118 "Run parser, then build and view CFGs with Graphviz."),
119 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +0000120 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000121 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000122 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000123 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000124 "Flag warnings of uses of unitialized variables."),
Ted Kremenek3862eb12008-02-14 22:36:46 +0000125 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner2528b5e2008-01-10 01:41:55 +0000126 "Perform path-sensitive constant propagation."),
Ted Kremenek1da5b142008-02-15 00:35:38 +0000127 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
128 "View results of path-sensitive constant propagation."),
Ted Kremenek827f93b2008-03-06 00:08:09 +0000129 clEnumValN(CheckerCFRef, "check-cfref",
130 "Run the Core Foundation reference count checker."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000131 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerc04cf132008-03-09 05:25:01 +0000132 "Run prototype serialization code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000133 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000134 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000135 clEnumValN(EmitBC, "emit-llvm-bc",
136 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000137 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000138 "Build ASTs and emit .ast file"),
Chris Lattnerb429ae42007-10-11 00:43:27 +0000139 clEnumValN(RewriteTest, "rewrite-test",
140 "Playground for the code rewriter"),
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000141 clEnumValN(HTMLTest, "html-test",
142 "Playground for the HTML displayer"),
Ted Kremenekfd75e312008-03-27 06:17:42 +0000143
Chris Lattner4b009652007-07-25 00:24:17 +0000144 clEnumValEnd));
145
Ted Kremenekd01eae62007-12-19 19:47:59 +0000146
147static llvm::cl::opt<std::string>
148OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000149 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000150 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
151
Ted Kremenek10389cf2007-09-26 19:42:19 +0000152static llvm::cl::opt<bool>
153VerifyDiagnostics("verify",
154 llvm::cl::desc("Verify emitted diagnostics and warnings."));
155
Ted Kremenekfd75e312008-03-27 06:17:42 +0000156static llvm::cl::opt<std::string>
157HTMLDiag("html-diags",
158 llvm::cl::desc("Generate HTML to report diagnostics"),
159 llvm::cl::value_desc("HTML directory"));
160
Chris Lattner4b009652007-07-25 00:24:17 +0000161//===----------------------------------------------------------------------===//
162// Language Options
163//===----------------------------------------------------------------------===//
164
165enum LangKind {
166 langkind_unspecified,
167 langkind_c,
168 langkind_c_cpp,
169 langkind_cxx,
170 langkind_cxx_cpp,
171 langkind_objc,
172 langkind_objc_cpp,
173 langkind_objcxx,
174 langkind_objcxx_cpp
175};
176
177/* TODO: GCC also accepts:
178 c-header c++-header objective-c-header objective-c++-header
179 assembler assembler-with-cpp
180 ada, f77*, ratfor (!), f95, java, treelang
181 */
182static llvm::cl::opt<LangKind>
183BaseLang("x", llvm::cl::desc("Base language to compile"),
184 llvm::cl::init(langkind_unspecified),
185 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
186 clEnumValN(langkind_cxx, "c++", "C++"),
187 clEnumValN(langkind_objc, "objective-c", "Objective C"),
188 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
189 clEnumValN(langkind_c_cpp, "c-cpp-output",
190 "Preprocessed C"),
191 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
192 "Preprocessed C++"),
193 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
194 "Preprocessed Objective C"),
195 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
196 "Preprocessed Objective C++"),
197 clEnumValEnd));
198
199static llvm::cl::opt<bool>
200LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
201 llvm::cl::Hidden);
202static llvm::cl::opt<bool>
203LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
204 llvm::cl::Hidden);
205
Ted Kremenek11ad8952007-12-05 23:49:08 +0000206/// InitializeBaseLanguage - Handle the -x foo options.
207static void InitializeBaseLanguage() {
208 if (LangObjC)
209 BaseLang = langkind_objc;
210 else if (LangObjCXX)
211 BaseLang = langkind_objcxx;
212}
213
214static LangKind GetLanguage(const std::string &Filename) {
215 if (BaseLang != langkind_unspecified)
216 return BaseLang;
217
218 std::string::size_type DotPos = Filename.rfind('.');
219
220 if (DotPos == std::string::npos) {
221 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000222 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000223 }
224
Ted Kremenek11ad8952007-12-05 23:49:08 +0000225 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
226 // C header: .h
227 // C++ header: .hh or .H;
228 // assembler no preprocessing: .s
229 // assembler: .S
230 if (Ext == "c")
231 return langkind_c;
232 else if (Ext == "i")
233 return langkind_c_cpp;
234 else if (Ext == "ii")
235 return langkind_cxx_cpp;
236 else if (Ext == "m")
237 return langkind_objc;
238 else if (Ext == "mi")
239 return langkind_objc_cpp;
240 else if (Ext == "mm" || Ext == "M")
241 return langkind_objcxx;
242 else if (Ext == "mii")
243 return langkind_objcxx_cpp;
244 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
245 Ext == "c++" || Ext == "cp" || Ext == "cxx")
246 return langkind_cxx;
247 else
248 return langkind_c;
249}
250
251
252static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000253 // FIXME: implement -fpreprocessed mode.
254 bool NoPreprocess = false;
255
Ted Kremenek11ad8952007-12-05 23:49:08 +0000256 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000257 default: assert(0 && "Unknown language kind!");
258 case langkind_c_cpp:
259 NoPreprocess = true;
260 // FALLTHROUGH
261 case langkind_c:
262 break;
263 case langkind_cxx_cpp:
264 NoPreprocess = true;
265 // FALLTHROUGH
266 case langkind_cxx:
267 Options.CPlusPlus = 1;
268 break;
269 case langkind_objc_cpp:
270 NoPreprocess = true;
271 // FALLTHROUGH
272 case langkind_objc:
273 Options.ObjC1 = Options.ObjC2 = 1;
274 break;
275 case langkind_objcxx_cpp:
276 NoPreprocess = true;
277 // FALLTHROUGH
278 case langkind_objcxx:
279 Options.ObjC1 = Options.ObjC2 = 1;
280 Options.CPlusPlus = 1;
281 break;
282 }
283}
284
285/// LangStds - Language standards we support.
286enum LangStds {
287 lang_unspecified,
288 lang_c89, lang_c94, lang_c99,
289 lang_gnu89, lang_gnu99,
290 lang_cxx98, lang_gnucxx98,
291 lang_cxx0x, lang_gnucxx0x
292};
293
294static llvm::cl::opt<LangStds>
295LangStd("std", llvm::cl::desc("Language standard to compile for"),
296 llvm::cl::init(lang_unspecified),
297 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
298 clEnumValN(lang_c89, "c90", "ISO C 1990"),
299 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
300 clEnumValN(lang_c94, "iso9899:199409",
301 "ISO C 1990 with amendment 1"),
302 clEnumValN(lang_c99, "c99", "ISO C 1999"),
303// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
304 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
305// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
306 clEnumValN(lang_gnu89, "gnu89",
307 "ISO C 1990 with GNU extensions (default for C)"),
308 clEnumValN(lang_gnu99, "gnu99",
309 "ISO C 1999 with GNU extensions"),
310 clEnumValN(lang_gnu99, "gnu9x",
311 "ISO C 1999 with GNU extensions"),
312 clEnumValN(lang_cxx98, "c++98",
313 "ISO C++ 1998 with amendments"),
314 clEnumValN(lang_gnucxx98, "gnu++98",
315 "ISO C++ 1998 with amendments and GNU "
316 "extensions (default for C++)"),
317 clEnumValN(lang_cxx0x, "c++0x",
318 "Upcoming ISO C++ 200x with amendments"),
319 clEnumValN(lang_gnucxx0x, "gnu++0x",
320 "Upcoming ISO C++ 200x with amendments and GNU "
321 "extensions (default for C++)"),
322 clEnumValEnd));
323
324static llvm::cl::opt<bool>
325NoOperatorNames("fno-operator-names",
326 llvm::cl::desc("Do not treat C++ operator name keywords as "
327 "synonyms for operators"));
328
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000329static llvm::cl::opt<bool>
330PascalStrings("fpascal-strings",
331 llvm::cl::desc("Recognize and construct Pascal-style "
332 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000333
334static llvm::cl::opt<bool>
335MSExtensions("fms-extensions",
336 llvm::cl::desc("Accept some non-standard constructs used in "
337 "Microsoft header files. "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000338
339static llvm::cl::opt<bool>
340WritableStrings("fwritable-strings",
341 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000342
343static llvm::cl::opt<bool>
344LaxVectorConversions("flax-vector-conversions",
345 llvm::cl::desc("Allow implicit conversions between vectors"
346 " with a different number of elements or "
347 "different element types."));
Chris Lattner4b009652007-07-25 00:24:17 +0000348// FIXME: add:
349// -ansi
350// -trigraphs
351// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000352// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000353static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000354 if (LangStd == lang_unspecified) {
355 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000356 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000357 default: assert(0 && "Unknown base language");
358 case langkind_c:
359 case langkind_c_cpp:
360 case langkind_objc:
361 case langkind_objc_cpp:
362 LangStd = lang_gnu99;
363 break;
364 case langkind_cxx:
365 case langkind_cxx_cpp:
366 case langkind_objcxx:
367 case langkind_objcxx_cpp:
368 LangStd = lang_gnucxx98;
369 break;
370 }
371 }
372
373 switch (LangStd) {
374 default: assert(0 && "Unknown language standard!");
375
376 // Fall through from newer standards to older ones. This isn't really right.
377 // FIXME: Enable specifically the right features based on the language stds.
378 case lang_gnucxx0x:
379 case lang_cxx0x:
380 Options.CPlusPlus0x = 1;
381 // FALL THROUGH
382 case lang_gnucxx98:
383 case lang_cxx98:
384 Options.CPlusPlus = 1;
385 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000386 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000387 // FALL THROUGH.
388 case lang_gnu99:
389 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000390 Options.C99 = 1;
391 Options.HexFloats = 1;
392 // FALL THROUGH.
393 case lang_gnu89:
394 Options.BCPLComment = 1; // Only for C99/C++.
395 // FALL THROUGH.
396 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000397 Options.Digraphs = 1; // C94, C99, C++.
398 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000399 case lang_c89:
400 break;
401 }
402
403 Options.Trigraphs = 1; // -trigraphs or -ansi
404 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000405 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000406 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000407 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000408 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000409}
410
411//===----------------------------------------------------------------------===//
412// Our DiagnosticClient implementation
413//===----------------------------------------------------------------------===//
414
415// FIXME: Werror should take a list of things, -Werror=foo,bar
416static llvm::cl::opt<bool>
417WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
418
419static llvm::cl::opt<bool>
420WarnOnExtensions("pedantic", llvm::cl::init(false),
421 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
422
423static llvm::cl::opt<bool>
424ErrorOnExtensions("pedantic-errors",
425 llvm::cl::desc("Issue an error on uses of GCC extensions"));
426
427static llvm::cl::opt<bool>
428WarnUnusedMacros("Wunused_macros",
429 llvm::cl::desc("Warn for unused macros in the main translation unit"));
430
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000431static llvm::cl::opt<bool>
432WarnFloatEqual("Wfloat-equal",
433 llvm::cl::desc("Warn about equality comparisons of floating point values."));
434
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000435static llvm::cl::opt<bool>
436WarnNoFormatNonLiteral("Wno-format-nonliteral",
437 llvm::cl::desc("Do not warn about non-literal format strings."));
438
Chris Lattnera616ee32008-01-23 17:19:46 +0000439static llvm::cl::opt<bool>
440WarnUndefMacros("Wundef",
441 llvm::cl::desc("Warn on use of undefined macros in #if's"));
442
443
Chris Lattner4b009652007-07-25 00:24:17 +0000444/// InitializeDiagnostics - Initialize the diagnostic object, based on the
445/// current command line option settings.
446static void InitializeDiagnostics(Diagnostic &Diags) {
447 Diags.setWarningsAsErrors(WarningsAsErrors);
448 Diags.setWarnOnExtensions(WarnOnExtensions);
449 Diags.setErrorOnExtensions(ErrorOnExtensions);
450
451 // Silence the "macro is not used" warning unless requested.
452 if (!WarnUnusedMacros)
453 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000454
455 // Silence "floating point comparison" warnings unless requested.
456 if (!WarnFloatEqual)
457 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000458
459 // Silence "format string is not a string literal" warnings if requested
460 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000461 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
462 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000463 if (!WarnUndefMacros)
464 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000465
466 if (MSExtensions) // MS allows unnamed struct/union fields.
467 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000468}
469
470//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000471// Analysis-specific options.
472//===----------------------------------------------------------------------===//
473
474static llvm::cl::opt<std::string>
475AnalyzeSpecificFunction("analyze-function",
476 llvm::cl::desc("Run analysis on specific function."));
477
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000478static llvm::cl::opt<bool>
479TrimGraph("trim-path-graph",
480 llvm::cl::desc("Only show error-related paths in the analysis graph."));
481
482
Ted Kremenek0118bb52008-02-18 21:21:23 +0000483//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000484// Target Triple Processing.
485//===----------------------------------------------------------------------===//
486
487static llvm::cl::opt<std::string>
488TargetTriple("triple",
489 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
490
Chris Lattnerfc457002008-03-05 01:18:20 +0000491static llvm::cl::opt<std::string>
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000492Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenek40499482007-12-03 22:06:55 +0000493
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000494static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000495 // Initialize base triple. If a -triple option has been specified, use
496 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000497 std::string Triple = TargetTriple;
498 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000499
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000500 // If -arch foo was specified, remove the architecture from the triple we have
501 // so far and replace it with the specified one.
502 if (Arch.empty())
503 return Triple;
504
Ted Kremenek40499482007-12-03 22:06:55 +0000505 // Decompose the base triple into "arch" and suffix.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000506 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000507
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000508 if (FirstDashIdx == std::string::npos) {
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000509 fprintf(stderr,
510 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000511 Triple.c_str());
512 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000513 }
Ted Kremenek40499482007-12-03 22:06:55 +0000514
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000515 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenek40499482007-12-03 22:06:55 +0000516}
517
518//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000519// Preprocessor Initialization
520//===----------------------------------------------------------------------===//
521
522// FIXME: Preprocessor builtins to support.
523// -A... - Play with #assertions
524// -undef - Undefine all predefined macros
525
526static llvm::cl::list<std::string>
527D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
528 llvm::cl::desc("Predefine the specified macro"));
529static llvm::cl::list<std::string>
530U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
531 llvm::cl::desc("Undefine the specified macro"));
532
Chris Lattner008da782008-01-10 01:53:41 +0000533static llvm::cl::list<std::string>
534ImplicitIncludes("include", llvm::cl::value_desc("file"),
535 llvm::cl::desc("Include file before parsing"));
536
537
Chris Lattner4b009652007-07-25 00:24:17 +0000538// Append a #define line to Buf for Macro. Macro should be of the form XXX,
539// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
540// "#define XXX Y z W". To get a #define with no value, use "XXX=".
541static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
542 const char *Command = "#define ") {
543 Buf.insert(Buf.end(), Command, Command+strlen(Command));
544 if (const char *Equal = strchr(Macro, '=')) {
545 // Turn the = into ' '.
546 Buf.insert(Buf.end(), Macro, Equal);
547 Buf.push_back(' ');
548 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
549 } else {
550 // Push "macroname 1".
551 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
552 Buf.push_back(' ');
553 Buf.push_back('1');
554 }
555 Buf.push_back('\n');
556}
557
Chris Lattner008da782008-01-10 01:53:41 +0000558/// AddImplicitInclude - Add an implicit #include of the specified file to the
559/// predefines buffer.
560static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
561 const char *Inc = "#include \"";
562 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
563 Buf.insert(Buf.end(), File.begin(), File.end());
564 Buf.push_back('"');
565 Buf.push_back('\n');
566}
567
Chris Lattner4b009652007-07-25 00:24:17 +0000568
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000569/// InitializePreprocessor - Initialize the preprocessor getting it and the
570/// environment ready to process a single file. This returns the file ID for the
571/// input file. If a failure happens, it returns 0.
572///
573static unsigned InitializePreprocessor(Preprocessor &PP,
574 const std::string &InFile,
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000575 std::vector<char> &PredefineBuffer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000576
Chris Lattner968982d2007-12-15 20:48:40 +0000577 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000578
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000579 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000580 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000581 if (InFile != "-") {
582 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000583 if (File) SourceMgr.createMainFileID(File, SourceLocation());
584 if (SourceMgr.getMainFileID() == 0) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000585 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
586 return 0;
587 }
588 } else {
589 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000590 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
591 if (SourceMgr.getMainFileID() == 0) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000592 fprintf(stderr, "Error reading standard input! Empty?\n");
593 return 0;
594 }
Chris Lattner4b009652007-07-25 00:24:17 +0000595 }
596
Chris Lattner4b009652007-07-25 00:24:17 +0000597 // Add macros from the command line.
598 // FIXME: Should traverse the #define/#undef lists in parallel.
599 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000600 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000601 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000602 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
603
Chris Lattner008da782008-01-10 01:53:41 +0000604 // FIXME: Read any files specified by -imacros.
605
606 // Add implicit #includes from -include.
607 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
608 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000609
610 // Null terminate PredefinedBuffer and add it.
611 PredefineBuffer.push_back(0);
612 PP.setPredefines(&PredefineBuffer[0]);
613
614 // Once we've read this, we're done.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +0000615 return SourceMgr.getMainFileID();
Chris Lattner4b009652007-07-25 00:24:17 +0000616}
617
618//===----------------------------------------------------------------------===//
619// Preprocessor include path information.
620//===----------------------------------------------------------------------===//
621
622// This tool exports a large number of command line options to control how the
623// preprocessor searches for header files. At root, however, the Preprocessor
624// object takes a very simple interface: a list of directories to search for
625//
626// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000627// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000628//
Chris Lattner008da782008-01-10 01:53:41 +0000629// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000630
631static llvm::cl::opt<bool>
632nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
633
634// Various command line options. These four add directories to each chain.
635static llvm::cl::list<std::string>
636F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
637 llvm::cl::desc("Add directory to framework include search path"));
638static llvm::cl::list<std::string>
639I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
640 llvm::cl::desc("Add directory to include search path"));
641static llvm::cl::list<std::string>
642idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
643 llvm::cl::desc("Add directory to AFTER include search path"));
644static llvm::cl::list<std::string>
645iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
646 llvm::cl::desc("Add directory to QUOTE include search path"));
647static llvm::cl::list<std::string>
648isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
649 llvm::cl::desc("Add directory to SYSTEM include search path"));
650
651// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
652static llvm::cl::list<std::string>
653iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
654 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
655static llvm::cl::list<std::string>
656iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
657 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
658static llvm::cl::list<std::string>
659iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
660 llvm::cl::Prefix,
661 llvm::cl::desc("Set directory to include search path with prefix"));
662
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000663static llvm::cl::opt<std::string>
664isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
665 llvm::cl::desc("Set the system root directory (usually /)"));
666
Chris Lattner4b009652007-07-25 00:24:17 +0000667// Finally, implement the code that groks the options above.
668enum IncludeDirGroup {
669 Quoted = 0,
670 Angled,
671 System,
672 After
673};
674
675static std::vector<DirectoryLookup> IncludeGroup[4];
676
677/// AddPath - Add the specified path to the specified group list.
678///
679static void AddPath(const std::string &Path, IncludeDirGroup Group,
680 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000681 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000682 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000683 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000684
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000685 // Compute the actual path, taking into consideration -isysroot.
686 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000687
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000688 // Handle isysroot.
689 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000690 // FIXME: Portability. This should be a sys::Path interface, this doesn't
691 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000692 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
693 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000694 }
695
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000696 MappedPath.append(Path.begin(), Path.end());
697
698 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000699 DirectoryLookup::DirType Type;
700 if (Group == Quoted || Group == Angled)
701 Type = DirectoryLookup::NormalHeaderDir;
702 else if (isCXXAware)
703 Type = DirectoryLookup::SystemHeaderDir;
704 else
705 Type = DirectoryLookup::ExternCSystemHeaderDir;
706
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000707
708 // If the directory exists, add it.
709 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
710 &MappedPath[0]+
711 MappedPath.size())) {
712 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
713 isFramework));
714 return;
715 }
716
Chris Lattnerb7426782007-12-17 07:52:39 +0000717 // Check to see if this is an apple-style headermap (which are not allowed to
718 // be frameworks).
719 if (!isFramework) {
720 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
721 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000722 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
723 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000724 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
725 return;
726 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000727 }
728 }
729
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000730 if (Verbose)
731 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000732}
733
734/// RemoveDuplicates - If there are duplicate directory entries in the specified
735/// search list, remove the later (dead) ones.
736static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000737 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000738 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000739 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000740 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000741 if (SearchList[i].isNormalDir()) {
742 // If this isn't the first time we've seen this dir, remove it.
743 if (SeenDirs.insert(SearchList[i].getDir()))
744 continue;
745
Chris Lattner4b009652007-07-25 00:24:17 +0000746 if (Verbose)
747 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
748 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000749 } else if (SearchList[i].isFramework()) {
750 // If this isn't the first time we've seen this framework dir, remove it.
751 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
752 continue;
753
754 if (Verbose)
755 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
756 SearchList[i].getFrameworkDir()->getName());
757
Chris Lattnercf33e932007-12-17 06:44:29 +0000758 } else {
759 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
760 // If this isn't the first time we've seen this headermap, remove it.
761 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
762 continue;
763
764 if (Verbose)
765 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
766 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000767 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000768
769 // This is reached if the current entry is a duplicate.
770 SearchList.erase(SearchList.begin()+i);
771 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000772 }
773}
774
Chris Lattner4f022a72008-03-01 08:07:28 +0000775// AddEnvVarPaths - Add a list of paths from an environment variable to a
776// header search list.
777//
778static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
779 const char* at = getenv(Name);
780 if (!at)
781 return;
782
783 const char* delim = strchr(at, llvm::sys::PathSeparator);
784 while (delim != 0) {
785 if (delim-at == 0)
786 AddPath(".", Angled, false, true, false, Headers);
787 else
788 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
789 true, false, Headers);
790 at = delim + 1;
791 delim = strchr(at, llvm::sys::PathSeparator);
792 }
793 if (*at == 0)
794 AddPath(".", Angled, false, true, false, Headers);
795 else
796 AddPath(at, Angled, false, true, false, Headers);
797}
798
Chris Lattner4b009652007-07-25 00:24:17 +0000799/// InitializeIncludePaths - Process the -I options and set them in the
800/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000801static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
802 FileManager &FM, const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000803 // Handle -F... options.
804 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000805 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000806
807 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000808 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000809 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000810
811 // Handle -idirafter... options.
812 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000813 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000814
815 // Handle -iquote... options.
816 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000817 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000818
819 // Handle -isystem... options.
820 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000821 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000822
823 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
824 // parallel, processing the values in order of occurance to get the right
825 // prefixes.
826 {
827 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
828 unsigned iprefix_idx = 0;
829 unsigned iwithprefix_idx = 0;
830 unsigned iwithprefixbefore_idx = 0;
831 bool iprefix_done = iprefix_vals.empty();
832 bool iwithprefix_done = iwithprefix_vals.empty();
833 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
834 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
835 if (!iprefix_done &&
836 (iwithprefix_done ||
837 iprefix_vals.getPosition(iprefix_idx) <
838 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
839 (iwithprefixbefore_done ||
840 iprefix_vals.getPosition(iprefix_idx) <
841 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
842 Prefix = iprefix_vals[iprefix_idx];
843 ++iprefix_idx;
844 iprefix_done = iprefix_idx == iprefix_vals.size();
845 } else if (!iwithprefix_done &&
846 (iwithprefixbefore_done ||
847 iwithprefix_vals.getPosition(iwithprefix_idx) <
848 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
849 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000850 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000851 ++iwithprefix_idx;
852 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
853 } else {
854 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000855 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000856 ++iwithprefixbefore_idx;
857 iwithprefixbefore_done =
858 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
859 }
860 }
861 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000862
863 AddEnvVarPaths("CPATH", Headers);
864 if (Lang.CPlusPlus && Lang.ObjC1)
865 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
866 else if (Lang.CPlusPlus)
867 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
868 else if (Lang.ObjC1)
869 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
870 else
871 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
872
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000873 // Add the clang headers, which are relative to the clang driver.
874 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000875 llvm::sys::Path::GetMainExecutable(Argv0,
876 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000877 if (!MainExecutablePath.isEmpty()) {
878 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
879 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
880 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
881 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
882 }
883
Chris Lattner4b009652007-07-25 00:24:17 +0000884 // FIXME: temporary hack: hard-coded paths.
885 // FIXME: get these from the target?
886 if (!nostdinc) {
887 if (Lang.CPlusPlus) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000888 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000889 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000890 false, Headers);
891 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
892 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000893
894 // Ubuntu 7.10 - Gutsy Gibbon
895 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
896 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
897 false, Headers);
898 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
899 Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000900 }
901
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000902 AddPath("/usr/local/include", System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000903 // leopard
904 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000905 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000906 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000907 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000908 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
909 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000910 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000911
912 // tiger
913 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000914 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000915 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000916 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000917 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
918 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000919 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000920
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000921 // Ubuntu 7.10 - Gutsy Gibbon
922 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +0000923 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000924
Andrew Lenharth6961ec42008-03-24 21:25:48 +0000925 //Debian testing/lenny x86
926 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
927 false, false, false, Headers);
Andrew Lenharthfccd7be2008-03-24 21:39:05 +0000928
929 //Debian testing/lenny amd64
930 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
931 false, false, false, Headers);
Andrew Lenharth6961ec42008-03-24 21:25:48 +0000932
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000933 AddPath("/usr/include", System, false, false, false, Headers);
934 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
935 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000936 }
937
938 // Now that we have collected all of the include paths, merge them all
939 // together and tell the preprocessor about them.
940
941 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
942 std::vector<DirectoryLookup> SearchList;
943 SearchList = IncludeGroup[Angled];
944 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
945 IncludeGroup[System].end());
946 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
947 IncludeGroup[After].end());
948 RemoveDuplicates(SearchList);
949 RemoveDuplicates(IncludeGroup[Quoted]);
950
951 // Prepend QUOTED list on the search list.
952 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
953 IncludeGroup[Quoted].end());
954
955
956 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
957 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
958 DontSearchCurDir);
959
960 // If verbose, print the list of directories that will be searched.
961 if (Verbose) {
962 fprintf(stderr, "#include \"...\" search starts here:\n");
963 unsigned QuotedIdx = IncludeGroup[Quoted].size();
964 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
965 if (i == QuotedIdx)
966 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +0000967 const char *Name = SearchList[i].getName();
968 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +0000969 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +0000970 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +0000971 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +0000972 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +0000973 else {
974 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +0000975 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +0000976 }
Chris Lattner1df68f92007-12-17 17:57:27 +0000977 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +0000978 }
Chris Lattnerac553842007-12-15 23:11:06 +0000979 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +0000980 }
981}
982
983
Chris Lattner4b009652007-07-25 00:24:17 +0000984//===----------------------------------------------------------------------===//
985// Basic Parser driver
986//===----------------------------------------------------------------------===//
987
Ted Kremenek17861c52007-12-19 22:51:13 +0000988static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Chris Lattner4b009652007-07-25 00:24:17 +0000989 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +0000990 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +0000991
992 // Parsing the specified input file.
993 P.ParseTranslationUnit();
994 delete PA;
995}
996
997//===----------------------------------------------------------------------===//
998// Main driver
999//===----------------------------------------------------------------------===//
1000
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001001/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1002/// action. These consumers can operate on both ASTs that are freshly
1003/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001004static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001005 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001006 const LangOptions& LangOpts,
1007 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001008 switch (ProgAction) {
1009 default:
1010 return NULL;
1011
1012 case ASTPrint:
1013 return CreateASTPrinter();
1014
1015 case ASTDump:
1016 return CreateASTDumper();
1017
1018 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001019 return CreateASTViewer();
1020
1021 case EmitHTML:
1022 return CreateHTMLPrinter();
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001023
Ted Kremeneke1a79d82008-03-19 07:53:42 +00001024 case HTMLTest:
1025 return CreateHTMLTest();
1026
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001027 case ParseCFGDump:
1028 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001029 return CreateCFGDumper(ProgAction == ParseCFGView,
1030 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001031
1032 case AnalysisLiveVariables:
Ted Kremenekb278abb2008-02-22 20:13:09 +00001033 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001034
1035 case WarnDeadStores:
1036 return CreateDeadStoreChecker(Diag);
1037
1038 case WarnUninitVals:
1039 return CreateUnitValsChecker(Diag);
1040
Ted Kremenek3862eb12008-02-14 22:36:46 +00001041 case AnalysisGRSimpleVals:
Ted Kremenek0118bb52008-02-18 21:21:23 +00001042 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremenek3b451132008-01-08 18:04:06 +00001043
Ted Kremenek1da5b142008-02-15 00:35:38 +00001044 case AnalysisGRSimpleValsView:
Ted Kremenek5e1e05c2008-03-07 22:58:01 +00001045 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true, TrimGraph);
Ted Kremenek1da5b142008-02-15 00:35:38 +00001046
Ted Kremenek827f93b2008-03-06 00:08:09 +00001047 case CheckerCFRef:
1048 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction);
1049
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001050 case TestSerialization:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001051 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001052
1053 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001054 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001055 DestModule = new llvm::Module(InFile);
1056 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001057
Ted Kremenekbde30332007-12-19 17:25:59 +00001058 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001059 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001060 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek397de012007-12-13 00:37:31 +00001061
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001062 case RewriteTest:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001063 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001064 }
1065}
1066
Chris Lattner4b009652007-07-25 00:24:17 +00001067/// ProcessInputFile - Process a single input file with the specified state.
1068///
Ted Kremenekfd75e312008-03-27 06:17:42 +00001069static void ProcessInputFile(Preprocessor &PP, const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001070
1071 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001072 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001073 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001074
Chris Lattner4b009652007-07-25 00:24:17 +00001075 switch (ProgAction) {
1076 default:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001077 Consumer = CreateASTConsumer(InFile,
1078 PP.getDiagnostics(),
Chris Lattner968982d2007-12-15 20:48:40 +00001079 PP.getFileManager(),
Chris Lattner8d72ee02008-02-06 01:42:25 +00001080 PP.getLangOptions(),
1081 CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001082
1083 if (!Consumer) {
1084 fprintf(stderr, "Unexpected program action!\n");
1085 return;
1086 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001087
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001088 break;
1089
Chris Lattner4b009652007-07-25 00:24:17 +00001090 case DumpTokens: { // Token dump mode.
1091 Token Tok;
1092 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001093 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001094 do {
1095 PP.Lex(Tok);
1096 PP.DumpToken(Tok, true);
1097 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001098 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001099 ClearSourceMgr = true;
1100 break;
1101 }
1102 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1103 Token Tok;
1104 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001105 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001106 do {
1107 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001108 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001109 ClearSourceMgr = true;
1110 break;
1111 }
1112
1113 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001114 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001115 ClearSourceMgr = true;
1116 break;
1117
1118 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001119 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001120 ClearSourceMgr = true;
1121 break;
1122
1123 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001124 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001125 ClearSourceMgr = true;
1126 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001127
Ted Kremenek6856c632007-09-26 18:39:29 +00001128 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001129 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001130 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001131 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001132
1133 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001134 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001135 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001136
1137 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001138 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001139 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001140
1141 // If running the code generator, finish up now.
1142 if (CodeGenModule) {
1143 std::ostream *Out;
1144 if (OutputFile == "-") {
1145 Out = llvm::cout.stream();
1146 } else if (!OutputFile.empty()) {
1147 Out = new std::ofstream(OutputFile.c_str(),
1148 std::ios_base::binary|std::ios_base::out);
1149 } else if (InFile == "-") {
1150 Out = llvm::cout.stream();
1151 } else {
1152 llvm::sys::Path Path(InFile);
1153 Path.eraseSuffix();
1154 if (ProgAction == EmitLLVM)
1155 Path.appendSuffix("ll");
1156 else if (ProgAction == EmitBC)
1157 Path.appendSuffix("bc");
1158 else
1159 assert(0 && "Unknown action");
1160 Out = new std::ofstream(Path.toString().c_str(),
1161 std::ios_base::binary|std::ios_base::out);
1162 }
1163
1164 if (ProgAction == EmitLLVM) {
1165 CodeGenModule->print(*Out);
1166 } else {
1167 assert(ProgAction == EmitBC);
1168 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1169 }
1170
1171 if (Out != llvm::cout.stream())
1172 delete Out;
1173 delete CodeGenModule;
1174 }
Chris Lattner4b009652007-07-25 00:24:17 +00001175
1176 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001177 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001178 PP.PrintStats();
1179 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001180 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001181 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001182 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001183 fprintf(stderr, "\n");
1184 }
1185
1186 // For a multi-file compilation, some things are ok with nuking the source
1187 // manager tables, other require stable fileid/macroid's across multiple
1188 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001189 if (ClearSourceMgr)
1190 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001191}
1192
Ted Kremenek80d53372007-12-12 23:41:08 +00001193static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1194 FileManager& FileMgr) {
1195
1196 if (VerifyDiagnostics) {
1197 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1198 exit (1);
1199 }
1200
1201 llvm::sys::Path Filename(InFile);
1202
1203 if (!Filename.isValid()) {
1204 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1205 exit (1);
1206 }
1207
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001208 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001209
1210 if (!TU) {
1211 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1212 InFile.c_str());
1213 exit (1);
1214 }
1215
Ted Kremenekab749372007-12-19 19:27:38 +00001216 // Observe that we use the source file name stored in the deserialized
1217 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001218 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001219 llvm::OwningPtr<ASTConsumer>
Chris Lattner8d72ee02008-02-06 01:42:25 +00001220 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1221 DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001222
1223 if (!Consumer) {
1224 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1225 exit (1);
1226 }
1227
Ted Kremenek17861c52007-12-19 22:51:13 +00001228 Consumer->Initialize(*TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001229
Chris Lattner8d72ee02008-02-06 01:42:25 +00001230 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001231 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1232 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001233}
1234
1235
Chris Lattner4b009652007-07-25 00:24:17 +00001236static llvm::cl::list<std::string>
1237InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1238
Ted Kremenek80d53372007-12-12 23:41:08 +00001239static bool isSerializedFile(const std::string& InFile) {
1240 if (InFile.size() < 4)
1241 return false;
1242
1243 const char* s = InFile.c_str()+InFile.size()-4;
1244
1245 return s[0] == '.' &&
1246 s[1] == 'a' &&
1247 s[2] == 's' &&
1248 s[3] == 't';
1249}
1250
Chris Lattner4b009652007-07-25 00:24:17 +00001251
1252int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001253 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001254 llvm::sys::PrintStackTraceOnErrorSignal();
1255
1256 // If no input was specified, read from stdin.
1257 if (InputFilenames.empty())
1258 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001259
Chris Lattner4b009652007-07-25 00:24:17 +00001260 // Create a file manager object to provide access to and cache the filesystem.
1261 FileManager FileMgr;
1262
Ted Kremenekb240e822007-12-11 23:28:38 +00001263 // Create the diagnostic client for reporting errors or for
1264 // implementing -verify.
Ted Kremenekfd75e312008-03-27 06:17:42 +00001265 std::auto_ptr<DiagnosticClient> DiagClient;
1266 TextDiagnostics* TextDiagClient = NULL;
1267
1268 if (!HTMLDiag.empty()) {
1269 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
1270 }
1271 else { // Use Text diagnostics.
1272 if (!VerifyDiagnostics) {
1273 // Print diagnostics to stderr by default.
1274 TextDiagClient = new TextDiagnosticPrinter();
1275 } else {
1276 // When checking diagnostics, just buffer them up.
1277 TextDiagClient = new TextDiagnosticBuffer();
1278
1279 if (InputFilenames.size() != 1) {
1280 fprintf(stderr,
1281 "-verify only works on single input files for now.\n");
1282 return 1;
1283 }
Chris Lattner4b009652007-07-25 00:24:17 +00001284 }
Ted Kremenekfd75e312008-03-27 06:17:42 +00001285
1286 assert (TextDiagClient);
1287 DiagClient.reset(TextDiagClient);
Chris Lattner4b009652007-07-25 00:24:17 +00001288 }
1289
1290 // Configure our handling of diagnostics.
1291 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001292 InitializeDiagnostics(Diags);
1293
Chris Lattner45a56e02007-12-05 23:24:17 +00001294 // -I- is a deprecated GCC feature, scan for it and reject it.
1295 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1296 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001297 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001298 I_dirs.erase(I_dirs.begin()+i);
1299 --i;
1300 }
1301 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001302
1303 // Get information about the target being compiled for.
1304 std::string Triple = CreateTargetTriple();
1305 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1306 if (Target == 0) {
1307 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1308 Triple.c_str());
1309 fprintf(stderr, "Please use -triple or -arch.\n");
1310 exit(1);
1311 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001312
Chris Lattner4b009652007-07-25 00:24:17 +00001313 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001314 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001315
Ted Kremenek80d53372007-12-12 23:41:08 +00001316 if (isSerializedFile(InFile))
1317 ProcessSerializedFile(InFile,Diags,FileMgr);
1318 else {
1319 /// Create a SourceManager object. This tracks and owns all the file
1320 /// buffers allocated to a translation unit.
1321 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001322
Ted Kremenek80d53372007-12-12 23:41:08 +00001323 // Initialize language options, inferring file types from input filenames.
1324 LangOptions LangInfo;
1325 InitializeBaseLanguage();
1326 LangKind LK = GetLanguage(InFile);
1327 InitializeLangOptions(LangInfo, LK);
1328 InitializeLanguageStandard(LangInfo, LK);
1329
1330 // Process the -I options and set them in the HeaderInfo.
1331 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekfd75e312008-03-27 06:17:42 +00001332 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001333 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001334
Ted Kremenek80d53372007-12-12 23:41:08 +00001335 // Set up the preprocessor with these options.
1336 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1337
1338 std::vector<char> PredefineBuffer;
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001339 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek2578dd02007-12-19 22:29:55 +00001340 continue;
1341
Ted Kremenekfd75e312008-03-27 06:17:42 +00001342 ProcessInputFile(PP, InFile);
Ted Kremenek80d53372007-12-12 23:41:08 +00001343 HeaderInfo.ClearFileInfo();
1344
1345 if (Stats)
1346 SourceMgr.PrintStats();
1347 }
Chris Lattner4b009652007-07-25 00:24:17 +00001348 }
1349
Chris Lattner2c77d852008-03-14 06:12:05 +00001350 delete Target;
1351
Chris Lattner4b009652007-07-25 00:24:17 +00001352 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1353
1354 if (NumDiagnostics)
1355 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1356 (NumDiagnostics == 1 ? "" : "s"));
1357
1358 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001359 FileMgr.PrintStats();
1360 fprintf(stderr, "\n");
1361 }
1362
1363 return Diags.getNumErrors() != 0;
1364}