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