blob: e7dacc44fd4ab4488b4bd6196b1eb4f736becad7 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenekac881932007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000035#include "clang/Parse/Parser.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Basic/FileManager.h"
38#include "clang/Basic/SourceManager.h"
39#include "clang/Basic/TargetInfo.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner8d72ee02008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner4b009652007-07-25 00:24:17 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenek40499482007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include <memory>
Chris Lattner8d72ee02008-02-06 01:42:25 +000050#include <fstream>
Ted Kremenek4e9899f2008-04-17 22:31:54 +000051#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Global options.
56//===----------------------------------------------------------------------===//
57
58static llvm::cl::opt<bool>
59Verbose("v", llvm::cl::desc("Enable verbose output"));
60static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000061Stats("print-stats",
62 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000063
64enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000065 RewriteObjC, // ObjC->C Rewriter.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000066 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000067 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000068 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000069 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000070 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000071 ASTPrint, // Parse ASTs and print them.
72 ASTDump, // Parse ASTs and dump them.
73 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek97f75312007-08-21 21:42:03 +000074 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000075 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000076 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek1da5b142008-02-15 00:35:38 +000077 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
78 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek827f93b2008-03-06 00:08:09 +000079 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000080 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000081 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000082 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000083 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000084 ParsePrintCallbacks, // Parse and print each callback.
85 ParseSyntaxOnly, // Parse and perform semantic analysis.
86 ParseNoop, // Parse with noop callbacks.
87 RunPreprocessorOnly, // Just lex, no output.
88 PrintPreprocessedInput, // -E mode.
89 DumpTokens // Token dump mode.
90};
91
92static llvm::cl::opt<ProgActions>
93ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
94 llvm::cl::init(ParseSyntaxOnly),
95 llvm::cl::values(
96 clEnumValN(RunPreprocessorOnly, "Eonly",
97 "Just run preprocessor, no output (for timings)"),
98 clEnumValN(PrintPreprocessedInput, "E",
99 "Run preprocessor, emit preprocessed file"),
100 clEnumValN(DumpTokens, "dumptokens",
101 "Run preprocessor, dump internal rep of tokens"),
102 clEnumValN(ParseNoop, "parse-noop",
103 "Run parser with noop callbacks (for timings)"),
104 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
105 "Run parser and perform semantic analysis"),
106 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
107 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000108 clEnumValN(EmitHTML, "emit-html",
109 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000110 clEnumValN(ASTPrint, "ast-print",
111 "Build ASTs and then pretty-print them"),
112 clEnumValN(ASTDump, "ast-dump",
113 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000114 clEnumValN(ASTView, "ast-view",
Chris Lattner4045a8a2007-10-11 00:18:28 +0000115 "Build ASTs and view them with GraphViz."),
Ted Kremenek97f75312007-08-21 21:42:03 +0000116 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000117 "Run parser, then build and print CFGs."),
118 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremenekaa04c512007-09-06 00:17:54 +0000119 "Run parser, then build and view CFGs with Graphviz."),
120 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek05334682007-09-06 21:26:58 +0000121 "Print results of live variable analysis."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000122 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremeneke805c4a2007-09-06 23:00:42 +0000123 "Flag warnings of stores to dead variables."),
Ted Kremenek945fb562007-09-25 18:05:45 +0000124 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek0a03ce62007-09-17 20:49:30 +0000125 "Flag warnings of uses of unitialized variables."),
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000126 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Chris Lattner2528b5e2008-01-10 01:41:55 +0000127 "Perform path-sensitive constant propagation."),
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000128 clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenek827f93b2008-03-06 00:08:09 +0000129 "Run the Core Foundation reference count checker."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000130 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerc04cf132008-03-09 05:25:01 +0000131 "Run prototype serialization code."),
Chris Lattner4b009652007-07-25 00:24:17 +0000132 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000133 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000134 clEnumValN(EmitBC, "emit-llvm-bc",
135 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000136 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000137 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000138 clEnumValN(RewriteObjC, "rewrite-objc",
Ted Kremenek33245d32008-04-16 04:38:45 +0000139 "Playground for the code rewriter"),
Chris Lattner4b009652007-07-25 00:24:17 +0000140 clEnumValEnd));
141
Ted Kremenekd01eae62007-12-19 19:47:59 +0000142
143static llvm::cl::opt<std::string>
144OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000145 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000146 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000147
148//===----------------------------------------------------------------------===//
149// Diagnostic Options
150//===----------------------------------------------------------------------===//
151
Ted Kremenek10389cf2007-09-26 19:42:19 +0000152static llvm::cl::opt<bool>
153VerifyDiagnostics("verify",
154 llvm::cl::desc("Verify emitted diagnostics and warnings."));
155
Ted Kremenekfd75e312008-03-27 06:17:42 +0000156static llvm::cl::opt<std::string>
157HTMLDiag("html-diags",
158 llvm::cl::desc("Generate HTML to report diagnostics"),
159 llvm::cl::value_desc("HTML directory"));
160
Chris Lattner4b009652007-07-25 00:24:17 +0000161//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000162// Analyzer Options
163//===----------------------------------------------------------------------===//
164
165static llvm::cl::opt<bool>
166VisualizeEG("visualize-egraph",
167 llvm::cl::desc("Display static analysis Exploded Graph."));
168
169static llvm::cl::opt<bool>
170AnalyzeAll("checker-opt-analyze-headers",
171 llvm::cl::desc("Force the static analyzer to analyze "
172 "functions defined in header files."));
173
174//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000175// Language Options
176//===----------------------------------------------------------------------===//
177
178enum LangKind {
179 langkind_unspecified,
180 langkind_c,
181 langkind_c_cpp,
182 langkind_cxx,
183 langkind_cxx_cpp,
184 langkind_objc,
185 langkind_objc_cpp,
186 langkind_objcxx,
187 langkind_objcxx_cpp
188};
189
190/* TODO: GCC also accepts:
191 c-header c++-header objective-c-header objective-c++-header
192 assembler assembler-with-cpp
193 ada, f77*, ratfor (!), f95, java, treelang
194 */
195static llvm::cl::opt<LangKind>
196BaseLang("x", llvm::cl::desc("Base language to compile"),
197 llvm::cl::init(langkind_unspecified),
198 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
199 clEnumValN(langkind_cxx, "c++", "C++"),
200 clEnumValN(langkind_objc, "objective-c", "Objective C"),
201 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
202 clEnumValN(langkind_c_cpp, "c-cpp-output",
203 "Preprocessed C"),
204 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
205 "Preprocessed C++"),
206 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
207 "Preprocessed Objective C"),
208 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
209 "Preprocessed Objective C++"),
210 clEnumValEnd));
211
212static llvm::cl::opt<bool>
213LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
214 llvm::cl::Hidden);
215static llvm::cl::opt<bool>
216LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
217 llvm::cl::Hidden);
218
Ted Kremenek11ad8952007-12-05 23:49:08 +0000219/// InitializeBaseLanguage - Handle the -x foo options.
220static void InitializeBaseLanguage() {
221 if (LangObjC)
222 BaseLang = langkind_objc;
223 else if (LangObjCXX)
224 BaseLang = langkind_objcxx;
225}
226
227static LangKind GetLanguage(const std::string &Filename) {
228 if (BaseLang != langkind_unspecified)
229 return BaseLang;
230
231 std::string::size_type DotPos = Filename.rfind('.');
232
233 if (DotPos == std::string::npos) {
234 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000235 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000236 }
237
Ted Kremenek11ad8952007-12-05 23:49:08 +0000238 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
239 // C header: .h
240 // C++ header: .hh or .H;
241 // assembler no preprocessing: .s
242 // assembler: .S
243 if (Ext == "c")
244 return langkind_c;
245 else if (Ext == "i")
246 return langkind_c_cpp;
247 else if (Ext == "ii")
248 return langkind_cxx_cpp;
249 else if (Ext == "m")
250 return langkind_objc;
251 else if (Ext == "mi")
252 return langkind_objc_cpp;
253 else if (Ext == "mm" || Ext == "M")
254 return langkind_objcxx;
255 else if (Ext == "mii")
256 return langkind_objcxx_cpp;
257 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
258 Ext == "c++" || Ext == "cp" || Ext == "cxx")
259 return langkind_cxx;
260 else
261 return langkind_c;
262}
263
264
265static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000266 // FIXME: implement -fpreprocessed mode.
267 bool NoPreprocess = false;
268
Ted Kremenek11ad8952007-12-05 23:49:08 +0000269 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000270 default: assert(0 && "Unknown language kind!");
271 case langkind_c_cpp:
272 NoPreprocess = true;
273 // FALLTHROUGH
274 case langkind_c:
275 break;
276 case langkind_cxx_cpp:
277 NoPreprocess = true;
278 // FALLTHROUGH
279 case langkind_cxx:
280 Options.CPlusPlus = 1;
281 break;
282 case langkind_objc_cpp:
283 NoPreprocess = true;
284 // FALLTHROUGH
285 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000286 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000287 break;
288 case langkind_objcxx_cpp:
289 NoPreprocess = true;
290 // FALLTHROUGH
291 case langkind_objcxx:
292 Options.ObjC1 = Options.ObjC2 = 1;
293 Options.CPlusPlus = 1;
294 break;
295 }
296}
297
298/// LangStds - Language standards we support.
299enum LangStds {
300 lang_unspecified,
301 lang_c89, lang_c94, lang_c99,
302 lang_gnu89, lang_gnu99,
303 lang_cxx98, lang_gnucxx98,
304 lang_cxx0x, lang_gnucxx0x
305};
306
307static llvm::cl::opt<LangStds>
308LangStd("std", llvm::cl::desc("Language standard to compile for"),
309 llvm::cl::init(lang_unspecified),
310 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
311 clEnumValN(lang_c89, "c90", "ISO C 1990"),
312 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
313 clEnumValN(lang_c94, "iso9899:199409",
314 "ISO C 1990 with amendment 1"),
315 clEnumValN(lang_c99, "c99", "ISO C 1999"),
316// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
317 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
318// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
319 clEnumValN(lang_gnu89, "gnu89",
320 "ISO C 1990 with GNU extensions (default for C)"),
321 clEnumValN(lang_gnu99, "gnu99",
322 "ISO C 1999 with GNU extensions"),
323 clEnumValN(lang_gnu99, "gnu9x",
324 "ISO C 1999 with GNU extensions"),
325 clEnumValN(lang_cxx98, "c++98",
326 "ISO C++ 1998 with amendments"),
327 clEnumValN(lang_gnucxx98, "gnu++98",
328 "ISO C++ 1998 with amendments and GNU "
329 "extensions (default for C++)"),
330 clEnumValN(lang_cxx0x, "c++0x",
331 "Upcoming ISO C++ 200x with amendments"),
332 clEnumValN(lang_gnucxx0x, "gnu++0x",
333 "Upcoming ISO C++ 200x with amendments and GNU "
334 "extensions (default for C++)"),
335 clEnumValEnd));
336
337static llvm::cl::opt<bool>
338NoOperatorNames("fno-operator-names",
339 llvm::cl::desc("Do not treat C++ operator name keywords as "
340 "synonyms for operators"));
341
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000342static llvm::cl::opt<bool>
343PascalStrings("fpascal-strings",
344 llvm::cl::desc("Recognize and construct Pascal-style "
345 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000346
347static llvm::cl::opt<bool>
348MSExtensions("fms-extensions",
349 llvm::cl::desc("Accept some non-standard constructs used in "
350 "Microsoft header files. "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000351
352static llvm::cl::opt<bool>
353WritableStrings("fwritable-strings",
354 llvm::cl::desc("Store string literals as writable data."));
Anders Carlssone87cd982007-11-30 04:21:22 +0000355
356static llvm::cl::opt<bool>
357LaxVectorConversions("flax-vector-conversions",
358 llvm::cl::desc("Allow implicit conversions between vectors"
359 " with a different number of elements or "
360 "different element types."));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000361
Chris Lattner4b009652007-07-25 00:24:17 +0000362// FIXME: add:
363// -ansi
364// -trigraphs
365// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000366// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000367static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000368 if (LangStd == lang_unspecified) {
369 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000370 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000371 default: assert(0 && "Unknown base language");
372 case langkind_c:
373 case langkind_c_cpp:
374 case langkind_objc:
375 case langkind_objc_cpp:
376 LangStd = lang_gnu99;
377 break;
378 case langkind_cxx:
379 case langkind_cxx_cpp:
380 case langkind_objcxx:
381 case langkind_objcxx_cpp:
382 LangStd = lang_gnucxx98;
383 break;
384 }
385 }
386
387 switch (LangStd) {
388 default: assert(0 && "Unknown language standard!");
389
390 // Fall through from newer standards to older ones. This isn't really right.
391 // FIXME: Enable specifically the right features based on the language stds.
392 case lang_gnucxx0x:
393 case lang_cxx0x:
394 Options.CPlusPlus0x = 1;
395 // FALL THROUGH
396 case lang_gnucxx98:
397 case lang_cxx98:
398 Options.CPlusPlus = 1;
399 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000400 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // FALL THROUGH.
402 case lang_gnu99:
403 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000404 Options.C99 = 1;
405 Options.HexFloats = 1;
406 // FALL THROUGH.
407 case lang_gnu89:
408 Options.BCPLComment = 1; // Only for C99/C++.
409 // FALL THROUGH.
410 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000411 Options.Digraphs = 1; // C94, C99, C++.
412 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000413 case lang_c89:
414 break;
415 }
416
Chris Lattner6ab935b2008-04-05 06:32:51 +0000417 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
418 Options.ImplicitInt = 1;
419 else
420 Options.ImplicitInt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000421 Options.Trigraphs = 1; // -trigraphs or -ansi
422 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000423 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000424 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000425 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000426 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000427}
428
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000429static llvm::cl::opt<bool>
430ObjCExclusiveGC("fobjc-gc-only",
431 llvm::cl::desc("Use GC exclusively for Objective-C related "
432 "memory management."));
433
434static llvm::cl::opt<bool>
435ObjCEnableGC("fobjc-gc",
436 llvm::cl::desc("Enable Objective-C garbage collection."));
437
438void InitializeGCMode(LangOptions &Options) {
439 if (ObjCExclusiveGC)
440 Options.setGCMode(LangOptions::GCOnly);
441 else if (ObjCEnableGC)
442 Options.setGCMode(LangOptions::HybridGC);
443}
444
445
Chris Lattner4b009652007-07-25 00:24:17 +0000446//===----------------------------------------------------------------------===//
447// Our DiagnosticClient implementation
448//===----------------------------------------------------------------------===//
449
450// FIXME: Werror should take a list of things, -Werror=foo,bar
451static llvm::cl::opt<bool>
452WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
453
454static llvm::cl::opt<bool>
455WarnOnExtensions("pedantic", llvm::cl::init(false),
456 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
457
458static llvm::cl::opt<bool>
459ErrorOnExtensions("pedantic-errors",
460 llvm::cl::desc("Issue an error on uses of GCC extensions"));
461
462static llvm::cl::opt<bool>
463WarnUnusedMacros("Wunused_macros",
464 llvm::cl::desc("Warn for unused macros in the main translation unit"));
465
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000466static llvm::cl::opt<bool>
467WarnFloatEqual("Wfloat-equal",
468 llvm::cl::desc("Warn about equality comparisons of floating point values."));
469
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000470static llvm::cl::opt<bool>
471WarnNoFormatNonLiteral("Wno-format-nonliteral",
472 llvm::cl::desc("Do not warn about non-literal format strings."));
473
Chris Lattnera616ee32008-01-23 17:19:46 +0000474static llvm::cl::opt<bool>
475WarnUndefMacros("Wundef",
476 llvm::cl::desc("Warn on use of undefined macros in #if's"));
477
478
Chris Lattner4b009652007-07-25 00:24:17 +0000479/// InitializeDiagnostics - Initialize the diagnostic object, based on the
480/// current command line option settings.
481static void InitializeDiagnostics(Diagnostic &Diags) {
482 Diags.setWarningsAsErrors(WarningsAsErrors);
483 Diags.setWarnOnExtensions(WarnOnExtensions);
484 Diags.setErrorOnExtensions(ErrorOnExtensions);
485
486 // Silence the "macro is not used" warning unless requested.
487 if (!WarnUnusedMacros)
488 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000489
490 // Silence "floating point comparison" warnings unless requested.
491 if (!WarnFloatEqual)
492 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000493
494 // Silence "format string is not a string literal" warnings if requested
495 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000496 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
497 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000498 if (!WarnUndefMacros)
499 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000500
501 if (MSExtensions) // MS allows unnamed struct/union fields.
502 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000503
504 // If -pedantic-errors is set, turn extensions that warn by default into
505 // errors.
506 if (ErrorOnExtensions) {
507 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
508 diag::MAP_ERROR);
509 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
510 diag::MAP_ERROR);
511 }
Chris Lattner4b009652007-07-25 00:24:17 +0000512}
513
514//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000515// Analysis-specific options.
516//===----------------------------------------------------------------------===//
517
518static llvm::cl::opt<std::string>
519AnalyzeSpecificFunction("analyze-function",
520 llvm::cl::desc("Run analysis on specific function."));
521
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000522static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000523TrimGraph("trim-egraph",
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000524 llvm::cl::desc("Only show error-related paths in the analysis graph."));
525
Ted Kremenek0118bb52008-02-18 21:21:23 +0000526//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000527// Target Triple Processing.
528//===----------------------------------------------------------------------===//
529
530static llvm::cl::opt<std::string>
531TargetTriple("triple",
532 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
533
Chris Lattnerfc457002008-03-05 01:18:20 +0000534static llvm::cl::opt<std::string>
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000535Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenek40499482007-12-03 22:06:55 +0000536
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000537static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000538 // Initialize base triple. If a -triple option has been specified, use
539 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000540 std::string Triple = TargetTriple;
541 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000542
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000543 // If -arch foo was specified, remove the architecture from the triple we have
544 // so far and replace it with the specified one.
545 if (Arch.empty())
546 return Triple;
547
Ted Kremenek40499482007-12-03 22:06:55 +0000548 // Decompose the base triple into "arch" and suffix.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000549 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000550
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000551 if (FirstDashIdx == std::string::npos) {
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000552 fprintf(stderr,
553 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000554 Triple.c_str());
555 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000556 }
Ted Kremenek40499482007-12-03 22:06:55 +0000557
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000558 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenek40499482007-12-03 22:06:55 +0000559}
560
561//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000562// Preprocessor Initialization
563//===----------------------------------------------------------------------===//
564
565// FIXME: Preprocessor builtins to support.
566// -A... - Play with #assertions
567// -undef - Undefine all predefined macros
568
569static llvm::cl::list<std::string>
570D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
571 llvm::cl::desc("Predefine the specified macro"));
572static llvm::cl::list<std::string>
573U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
574 llvm::cl::desc("Undefine the specified macro"));
575
Chris Lattner008da782008-01-10 01:53:41 +0000576static llvm::cl::list<std::string>
577ImplicitIncludes("include", llvm::cl::value_desc("file"),
578 llvm::cl::desc("Include file before parsing"));
579
580
Chris Lattner4b009652007-07-25 00:24:17 +0000581// Append a #define line to Buf for Macro. Macro should be of the form XXX,
582// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
583// "#define XXX Y z W". To get a #define with no value, use "XXX=".
584static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
585 const char *Command = "#define ") {
586 Buf.insert(Buf.end(), Command, Command+strlen(Command));
587 if (const char *Equal = strchr(Macro, '=')) {
588 // Turn the = into ' '.
589 Buf.insert(Buf.end(), Macro, Equal);
590 Buf.push_back(' ');
591 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
592 } else {
593 // Push "macroname 1".
594 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
595 Buf.push_back(' ');
596 Buf.push_back('1');
597 }
598 Buf.push_back('\n');
599}
600
Chris Lattner008da782008-01-10 01:53:41 +0000601/// AddImplicitInclude - Add an implicit #include of the specified file to the
602/// predefines buffer.
603static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
604 const char *Inc = "#include \"";
605 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
606 Buf.insert(Buf.end(), File.begin(), File.end());
607 Buf.push_back('"');
608 Buf.push_back('\n');
609}
610
Chris Lattner4b009652007-07-25 00:24:17 +0000611
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000612/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000613/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000614///
Chris Lattner9d818a22008-04-19 23:25:44 +0000615static bool InitializePreprocessor(Preprocessor &PP,
616 bool InitializeSourceMgr,
617 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000618 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000619
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000620 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000621 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000622
623 if (InitializeSourceMgr) {
624 if (InFile != "-") {
625 const FileEntry *File = FileMgr.getFile(InFile);
626 if (File) SourceMgr.createMainFileID(File, SourceLocation());
627 if (SourceMgr.getMainFileID() == 0) {
628 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000629 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000630 }
631 } else {
632 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
633 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
634 if (SourceMgr.getMainFileID() == 0) {
635 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000636 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000637 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000638 }
Chris Lattner4b009652007-07-25 00:24:17 +0000639 }
Sam Bishop61a20782008-04-14 14:41:57 +0000640
Chris Lattner47b6a162008-04-19 23:09:31 +0000641 std::vector<char> PredefineBuffer;
642
Chris Lattner4b009652007-07-25 00:24:17 +0000643 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000644 unsigned d = 0, D = D_macros.size();
645 unsigned u = 0, U = U_macros.size();
646 while (d < D || u < U) {
647 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
648 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
649 else
650 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
651 }
652
Chris Lattner008da782008-01-10 01:53:41 +0000653 // FIXME: Read any files specified by -imacros.
654
655 // Add implicit #includes from -include.
656 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
657 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000658
Chris Lattner47b6a162008-04-19 23:09:31 +0000659 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000660 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000661 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000662
663 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000664 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000665}
666
667//===----------------------------------------------------------------------===//
668// Preprocessor include path information.
669//===----------------------------------------------------------------------===//
670
671// This tool exports a large number of command line options to control how the
672// preprocessor searches for header files. At root, however, the Preprocessor
673// object takes a very simple interface: a list of directories to search for
674//
675// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000676// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000677//
Chris Lattner008da782008-01-10 01:53:41 +0000678// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000679
680static llvm::cl::opt<bool>
681nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
682
683// Various command line options. These four add directories to each chain.
684static llvm::cl::list<std::string>
685F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
686 llvm::cl::desc("Add directory to framework include search path"));
687static llvm::cl::list<std::string>
688I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
689 llvm::cl::desc("Add directory to include search path"));
690static llvm::cl::list<std::string>
691idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
692 llvm::cl::desc("Add directory to AFTER include search path"));
693static llvm::cl::list<std::string>
694iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
695 llvm::cl::desc("Add directory to QUOTE include search path"));
696static llvm::cl::list<std::string>
697isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
698 llvm::cl::desc("Add directory to SYSTEM include search path"));
699
700// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
701static llvm::cl::list<std::string>
702iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
703 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
704static llvm::cl::list<std::string>
705iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
706 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
707static llvm::cl::list<std::string>
708iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
709 llvm::cl::Prefix,
710 llvm::cl::desc("Set directory to include search path with prefix"));
711
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000712static llvm::cl::opt<std::string>
713isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
714 llvm::cl::desc("Set the system root directory (usually /)"));
715
Chris Lattner4b009652007-07-25 00:24:17 +0000716// Finally, implement the code that groks the options above.
717enum IncludeDirGroup {
718 Quoted = 0,
719 Angled,
720 System,
721 After
722};
723
724static std::vector<DirectoryLookup> IncludeGroup[4];
725
726/// AddPath - Add the specified path to the specified group list.
727///
728static void AddPath(const std::string &Path, IncludeDirGroup Group,
729 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000730 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000731 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000732 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000733
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000734 // Compute the actual path, taking into consideration -isysroot.
735 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000736
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000737 // Handle isysroot.
738 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000739 // FIXME: Portability. This should be a sys::Path interface, this doesn't
740 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000741 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
742 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000743 }
744
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000745 MappedPath.append(Path.begin(), Path.end());
746
747 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000748 DirectoryLookup::DirType Type;
749 if (Group == Quoted || Group == Angled)
750 Type = DirectoryLookup::NormalHeaderDir;
751 else if (isCXXAware)
752 Type = DirectoryLookup::SystemHeaderDir;
753 else
754 Type = DirectoryLookup::ExternCSystemHeaderDir;
755
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000756
757 // If the directory exists, add it.
758 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
759 &MappedPath[0]+
760 MappedPath.size())) {
761 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
762 isFramework));
763 return;
764 }
765
Chris Lattnerb7426782007-12-17 07:52:39 +0000766 // Check to see if this is an apple-style headermap (which are not allowed to
767 // be frameworks).
768 if (!isFramework) {
769 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
770 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000771 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
772 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000773 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
774 return;
775 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000776 }
777 }
778
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000779 if (Verbose)
780 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000781}
782
783/// RemoveDuplicates - If there are duplicate directory entries in the specified
784/// search list, remove the later (dead) ones.
785static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000786 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000787 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000788 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000789 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000790 if (SearchList[i].isNormalDir()) {
791 // If this isn't the first time we've seen this dir, remove it.
792 if (SeenDirs.insert(SearchList[i].getDir()))
793 continue;
794
Chris Lattner4b009652007-07-25 00:24:17 +0000795 if (Verbose)
796 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
797 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000798 } else if (SearchList[i].isFramework()) {
799 // If this isn't the first time we've seen this framework dir, remove it.
800 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
801 continue;
802
803 if (Verbose)
804 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
805 SearchList[i].getFrameworkDir()->getName());
806
Chris Lattnercf33e932007-12-17 06:44:29 +0000807 } else {
808 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
809 // If this isn't the first time we've seen this headermap, remove it.
810 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
811 continue;
812
813 if (Verbose)
814 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
815 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000816 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000817
818 // This is reached if the current entry is a duplicate.
819 SearchList.erase(SearchList.begin()+i);
820 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000821 }
822}
823
Chris Lattner4f022a72008-03-01 08:07:28 +0000824// AddEnvVarPaths - Add a list of paths from an environment variable to a
825// header search list.
826//
827static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
828 const char* at = getenv(Name);
829 if (!at)
830 return;
831
832 const char* delim = strchr(at, llvm::sys::PathSeparator);
833 while (delim != 0) {
834 if (delim-at == 0)
835 AddPath(".", Angled, false, true, false, Headers);
836 else
837 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
838 true, false, Headers);
839 at = delim + 1;
840 delim = strchr(at, llvm::sys::PathSeparator);
841 }
842 if (*at == 0)
843 AddPath(".", Angled, false, true, false, Headers);
844 else
845 AddPath(at, Angled, false, true, false, Headers);
846}
847
Chris Lattner4b009652007-07-25 00:24:17 +0000848/// InitializeIncludePaths - Process the -I options and set them in the
849/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000850static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
851 FileManager &FM, const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000852 // Handle -F... options.
853 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000854 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000855
856 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000857 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000858 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000859
860 // Handle -idirafter... options.
861 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000862 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000863
864 // Handle -iquote... options.
865 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000866 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000867
868 // Handle -isystem... options.
869 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000870 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000871
872 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
873 // parallel, processing the values in order of occurance to get the right
874 // prefixes.
875 {
876 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
877 unsigned iprefix_idx = 0;
878 unsigned iwithprefix_idx = 0;
879 unsigned iwithprefixbefore_idx = 0;
880 bool iprefix_done = iprefix_vals.empty();
881 bool iwithprefix_done = iwithprefix_vals.empty();
882 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
883 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
884 if (!iprefix_done &&
885 (iwithprefix_done ||
886 iprefix_vals.getPosition(iprefix_idx) <
887 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
888 (iwithprefixbefore_done ||
889 iprefix_vals.getPosition(iprefix_idx) <
890 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
891 Prefix = iprefix_vals[iprefix_idx];
892 ++iprefix_idx;
893 iprefix_done = iprefix_idx == iprefix_vals.size();
894 } else if (!iwithprefix_done &&
895 (iwithprefixbefore_done ||
896 iwithprefix_vals.getPosition(iwithprefix_idx) <
897 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
898 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000899 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000900 ++iwithprefix_idx;
901 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
902 } else {
903 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000904 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000905 ++iwithprefixbefore_idx;
906 iwithprefixbefore_done =
907 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
908 }
909 }
910 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000911
912 AddEnvVarPaths("CPATH", Headers);
913 if (Lang.CPlusPlus && Lang.ObjC1)
914 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
915 else if (Lang.CPlusPlus)
916 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
917 else if (Lang.ObjC1)
918 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
919 else
920 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
921
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000922 // Add the clang headers, which are relative to the clang driver.
923 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000924 llvm::sys::Path::GetMainExecutable(Argv0,
925 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000926 if (!MainExecutablePath.isEmpty()) {
927 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
928 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
929 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
930 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
931 }
932
Chris Lattner4b009652007-07-25 00:24:17 +0000933 // FIXME: temporary hack: hard-coded paths.
934 // FIXME: get these from the target?
935 if (!nostdinc) {
936 if (Lang.CPlusPlus) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000937 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000938 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000939 false, Headers);
940 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
941 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000942
943 // Ubuntu 7.10 - Gutsy Gibbon
944 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
945 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
946 false, Headers);
947 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
948 Headers);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000949
950 // Fedora 8
951 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner5fdcc302008-04-16 05:21:09 +0000952 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
953 false, Headers);
954 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
955 Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000956 }
957
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000958 AddPath("/usr/local/include", System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000959 // leopard
960 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000961 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000962 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000963 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000964 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
965 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000966 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000967
968 // tiger
969 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000970 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000971 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000972 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000973 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
974 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000975 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000976
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000977 // Ubuntu 7.10 - Gutsy Gibbon
978 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +0000979 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000980
Chris Lattner3e254fb2008-04-08 04:40:51 +0000981 // Fedora 8
982 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
983 false, false, false, Headers);
984
Andrew Lenharth6961ec42008-03-24 21:25:48 +0000985 //Debian testing/lenny x86
986 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
987 false, false, false, Headers);
Andrew Lenharthfccd7be2008-03-24 21:39:05 +0000988
989 //Debian testing/lenny amd64
990 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
991 false, false, false, Headers);
Andrew Lenharth6961ec42008-03-24 21:25:48 +0000992
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000993 AddPath("/usr/include", System, false, false, false, Headers);
994 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
995 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000996 }
997
998 // Now that we have collected all of the include paths, merge them all
999 // together and tell the preprocessor about them.
1000
1001 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1002 std::vector<DirectoryLookup> SearchList;
1003 SearchList = IncludeGroup[Angled];
1004 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1005 IncludeGroup[System].end());
1006 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1007 IncludeGroup[After].end());
1008 RemoveDuplicates(SearchList);
1009 RemoveDuplicates(IncludeGroup[Quoted]);
1010
1011 // Prepend QUOTED list on the search list.
1012 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1013 IncludeGroup[Quoted].end());
1014
1015
1016 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1017 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1018 DontSearchCurDir);
1019
1020 // If verbose, print the list of directories that will be searched.
1021 if (Verbose) {
1022 fprintf(stderr, "#include \"...\" search starts here:\n");
1023 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1024 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1025 if (i == QuotedIdx)
1026 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +00001027 const char *Name = SearchList[i].getName();
1028 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +00001029 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +00001030 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +00001031 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +00001032 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001033 else {
1034 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +00001035 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001036 }
Chris Lattner1df68f92007-12-17 17:57:27 +00001037 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +00001038 }
Chris Lattnerac553842007-12-15 23:11:06 +00001039 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001040 }
1041}
1042
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001043//===----------------------------------------------------------------------===//
1044// Driver PreprocessorFactory - For lazily generating preprocessors ...
1045//===----------------------------------------------------------------------===//
1046
1047namespace {
1048class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001049 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001050 Diagnostic &Diags;
1051 const LangOptions &LangInfo;
1052 TargetInfo &Target;
1053 SourceManager &SourceMgr;
1054 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001055 bool InitializeSourceMgr;
1056
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001057public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001058 DriverPreprocessorFactory(const std::string &infile,
1059 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001060 TargetInfo &target, SourceManager &SM,
1061 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001062 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1063 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1064
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001065
1066 virtual ~DriverPreprocessorFactory() {}
1067
1068 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001069 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1070 SourceMgr, HeaderInfo);
1071
Chris Lattner9d818a22008-04-19 23:25:44 +00001072 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001073 delete PP;
1074 return NULL;
1075 }
1076
1077 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001078 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001079 }
1080};
1081}
Chris Lattner4b009652007-07-25 00:24:17 +00001082
Chris Lattner4b009652007-07-25 00:24:17 +00001083//===----------------------------------------------------------------------===//
1084// Basic Parser driver
1085//===----------------------------------------------------------------------===//
1086
Chris Lattner9d818a22008-04-19 23:25:44 +00001087static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001088 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001089 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001090
1091 // Parsing the specified input file.
1092 P.ParseTranslationUnit();
1093 delete PA;
1094}
1095
1096//===----------------------------------------------------------------------===//
1097// Main driver
1098//===----------------------------------------------------------------------===//
1099
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001100/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1101/// action. These consumers can operate on both ASTs that are freshly
1102/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001103static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001104 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001105 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001106 Preprocessor *PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001107 PreprocessorFactory *PPF,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001108 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001109 switch (ProgAction) {
1110 default:
1111 return NULL;
1112
1113 case ASTPrint:
1114 return CreateASTPrinter();
1115
1116 case ASTDump:
1117 return CreateASTDumper();
1118
1119 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001120 return CreateASTViewer();
1121
1122 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001123 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001124
1125 case ParseCFGDump:
1126 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001127 return CreateCFGDumper(ProgAction == ParseCFGView,
1128 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001129
1130 case AnalysisLiveVariables:
Ted Kremenekb278abb2008-02-22 20:13:09 +00001131 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001132
1133 case WarnDeadStores:
1134 return CreateDeadStoreChecker(Diag);
1135
1136 case WarnUninitVals:
1137 return CreateUnitValsChecker(Diag);
1138
Ted Kremenek3862eb12008-02-14 22:36:46 +00001139 case AnalysisGRSimpleVals:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001140 return CreateGRSimpleVals(Diag, PP, PPF, AnalyzeSpecificFunction,
1141 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek1da5b142008-02-15 00:35:38 +00001142
Ted Kremenek827f93b2008-03-06 00:08:09 +00001143 case CheckerCFRef:
Ted Kremenek102d42e2008-04-29 05:13:59 +00001144 return CreateCFRefChecker(Diag, PP, PPF, LangOpts,
1145 AnalyzeSpecificFunction,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001146 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001147
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001148 case TestSerialization:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001149 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001150
1151 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001152 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001153 DestModule = new llvm::Module(InFile);
1154 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001155
Ted Kremenekbde30332007-12-19 17:25:59 +00001156 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001157 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001158 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek397de012007-12-13 00:37:31 +00001159
Steve Naroff44e81222008-04-14 22:03:09 +00001160 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001161 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001162 }
1163}
1164
Chris Lattner4b009652007-07-25 00:24:17 +00001165/// ProcessInputFile - Process a single input file with the specified state.
1166///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001167static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1168 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001169
1170 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001171 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001172 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001173
Chris Lattner4b009652007-07-25 00:24:17 +00001174 switch (ProgAction) {
1175 default:
Chris Lattner21f72d62008-04-16 06:11:58 +00001176 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1177 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001178 &PPF, CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001179
1180 if (!Consumer) {
1181 fprintf(stderr, "Unexpected program action!\n");
1182 return;
1183 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001184
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001185 break;
1186
Chris Lattner4b009652007-07-25 00:24:17 +00001187 case DumpTokens: { // Token dump mode.
1188 Token Tok;
1189 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001190 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001191 do {
1192 PP.Lex(Tok);
1193 PP.DumpToken(Tok, true);
1194 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001195 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001196 ClearSourceMgr = true;
1197 break;
1198 }
1199 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1200 Token Tok;
1201 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001202 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001203 do {
1204 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001205 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001206 ClearSourceMgr = true;
1207 break;
1208 }
1209
1210 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001211 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001212 ClearSourceMgr = true;
1213 break;
1214
1215 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001216 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001217 ClearSourceMgr = true;
1218 break;
1219
1220 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001221 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001222 ClearSourceMgr = true;
1223 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001224
Ted Kremenek6856c632007-09-26 18:39:29 +00001225 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001226 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001227 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001228 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001229
1230 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001231 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001232 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001233
1234 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001235 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001236 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001237
1238 // If running the code generator, finish up now.
1239 if (CodeGenModule) {
1240 std::ostream *Out;
1241 if (OutputFile == "-") {
1242 Out = llvm::cout.stream();
1243 } else if (!OutputFile.empty()) {
1244 Out = new std::ofstream(OutputFile.c_str(),
1245 std::ios_base::binary|std::ios_base::out);
1246 } else if (InFile == "-") {
1247 Out = llvm::cout.stream();
1248 } else {
1249 llvm::sys::Path Path(InFile);
1250 Path.eraseSuffix();
1251 if (ProgAction == EmitLLVM)
1252 Path.appendSuffix("ll");
1253 else if (ProgAction == EmitBC)
1254 Path.appendSuffix("bc");
1255 else
1256 assert(0 && "Unknown action");
1257 Out = new std::ofstream(Path.toString().c_str(),
1258 std::ios_base::binary|std::ios_base::out);
1259 }
1260
1261 if (ProgAction == EmitLLVM) {
1262 CodeGenModule->print(*Out);
1263 } else {
1264 assert(ProgAction == EmitBC);
1265 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1266 }
1267
1268 if (Out != llvm::cout.stream())
1269 delete Out;
1270 delete CodeGenModule;
1271 }
Chris Lattner4b009652007-07-25 00:24:17 +00001272
1273 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001274 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001275 PP.PrintStats();
1276 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001277 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001278 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001279 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001280 fprintf(stderr, "\n");
1281 }
1282
1283 // For a multi-file compilation, some things are ok with nuking the source
1284 // manager tables, other require stable fileid/macroid's across multiple
1285 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001286 if (ClearSourceMgr)
1287 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001288}
1289
Ted Kremenek80d53372007-12-12 23:41:08 +00001290static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1291 FileManager& FileMgr) {
1292
1293 if (VerifyDiagnostics) {
1294 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1295 exit (1);
1296 }
1297
1298 llvm::sys::Path Filename(InFile);
1299
1300 if (!Filename.isValid()) {
1301 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1302 exit (1);
1303 }
1304
Ted Kremenek863b01f2008-04-23 16:25:39 +00001305 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001306
1307 if (!TU) {
1308 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1309 InFile.c_str());
1310 exit (1);
1311 }
1312
Ted Kremenekab749372007-12-19 19:27:38 +00001313 // Observe that we use the source file name stored in the deserialized
1314 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001315 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001316 llvm::OwningPtr<ASTConsumer>
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001317 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(), 0, 0,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001318 DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001319
1320 if (!Consumer) {
1321 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1322 exit (1);
1323 }
1324
Ted Kremenek863b01f2008-04-23 16:25:39 +00001325 Consumer->Initialize(TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001326
Chris Lattner8d72ee02008-02-06 01:42:25 +00001327 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001328 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1329 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001330}
1331
1332
Chris Lattner4b009652007-07-25 00:24:17 +00001333static llvm::cl::list<std::string>
1334InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1335
Ted Kremenek80d53372007-12-12 23:41:08 +00001336static bool isSerializedFile(const std::string& InFile) {
1337 if (InFile.size() < 4)
1338 return false;
1339
1340 const char* s = InFile.c_str()+InFile.size()-4;
1341
1342 return s[0] == '.' &&
1343 s[1] == 'a' &&
1344 s[2] == 's' &&
1345 s[3] == 't';
1346}
1347
Chris Lattner4b009652007-07-25 00:24:17 +00001348
1349int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001350 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001351 llvm::sys::PrintStackTraceOnErrorSignal();
1352
1353 // If no input was specified, read from stdin.
1354 if (InputFilenames.empty())
1355 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001356
Chris Lattner4b009652007-07-25 00:24:17 +00001357 // Create a file manager object to provide access to and cache the filesystem.
1358 FileManager FileMgr;
1359
Ted Kremenekb240e822007-12-11 23:28:38 +00001360 // Create the diagnostic client for reporting errors or for
1361 // implementing -verify.
Ted Kremenekfd75e312008-03-27 06:17:42 +00001362 std::auto_ptr<DiagnosticClient> DiagClient;
1363 TextDiagnostics* TextDiagClient = NULL;
1364
1365 if (!HTMLDiag.empty()) {
Ted Kremenek675ac6f2008-04-16 16:53:18 +00001366
1367 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1368 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1369 // Fix this dependency later.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001370 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenekfd75e312008-03-27 06:17:42 +00001371 }
1372 else { // Use Text diagnostics.
1373 if (!VerifyDiagnostics) {
1374 // Print diagnostics to stderr by default.
1375 TextDiagClient = new TextDiagnosticPrinter();
1376 } else {
1377 // When checking diagnostics, just buffer them up.
1378 TextDiagClient = new TextDiagnosticBuffer();
1379
1380 if (InputFilenames.size() != 1) {
1381 fprintf(stderr,
1382 "-verify only works on single input files for now.\n");
1383 return 1;
1384 }
Chris Lattner4b009652007-07-25 00:24:17 +00001385 }
Ted Kremenekfd75e312008-03-27 06:17:42 +00001386
1387 assert (TextDiagClient);
1388 DiagClient.reset(TextDiagClient);
Chris Lattner4b009652007-07-25 00:24:17 +00001389 }
1390
1391 // Configure our handling of diagnostics.
1392 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001393 InitializeDiagnostics(Diags);
1394
Chris Lattner45a56e02007-12-05 23:24:17 +00001395 // -I- is a deprecated GCC feature, scan for it and reject it.
1396 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1397 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001398 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001399 I_dirs.erase(I_dirs.begin()+i);
1400 --i;
1401 }
1402 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001403
1404 // Get information about the target being compiled for.
1405 std::string Triple = CreateTargetTriple();
1406 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1407 if (Target == 0) {
1408 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1409 Triple.c_str());
1410 fprintf(stderr, "Please use -triple or -arch.\n");
1411 exit(1);
1412 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001413
Chris Lattner4b009652007-07-25 00:24:17 +00001414 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001415 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001416
Ted Kremenek80d53372007-12-12 23:41:08 +00001417 if (isSerializedFile(InFile))
1418 ProcessSerializedFile(InFile,Diags,FileMgr);
1419 else {
1420 /// Create a SourceManager object. This tracks and owns all the file
1421 /// buffers allocated to a translation unit.
1422 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001423
Ted Kremenek80d53372007-12-12 23:41:08 +00001424 // Initialize language options, inferring file types from input filenames.
1425 LangOptions LangInfo;
1426 InitializeBaseLanguage();
1427 LangKind LK = GetLanguage(InFile);
1428 InitializeLangOptions(LangInfo, LK);
1429 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001430 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001431
1432 // Process the -I options and set them in the HeaderInfo.
1433 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekfd75e312008-03-27 06:17:42 +00001434 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001435 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001436
Ted Kremenek80d53372007-12-12 23:41:08 +00001437 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001438 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001439 SourceMgr, HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001440
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001441 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1442
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001443 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001444 continue;
1445
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001446 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek80d53372007-12-12 23:41:08 +00001447 HeaderInfo.ClearFileInfo();
1448
1449 if (Stats)
1450 SourceMgr.PrintStats();
1451 }
Chris Lattner4b009652007-07-25 00:24:17 +00001452 }
1453
Chris Lattner2c77d852008-03-14 06:12:05 +00001454 delete Target;
1455
Chris Lattner4b009652007-07-25 00:24:17 +00001456 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1457
1458 if (NumDiagnostics)
1459 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1460 (NumDiagnostics == 1 ? "" : "s"));
1461
1462 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001463 FileMgr.PrintStats();
1464 fprintf(stderr, "\n");
1465 }
1466
1467 return Diags.getNumErrors() != 0;
1468}