blob: 15cbcae516f3e46d7e27e79e60fbe356de0ac755 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 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"
Ted Kremenek77cda502007-12-18 21:34:28 +000029#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000030#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000031#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000032#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Parse/Parser.h"
34#include "clang/Lex/HeaderSearch.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000038#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000044#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000046#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000048#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000049using namespace clang;
50
51//===----------------------------------------------------------------------===//
52// Global options.
53//===----------------------------------------------------------------------===//
54
55static llvm::cl::opt<bool>
56Verbose("v", llvm::cl::desc("Enable verbose output"));
57static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000058Stats("print-stats",
59 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000060
61enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000063 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000064 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000065 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000066 ASTPrint, // Parse ASTs and print them.
67 ASTDump, // Parse ASTs and dump them.
68 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000069 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000070 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000071 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000072 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
73 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek2fff37e2008-03-06 00:08:09 +000074 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremenek055c2752007-09-06 23:00:42 +000075 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000076 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000077 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000078 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000079 ParsePrintCallbacks, // Parse and print each callback.
80 ParseSyntaxOnly, // Parse and perform semantic analysis.
81 ParseNoop, // Parse with noop callbacks.
82 RunPreprocessorOnly, // Just lex, no output.
83 PrintPreprocessedInput, // -E mode.
84 DumpTokens // Token dump mode.
85};
86
87static llvm::cl::opt<ProgActions>
88ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
89 llvm::cl::init(ParseSyntaxOnly),
90 llvm::cl::values(
91 clEnumValN(RunPreprocessorOnly, "Eonly",
92 "Just run preprocessor, no output (for timings)"),
93 clEnumValN(PrintPreprocessedInput, "E",
94 "Run preprocessor, emit preprocessed file"),
95 clEnumValN(DumpTokens, "dumptokens",
96 "Run preprocessor, dump internal rep of tokens"),
97 clEnumValN(ParseNoop, "parse-noop",
98 "Run parser with noop callbacks (for timings)"),
99 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
100 "Run parser and perform semantic analysis"),
101 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
102 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000103 clEnumValN(ASTPrint, "ast-print",
104 "Build ASTs and then pretty-print them"),
105 clEnumValN(ASTDump, "ast-dump",
106 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000107 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000108 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000109 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000110 "Run parser, then build and print CFGs."),
111 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000112 "Run parser, then build and view CFGs with Graphviz."),
113 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000114 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000115 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000116 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000117 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000118 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke01c9872008-02-14 22:36:46 +0000119 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000120 "Perform path-sensitive constant propagation."),
Ted Kremenekd55fe522008-02-15 00:35:38 +0000121 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
122 "View results of path-sensitive constant propagation."),
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000123 clEnumValN(CheckerCFRef, "check-cfref",
124 "Run the Core Foundation reference count checker."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000125 clEnumValN(TestSerialization, "test-pickling",
126 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000128 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000129 clEnumValN(EmitBC, "emit-llvm-bc",
130 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000131 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000132 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000133 clEnumValN(RewriteTest, "rewrite-test",
134 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 clEnumValEnd));
136
Ted Kremenekccc76472007-12-19 19:47:59 +0000137
138static llvm::cl::opt<std::string>
139OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000140 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000141 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
142
Ted Kremenek41193e42007-09-26 19:42:19 +0000143static llvm::cl::opt<bool>
144VerifyDiagnostics("verify",
145 llvm::cl::desc("Verify emitted diagnostics and warnings."));
146
Reid Spencer5f016e22007-07-11 17:01:13 +0000147//===----------------------------------------------------------------------===//
148// Language Options
149//===----------------------------------------------------------------------===//
150
151enum LangKind {
152 langkind_unspecified,
153 langkind_c,
154 langkind_c_cpp,
155 langkind_cxx,
156 langkind_cxx_cpp,
157 langkind_objc,
158 langkind_objc_cpp,
159 langkind_objcxx,
160 langkind_objcxx_cpp
161};
162
163/* TODO: GCC also accepts:
164 c-header c++-header objective-c-header objective-c++-header
165 assembler assembler-with-cpp
166 ada, f77*, ratfor (!), f95, java, treelang
167 */
168static llvm::cl::opt<LangKind>
169BaseLang("x", llvm::cl::desc("Base language to compile"),
170 llvm::cl::init(langkind_unspecified),
171 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
172 clEnumValN(langkind_cxx, "c++", "C++"),
173 clEnumValN(langkind_objc, "objective-c", "Objective C"),
174 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
175 clEnumValN(langkind_c_cpp, "c-cpp-output",
176 "Preprocessed C"),
177 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
178 "Preprocessed C++"),
179 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
180 "Preprocessed Objective C"),
181 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
182 "Preprocessed Objective C++"),
183 clEnumValEnd));
184
185static llvm::cl::opt<bool>
186LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
187 llvm::cl::Hidden);
188static llvm::cl::opt<bool>
189LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
190 llvm::cl::Hidden);
191
Ted Kremenek8904f152007-12-05 23:49:08 +0000192/// InitializeBaseLanguage - Handle the -x foo options.
193static void InitializeBaseLanguage() {
194 if (LangObjC)
195 BaseLang = langkind_objc;
196 else if (LangObjCXX)
197 BaseLang = langkind_objcxx;
198}
199
200static LangKind GetLanguage(const std::string &Filename) {
201 if (BaseLang != langkind_unspecified)
202 return BaseLang;
203
204 std::string::size_type DotPos = Filename.rfind('.');
205
206 if (DotPos == std::string::npos) {
207 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000208 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 }
210
Ted Kremenek8904f152007-12-05 23:49:08 +0000211 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
212 // C header: .h
213 // C++ header: .hh or .H;
214 // assembler no preprocessing: .s
215 // assembler: .S
216 if (Ext == "c")
217 return langkind_c;
218 else if (Ext == "i")
219 return langkind_c_cpp;
220 else if (Ext == "ii")
221 return langkind_cxx_cpp;
222 else if (Ext == "m")
223 return langkind_objc;
224 else if (Ext == "mi")
225 return langkind_objc_cpp;
226 else if (Ext == "mm" || Ext == "M")
227 return langkind_objcxx;
228 else if (Ext == "mii")
229 return langkind_objcxx_cpp;
230 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
231 Ext == "c++" || Ext == "cp" || Ext == "cxx")
232 return langkind_cxx;
233 else
234 return langkind_c;
235}
236
237
238static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 // FIXME: implement -fpreprocessed mode.
240 bool NoPreprocess = false;
241
Ted Kremenek8904f152007-12-05 23:49:08 +0000242 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 default: assert(0 && "Unknown language kind!");
244 case langkind_c_cpp:
245 NoPreprocess = true;
246 // FALLTHROUGH
247 case langkind_c:
248 break;
249 case langkind_cxx_cpp:
250 NoPreprocess = true;
251 // FALLTHROUGH
252 case langkind_cxx:
253 Options.CPlusPlus = 1;
254 break;
255 case langkind_objc_cpp:
256 NoPreprocess = true;
257 // FALLTHROUGH
258 case langkind_objc:
259 Options.ObjC1 = Options.ObjC2 = 1;
260 break;
261 case langkind_objcxx_cpp:
262 NoPreprocess = true;
263 // FALLTHROUGH
264 case langkind_objcxx:
265 Options.ObjC1 = Options.ObjC2 = 1;
266 Options.CPlusPlus = 1;
267 break;
268 }
269}
270
271/// LangStds - Language standards we support.
272enum LangStds {
273 lang_unspecified,
274 lang_c89, lang_c94, lang_c99,
275 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000276 lang_cxx98, lang_gnucxx98,
277 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000278};
279
280static llvm::cl::opt<LangStds>
281LangStd("std", llvm::cl::desc("Language standard to compile for"),
282 llvm::cl::init(lang_unspecified),
283 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
284 clEnumValN(lang_c89, "c90", "ISO C 1990"),
285 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
286 clEnumValN(lang_c94, "iso9899:199409",
287 "ISO C 1990 with amendment 1"),
288 clEnumValN(lang_c99, "c99", "ISO C 1999"),
289// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
290 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
291// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
292 clEnumValN(lang_gnu89, "gnu89",
293 "ISO C 1990 with GNU extensions (default for C)"),
294 clEnumValN(lang_gnu99, "gnu99",
295 "ISO C 1999 with GNU extensions"),
296 clEnumValN(lang_gnu99, "gnu9x",
297 "ISO C 1999 with GNU extensions"),
298 clEnumValN(lang_cxx98, "c++98",
299 "ISO C++ 1998 with amendments"),
300 clEnumValN(lang_gnucxx98, "gnu++98",
301 "ISO C++ 1998 with amendments and GNU "
302 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000303 clEnumValN(lang_cxx0x, "c++0x",
304 "Upcoming ISO C++ 200x with amendments"),
305 clEnumValN(lang_gnucxx0x, "gnu++0x",
306 "Upcoming ISO C++ 200x with amendments and GNU "
307 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 clEnumValEnd));
309
310static llvm::cl::opt<bool>
311NoOperatorNames("fno-operator-names",
312 llvm::cl::desc("Do not treat C++ operator name keywords as "
313 "synonyms for operators"));
314
Anders Carlssonee98ac52007-10-15 02:50:23 +0000315static llvm::cl::opt<bool>
316PascalStrings("fpascal-strings",
317 llvm::cl::desc("Recognize and construct Pascal-style "
318 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000319
320static llvm::cl::opt<bool>
321MSExtensions("fms-extensions",
322 llvm::cl::desc("Accept some non-standard constructs used in "
323 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000324
325static llvm::cl::opt<bool>
326WritableStrings("fwritable-strings",
327 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000328
329static llvm::cl::opt<bool>
330LaxVectorConversions("flax-vector-conversions",
331 llvm::cl::desc("Allow implicit conversions between vectors"
332 " with a different number of elements or "
333 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000334// FIXME: add:
335// -ansi
336// -trigraphs
337// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000338// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000339static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 if (LangStd == lang_unspecified) {
341 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000342 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 default: assert(0 && "Unknown base language");
344 case langkind_c:
345 case langkind_c_cpp:
346 case langkind_objc:
347 case langkind_objc_cpp:
348 LangStd = lang_gnu99;
349 break;
350 case langkind_cxx:
351 case langkind_cxx_cpp:
352 case langkind_objcxx:
353 case langkind_objcxx_cpp:
354 LangStd = lang_gnucxx98;
355 break;
356 }
357 }
358
359 switch (LangStd) {
360 default: assert(0 && "Unknown language standard!");
361
362 // Fall through from newer standards to older ones. This isn't really right.
363 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000364 case lang_gnucxx0x:
365 case lang_cxx0x:
366 Options.CPlusPlus0x = 1;
367 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 case lang_gnucxx98:
369 case lang_cxx98:
370 Options.CPlusPlus = 1;
371 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000372 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // FALL THROUGH.
374 case lang_gnu99:
375 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 Options.C99 = 1;
377 Options.HexFloats = 1;
378 // FALL THROUGH.
379 case lang_gnu89:
380 Options.BCPLComment = 1; // Only for C99/C++.
381 // FALL THROUGH.
382 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000383 Options.Digraphs = 1; // C94, C99, C++.
384 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 case lang_c89:
386 break;
387 }
388
389 Options.Trigraphs = 1; // -trigraphs or -ansi
390 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000391 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000392 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000393 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000394 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000395}
396
397//===----------------------------------------------------------------------===//
398// Our DiagnosticClient implementation
399//===----------------------------------------------------------------------===//
400
401// FIXME: Werror should take a list of things, -Werror=foo,bar
402static llvm::cl::opt<bool>
403WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
404
405static llvm::cl::opt<bool>
406WarnOnExtensions("pedantic", llvm::cl::init(false),
407 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
408
409static llvm::cl::opt<bool>
410ErrorOnExtensions("pedantic-errors",
411 llvm::cl::desc("Issue an error on uses of GCC extensions"));
412
413static llvm::cl::opt<bool>
414WarnUnusedMacros("Wunused_macros",
415 llvm::cl::desc("Warn for unused macros in the main translation unit"));
416
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000417static llvm::cl::opt<bool>
418WarnFloatEqual("Wfloat-equal",
419 llvm::cl::desc("Warn about equality comparisons of floating point values."));
420
Ted Kremenek73da5902007-12-17 17:50:07 +0000421static llvm::cl::opt<bool>
422WarnNoFormatNonLiteral("Wno-format-nonliteral",
423 llvm::cl::desc("Do not warn about non-literal format strings."));
424
Chris Lattner116a4b12008-01-23 17:19:46 +0000425static llvm::cl::opt<bool>
426WarnUndefMacros("Wundef",
427 llvm::cl::desc("Warn on use of undefined macros in #if's"));
428
429
Reid Spencer5f016e22007-07-11 17:01:13 +0000430/// InitializeDiagnostics - Initialize the diagnostic object, based on the
431/// current command line option settings.
432static void InitializeDiagnostics(Diagnostic &Diags) {
433 Diags.setWarningsAsErrors(WarningsAsErrors);
434 Diags.setWarnOnExtensions(WarnOnExtensions);
435 Diags.setErrorOnExtensions(ErrorOnExtensions);
436
437 // Silence the "macro is not used" warning unless requested.
438 if (!WarnUnusedMacros)
439 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000440
441 // Silence "floating point comparison" warnings unless requested.
442 if (!WarnFloatEqual)
443 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000444
445 // Silence "format string is not a string literal" warnings if requested
446 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000447 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
448 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000449 if (!WarnUndefMacros)
450 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000451
452 if (MSExtensions) // MS allows unnamed struct/union fields.
453 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454}
455
456//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000457// Analysis-specific options.
458//===----------------------------------------------------------------------===//
459
460static llvm::cl::opt<std::string>
461AnalyzeSpecificFunction("analyze-function",
462 llvm::cl::desc("Run analysis on specific function."));
463
Ted Kremenekffe0f432008-03-07 22:58:01 +0000464static llvm::cl::opt<bool>
465TrimGraph("trim-path-graph",
466 llvm::cl::desc("Only show error-related paths in the analysis graph."));
467
468
Ted Kremenekcb330932008-02-18 21:21:23 +0000469//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000470// Target Triple Processing.
471//===----------------------------------------------------------------------===//
472
473static llvm::cl::opt<std::string>
474TargetTriple("triple",
475 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
476
Chris Lattner42e67372008-03-05 01:18:20 +0000477static llvm::cl::opt<std::string>
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000478Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenekae360762007-12-03 22:06:55 +0000479
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000480static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000481 // Initialize base triple. If a -triple option has been specified, use
482 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000483 std::string Triple = TargetTriple;
484 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000485
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000486 // If -arch foo was specified, remove the architecture from the triple we have
487 // so far and replace it with the specified one.
488 if (Arch.empty())
489 return Triple;
490
Ted Kremenekae360762007-12-03 22:06:55 +0000491 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000492 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000493
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000494 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000495 fprintf(stderr,
496 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000497 Triple.c_str());
498 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000499 }
Ted Kremenekae360762007-12-03 22:06:55 +0000500
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000501 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000502}
503
504//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000505// Preprocessor Initialization
506//===----------------------------------------------------------------------===//
507
508// FIXME: Preprocessor builtins to support.
509// -A... - Play with #assertions
510// -undef - Undefine all predefined macros
511
512static llvm::cl::list<std::string>
513D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
514 llvm::cl::desc("Predefine the specified macro"));
515static llvm::cl::list<std::string>
516U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
517 llvm::cl::desc("Undefine the specified macro"));
518
Chris Lattner64299f82008-01-10 01:53:41 +0000519static llvm::cl::list<std::string>
520ImplicitIncludes("include", llvm::cl::value_desc("file"),
521 llvm::cl::desc("Include file before parsing"));
522
523
Reid Spencer5f016e22007-07-11 17:01:13 +0000524// Append a #define line to Buf for Macro. Macro should be of the form XXX,
525// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
526// "#define XXX Y z W". To get a #define with no value, use "XXX=".
527static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
528 const char *Command = "#define ") {
529 Buf.insert(Buf.end(), Command, Command+strlen(Command));
530 if (const char *Equal = strchr(Macro, '=')) {
531 // Turn the = into ' '.
532 Buf.insert(Buf.end(), Macro, Equal);
533 Buf.push_back(' ');
534 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
535 } else {
536 // Push "macroname 1".
537 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
538 Buf.push_back(' ');
539 Buf.push_back('1');
540 }
541 Buf.push_back('\n');
542}
543
Chris Lattner64299f82008-01-10 01:53:41 +0000544/// AddImplicitInclude - Add an implicit #include of the specified file to the
545/// predefines buffer.
546static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
547 const char *Inc = "#include \"";
548 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
549 Buf.insert(Buf.end(), File.begin(), File.end());
550 Buf.push_back('"');
551 Buf.push_back('\n');
552}
553
Reid Spencer5f016e22007-07-11 17:01:13 +0000554
Chris Lattner53b0dab2007-10-09 22:10:18 +0000555/// InitializePreprocessor - Initialize the preprocessor getting it and the
556/// environment ready to process a single file. This returns the file ID for the
557/// input file. If a failure happens, it returns 0.
558///
559static unsigned InitializePreprocessor(Preprocessor &PP,
560 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000561 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000562
Chris Lattnerdee73592007-12-15 20:48:40 +0000563 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000564
Chris Lattner53b0dab2007-10-09 22:10:18 +0000565 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000566 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000567 if (InFile != "-") {
568 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000569 if (File) SourceMgr.createMainFileID(File, SourceLocation());
570 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000571 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
572 return 0;
573 }
574 } else {
575 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000576 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
577 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000578 fprintf(stderr, "Error reading standard input! Empty?\n");
579 return 0;
580 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 }
582
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 // Add macros from the command line.
584 // FIXME: Should traverse the #define/#undef lists in parallel.
585 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000586 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000588 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
589
Chris Lattner64299f82008-01-10 01:53:41 +0000590 // FIXME: Read any files specified by -imacros.
591
592 // Add implicit #includes from -include.
593 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
594 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000595
596 // Null terminate PredefinedBuffer and add it.
597 PredefineBuffer.push_back(0);
598 PP.setPredefines(&PredefineBuffer[0]);
599
600 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000601 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000602}
603
604//===----------------------------------------------------------------------===//
605// Preprocessor include path information.
606//===----------------------------------------------------------------------===//
607
608// This tool exports a large number of command line options to control how the
609// preprocessor searches for header files. At root, however, the Preprocessor
610// object takes a very simple interface: a list of directories to search for
611//
612// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000613// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000614//
Chris Lattner64299f82008-01-10 01:53:41 +0000615// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000616
617static llvm::cl::opt<bool>
618nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
619
620// Various command line options. These four add directories to each chain.
621static llvm::cl::list<std::string>
622F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
623 llvm::cl::desc("Add directory to framework include search path"));
624static llvm::cl::list<std::string>
625I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
626 llvm::cl::desc("Add directory to include search path"));
627static llvm::cl::list<std::string>
628idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
629 llvm::cl::desc("Add directory to AFTER include search path"));
630static llvm::cl::list<std::string>
631iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
632 llvm::cl::desc("Add directory to QUOTE include search path"));
633static llvm::cl::list<std::string>
634isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
635 llvm::cl::desc("Add directory to SYSTEM include search path"));
636
637// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
638static llvm::cl::list<std::string>
639iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
640 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
641static llvm::cl::list<std::string>
642iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
643 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
644static llvm::cl::list<std::string>
645iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
646 llvm::cl::Prefix,
647 llvm::cl::desc("Set directory to include search path with prefix"));
648
Chris Lattner0c946412007-08-26 17:47:35 +0000649static llvm::cl::opt<std::string>
650isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
651 llvm::cl::desc("Set the system root directory (usually /)"));
652
Reid Spencer5f016e22007-07-11 17:01:13 +0000653// Finally, implement the code that groks the options above.
654enum IncludeDirGroup {
655 Quoted = 0,
656 Angled,
657 System,
658 After
659};
660
661static std::vector<DirectoryLookup> IncludeGroup[4];
662
663/// AddPath - Add the specified path to the specified group list.
664///
665static void AddPath(const std::string &Path, IncludeDirGroup Group,
666 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000667 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000668 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000669 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000670
Chris Lattnerd6655272007-12-17 05:59:27 +0000671 // Compute the actual path, taking into consideration -isysroot.
672 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000673
Chris Lattnerd6655272007-12-17 05:59:27 +0000674 // Handle isysroot.
675 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000676 // FIXME: Portability. This should be a sys::Path interface, this doesn't
677 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000678 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
679 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000680 }
681
Chris Lattnerd6655272007-12-17 05:59:27 +0000682 MappedPath.append(Path.begin(), Path.end());
683
684 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000685 DirectoryLookup::DirType Type;
686 if (Group == Quoted || Group == Angled)
687 Type = DirectoryLookup::NormalHeaderDir;
688 else if (isCXXAware)
689 Type = DirectoryLookup::SystemHeaderDir;
690 else
691 Type = DirectoryLookup::ExternCSystemHeaderDir;
692
Chris Lattnerd6655272007-12-17 05:59:27 +0000693
694 // If the directory exists, add it.
695 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
696 &MappedPath[0]+
697 MappedPath.size())) {
698 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
699 isFramework));
700 return;
701 }
702
Chris Lattnerdf772332007-12-17 07:52:39 +0000703 // Check to see if this is an apple-style headermap (which are not allowed to
704 // be frameworks).
705 if (!isFramework) {
706 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
707 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000708 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
709 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000710 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
711 return;
712 }
Chris Lattner822da612007-12-17 06:36:45 +0000713 }
714 }
715
Chris Lattnerd6655272007-12-17 05:59:27 +0000716 if (Verbose)
717 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000718}
719
720/// RemoveDuplicates - If there are duplicate directory entries in the specified
721/// search list, remove the later (dead) ones.
722static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000723 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000724 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000725 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000727 if (SearchList[i].isNormalDir()) {
728 // If this isn't the first time we've seen this dir, remove it.
729 if (SeenDirs.insert(SearchList[i].getDir()))
730 continue;
731
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 if (Verbose)
733 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
734 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000735 } else if (SearchList[i].isFramework()) {
736 // If this isn't the first time we've seen this framework dir, remove it.
737 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
738 continue;
739
740 if (Verbose)
741 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
742 SearchList[i].getFrameworkDir()->getName());
743
Chris Lattnerb94c7072007-12-17 06:44:29 +0000744 } else {
745 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
746 // If this isn't the first time we've seen this headermap, remove it.
747 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
748 continue;
749
750 if (Verbose)
751 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
752 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000754
755 // This is reached if the current entry is a duplicate.
756 SearchList.erase(SearchList.begin()+i);
757 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 }
759}
760
Chris Lattner5f9eae52008-03-01 08:07:28 +0000761// AddEnvVarPaths - Add a list of paths from an environment variable to a
762// header search list.
763//
764static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
765 const char* at = getenv(Name);
766 if (!at)
767 return;
768
769 const char* delim = strchr(at, llvm::sys::PathSeparator);
770 while (delim != 0) {
771 if (delim-at == 0)
772 AddPath(".", Angled, false, true, false, Headers);
773 else
774 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
775 true, false, Headers);
776 at = delim + 1;
777 delim = strchr(at, llvm::sys::PathSeparator);
778 }
779 if (*at == 0)
780 AddPath(".", Angled, false, true, false, Headers);
781 else
782 AddPath(at, Angled, false, true, false, Headers);
783}
784
Reid Spencer5f016e22007-07-11 17:01:13 +0000785/// InitializeIncludePaths - Process the -I options and set them in the
786/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000787static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
788 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 // Handle -F... options.
790 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000791 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000792
793 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000794 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000795 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000796
797 // Handle -idirafter... options.
798 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000799 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000800
801 // Handle -iquote... options.
802 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000803 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000804
805 // Handle -isystem... options.
806 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000807 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000808
809 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
810 // parallel, processing the values in order of occurance to get the right
811 // prefixes.
812 {
813 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
814 unsigned iprefix_idx = 0;
815 unsigned iwithprefix_idx = 0;
816 unsigned iwithprefixbefore_idx = 0;
817 bool iprefix_done = iprefix_vals.empty();
818 bool iwithprefix_done = iwithprefix_vals.empty();
819 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
820 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
821 if (!iprefix_done &&
822 (iwithprefix_done ||
823 iprefix_vals.getPosition(iprefix_idx) <
824 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
825 (iwithprefixbefore_done ||
826 iprefix_vals.getPosition(iprefix_idx) <
827 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
828 Prefix = iprefix_vals[iprefix_idx];
829 ++iprefix_idx;
830 iprefix_done = iprefix_idx == iprefix_vals.size();
831 } else if (!iwithprefix_done &&
832 (iwithprefixbefore_done ||
833 iwithprefix_vals.getPosition(iwithprefix_idx) <
834 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
835 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000836 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 ++iwithprefix_idx;
838 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
839 } else {
840 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000841 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 ++iwithprefixbefore_idx;
843 iwithprefixbefore_done =
844 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
845 }
846 }
847 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000848
849 AddEnvVarPaths("CPATH", Headers);
850 if (Lang.CPlusPlus && Lang.ObjC1)
851 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
852 else if (Lang.CPlusPlus)
853 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
854 else if (Lang.ObjC1)
855 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
856 else
857 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
858
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000859 // Add the clang headers, which are relative to the clang driver.
860 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000861 llvm::sys::Path::GetMainExecutable(Argv0,
862 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000863 if (!MainExecutablePath.isEmpty()) {
864 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
865 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
866 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
867 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
868 }
869
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 // FIXME: temporary hack: hard-coded paths.
871 // FIXME: get these from the target?
872 if (!nostdinc) {
873 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000874 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000876 false, Headers);
877 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
878 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000879
880 // Ubuntu 7.10 - Gutsy Gibbon
881 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
882 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
883 false, Headers);
884 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
885 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 }
887
Chris Lattner822da612007-12-17 06:36:45 +0000888 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 // leopard
890 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000891 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000893 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
895 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000896 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000897
898 // tiger
899 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000900 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000902 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000903 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
904 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000905 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000906
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000907 // Ubuntu 7.10 - Gutsy Gibbon
908 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000909 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000910
Chris Lattner822da612007-12-17 06:36:45 +0000911 AddPath("/usr/include", System, false, false, false, Headers);
912 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
913 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 }
915
916 // Now that we have collected all of the include paths, merge them all
917 // together and tell the preprocessor about them.
918
919 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
920 std::vector<DirectoryLookup> SearchList;
921 SearchList = IncludeGroup[Angled];
922 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
923 IncludeGroup[System].end());
924 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
925 IncludeGroup[After].end());
926 RemoveDuplicates(SearchList);
927 RemoveDuplicates(IncludeGroup[Quoted]);
928
929 // Prepend QUOTED list on the search list.
930 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
931 IncludeGroup[Quoted].end());
932
933
934 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
935 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
936 DontSearchCurDir);
937
938 // If verbose, print the list of directories that will be searched.
939 if (Verbose) {
940 fprintf(stderr, "#include \"...\" search starts here:\n");
941 unsigned QuotedIdx = IncludeGroup[Quoted].size();
942 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
943 if (i == QuotedIdx)
944 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000945 const char *Name = SearchList[i].getName();
946 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000947 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000948 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000949 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000950 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000951 else {
952 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000953 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000954 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000955 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 }
Chris Lattner80e17152007-12-15 23:11:06 +0000957 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 }
959}
960
961
Reid Spencer5f016e22007-07-11 17:01:13 +0000962//===----------------------------------------------------------------------===//
963// Basic Parser driver
964//===----------------------------------------------------------------------===//
965
Ted Kremenek95041a22007-12-19 22:51:13 +0000966static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000968 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000969
970 // Parsing the specified input file.
971 P.ParseTranslationUnit();
972 delete PA;
973}
974
975//===----------------------------------------------------------------------===//
976// Main driver
977//===----------------------------------------------------------------------===//
978
Ted Kremenekdb094a22007-12-05 18:27:04 +0000979/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
980/// action. These consumers can operate on both ASTs that are freshly
981/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000982static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000983 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +0000984 const LangOptions& LangOpts,
985 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +0000986 switch (ProgAction) {
987 default:
988 return NULL;
989
990 case ASTPrint:
991 return CreateASTPrinter();
992
993 case ASTDump:
994 return CreateASTDumper();
995
996 case ASTView:
997 return CreateASTViewer();
998
999 case ParseCFGDump:
1000 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001001 return CreateCFGDumper(ProgAction == ParseCFGView,
1002 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001003
1004 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001005 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001006
1007 case WarnDeadStores:
1008 return CreateDeadStoreChecker(Diag);
1009
1010 case WarnUninitVals:
1011 return CreateUnitValsChecker(Diag);
1012
Ted Kremeneke01c9872008-02-14 22:36:46 +00001013 case AnalysisGRSimpleVals:
Ted Kremenekcb330932008-02-18 21:21:23 +00001014 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremeneke603df42008-01-08 18:04:06 +00001015
Ted Kremenekd55fe522008-02-15 00:35:38 +00001016 case AnalysisGRSimpleValsView:
Ted Kremenekffe0f432008-03-07 22:58:01 +00001017 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true, TrimGraph);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001018
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001019 case CheckerCFRef:
1020 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction);
1021
Ted Kremenekdb094a22007-12-05 18:27:04 +00001022 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001023 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001024
1025 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001026 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001027 DestModule = new llvm::Module(InFile);
1028 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001029
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001030 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001031 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001032 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001033
Ted Kremenekdb094a22007-12-05 18:27:04 +00001034 case RewriteTest:
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +00001035 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001036 }
1037}
1038
Reid Spencer5f016e22007-07-11 17:01:13 +00001039/// ProcessInputFile - Process a single input file with the specified state.
1040///
Ted Kremenek7dcc9682007-12-19 22:32:34 +00001041static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +00001042 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001043
1044 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001045 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001046 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001047
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 switch (ProgAction) {
1049 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001050 Consumer = CreateASTConsumer(InFile,
1051 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001052 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001053 PP.getLangOptions(),
1054 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001055
1056 if (!Consumer) {
1057 fprintf(stderr, "Unexpected program action!\n");
1058 return;
1059 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001060
Ted Kremenekdb094a22007-12-05 18:27:04 +00001061 break;
1062
Reid Spencer5f016e22007-07-11 17:01:13 +00001063 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001064 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001066 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 do {
1068 PP.Lex(Tok);
1069 PP.DumpToken(Tok, true);
1070 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001071 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001072 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 break;
1074 }
1075 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001076 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001078 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 do {
1080 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001081 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001082 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 break;
1084 }
1085
1086 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001087 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001088 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 break;
1090
1091 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001092 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001093 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 break;
1095
1096 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001097 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001098 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001100
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001101 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001102 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001103 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001104 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001105
1106 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001107 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001108 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001109
1110 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001111 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001113
1114 // If running the code generator, finish up now.
1115 if (CodeGenModule) {
1116 std::ostream *Out;
1117 if (OutputFile == "-") {
1118 Out = llvm::cout.stream();
1119 } else if (!OutputFile.empty()) {
1120 Out = new std::ofstream(OutputFile.c_str(),
1121 std::ios_base::binary|std::ios_base::out);
1122 } else if (InFile == "-") {
1123 Out = llvm::cout.stream();
1124 } else {
1125 llvm::sys::Path Path(InFile);
1126 Path.eraseSuffix();
1127 if (ProgAction == EmitLLVM)
1128 Path.appendSuffix("ll");
1129 else if (ProgAction == EmitBC)
1130 Path.appendSuffix("bc");
1131 else
1132 assert(0 && "Unknown action");
1133 Out = new std::ofstream(Path.toString().c_str(),
1134 std::ios_base::binary|std::ios_base::out);
1135 }
1136
1137 if (ProgAction == EmitLLVM) {
1138 CodeGenModule->print(*Out);
1139 } else {
1140 assert(ProgAction == EmitBC);
1141 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1142 }
1143
1144 if (Out != llvm::cout.stream())
1145 delete Out;
1146 delete CodeGenModule;
1147 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001148
1149 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001150 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 PP.PrintStats();
1152 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001153 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001154 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001155 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 fprintf(stderr, "\n");
1157 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001158
1159 // For a multi-file compilation, some things are ok with nuking the source
1160 // manager tables, other require stable fileid/macroid's across multiple
1161 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001162 if (ClearSourceMgr)
1163 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001164}
1165
Ted Kremenek20e97482007-12-12 23:41:08 +00001166static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1167 FileManager& FileMgr) {
1168
1169 if (VerifyDiagnostics) {
1170 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1171 exit (1);
1172 }
1173
1174 llvm::sys::Path Filename(InFile);
1175
1176 if (!Filename.isValid()) {
1177 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1178 exit (1);
1179 }
1180
Ted Kremenekee533642007-12-20 19:47:16 +00001181 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001182
1183 if (!TU) {
1184 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1185 InFile.c_str());
1186 exit (1);
1187 }
1188
Ted Kremenek63ea8632007-12-19 19:27:38 +00001189 // Observe that we use the source file name stored in the deserialized
1190 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001191 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001192 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001193 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1194 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001195
1196 if (!Consumer) {
1197 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1198 exit (1);
1199 }
1200
Ted Kremenek95041a22007-12-19 22:51:13 +00001201 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001202
Chris Lattnere66b65c2008-02-06 01:42:25 +00001203 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001204 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1205 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001206}
1207
1208
Reid Spencer5f016e22007-07-11 17:01:13 +00001209static llvm::cl::list<std::string>
1210InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1211
Ted Kremenek20e97482007-12-12 23:41:08 +00001212static bool isSerializedFile(const std::string& InFile) {
1213 if (InFile.size() < 4)
1214 return false;
1215
1216 const char* s = InFile.c_str()+InFile.size()-4;
1217
1218 return s[0] == '.' &&
1219 s[1] == 'a' &&
1220 s[2] == 's' &&
1221 s[3] == 't';
1222}
1223
Reid Spencer5f016e22007-07-11 17:01:13 +00001224
1225int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001226 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 llvm::sys::PrintStackTraceOnErrorSignal();
1228
1229 // If no input was specified, read from stdin.
1230 if (InputFilenames.empty())
1231 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001232
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 // Create a file manager object to provide access to and cache the filesystem.
1234 FileManager FileMgr;
1235
Ted Kremenek31e703b2007-12-11 23:28:38 +00001236 // Create the diagnostic client for reporting errors or for
1237 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001239 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001241 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 } else {
1243 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001244 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001245
1246 if (InputFilenames.size() != 1) {
1247 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001248 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 return 1;
1250 }
1251 }
1252
1253 // Configure our handling of diagnostics.
1254 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001255 InitializeDiagnostics(Diags);
1256
Chris Lattner4f037832007-12-05 23:24:17 +00001257 // -I- is a deprecated GCC feature, scan for it and reject it.
1258 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1259 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001260 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001261 I_dirs.erase(I_dirs.begin()+i);
1262 --i;
1263 }
1264 }
1265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001267 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001268
Ted Kremenek20e97482007-12-12 23:41:08 +00001269 if (isSerializedFile(InFile))
1270 ProcessSerializedFile(InFile,Diags,FileMgr);
1271 else {
1272 /// Create a SourceManager object. This tracks and owns all the file
1273 /// buffers allocated to a translation unit.
1274 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001275
Ted Kremenek20e97482007-12-12 23:41:08 +00001276 // Initialize language options, inferring file types from input filenames.
1277 LangOptions LangInfo;
1278 InitializeBaseLanguage();
1279 LangKind LK = GetLanguage(InFile);
1280 InitializeLangOptions(LangInfo, LK);
1281 InitializeLanguageStandard(LangInfo, LK);
1282
1283 // Process the -I options and set them in the HeaderInfo.
1284 HeaderSearch HeaderInfo(FileMgr);
1285 DiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001286 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001287
1288 // Get information about the targets being compiled for. Note that this
1289 // pointer and the TargetInfoImpl objects are never deleted by this toy
1290 // driver.
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001291 std::string Triple = CreateTargetTriple();
1292 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
Ted Kremenek20e97482007-12-12 23:41:08 +00001293
1294 if (Target == 0) {
1295 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001296 Triple.c_str());
Ted Kremenek20e97482007-12-12 23:41:08 +00001297 fprintf(stderr, "Please use -triple or -arch.\n");
1298 exit(1);
1299 }
1300
1301 // Set up the preprocessor with these options.
1302 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1303
1304 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001305 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001306 continue;
1307
Ted Kremenek1036b682007-12-19 23:48:45 +00001308 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001309 HeaderInfo.ClearFileInfo();
1310
1311 if (Stats)
1312 SourceMgr.PrintStats();
1313 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 }
1315
1316 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1317
1318 if (NumDiagnostics)
1319 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1320 (NumDiagnostics == 1 ? "" : "s"));
1321
1322 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 FileMgr.PrintStats();
1324 fprintf(stderr, "\n");
1325 }
1326
Chris Lattner96f1a642007-07-21 05:40:53 +00001327 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001328}