blob: 36a7f16d7cd14008409a3088e91064a18dde7827 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000046#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000047#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000048using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// Global options.
52//===----------------------------------------------------------------------===//
53
54static llvm::cl::opt<bool>
55Verbose("v", llvm::cl::desc("Enable verbose output"));
56static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000057Stats("print-stats",
58 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000059
60enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000061 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000062 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000063 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000064 SerializeAST, // Emit a .ast file.
Chris Lattner3b427b32007-10-11 00:18:28 +000065 ASTPrint, // Parse ASTs and print them.
66 ASTDump, // Parse ASTs and dump them.
67 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000068 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000069 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000070 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000071 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
72 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek055c2752007-09-06 23:00:42 +000073 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000074 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000075 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000076 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000077 ParsePrintCallbacks, // Parse and print each callback.
78 ParseSyntaxOnly, // Parse and perform semantic analysis.
79 ParseNoop, // Parse with noop callbacks.
80 RunPreprocessorOnly, // Just lex, no output.
81 PrintPreprocessedInput, // -E mode.
82 DumpTokens // Token dump mode.
83};
84
85static llvm::cl::opt<ProgActions>
86ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
87 llvm::cl::init(ParseSyntaxOnly),
88 llvm::cl::values(
89 clEnumValN(RunPreprocessorOnly, "Eonly",
90 "Just run preprocessor, no output (for timings)"),
91 clEnumValN(PrintPreprocessedInput, "E",
92 "Run preprocessor, emit preprocessed file"),
93 clEnumValN(DumpTokens, "dumptokens",
94 "Run preprocessor, dump internal rep of tokens"),
95 clEnumValN(ParseNoop, "parse-noop",
96 "Run parser with noop callbacks (for timings)"),
97 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
98 "Run parser and perform semantic analysis"),
99 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
100 "Run parser and print each callback invoked"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000101 clEnumValN(ASTPrint, "ast-print",
102 "Build ASTs and then pretty-print them"),
103 clEnumValN(ASTDump, "ast-dump",
104 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000105 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000106 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000107 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000108 "Run parser, then build and print CFGs."),
109 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000110 "Run parser, then build and view CFGs with Graphviz."),
111 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000112 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000113 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000114 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000115 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000116 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke01c9872008-02-14 22:36:46 +0000117 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000118 "Perform path-sensitive constant propagation."),
Ted Kremenekd55fe522008-02-15 00:35:38 +0000119 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
120 "View results of path-sensitive constant propagation."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000121 clEnumValN(TestSerialization, "test-pickling",
122 "Run prototype serializtion code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000124 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000125 clEnumValN(EmitBC, "emit-llvm-bc",
126 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000127 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000128 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000129 clEnumValN(RewriteTest, "rewrite-test",
130 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 clEnumValEnd));
132
Ted Kremenekccc76472007-12-19 19:47:59 +0000133
134static llvm::cl::opt<std::string>
135OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000136 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000137 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
138
Ted Kremenek41193e42007-09-26 19:42:19 +0000139static llvm::cl::opt<bool>
140VerifyDiagnostics("verify",
141 llvm::cl::desc("Verify emitted diagnostics and warnings."));
142
Reid Spencer5f016e22007-07-11 17:01:13 +0000143//===----------------------------------------------------------------------===//
144// Language Options
145//===----------------------------------------------------------------------===//
146
147enum LangKind {
148 langkind_unspecified,
149 langkind_c,
150 langkind_c_cpp,
151 langkind_cxx,
152 langkind_cxx_cpp,
153 langkind_objc,
154 langkind_objc_cpp,
155 langkind_objcxx,
156 langkind_objcxx_cpp
157};
158
159/* TODO: GCC also accepts:
160 c-header c++-header objective-c-header objective-c++-header
161 assembler assembler-with-cpp
162 ada, f77*, ratfor (!), f95, java, treelang
163 */
164static llvm::cl::opt<LangKind>
165BaseLang("x", llvm::cl::desc("Base language to compile"),
166 llvm::cl::init(langkind_unspecified),
167 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
168 clEnumValN(langkind_cxx, "c++", "C++"),
169 clEnumValN(langkind_objc, "objective-c", "Objective C"),
170 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
171 clEnumValN(langkind_c_cpp, "c-cpp-output",
172 "Preprocessed C"),
173 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
174 "Preprocessed C++"),
175 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
176 "Preprocessed Objective C"),
177 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
178 "Preprocessed Objective C++"),
179 clEnumValEnd));
180
181static llvm::cl::opt<bool>
182LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
183 llvm::cl::Hidden);
184static llvm::cl::opt<bool>
185LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
186 llvm::cl::Hidden);
187
Ted Kremenek8904f152007-12-05 23:49:08 +0000188/// InitializeBaseLanguage - Handle the -x foo options.
189static void InitializeBaseLanguage() {
190 if (LangObjC)
191 BaseLang = langkind_objc;
192 else if (LangObjCXX)
193 BaseLang = langkind_objcxx;
194}
195
196static LangKind GetLanguage(const std::string &Filename) {
197 if (BaseLang != langkind_unspecified)
198 return BaseLang;
199
200 std::string::size_type DotPos = Filename.rfind('.');
201
202 if (DotPos == std::string::npos) {
203 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000204 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 }
206
Ted Kremenek8904f152007-12-05 23:49:08 +0000207 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
208 // C header: .h
209 // C++ header: .hh or .H;
210 // assembler no preprocessing: .s
211 // assembler: .S
212 if (Ext == "c")
213 return langkind_c;
214 else if (Ext == "i")
215 return langkind_c_cpp;
216 else if (Ext == "ii")
217 return langkind_cxx_cpp;
218 else if (Ext == "m")
219 return langkind_objc;
220 else if (Ext == "mi")
221 return langkind_objc_cpp;
222 else if (Ext == "mm" || Ext == "M")
223 return langkind_objcxx;
224 else if (Ext == "mii")
225 return langkind_objcxx_cpp;
226 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
227 Ext == "c++" || Ext == "cp" || Ext == "cxx")
228 return langkind_cxx;
229 else
230 return langkind_c;
231}
232
233
234static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 // FIXME: implement -fpreprocessed mode.
236 bool NoPreprocess = false;
237
Ted Kremenek8904f152007-12-05 23:49:08 +0000238 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 default: assert(0 && "Unknown language kind!");
240 case langkind_c_cpp:
241 NoPreprocess = true;
242 // FALLTHROUGH
243 case langkind_c:
244 break;
245 case langkind_cxx_cpp:
246 NoPreprocess = true;
247 // FALLTHROUGH
248 case langkind_cxx:
249 Options.CPlusPlus = 1;
250 break;
251 case langkind_objc_cpp:
252 NoPreprocess = true;
253 // FALLTHROUGH
254 case langkind_objc:
255 Options.ObjC1 = Options.ObjC2 = 1;
256 break;
257 case langkind_objcxx_cpp:
258 NoPreprocess = true;
259 // FALLTHROUGH
260 case langkind_objcxx:
261 Options.ObjC1 = Options.ObjC2 = 1;
262 Options.CPlusPlus = 1;
263 break;
264 }
265}
266
267/// LangStds - Language standards we support.
268enum LangStds {
269 lang_unspecified,
270 lang_c89, lang_c94, lang_c99,
271 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000272 lang_cxx98, lang_gnucxx98,
273 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000274};
275
276static llvm::cl::opt<LangStds>
277LangStd("std", llvm::cl::desc("Language standard to compile for"),
278 llvm::cl::init(lang_unspecified),
279 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
280 clEnumValN(lang_c89, "c90", "ISO C 1990"),
281 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
282 clEnumValN(lang_c94, "iso9899:199409",
283 "ISO C 1990 with amendment 1"),
284 clEnumValN(lang_c99, "c99", "ISO C 1999"),
285// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
286 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
287// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
288 clEnumValN(lang_gnu89, "gnu89",
289 "ISO C 1990 with GNU extensions (default for C)"),
290 clEnumValN(lang_gnu99, "gnu99",
291 "ISO C 1999 with GNU extensions"),
292 clEnumValN(lang_gnu99, "gnu9x",
293 "ISO C 1999 with GNU extensions"),
294 clEnumValN(lang_cxx98, "c++98",
295 "ISO C++ 1998 with amendments"),
296 clEnumValN(lang_gnucxx98, "gnu++98",
297 "ISO C++ 1998 with amendments and GNU "
298 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000299 clEnumValN(lang_cxx0x, "c++0x",
300 "Upcoming ISO C++ 200x with amendments"),
301 clEnumValN(lang_gnucxx0x, "gnu++0x",
302 "Upcoming ISO C++ 200x with amendments and GNU "
303 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 clEnumValEnd));
305
306static llvm::cl::opt<bool>
307NoOperatorNames("fno-operator-names",
308 llvm::cl::desc("Do not treat C++ operator name keywords as "
309 "synonyms for operators"));
310
Anders Carlssonee98ac52007-10-15 02:50:23 +0000311static llvm::cl::opt<bool>
312PascalStrings("fpascal-strings",
313 llvm::cl::desc("Recognize and construct Pascal-style "
314 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000315
316static llvm::cl::opt<bool>
317MSExtensions("fms-extensions",
318 llvm::cl::desc("Accept some non-standard constructs used in "
319 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000320
321static llvm::cl::opt<bool>
322WritableStrings("fwritable-strings",
323 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000324
325static llvm::cl::opt<bool>
326LaxVectorConversions("flax-vector-conversions",
327 llvm::cl::desc("Allow implicit conversions between vectors"
328 " with a different number of elements or "
329 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000330// FIXME: add:
331// -ansi
332// -trigraphs
333// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000334// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000335static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 if (LangStd == lang_unspecified) {
337 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000338 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 default: assert(0 && "Unknown base language");
340 case langkind_c:
341 case langkind_c_cpp:
342 case langkind_objc:
343 case langkind_objc_cpp:
344 LangStd = lang_gnu99;
345 break;
346 case langkind_cxx:
347 case langkind_cxx_cpp:
348 case langkind_objcxx:
349 case langkind_objcxx_cpp:
350 LangStd = lang_gnucxx98;
351 break;
352 }
353 }
354
355 switch (LangStd) {
356 default: assert(0 && "Unknown language standard!");
357
358 // Fall through from newer standards to older ones. This isn't really right.
359 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000360 case lang_gnucxx0x:
361 case lang_cxx0x:
362 Options.CPlusPlus0x = 1;
363 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 case lang_gnucxx98:
365 case lang_cxx98:
366 Options.CPlusPlus = 1;
367 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000368 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // FALL THROUGH.
370 case lang_gnu99:
371 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 Options.C99 = 1;
373 Options.HexFloats = 1;
374 // FALL THROUGH.
375 case lang_gnu89:
376 Options.BCPLComment = 1; // Only for C99/C++.
377 // FALL THROUGH.
378 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000379 Options.Digraphs = 1; // C94, C99, C++.
380 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 case lang_c89:
382 break;
383 }
384
385 Options.Trigraphs = 1; // -trigraphs or -ansi
386 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000387 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000388 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000389 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000390 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000391}
392
393//===----------------------------------------------------------------------===//
394// Our DiagnosticClient implementation
395//===----------------------------------------------------------------------===//
396
397// FIXME: Werror should take a list of things, -Werror=foo,bar
398static llvm::cl::opt<bool>
399WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
400
401static llvm::cl::opt<bool>
402WarnOnExtensions("pedantic", llvm::cl::init(false),
403 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
404
405static llvm::cl::opt<bool>
406ErrorOnExtensions("pedantic-errors",
407 llvm::cl::desc("Issue an error on uses of GCC extensions"));
408
409static llvm::cl::opt<bool>
410WarnUnusedMacros("Wunused_macros",
411 llvm::cl::desc("Warn for unused macros in the main translation unit"));
412
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000413static llvm::cl::opt<bool>
414WarnFloatEqual("Wfloat-equal",
415 llvm::cl::desc("Warn about equality comparisons of floating point values."));
416
Ted Kremenek73da5902007-12-17 17:50:07 +0000417static llvm::cl::opt<bool>
418WarnNoFormatNonLiteral("Wno-format-nonliteral",
419 llvm::cl::desc("Do not warn about non-literal format strings."));
420
Chris Lattner116a4b12008-01-23 17:19:46 +0000421static llvm::cl::opt<bool>
422WarnUndefMacros("Wundef",
423 llvm::cl::desc("Warn on use of undefined macros in #if's"));
424
425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426/// InitializeDiagnostics - Initialize the diagnostic object, based on the
427/// current command line option settings.
428static void InitializeDiagnostics(Diagnostic &Diags) {
429 Diags.setWarningsAsErrors(WarningsAsErrors);
430 Diags.setWarnOnExtensions(WarnOnExtensions);
431 Diags.setErrorOnExtensions(ErrorOnExtensions);
432
433 // Silence the "macro is not used" warning unless requested.
434 if (!WarnUnusedMacros)
435 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000436
437 // Silence "floating point comparison" warnings unless requested.
438 if (!WarnFloatEqual)
439 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000440
441 // Silence "format string is not a string literal" warnings if requested
442 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000443 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
444 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000445 if (!WarnUndefMacros)
446 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000447
448 if (MSExtensions) // MS allows unnamed struct/union fields.
449 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000450}
451
452//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000453// Analysis-specific options.
454//===----------------------------------------------------------------------===//
455
456static llvm::cl::opt<std::string>
457AnalyzeSpecificFunction("analyze-function",
458 llvm::cl::desc("Run analysis on specific function."));
459
460//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000461// Target Triple Processing.
462//===----------------------------------------------------------------------===//
463
464static llvm::cl::opt<std::string>
465TargetTriple("triple",
466 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
467
468static llvm::cl::list<std::string>
469Archs("arch",
470 llvm::cl::desc("Specify target architecture (e.g. i686)."));
471
472namespace {
473 class TripleProcessor {
474 llvm::StringMap<char> TriplesProcessed;
475 std::vector<std::string>& triples;
476 public:
477 TripleProcessor(std::vector<std::string>& t) : triples(t) {}
478
479 void addTriple(const std::string& t) {
480 if (TriplesProcessed.find(t.c_str(),t.c_str()+t.size()) ==
481 TriplesProcessed.end()) {
482 triples.push_back(t);
483 TriplesProcessed.GetOrCreateValue(t.c_str(),t.c_str()+t.size());
484 }
485 }
486 };
487}
488
489static void CreateTargetTriples(std::vector<std::string>& triples) {
Ted Kremenekae360762007-12-03 22:06:55 +0000490 // Initialize base triple. If a -triple option has been specified, use
491 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000492 std::string Triple = TargetTriple;
493 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000494
495 // Decompose the base triple into "arch" and suffix.
Chris Lattner6590d212007-12-12 05:01:48 +0000496 std::string::size_type firstDash = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000497
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000498 if (firstDash == std::string::npos) {
499 fprintf(stderr,
500 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000501 Triple.c_str());
502 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000503 }
Ted Kremenekae360762007-12-03 22:06:55 +0000504
Chris Lattner6590d212007-12-12 05:01:48 +0000505 std::string suffix(Triple, firstDash+1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000506
507 if (suffix.empty()) {
Chris Lattner6590d212007-12-12 05:01:48 +0000508 fprintf(stderr, "Malformed target triple: \"%s\" (no vendor or OS).\n",
509 Triple.c_str());
510 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000511 }
Ted Kremenekae360762007-12-03 22:06:55 +0000512
513 // Create triple cacher.
514 TripleProcessor tp(triples);
515
516 // Add the primary triple to our set of triples if we are using the
517 // host-triple with no archs or using a specified target triple.
518 if (!TargetTriple.getValue().empty() || Archs.empty())
Chris Lattner6590d212007-12-12 05:01:48 +0000519 tp.addTriple(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000520
521 for (unsigned i = 0, e = Archs.size(); i !=e; ++i)
522 tp.addTriple(Archs[i] + "-" + suffix);
523}
524
525//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000526// Preprocessor Initialization
527//===----------------------------------------------------------------------===//
528
529// FIXME: Preprocessor builtins to support.
530// -A... - Play with #assertions
531// -undef - Undefine all predefined macros
532
533static llvm::cl::list<std::string>
534D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
535 llvm::cl::desc("Predefine the specified macro"));
536static llvm::cl::list<std::string>
537U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
538 llvm::cl::desc("Undefine the specified macro"));
539
Chris Lattner64299f82008-01-10 01:53:41 +0000540static llvm::cl::list<std::string>
541ImplicitIncludes("include", llvm::cl::value_desc("file"),
542 llvm::cl::desc("Include file before parsing"));
543
544
Reid Spencer5f016e22007-07-11 17:01:13 +0000545// Append a #define line to Buf for Macro. Macro should be of the form XXX,
546// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
547// "#define XXX Y z W". To get a #define with no value, use "XXX=".
548static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
549 const char *Command = "#define ") {
550 Buf.insert(Buf.end(), Command, Command+strlen(Command));
551 if (const char *Equal = strchr(Macro, '=')) {
552 // Turn the = into ' '.
553 Buf.insert(Buf.end(), Macro, Equal);
554 Buf.push_back(' ');
555 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
556 } else {
557 // Push "macroname 1".
558 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
559 Buf.push_back(' ');
560 Buf.push_back('1');
561 }
562 Buf.push_back('\n');
563}
564
Chris Lattner64299f82008-01-10 01:53:41 +0000565/// AddImplicitInclude - Add an implicit #include of the specified file to the
566/// predefines buffer.
567static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
568 const char *Inc = "#include \"";
569 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
570 Buf.insert(Buf.end(), File.begin(), File.end());
571 Buf.push_back('"');
572 Buf.push_back('\n');
573}
574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575
Chris Lattner53b0dab2007-10-09 22:10:18 +0000576/// InitializePreprocessor - Initialize the preprocessor getting it and the
577/// environment ready to process a single file. This returns the file ID for the
578/// input file. If a failure happens, it returns 0.
579///
580static unsigned InitializePreprocessor(Preprocessor &PP,
581 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000582 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000583
Chris Lattnerdee73592007-12-15 20:48:40 +0000584 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000585
Chris Lattner53b0dab2007-10-09 22:10:18 +0000586 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000587 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000588 if (InFile != "-") {
589 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000590 if (File) SourceMgr.createMainFileID(File, SourceLocation());
591 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000592 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
593 return 0;
594 }
595 } else {
596 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000597 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
598 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000599 fprintf(stderr, "Error reading standard input! Empty?\n");
600 return 0;
601 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 }
603
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 // Add macros from the command line.
605 // FIXME: Should traverse the #define/#undef lists in parallel.
606 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000607 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000609 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
610
Chris Lattner64299f82008-01-10 01:53:41 +0000611 // FIXME: Read any files specified by -imacros.
612
613 // Add implicit #includes from -include.
614 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
615 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000616
617 // Null terminate PredefinedBuffer and add it.
618 PredefineBuffer.push_back(0);
619 PP.setPredefines(&PredefineBuffer[0]);
620
621 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000622 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000623}
624
625//===----------------------------------------------------------------------===//
626// Preprocessor include path information.
627//===----------------------------------------------------------------------===//
628
629// This tool exports a large number of command line options to control how the
630// preprocessor searches for header files. At root, however, the Preprocessor
631// object takes a very simple interface: a list of directories to search for
632//
633// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000634// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000635//
Chris Lattner64299f82008-01-10 01:53:41 +0000636// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000637
638static llvm::cl::opt<bool>
639nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
640
641// Various command line options. These four add directories to each chain.
642static llvm::cl::list<std::string>
643F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
644 llvm::cl::desc("Add directory to framework include search path"));
645static llvm::cl::list<std::string>
646I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
647 llvm::cl::desc("Add directory to include search path"));
648static llvm::cl::list<std::string>
649idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
650 llvm::cl::desc("Add directory to AFTER include search path"));
651static llvm::cl::list<std::string>
652iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
653 llvm::cl::desc("Add directory to QUOTE include search path"));
654static llvm::cl::list<std::string>
655isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
656 llvm::cl::desc("Add directory to SYSTEM include search path"));
657
658// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
659static llvm::cl::list<std::string>
660iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
661 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
662static llvm::cl::list<std::string>
663iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
664 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
665static llvm::cl::list<std::string>
666iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
667 llvm::cl::Prefix,
668 llvm::cl::desc("Set directory to include search path with prefix"));
669
Chris Lattner0c946412007-08-26 17:47:35 +0000670static llvm::cl::opt<std::string>
671isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
672 llvm::cl::desc("Set the system root directory (usually /)"));
673
Reid Spencer5f016e22007-07-11 17:01:13 +0000674// Finally, implement the code that groks the options above.
675enum IncludeDirGroup {
676 Quoted = 0,
677 Angled,
678 System,
679 After
680};
681
682static std::vector<DirectoryLookup> IncludeGroup[4];
683
684/// AddPath - Add the specified path to the specified group list.
685///
686static void AddPath(const std::string &Path, IncludeDirGroup Group,
687 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000688 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000689 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000690 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000691
Chris Lattnerd6655272007-12-17 05:59:27 +0000692 // Compute the actual path, taking into consideration -isysroot.
693 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000694
Chris Lattnerd6655272007-12-17 05:59:27 +0000695 // Handle isysroot.
696 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000697 // FIXME: Portability. This should be a sys::Path interface, this doesn't
698 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000699 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
700 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 }
702
Chris Lattnerd6655272007-12-17 05:59:27 +0000703 MappedPath.append(Path.begin(), Path.end());
704
705 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 DirectoryLookup::DirType Type;
707 if (Group == Quoted || Group == Angled)
708 Type = DirectoryLookup::NormalHeaderDir;
709 else if (isCXXAware)
710 Type = DirectoryLookup::SystemHeaderDir;
711 else
712 Type = DirectoryLookup::ExternCSystemHeaderDir;
713
Chris Lattnerd6655272007-12-17 05:59:27 +0000714
715 // If the directory exists, add it.
716 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
717 &MappedPath[0]+
718 MappedPath.size())) {
719 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
720 isFramework));
721 return;
722 }
723
Chris Lattnerdf772332007-12-17 07:52:39 +0000724 // Check to see if this is an apple-style headermap (which are not allowed to
725 // be frameworks).
726 if (!isFramework) {
727 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
728 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000729 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
730 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000731 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
732 return;
733 }
Chris Lattner822da612007-12-17 06:36:45 +0000734 }
735 }
736
Chris Lattnerd6655272007-12-17 05:59:27 +0000737 if (Verbose)
738 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000739}
740
741/// RemoveDuplicates - If there are duplicate directory entries in the specified
742/// search list, remove the later (dead) ones.
743static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000744 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000745 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000746 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000748 if (SearchList[i].isNormalDir()) {
749 // If this isn't the first time we've seen this dir, remove it.
750 if (SeenDirs.insert(SearchList[i].getDir()))
751 continue;
752
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 if (Verbose)
754 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
755 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000756 } else if (SearchList[i].isFramework()) {
757 // If this isn't the first time we've seen this framework dir, remove it.
758 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
759 continue;
760
761 if (Verbose)
762 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
763 SearchList[i].getFrameworkDir()->getName());
764
Chris Lattnerb94c7072007-12-17 06:44:29 +0000765 } else {
766 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
767 // If this isn't the first time we've seen this headermap, remove it.
768 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
769 continue;
770
771 if (Verbose)
772 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
773 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000775
776 // This is reached if the current entry is a duplicate.
777 SearchList.erase(SearchList.begin()+i);
778 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 }
780}
781
Chris Lattner5f9eae52008-03-01 08:07:28 +0000782// AddEnvVarPaths - Add a list of paths from an environment variable to a
783// header search list.
784//
785static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
786 const char* at = getenv(Name);
787 if (!at)
788 return;
789
790 const char* delim = strchr(at, llvm::sys::PathSeparator);
791 while (delim != 0) {
792 if (delim-at == 0)
793 AddPath(".", Angled, false, true, false, Headers);
794 else
795 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
796 true, false, Headers);
797 at = delim + 1;
798 delim = strchr(at, llvm::sys::PathSeparator);
799 }
800 if (*at == 0)
801 AddPath(".", Angled, false, true, false, Headers);
802 else
803 AddPath(at, Angled, false, true, false, Headers);
804}
805
Reid Spencer5f016e22007-07-11 17:01:13 +0000806/// InitializeIncludePaths - Process the -I options and set them in the
807/// HeaderSearch object.
808static void InitializeIncludePaths(HeaderSearch &Headers, FileManager &FM,
Chris Lattner4f037832007-12-05 23:24:17 +0000809 const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 // Handle -F... options.
811 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000812 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000813
814 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000815 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000816 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000817
818 // Handle -idirafter... options.
819 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000820 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000821
822 // Handle -iquote... options.
823 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000824 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000825
826 // Handle -isystem... options.
827 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000828 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000829
830 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
831 // parallel, processing the values in order of occurance to get the right
832 // prefixes.
833 {
834 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
835 unsigned iprefix_idx = 0;
836 unsigned iwithprefix_idx = 0;
837 unsigned iwithprefixbefore_idx = 0;
838 bool iprefix_done = iprefix_vals.empty();
839 bool iwithprefix_done = iwithprefix_vals.empty();
840 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
841 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
842 if (!iprefix_done &&
843 (iwithprefix_done ||
844 iprefix_vals.getPosition(iprefix_idx) <
845 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
846 (iwithprefixbefore_done ||
847 iprefix_vals.getPosition(iprefix_idx) <
848 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
849 Prefix = iprefix_vals[iprefix_idx];
850 ++iprefix_idx;
851 iprefix_done = iprefix_idx == iprefix_vals.size();
852 } else if (!iwithprefix_done &&
853 (iwithprefixbefore_done ||
854 iwithprefix_vals.getPosition(iwithprefix_idx) <
855 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
856 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000857 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 ++iwithprefix_idx;
859 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
860 } else {
861 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000862 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 ++iwithprefixbefore_idx;
864 iwithprefixbefore_done =
865 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
866 }
867 }
868 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000869
870 AddEnvVarPaths("CPATH", Headers);
871 if (Lang.CPlusPlus && Lang.ObjC1)
872 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
873 else if (Lang.CPlusPlus)
874 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
875 else if (Lang.ObjC1)
876 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
877 else
878 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
879
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 // FIXME: temporary hack: hard-coded paths.
881 // FIXME: get these from the target?
882 if (!nostdinc) {
883 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000884 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000886 false, Headers);
887 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
888 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000889
890 // Ubuntu 7.10 - Gutsy Gibbon
891 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
892 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
893 false, Headers);
894 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
895 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 }
897
Chris Lattner822da612007-12-17 06:36:45 +0000898 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 // leopard
900 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000901 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000903 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
905 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000906 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000907
908 // tiger
909 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000910 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000912 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
914 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000915 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000916
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000917 // Ubuntu 7.10 - Gutsy Gibbon
918 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000919 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000920
Chris Lattner822da612007-12-17 06:36:45 +0000921 AddPath("/usr/include", System, false, false, false, Headers);
922 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
923 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000924 }
925
926 // Now that we have collected all of the include paths, merge them all
927 // together and tell the preprocessor about them.
928
929 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
930 std::vector<DirectoryLookup> SearchList;
931 SearchList = IncludeGroup[Angled];
932 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
933 IncludeGroup[System].end());
934 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
935 IncludeGroup[After].end());
936 RemoveDuplicates(SearchList);
937 RemoveDuplicates(IncludeGroup[Quoted]);
938
939 // Prepend QUOTED list on the search list.
940 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
941 IncludeGroup[Quoted].end());
942
943
944 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
945 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
946 DontSearchCurDir);
947
948 // If verbose, print the list of directories that will be searched.
949 if (Verbose) {
950 fprintf(stderr, "#include \"...\" search starts here:\n");
951 unsigned QuotedIdx = IncludeGroup[Quoted].size();
952 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
953 if (i == QuotedIdx)
954 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000955 const char *Name = SearchList[i].getName();
956 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000957 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000958 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000959 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000960 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000961 else {
962 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000963 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000964 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000965 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 }
Chris Lattner80e17152007-12-15 23:11:06 +0000967 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 }
969}
970
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972//===----------------------------------------------------------------------===//
973// Basic Parser driver
974//===----------------------------------------------------------------------===//
975
Ted Kremenek95041a22007-12-19 22:51:13 +0000976static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000978 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000979
980 // Parsing the specified input file.
981 P.ParseTranslationUnit();
982 delete PA;
983}
984
985//===----------------------------------------------------------------------===//
986// Main driver
987//===----------------------------------------------------------------------===//
988
Ted Kremenekdb094a22007-12-05 18:27:04 +0000989/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
990/// action. These consumers can operate on both ASTs that are freshly
991/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000992static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000993 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +0000994 const LangOptions& LangOpts,
995 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +0000996 switch (ProgAction) {
997 default:
998 return NULL;
999
1000 case ASTPrint:
1001 return CreateASTPrinter();
1002
1003 case ASTDump:
1004 return CreateASTDumper();
1005
1006 case ASTView:
1007 return CreateASTViewer();
1008
1009 case ParseCFGDump:
1010 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001011 return CreateCFGDumper(ProgAction == ParseCFGView,
1012 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001013
1014 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001015 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001016
1017 case WarnDeadStores:
1018 return CreateDeadStoreChecker(Diag);
1019
1020 case WarnUninitVals:
1021 return CreateUnitValsChecker(Diag);
1022
Ted Kremeneke01c9872008-02-14 22:36:46 +00001023 case AnalysisGRSimpleVals:
Ted Kremenekcb330932008-02-18 21:21:23 +00001024 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremeneke603df42008-01-08 18:04:06 +00001025
Ted Kremenekd55fe522008-02-15 00:35:38 +00001026 case AnalysisGRSimpleValsView:
Ted Kremenekcb330932008-02-18 21:21:23 +00001027 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001028
Ted Kremenekdb094a22007-12-05 18:27:04 +00001029 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001030 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001031
1032 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001033 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001034 DestModule = new llvm::Module(InFile);
1035 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001036
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001037 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001038 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001039 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001040
Ted Kremenekdb094a22007-12-05 18:27:04 +00001041 case RewriteTest:
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +00001042 return CreateCodeRewriterTest(InFile, Diag);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001043 }
1044}
1045
Reid Spencer5f016e22007-07-11 17:01:13 +00001046/// ProcessInputFile - Process a single input file with the specified state.
1047///
Ted Kremenek7dcc9682007-12-19 22:32:34 +00001048static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +00001049 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001050
1051 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001052 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001053 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001054
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 switch (ProgAction) {
1056 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001057 Consumer = CreateASTConsumer(InFile,
1058 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001059 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001060 PP.getLangOptions(),
1061 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001062
1063 if (!Consumer) {
1064 fprintf(stderr, "Unexpected program action!\n");
1065 return;
1066 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001067
Ted Kremenekdb094a22007-12-05 18:27:04 +00001068 break;
1069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001071 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001073 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 do {
1075 PP.Lex(Tok);
1076 PP.DumpToken(Tok, true);
1077 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001078 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001079 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001080 break;
1081 }
1082 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001083 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001085 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 do {
1087 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001088 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001089 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 break;
1091 }
1092
1093 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001094 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001095 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 break;
1097
1098 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001099 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001100 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 break;
1102
1103 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001104 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001105 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001107
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001108 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001109 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001110 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001111 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001112
1113 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001114 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001115 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001116
1117 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001118 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001120
1121 // If running the code generator, finish up now.
1122 if (CodeGenModule) {
1123 std::ostream *Out;
1124 if (OutputFile == "-") {
1125 Out = llvm::cout.stream();
1126 } else if (!OutputFile.empty()) {
1127 Out = new std::ofstream(OutputFile.c_str(),
1128 std::ios_base::binary|std::ios_base::out);
1129 } else if (InFile == "-") {
1130 Out = llvm::cout.stream();
1131 } else {
1132 llvm::sys::Path Path(InFile);
1133 Path.eraseSuffix();
1134 if (ProgAction == EmitLLVM)
1135 Path.appendSuffix("ll");
1136 else if (ProgAction == EmitBC)
1137 Path.appendSuffix("bc");
1138 else
1139 assert(0 && "Unknown action");
1140 Out = new std::ofstream(Path.toString().c_str(),
1141 std::ios_base::binary|std::ios_base::out);
1142 }
1143
1144 if (ProgAction == EmitLLVM) {
1145 CodeGenModule->print(*Out);
1146 } else {
1147 assert(ProgAction == EmitBC);
1148 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1149 }
1150
1151 if (Out != llvm::cout.stream())
1152 delete Out;
1153 delete CodeGenModule;
1154 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001155
1156 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001157 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001158 PP.PrintStats();
1159 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001160 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001161 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001162 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 fprintf(stderr, "\n");
1164 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001165
1166 // For a multi-file compilation, some things are ok with nuking the source
1167 // manager tables, other require stable fileid/macroid's across multiple
1168 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001169 if (ClearSourceMgr)
1170 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001171}
1172
Ted Kremenek20e97482007-12-12 23:41:08 +00001173static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1174 FileManager& FileMgr) {
1175
1176 if (VerifyDiagnostics) {
1177 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1178 exit (1);
1179 }
1180
1181 llvm::sys::Path Filename(InFile);
1182
1183 if (!Filename.isValid()) {
1184 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1185 exit (1);
1186 }
1187
Ted Kremenekee533642007-12-20 19:47:16 +00001188 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001189
1190 if (!TU) {
1191 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1192 InFile.c_str());
1193 exit (1);
1194 }
1195
Ted Kremenek63ea8632007-12-19 19:27:38 +00001196 // Observe that we use the source file name stored in the deserialized
1197 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001198 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001199 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001200 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1201 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001202
1203 if (!Consumer) {
1204 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1205 exit (1);
1206 }
1207
Ted Kremenek95041a22007-12-19 22:51:13 +00001208 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001209
Chris Lattnere66b65c2008-02-06 01:42:25 +00001210 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001211 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1212 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001213}
1214
1215
Reid Spencer5f016e22007-07-11 17:01:13 +00001216static llvm::cl::list<std::string>
1217InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1218
Ted Kremenek20e97482007-12-12 23:41:08 +00001219static bool isSerializedFile(const std::string& InFile) {
1220 if (InFile.size() < 4)
1221 return false;
1222
1223 const char* s = InFile.c_str()+InFile.size()-4;
1224
1225 return s[0] == '.' &&
1226 s[1] == 'a' &&
1227 s[2] == 's' &&
1228 s[3] == 't';
1229}
1230
Reid Spencer5f016e22007-07-11 17:01:13 +00001231
1232int main(int argc, char **argv) {
1233 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm cfe\n");
1234 llvm::sys::PrintStackTraceOnErrorSignal();
1235
1236 // If no input was specified, read from stdin.
1237 if (InputFilenames.empty())
1238 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // Create a file manager object to provide access to and cache the filesystem.
1241 FileManager FileMgr;
1242
Ted Kremenek31e703b2007-12-11 23:28:38 +00001243 // Create the diagnostic client for reporting errors or for
1244 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001246 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001248 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 } else {
1250 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001251 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001252
1253 if (InputFilenames.size() != 1) {
1254 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001255 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001256 return 1;
1257 }
1258 }
1259
1260 // Configure our handling of diagnostics.
1261 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001262 InitializeDiagnostics(Diags);
1263
Chris Lattner4f037832007-12-05 23:24:17 +00001264 // -I- is a deprecated GCC feature, scan for it and reject it.
1265 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1266 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001267 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001268 I_dirs.erase(I_dirs.begin()+i);
1269 --i;
1270 }
1271 }
1272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001274 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001275
Ted Kremenek20e97482007-12-12 23:41:08 +00001276 if (isSerializedFile(InFile))
1277 ProcessSerializedFile(InFile,Diags,FileMgr);
1278 else {
1279 /// Create a SourceManager object. This tracks and owns all the file
1280 /// buffers allocated to a translation unit.
1281 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001282
Ted Kremenek20e97482007-12-12 23:41:08 +00001283 // Initialize language options, inferring file types from input filenames.
1284 LangOptions LangInfo;
1285 InitializeBaseLanguage();
1286 LangKind LK = GetLanguage(InFile);
1287 InitializeLangOptions(LangInfo, LK);
1288 InitializeLanguageStandard(LangInfo, LK);
1289
1290 // Process the -I options and set them in the HeaderInfo.
1291 HeaderSearch HeaderInfo(FileMgr);
1292 DiagClient->setHeaderSearch(HeaderInfo);
1293 InitializeIncludePaths(HeaderInfo, FileMgr, LangInfo);
1294
1295 // Get information about the targets being compiled for. Note that this
1296 // pointer and the TargetInfoImpl objects are never deleted by this toy
1297 // driver.
1298 TargetInfo *Target;
1299
1300 // Create triples, and create the TargetInfo.
1301 std::vector<std::string> triples;
1302 CreateTargetTriples(triples);
1303 Target = TargetInfo::CreateTargetInfo(&triples[0],
1304 &triples[0]+triples.size(),
1305 &Diags);
1306
1307 if (Target == 0) {
1308 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1309 triples[0].c_str());
1310 fprintf(stderr, "Please use -triple or -arch.\n");
1311 exit(1);
1312 }
1313
1314 // Set up the preprocessor with these options.
1315 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1316
1317 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001318 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001319 continue;
1320
Ted Kremenek1036b682007-12-19 23:48:45 +00001321 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001322 HeaderInfo.ClearFileInfo();
1323
1324 if (Stats)
1325 SourceMgr.PrintStats();
1326 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 }
1328
1329 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1330
1331 if (NumDiagnostics)
1332 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1333 (NumDiagnostics == 1 ? "" : "s"));
1334
1335 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 FileMgr.PrintStats();
1337 fprintf(stderr, "\n");
1338 }
1339
Chris Lattner96f1a642007-07-21 05:40:53 +00001340 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341}