blob: 4c8a3525c82144c7d74e40df2b87ef0e4fb4eedb [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 Kremenekd71ed262008-04-10 22:16:52 +0000125 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000126 "Perform path-sensitive constant propagation."),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000127 clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000128 "Run the Core Foundation reference count checker."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000129 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerf3dabbd2008-03-09 05:25:01 +0000130 "Run prototype serialization code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000132 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000133 clEnumValN(EmitBC, "emit-llvm-bc",
134 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000135 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000136 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000137 clEnumValN(RewriteTest, "rewrite-test",
138 "Playground for the code rewriter"),
Ted Kremenek13e479b2008-03-19 07:53:42 +0000139 clEnumValN(HTMLTest, "html-test",
140 "Playground for the HTML displayer"),
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000141
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 clEnumValEnd));
143
Ted Kremenekccc76472007-12-19 19:47:59 +0000144
145static llvm::cl::opt<std::string>
146OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000147 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000148 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
149
Ted Kremenek41193e42007-09-26 19:42:19 +0000150static llvm::cl::opt<bool>
151VerifyDiagnostics("verify",
152 llvm::cl::desc("Verify emitted diagnostics and warnings."));
153
Ted Kremenekd71ed262008-04-10 22:16:52 +0000154static llvm::cl::opt<bool>
155VisualizeEG("visualize-egraph",
156 llvm::cl::desc("Display static analysis Exploded Graph."));
157
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000158static llvm::cl::opt<std::string>
159HTMLDiag("html-diags",
160 llvm::cl::desc("Generate HTML to report diagnostics"),
161 llvm::cl::value_desc("HTML directory"));
162
Reid Spencer5f016e22007-07-11 17:01:13 +0000163//===----------------------------------------------------------------------===//
164// Language Options
165//===----------------------------------------------------------------------===//
166
167enum LangKind {
168 langkind_unspecified,
169 langkind_c,
170 langkind_c_cpp,
171 langkind_cxx,
172 langkind_cxx_cpp,
173 langkind_objc,
174 langkind_objc_cpp,
175 langkind_objcxx,
176 langkind_objcxx_cpp
177};
178
179/* TODO: GCC also accepts:
180 c-header c++-header objective-c-header objective-c++-header
181 assembler assembler-with-cpp
182 ada, f77*, ratfor (!), f95, java, treelang
183 */
184static llvm::cl::opt<LangKind>
185BaseLang("x", llvm::cl::desc("Base language to compile"),
186 llvm::cl::init(langkind_unspecified),
187 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
188 clEnumValN(langkind_cxx, "c++", "C++"),
189 clEnumValN(langkind_objc, "objective-c", "Objective C"),
190 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
191 clEnumValN(langkind_c_cpp, "c-cpp-output",
192 "Preprocessed C"),
193 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
194 "Preprocessed C++"),
195 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
196 "Preprocessed Objective C"),
197 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
198 "Preprocessed Objective C++"),
199 clEnumValEnd));
200
201static llvm::cl::opt<bool>
202LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
203 llvm::cl::Hidden);
204static llvm::cl::opt<bool>
205LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
206 llvm::cl::Hidden);
207
Ted Kremenek8904f152007-12-05 23:49:08 +0000208/// InitializeBaseLanguage - Handle the -x foo options.
209static void InitializeBaseLanguage() {
210 if (LangObjC)
211 BaseLang = langkind_objc;
212 else if (LangObjCXX)
213 BaseLang = langkind_objcxx;
214}
215
216static LangKind GetLanguage(const std::string &Filename) {
217 if (BaseLang != langkind_unspecified)
218 return BaseLang;
219
220 std::string::size_type DotPos = Filename.rfind('.');
221
222 if (DotPos == std::string::npos) {
223 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000224 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 }
226
Ted Kremenek8904f152007-12-05 23:49:08 +0000227 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
228 // C header: .h
229 // C++ header: .hh or .H;
230 // assembler no preprocessing: .s
231 // assembler: .S
232 if (Ext == "c")
233 return langkind_c;
234 else if (Ext == "i")
235 return langkind_c_cpp;
236 else if (Ext == "ii")
237 return langkind_cxx_cpp;
238 else if (Ext == "m")
239 return langkind_objc;
240 else if (Ext == "mi")
241 return langkind_objc_cpp;
242 else if (Ext == "mm" || Ext == "M")
243 return langkind_objcxx;
244 else if (Ext == "mii")
245 return langkind_objcxx_cpp;
246 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
247 Ext == "c++" || Ext == "cp" || Ext == "cxx")
248 return langkind_cxx;
249 else
250 return langkind_c;
251}
252
253
254static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 // FIXME: implement -fpreprocessed mode.
256 bool NoPreprocess = false;
257
Ted Kremenek8904f152007-12-05 23:49:08 +0000258 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 default: assert(0 && "Unknown language kind!");
260 case langkind_c_cpp:
261 NoPreprocess = true;
262 // FALLTHROUGH
263 case langkind_c:
264 break;
265 case langkind_cxx_cpp:
266 NoPreprocess = true;
267 // FALLTHROUGH
268 case langkind_cxx:
269 Options.CPlusPlus = 1;
270 break;
271 case langkind_objc_cpp:
272 NoPreprocess = true;
273 // FALLTHROUGH
274 case langkind_objc:
275 Options.ObjC1 = Options.ObjC2 = 1;
276 break;
277 case langkind_objcxx_cpp:
278 NoPreprocess = true;
279 // FALLTHROUGH
280 case langkind_objcxx:
281 Options.ObjC1 = Options.ObjC2 = 1;
282 Options.CPlusPlus = 1;
283 break;
284 }
285}
286
287/// LangStds - Language standards we support.
288enum LangStds {
289 lang_unspecified,
290 lang_c89, lang_c94, lang_c99,
291 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000292 lang_cxx98, lang_gnucxx98,
293 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000294};
295
296static llvm::cl::opt<LangStds>
297LangStd("std", llvm::cl::desc("Language standard to compile for"),
298 llvm::cl::init(lang_unspecified),
299 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
300 clEnumValN(lang_c89, "c90", "ISO C 1990"),
301 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
302 clEnumValN(lang_c94, "iso9899:199409",
303 "ISO C 1990 with amendment 1"),
304 clEnumValN(lang_c99, "c99", "ISO C 1999"),
305// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
306 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
307// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
308 clEnumValN(lang_gnu89, "gnu89",
309 "ISO C 1990 with GNU extensions (default for C)"),
310 clEnumValN(lang_gnu99, "gnu99",
311 "ISO C 1999 with GNU extensions"),
312 clEnumValN(lang_gnu99, "gnu9x",
313 "ISO C 1999 with GNU extensions"),
314 clEnumValN(lang_cxx98, "c++98",
315 "ISO C++ 1998 with amendments"),
316 clEnumValN(lang_gnucxx98, "gnu++98",
317 "ISO C++ 1998 with amendments and GNU "
318 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000319 clEnumValN(lang_cxx0x, "c++0x",
320 "Upcoming ISO C++ 200x with amendments"),
321 clEnumValN(lang_gnucxx0x, "gnu++0x",
322 "Upcoming ISO C++ 200x with amendments and GNU "
323 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 clEnumValEnd));
325
326static llvm::cl::opt<bool>
327NoOperatorNames("fno-operator-names",
328 llvm::cl::desc("Do not treat C++ operator name keywords as "
329 "synonyms for operators"));
330
Anders Carlssonee98ac52007-10-15 02:50:23 +0000331static llvm::cl::opt<bool>
332PascalStrings("fpascal-strings",
333 llvm::cl::desc("Recognize and construct Pascal-style "
334 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000335
336static llvm::cl::opt<bool>
337MSExtensions("fms-extensions",
338 llvm::cl::desc("Accept some non-standard constructs used in "
339 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000340
341static llvm::cl::opt<bool>
342WritableStrings("fwritable-strings",
343 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000344
345static llvm::cl::opt<bool>
346LaxVectorConversions("flax-vector-conversions",
347 llvm::cl::desc("Allow implicit conversions between vectors"
348 " with a different number of elements or "
349 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000350// FIXME: add:
351// -ansi
352// -trigraphs
353// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000354// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000355static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 if (LangStd == lang_unspecified) {
357 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000358 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 default: assert(0 && "Unknown base language");
360 case langkind_c:
361 case langkind_c_cpp:
362 case langkind_objc:
363 case langkind_objc_cpp:
364 LangStd = lang_gnu99;
365 break;
366 case langkind_cxx:
367 case langkind_cxx_cpp:
368 case langkind_objcxx:
369 case langkind_objcxx_cpp:
370 LangStd = lang_gnucxx98;
371 break;
372 }
373 }
374
375 switch (LangStd) {
376 default: assert(0 && "Unknown language standard!");
377
378 // Fall through from newer standards to older ones. This isn't really right.
379 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000380 case lang_gnucxx0x:
381 case lang_cxx0x:
382 Options.CPlusPlus0x = 1;
383 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 case lang_gnucxx98:
385 case lang_cxx98:
386 Options.CPlusPlus = 1;
387 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000388 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // FALL THROUGH.
390 case lang_gnu99:
391 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 Options.C99 = 1;
393 Options.HexFloats = 1;
394 // FALL THROUGH.
395 case lang_gnu89:
396 Options.BCPLComment = 1; // Only for C99/C++.
397 // FALL THROUGH.
398 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000399 Options.Digraphs = 1; // C94, C99, C++.
400 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 case lang_c89:
402 break;
403 }
404
Chris Lattnerd658b562008-04-05 06:32:51 +0000405 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
406 Options.ImplicitInt = 1;
407 else
408 Options.ImplicitInt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 Options.Trigraphs = 1; // -trigraphs or -ansi
410 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000411 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000412 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000413 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000414 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000415}
416
417//===----------------------------------------------------------------------===//
418// Our DiagnosticClient implementation
419//===----------------------------------------------------------------------===//
420
421// FIXME: Werror should take a list of things, -Werror=foo,bar
422static llvm::cl::opt<bool>
423WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
424
425static llvm::cl::opt<bool>
426WarnOnExtensions("pedantic", llvm::cl::init(false),
427 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
428
429static llvm::cl::opt<bool>
430ErrorOnExtensions("pedantic-errors",
431 llvm::cl::desc("Issue an error on uses of GCC extensions"));
432
433static llvm::cl::opt<bool>
434WarnUnusedMacros("Wunused_macros",
435 llvm::cl::desc("Warn for unused macros in the main translation unit"));
436
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000437static llvm::cl::opt<bool>
438WarnFloatEqual("Wfloat-equal",
439 llvm::cl::desc("Warn about equality comparisons of floating point values."));
440
Ted Kremenek73da5902007-12-17 17:50:07 +0000441static llvm::cl::opt<bool>
442WarnNoFormatNonLiteral("Wno-format-nonliteral",
443 llvm::cl::desc("Do not warn about non-literal format strings."));
444
Chris Lattner116a4b12008-01-23 17:19:46 +0000445static llvm::cl::opt<bool>
446WarnUndefMacros("Wundef",
447 llvm::cl::desc("Warn on use of undefined macros in #if's"));
448
449
Reid Spencer5f016e22007-07-11 17:01:13 +0000450/// InitializeDiagnostics - Initialize the diagnostic object, based on the
451/// current command line option settings.
452static void InitializeDiagnostics(Diagnostic &Diags) {
453 Diags.setWarningsAsErrors(WarningsAsErrors);
454 Diags.setWarnOnExtensions(WarnOnExtensions);
455 Diags.setErrorOnExtensions(ErrorOnExtensions);
456
457 // Silence the "macro is not used" warning unless requested.
458 if (!WarnUnusedMacros)
459 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000460
461 // Silence "floating point comparison" warnings unless requested.
462 if (!WarnFloatEqual)
463 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000464
465 // Silence "format string is not a string literal" warnings if requested
466 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000467 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
468 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000469 if (!WarnUndefMacros)
470 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000471
472 if (MSExtensions) // MS allows unnamed struct/union fields.
473 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000474}
475
476//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000477// Analysis-specific options.
478//===----------------------------------------------------------------------===//
479
480static llvm::cl::opt<std::string>
481AnalyzeSpecificFunction("analyze-function",
482 llvm::cl::desc("Run analysis on specific function."));
483
Ted Kremenekffe0f432008-03-07 22:58:01 +0000484static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000485TrimGraph("trim-egraph",
Ted Kremenekffe0f432008-03-07 22:58:01 +0000486 llvm::cl::desc("Only show error-related paths in the analysis graph."));
487
Ted Kremenekcb330932008-02-18 21:21:23 +0000488//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000489// Target Triple Processing.
490//===----------------------------------------------------------------------===//
491
492static llvm::cl::opt<std::string>
493TargetTriple("triple",
494 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
495
Chris Lattner42e67372008-03-05 01:18:20 +0000496static llvm::cl::opt<std::string>
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000497Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenekae360762007-12-03 22:06:55 +0000498
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000499static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000500 // Initialize base triple. If a -triple option has been specified, use
501 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000502 std::string Triple = TargetTriple;
503 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000504
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000505 // If -arch foo was specified, remove the architecture from the triple we have
506 // so far and replace it with the specified one.
507 if (Arch.empty())
508 return Triple;
509
Ted Kremenekae360762007-12-03 22:06:55 +0000510 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000511 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000512
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000513 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000514 fprintf(stderr,
515 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000516 Triple.c_str());
517 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000518 }
Ted Kremenekae360762007-12-03 22:06:55 +0000519
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000520 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000521}
522
523//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000524// Preprocessor Initialization
525//===----------------------------------------------------------------------===//
526
527// FIXME: Preprocessor builtins to support.
528// -A... - Play with #assertions
529// -undef - Undefine all predefined macros
530
531static llvm::cl::list<std::string>
532D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
533 llvm::cl::desc("Predefine the specified macro"));
534static llvm::cl::list<std::string>
535U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
536 llvm::cl::desc("Undefine the specified macro"));
537
Chris Lattner64299f82008-01-10 01:53:41 +0000538static llvm::cl::list<std::string>
539ImplicitIncludes("include", llvm::cl::value_desc("file"),
540 llvm::cl::desc("Include file before parsing"));
541
542
Reid Spencer5f016e22007-07-11 17:01:13 +0000543// Append a #define line to Buf for Macro. Macro should be of the form XXX,
544// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
545// "#define XXX Y z W". To get a #define with no value, use "XXX=".
546static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
547 const char *Command = "#define ") {
548 Buf.insert(Buf.end(), Command, Command+strlen(Command));
549 if (const char *Equal = strchr(Macro, '=')) {
550 // Turn the = into ' '.
551 Buf.insert(Buf.end(), Macro, Equal);
552 Buf.push_back(' ');
553 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
554 } else {
555 // Push "macroname 1".
556 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
557 Buf.push_back(' ');
558 Buf.push_back('1');
559 }
560 Buf.push_back('\n');
561}
562
Chris Lattner64299f82008-01-10 01:53:41 +0000563/// AddImplicitInclude - Add an implicit #include of the specified file to the
564/// predefines buffer.
565static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
566 const char *Inc = "#include \"";
567 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
568 Buf.insert(Buf.end(), File.begin(), File.end());
569 Buf.push_back('"');
570 Buf.push_back('\n');
571}
572
Reid Spencer5f016e22007-07-11 17:01:13 +0000573
Chris Lattner53b0dab2007-10-09 22:10:18 +0000574/// InitializePreprocessor - Initialize the preprocessor getting it and the
575/// environment ready to process a single file. This returns the file ID for the
576/// input file. If a failure happens, it returns 0.
577///
578static unsigned InitializePreprocessor(Preprocessor &PP,
579 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000580 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000581
Chris Lattnerdee73592007-12-15 20:48:40 +0000582 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000583
Chris Lattner53b0dab2007-10-09 22:10:18 +0000584 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000585 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000586 if (InFile != "-") {
587 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000588 if (File) SourceMgr.createMainFileID(File, SourceLocation());
589 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000590 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
591 return 0;
592 }
593 } else {
594 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000595 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
596 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000597 fprintf(stderr, "Error reading standard input! Empty?\n");
598 return 0;
599 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 }
601
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 // Add macros from the command line.
603 // FIXME: Should traverse the #define/#undef lists in parallel.
604 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000605 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000607 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
608
Chris Lattner64299f82008-01-10 01:53:41 +0000609 // FIXME: Read any files specified by -imacros.
610
611 // Add implicit #includes from -include.
612 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
613 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000614
615 // Null terminate PredefinedBuffer and add it.
616 PredefineBuffer.push_back(0);
617 PP.setPredefines(&PredefineBuffer[0]);
618
619 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000620 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000621}
622
623//===----------------------------------------------------------------------===//
624// Preprocessor include path information.
625//===----------------------------------------------------------------------===//
626
627// This tool exports a large number of command line options to control how the
628// preprocessor searches for header files. At root, however, the Preprocessor
629// object takes a very simple interface: a list of directories to search for
630//
631// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000632// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000633//
Chris Lattner64299f82008-01-10 01:53:41 +0000634// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000635
636static llvm::cl::opt<bool>
637nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
638
639// Various command line options. These four add directories to each chain.
640static llvm::cl::list<std::string>
641F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
642 llvm::cl::desc("Add directory to framework include search path"));
643static llvm::cl::list<std::string>
644I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
645 llvm::cl::desc("Add directory to include search path"));
646static llvm::cl::list<std::string>
647idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
648 llvm::cl::desc("Add directory to AFTER include search path"));
649static llvm::cl::list<std::string>
650iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
651 llvm::cl::desc("Add directory to QUOTE include search path"));
652static llvm::cl::list<std::string>
653isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
654 llvm::cl::desc("Add directory to SYSTEM include search path"));
655
656// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
657static llvm::cl::list<std::string>
658iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
659 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
660static llvm::cl::list<std::string>
661iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
662 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
663static llvm::cl::list<std::string>
664iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
665 llvm::cl::Prefix,
666 llvm::cl::desc("Set directory to include search path with prefix"));
667
Chris Lattner0c946412007-08-26 17:47:35 +0000668static llvm::cl::opt<std::string>
669isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
670 llvm::cl::desc("Set the system root directory (usually /)"));
671
Reid Spencer5f016e22007-07-11 17:01:13 +0000672// Finally, implement the code that groks the options above.
673enum IncludeDirGroup {
674 Quoted = 0,
675 Angled,
676 System,
677 After
678};
679
680static std::vector<DirectoryLookup> IncludeGroup[4];
681
682/// AddPath - Add the specified path to the specified group list.
683///
684static void AddPath(const std::string &Path, IncludeDirGroup Group,
685 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000686 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000687 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000688 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000689
Chris Lattnerd6655272007-12-17 05:59:27 +0000690 // Compute the actual path, taking into consideration -isysroot.
691 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000692
Chris Lattnerd6655272007-12-17 05:59:27 +0000693 // Handle isysroot.
694 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000695 // FIXME: Portability. This should be a sys::Path interface, this doesn't
696 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000697 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
698 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 }
700
Chris Lattnerd6655272007-12-17 05:59:27 +0000701 MappedPath.append(Path.begin(), Path.end());
702
703 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 DirectoryLookup::DirType Type;
705 if (Group == Quoted || Group == Angled)
706 Type = DirectoryLookup::NormalHeaderDir;
707 else if (isCXXAware)
708 Type = DirectoryLookup::SystemHeaderDir;
709 else
710 Type = DirectoryLookup::ExternCSystemHeaderDir;
711
Chris Lattnerd6655272007-12-17 05:59:27 +0000712
713 // If the directory exists, add it.
714 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
715 &MappedPath[0]+
716 MappedPath.size())) {
717 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
718 isFramework));
719 return;
720 }
721
Chris Lattnerdf772332007-12-17 07:52:39 +0000722 // Check to see if this is an apple-style headermap (which are not allowed to
723 // be frameworks).
724 if (!isFramework) {
725 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
726 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000727 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
728 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000729 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
730 return;
731 }
Chris Lattner822da612007-12-17 06:36:45 +0000732 }
733 }
734
Chris Lattnerd6655272007-12-17 05:59:27 +0000735 if (Verbose)
736 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000737}
738
739/// RemoveDuplicates - If there are duplicate directory entries in the specified
740/// search list, remove the later (dead) ones.
741static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000742 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000743 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000744 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000746 if (SearchList[i].isNormalDir()) {
747 // If this isn't the first time we've seen this dir, remove it.
748 if (SeenDirs.insert(SearchList[i].getDir()))
749 continue;
750
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 if (Verbose)
752 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
753 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000754 } else if (SearchList[i].isFramework()) {
755 // If this isn't the first time we've seen this framework dir, remove it.
756 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
757 continue;
758
759 if (Verbose)
760 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
761 SearchList[i].getFrameworkDir()->getName());
762
Chris Lattnerb94c7072007-12-17 06:44:29 +0000763 } else {
764 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
765 // If this isn't the first time we've seen this headermap, remove it.
766 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
767 continue;
768
769 if (Verbose)
770 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
771 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000772 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000773
774 // This is reached if the current entry is a duplicate.
775 SearchList.erase(SearchList.begin()+i);
776 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 }
778}
779
Chris Lattner5f9eae52008-03-01 08:07:28 +0000780// AddEnvVarPaths - Add a list of paths from an environment variable to a
781// header search list.
782//
783static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
784 const char* at = getenv(Name);
785 if (!at)
786 return;
787
788 const char* delim = strchr(at, llvm::sys::PathSeparator);
789 while (delim != 0) {
790 if (delim-at == 0)
791 AddPath(".", Angled, false, true, false, Headers);
792 else
793 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
794 true, false, Headers);
795 at = delim + 1;
796 delim = strchr(at, llvm::sys::PathSeparator);
797 }
798 if (*at == 0)
799 AddPath(".", Angled, false, true, false, Headers);
800 else
801 AddPath(at, Angled, false, true, false, Headers);
802}
803
Reid Spencer5f016e22007-07-11 17:01:13 +0000804/// InitializeIncludePaths - Process the -I options and set them in the
805/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000806static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
807 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 // Handle -F... options.
809 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000810 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000811
812 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000813 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000814 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000815
816 // Handle -idirafter... options.
817 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000818 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000819
820 // Handle -iquote... options.
821 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000822 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000823
824 // Handle -isystem... options.
825 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000826 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827
828 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
829 // parallel, processing the values in order of occurance to get the right
830 // prefixes.
831 {
832 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
833 unsigned iprefix_idx = 0;
834 unsigned iwithprefix_idx = 0;
835 unsigned iwithprefixbefore_idx = 0;
836 bool iprefix_done = iprefix_vals.empty();
837 bool iwithprefix_done = iwithprefix_vals.empty();
838 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
839 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
840 if (!iprefix_done &&
841 (iwithprefix_done ||
842 iprefix_vals.getPosition(iprefix_idx) <
843 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
844 (iwithprefixbefore_done ||
845 iprefix_vals.getPosition(iprefix_idx) <
846 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
847 Prefix = iprefix_vals[iprefix_idx];
848 ++iprefix_idx;
849 iprefix_done = iprefix_idx == iprefix_vals.size();
850 } else if (!iwithprefix_done &&
851 (iwithprefixbefore_done ||
852 iwithprefix_vals.getPosition(iwithprefix_idx) <
853 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
854 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000855 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 ++iwithprefix_idx;
857 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
858 } else {
859 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000860 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000861 ++iwithprefixbefore_idx;
862 iwithprefixbefore_done =
863 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
864 }
865 }
866 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000867
868 AddEnvVarPaths("CPATH", Headers);
869 if (Lang.CPlusPlus && Lang.ObjC1)
870 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
871 else if (Lang.CPlusPlus)
872 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
873 else if (Lang.ObjC1)
874 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
875 else
876 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
877
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000878 // Add the clang headers, which are relative to the clang driver.
879 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000880 llvm::sys::Path::GetMainExecutable(Argv0,
881 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000882 if (!MainExecutablePath.isEmpty()) {
883 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
884 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
885 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
886 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
887 }
888
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 // FIXME: temporary hack: hard-coded paths.
890 // FIXME: get these from the target?
891 if (!nostdinc) {
892 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000893 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000895 false, Headers);
896 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
897 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000898
899 // Ubuntu 7.10 - Gutsy Gibbon
900 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
901 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
902 false, Headers);
903 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
904 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000905
906 // Fedora 8
907 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
908 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false, false, Headers);
909 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 }
911
Chris Lattner822da612007-12-17 06:36:45 +0000912 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 // leopard
914 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000915 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000917 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
919 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000920 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000921
922 // tiger
923 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000924 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000926 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
928 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000929 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000930
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000931 // Ubuntu 7.10 - Gutsy Gibbon
932 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000933 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000934
Chris Lattner04421082008-04-08 04:40:51 +0000935 // Fedora 8
936 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
937 false, false, false, Headers);
938
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000939 //Debian testing/lenny x86
940 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
941 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +0000942
943 //Debian testing/lenny amd64
944 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
945 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000946
Chris Lattner822da612007-12-17 06:36:45 +0000947 AddPath("/usr/include", System, false, false, false, Headers);
948 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
949 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 }
951
952 // Now that we have collected all of the include paths, merge them all
953 // together and tell the preprocessor about them.
954
955 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
956 std::vector<DirectoryLookup> SearchList;
957 SearchList = IncludeGroup[Angled];
958 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
959 IncludeGroup[System].end());
960 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
961 IncludeGroup[After].end());
962 RemoveDuplicates(SearchList);
963 RemoveDuplicates(IncludeGroup[Quoted]);
964
965 // Prepend QUOTED list on the search list.
966 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
967 IncludeGroup[Quoted].end());
968
969
970 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
971 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
972 DontSearchCurDir);
973
974 // If verbose, print the list of directories that will be searched.
975 if (Verbose) {
976 fprintf(stderr, "#include \"...\" search starts here:\n");
977 unsigned QuotedIdx = IncludeGroup[Quoted].size();
978 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
979 if (i == QuotedIdx)
980 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000981 const char *Name = SearchList[i].getName();
982 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000983 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000984 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000985 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000986 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000987 else {
988 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000989 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000990 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000991 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 }
Chris Lattner80e17152007-12-15 23:11:06 +0000993 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 }
995}
996
997
Reid Spencer5f016e22007-07-11 17:01:13 +0000998//===----------------------------------------------------------------------===//
999// Basic Parser driver
1000//===----------------------------------------------------------------------===//
1001
Ted Kremenek95041a22007-12-19 22:51:13 +00001002static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001004 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001005
1006 // Parsing the specified input file.
1007 P.ParseTranslationUnit();
1008 delete PA;
1009}
1010
1011//===----------------------------------------------------------------------===//
1012// Main driver
1013//===----------------------------------------------------------------------===//
1014
Ted Kremenekdb094a22007-12-05 18:27:04 +00001015/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1016/// action. These consumers can operate on both ASTs that are freshly
1017/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001018static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001019 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001020 const LangOptions& LangOpts,
1021 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001022 switch (ProgAction) {
1023 default:
1024 return NULL;
1025
1026 case ASTPrint:
1027 return CreateASTPrinter();
1028
1029 case ASTDump:
1030 return CreateASTDumper();
1031
1032 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001033 return CreateASTViewer();
1034
1035 case EmitHTML:
1036 return CreateHTMLPrinter();
Ted Kremenekdb094a22007-12-05 18:27:04 +00001037
Ted Kremenek13e479b2008-03-19 07:53:42 +00001038 case HTMLTest:
1039 return CreateHTMLTest();
1040
Ted Kremenekdb094a22007-12-05 18:27:04 +00001041 case ParseCFGDump:
1042 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001043 return CreateCFGDumper(ProgAction == ParseCFGView,
1044 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001045
1046 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001047 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001048
1049 case WarnDeadStores:
1050 return CreateDeadStoreChecker(Diag);
1051
1052 case WarnUninitVals:
1053 return CreateUnitValsChecker(Diag);
1054
Ted Kremeneke01c9872008-02-14 22:36:46 +00001055 case AnalysisGRSimpleVals:
Ted Kremenek4dc41cc2008-03-31 18:26:32 +00001056 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, OutputFile,
Ted Kremenekd71ed262008-04-10 22:16:52 +00001057 VisualizeEG, TrimGraph);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001058
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001059 case CheckerCFRef:
Ted Kremenekd71ed262008-04-10 22:16:52 +00001060 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction, OutputFile,
1061 VisualizeEG, TrimGraph);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001062
Ted Kremenekdb094a22007-12-05 18:27:04 +00001063 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001064 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001065
1066 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001067 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001068 DestModule = new llvm::Module(InFile);
1069 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001070
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001071 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001072 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001073 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001074
Ted Kremenekdb094a22007-12-05 18:27:04 +00001075 case RewriteTest:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001076 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001077 }
1078}
1079
Reid Spencer5f016e22007-07-11 17:01:13 +00001080/// ProcessInputFile - Process a single input file with the specified state.
1081///
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001082static void ProcessInputFile(Preprocessor &PP, const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001083
1084 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001085 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001086 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001087
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 switch (ProgAction) {
1089 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001090 Consumer = CreateASTConsumer(InFile,
1091 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001092 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001093 PP.getLangOptions(),
1094 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001095
1096 if (!Consumer) {
1097 fprintf(stderr, "Unexpected program action!\n");
1098 return;
1099 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001100
Ted Kremenekdb094a22007-12-05 18:27:04 +00001101 break;
1102
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 case DumpTokens: { // Token dump mode.
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);
1109 PP.DumpToken(Tok, true);
1110 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001111 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001112 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 break;
1114 }
1115 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001116 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001118 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 do {
1120 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001121 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001122 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 break;
1124 }
1125
1126 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001127 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001128 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 break;
1130
1131 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001132 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001133 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 break;
1135
1136 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001137 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001138 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001140
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001141 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001142 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001143 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001144 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001145
1146 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001147 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001148 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001149
1150 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001151 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001153
1154 // If running the code generator, finish up now.
1155 if (CodeGenModule) {
1156 std::ostream *Out;
1157 if (OutputFile == "-") {
1158 Out = llvm::cout.stream();
1159 } else if (!OutputFile.empty()) {
1160 Out = new std::ofstream(OutputFile.c_str(),
1161 std::ios_base::binary|std::ios_base::out);
1162 } else if (InFile == "-") {
1163 Out = llvm::cout.stream();
1164 } else {
1165 llvm::sys::Path Path(InFile);
1166 Path.eraseSuffix();
1167 if (ProgAction == EmitLLVM)
1168 Path.appendSuffix("ll");
1169 else if (ProgAction == EmitBC)
1170 Path.appendSuffix("bc");
1171 else
1172 assert(0 && "Unknown action");
1173 Out = new std::ofstream(Path.toString().c_str(),
1174 std::ios_base::binary|std::ios_base::out);
1175 }
1176
1177 if (ProgAction == EmitLLVM) {
1178 CodeGenModule->print(*Out);
1179 } else {
1180 assert(ProgAction == EmitBC);
1181 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1182 }
1183
1184 if (Out != llvm::cout.stream())
1185 delete Out;
1186 delete CodeGenModule;
1187 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001188
1189 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001190 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 PP.PrintStats();
1192 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001193 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001194 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001195 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 fprintf(stderr, "\n");
1197 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001198
1199 // For a multi-file compilation, some things are ok with nuking the source
1200 // manager tables, other require stable fileid/macroid's across multiple
1201 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001202 if (ClearSourceMgr)
1203 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001204}
1205
Ted Kremenek20e97482007-12-12 23:41:08 +00001206static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1207 FileManager& FileMgr) {
1208
1209 if (VerifyDiagnostics) {
1210 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1211 exit (1);
1212 }
1213
1214 llvm::sys::Path Filename(InFile);
1215
1216 if (!Filename.isValid()) {
1217 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1218 exit (1);
1219 }
1220
Ted Kremenekee533642007-12-20 19:47:16 +00001221 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001222
1223 if (!TU) {
1224 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1225 InFile.c_str());
1226 exit (1);
1227 }
1228
Ted Kremenek63ea8632007-12-19 19:27:38 +00001229 // Observe that we use the source file name stored in the deserialized
1230 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001231 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001232 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001233 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1234 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001235
1236 if (!Consumer) {
1237 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1238 exit (1);
1239 }
1240
Ted Kremenek95041a22007-12-19 22:51:13 +00001241 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001242
Chris Lattnere66b65c2008-02-06 01:42:25 +00001243 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001244 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1245 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001246}
1247
1248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249static llvm::cl::list<std::string>
1250InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1251
Ted Kremenek20e97482007-12-12 23:41:08 +00001252static bool isSerializedFile(const std::string& InFile) {
1253 if (InFile.size() < 4)
1254 return false;
1255
1256 const char* s = InFile.c_str()+InFile.size()-4;
1257
1258 return s[0] == '.' &&
1259 s[1] == 'a' &&
1260 s[2] == 's' &&
1261 s[3] == 't';
1262}
1263
Reid Spencer5f016e22007-07-11 17:01:13 +00001264
1265int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001266 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 llvm::sys::PrintStackTraceOnErrorSignal();
1268
1269 // If no input was specified, read from stdin.
1270 if (InputFilenames.empty())
1271 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 // Create a file manager object to provide access to and cache the filesystem.
1274 FileManager FileMgr;
1275
Ted Kremenek31e703b2007-12-11 23:28:38 +00001276 // Create the diagnostic client for reporting errors or for
1277 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001278 std::auto_ptr<DiagnosticClient> DiagClient;
1279 TextDiagnostics* TextDiagClient = NULL;
1280
1281 if (!HTMLDiag.empty()) {
1282 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
1283 }
1284 else { // Use Text diagnostics.
1285 if (!VerifyDiagnostics) {
1286 // Print diagnostics to stderr by default.
1287 TextDiagClient = new TextDiagnosticPrinter();
1288 } else {
1289 // When checking diagnostics, just buffer them up.
1290 TextDiagClient = new TextDiagnosticBuffer();
1291
1292 if (InputFilenames.size() != 1) {
1293 fprintf(stderr,
1294 "-verify only works on single input files for now.\n");
1295 return 1;
1296 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001298
1299 assert (TextDiagClient);
1300 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 }
1302
1303 // Configure our handling of diagnostics.
1304 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001305 InitializeDiagnostics(Diags);
1306
Chris Lattner4f037832007-12-05 23:24:17 +00001307 // -I- is a deprecated GCC feature, scan for it and reject it.
1308 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1309 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001310 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001311 I_dirs.erase(I_dirs.begin()+i);
1312 --i;
1313 }
1314 }
Chris Lattner11215192008-03-14 06:12:05 +00001315
1316 // Get information about the target being compiled for.
1317 std::string Triple = CreateTargetTriple();
1318 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1319 if (Target == 0) {
1320 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1321 Triple.c_str());
1322 fprintf(stderr, "Please use -triple or -arch.\n");
1323 exit(1);
1324 }
Chris Lattner4f037832007-12-05 23:24:17 +00001325
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001327 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001328
Ted Kremenek20e97482007-12-12 23:41:08 +00001329 if (isSerializedFile(InFile))
1330 ProcessSerializedFile(InFile,Diags,FileMgr);
1331 else {
1332 /// Create a SourceManager object. This tracks and owns all the file
1333 /// buffers allocated to a translation unit.
1334 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001335
Ted Kremenek20e97482007-12-12 23:41:08 +00001336 // Initialize language options, inferring file types from input filenames.
1337 LangOptions LangInfo;
1338 InitializeBaseLanguage();
1339 LangKind LK = GetLanguage(InFile);
1340 InitializeLangOptions(LangInfo, LK);
1341 InitializeLanguageStandard(LangInfo, LK);
1342
1343 // Process the -I options and set them in the HeaderInfo.
1344 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001345 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001346 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001347
Ted Kremenek20e97482007-12-12 23:41:08 +00001348 // Set up the preprocessor with these options.
1349 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1350
1351 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001352 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001353 continue;
1354
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001355 ProcessInputFile(PP, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001356 HeaderInfo.ClearFileInfo();
1357
1358 if (Stats)
1359 SourceMgr.PrintStats();
1360 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 }
1362
Chris Lattner11215192008-03-14 06:12:05 +00001363 delete Target;
1364
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1366
1367 if (NumDiagnostics)
1368 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1369 (NumDiagnostics == 1 ? "" : "s"));
1370
1371 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 FileMgr.PrintStats();
1373 fprintf(stderr, "\n");
1374 }
1375
Chris Lattner96f1a642007-07-21 05:40:53 +00001376 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001377}