blob: d3c40dcd25dd6c21a7b1f9d553aece861a1eb46a [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.
Chris Lattner1665a9f2008-05-08 06:52:13 +000066 RewriteMacros, // Expand macros but not #includes.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000067 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000068 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000069 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000070 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000071 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000072 ASTPrint, // Parse ASTs and print them.
73 ASTDump, // Parse ASTs and dump them.
74 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek97f75312007-08-21 21:42:03 +000075 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000076 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremenekaa04c512007-09-06 00:17:54 +000077 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenek1da5b142008-02-15 00:35:38 +000078 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
79 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek827f93b2008-03-06 00:08:09 +000080 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremeneke805c4a2007-09-06 23:00:42 +000081 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek0841c702007-09-25 18:37:20 +000082 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek0a03ce62007-09-17 20:49:30 +000083 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000084 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000085 ParsePrintCallbacks, // Parse and print each callback.
86 ParseSyntaxOnly, // Parse and perform semantic analysis.
87 ParseNoop, // Parse with noop callbacks.
88 RunPreprocessorOnly, // Just lex, no output.
89 PrintPreprocessedInput, // -E mode.
90 DumpTokens // Token dump mode.
91};
92
93static llvm::cl::opt<ProgActions>
94ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
95 llvm::cl::init(ParseSyntaxOnly),
96 llvm::cl::values(
97 clEnumValN(RunPreprocessorOnly, "Eonly",
98 "Just run preprocessor, no output (for timings)"),
99 clEnumValN(PrintPreprocessedInput, "E",
100 "Run preprocessor, emit preprocessed file"),
101 clEnumValN(DumpTokens, "dumptokens",
102 "Run preprocessor, dump internal rep of tokens"),
103 clEnumValN(ParseNoop, "parse-noop",
104 "Run parser with noop callbacks (for timings)"),
105 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
106 "Run parser and perform semantic analysis"),
107 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
108 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000109 clEnumValN(EmitHTML, "emit-html",
110 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000111 clEnumValN(ASTPrint, "ast-print",
112 "Build ASTs and then pretty-print them"),
113 clEnumValN(ASTDump, "ast-dump",
114 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000115 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000116 "Build ASTs and view them with GraphViz"),
Ted Kremenek97f75312007-08-21 21:42:03 +0000117 clEnumValN(ParseCFGDump, "dump-cfg",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000118 "Run parser, then build and print CFGs"),
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000119 clEnumValN(ParseCFGView, "view-cfg",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000120 "Run parser, then build and view CFGs with Graphviz"),
Ted Kremenekaa04c512007-09-06 00:17:54 +0000121 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000122 "Print results of live variable analysis"),
Ted Kremenek945fb562007-09-25 18:05:45 +0000123 clEnumValN(WarnDeadStores, "warn-dead-stores",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000124 "Flag warnings of stores to dead variables"),
Ted Kremenek945fb562007-09-25 18:05:45 +0000125 clEnumValN(WarnUninitVals, "warn-uninit-values",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000126 "Flag warnings of uses of unitialized variables"),
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000127 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000128 "Perform path-sensitive constant propagation"),
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000129 clEnumValN(CheckerCFRef, "checker-cfref",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000130 "Run the Core Foundation reference count checker"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000131 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000132 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000133 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000134 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000135 clEnumValN(EmitBC, "emit-llvm-bc",
136 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000137 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000138 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000139 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000140 "Rewrite ObjC into C (code rewriter example)"),
141 clEnumValN(RewriteMacros, "rewrite-macros",
142 "Expand macros without full preprocessing"),
Chris Lattner4b009652007-07-25 00:24:17 +0000143 clEnumValEnd));
144
Ted Kremenekd01eae62007-12-19 19:47:59 +0000145
146static llvm::cl::opt<std::string>
147OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000148 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000149 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000150
151//===----------------------------------------------------------------------===//
152// Diagnostic Options
153//===----------------------------------------------------------------------===//
154
Ted Kremenek10389cf2007-09-26 19:42:19 +0000155static llvm::cl::opt<bool>
156VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000157 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000158
Ted Kremenekfd75e312008-03-27 06:17:42 +0000159static llvm::cl::opt<std::string>
160HTMLDiag("html-diags",
161 llvm::cl::desc("Generate HTML to report diagnostics"),
162 llvm::cl::value_desc("HTML directory"));
163
Chris Lattner4b009652007-07-25 00:24:17 +0000164//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000165// Analyzer Options
166//===----------------------------------------------------------------------===//
167
168static llvm::cl::opt<bool>
169VisualizeEG("visualize-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000170 llvm::cl::desc("Display static analysis Exploded Graph"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000171
172static llvm::cl::opt<bool>
173AnalyzeAll("checker-opt-analyze-headers",
174 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000175 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000176
177//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000178// Language Options
179//===----------------------------------------------------------------------===//
180
181enum LangKind {
182 langkind_unspecified,
183 langkind_c,
184 langkind_c_cpp,
185 langkind_cxx,
186 langkind_cxx_cpp,
187 langkind_objc,
188 langkind_objc_cpp,
189 langkind_objcxx,
190 langkind_objcxx_cpp
191};
192
193/* TODO: GCC also accepts:
194 c-header c++-header objective-c-header objective-c++-header
195 assembler assembler-with-cpp
196 ada, f77*, ratfor (!), f95, java, treelang
197 */
198static llvm::cl::opt<LangKind>
199BaseLang("x", llvm::cl::desc("Base language to compile"),
200 llvm::cl::init(langkind_unspecified),
201 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
202 clEnumValN(langkind_cxx, "c++", "C++"),
203 clEnumValN(langkind_objc, "objective-c", "Objective C"),
204 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
205 clEnumValN(langkind_c_cpp, "c-cpp-output",
206 "Preprocessed C"),
207 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
208 "Preprocessed C++"),
209 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
210 "Preprocessed Objective C"),
211 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
212 "Preprocessed Objective C++"),
213 clEnumValEnd));
214
215static llvm::cl::opt<bool>
216LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
217 llvm::cl::Hidden);
218static llvm::cl::opt<bool>
219LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
220 llvm::cl::Hidden);
221
Ted Kremenek11ad8952007-12-05 23:49:08 +0000222/// InitializeBaseLanguage - Handle the -x foo options.
223static void InitializeBaseLanguage() {
224 if (LangObjC)
225 BaseLang = langkind_objc;
226 else if (LangObjCXX)
227 BaseLang = langkind_objcxx;
228}
229
230static LangKind GetLanguage(const std::string &Filename) {
231 if (BaseLang != langkind_unspecified)
232 return BaseLang;
233
234 std::string::size_type DotPos = Filename.rfind('.');
235
236 if (DotPos == std::string::npos) {
237 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000238 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000239 }
240
Ted Kremenek11ad8952007-12-05 23:49:08 +0000241 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
242 // C header: .h
243 // C++ header: .hh or .H;
244 // assembler no preprocessing: .s
245 // assembler: .S
246 if (Ext == "c")
247 return langkind_c;
248 else if (Ext == "i")
249 return langkind_c_cpp;
250 else if (Ext == "ii")
251 return langkind_cxx_cpp;
252 else if (Ext == "m")
253 return langkind_objc;
254 else if (Ext == "mi")
255 return langkind_objc_cpp;
256 else if (Ext == "mm" || Ext == "M")
257 return langkind_objcxx;
258 else if (Ext == "mii")
259 return langkind_objcxx_cpp;
260 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
261 Ext == "c++" || Ext == "cp" || Ext == "cxx")
262 return langkind_cxx;
263 else
264 return langkind_c;
265}
266
267
268static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000269 // FIXME: implement -fpreprocessed mode.
270 bool NoPreprocess = false;
271
Ted Kremenek11ad8952007-12-05 23:49:08 +0000272 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000273 default: assert(0 && "Unknown language kind!");
274 case langkind_c_cpp:
275 NoPreprocess = true;
276 // FALLTHROUGH
277 case langkind_c:
278 break;
279 case langkind_cxx_cpp:
280 NoPreprocess = true;
281 // FALLTHROUGH
282 case langkind_cxx:
283 Options.CPlusPlus = 1;
284 break;
285 case langkind_objc_cpp:
286 NoPreprocess = true;
287 // FALLTHROUGH
288 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000289 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000290 break;
291 case langkind_objcxx_cpp:
292 NoPreprocess = true;
293 // FALLTHROUGH
294 case langkind_objcxx:
295 Options.ObjC1 = Options.ObjC2 = 1;
296 Options.CPlusPlus = 1;
297 break;
298 }
299}
300
301/// LangStds - Language standards we support.
302enum LangStds {
303 lang_unspecified,
304 lang_c89, lang_c94, lang_c99,
305 lang_gnu89, lang_gnu99,
306 lang_cxx98, lang_gnucxx98,
307 lang_cxx0x, lang_gnucxx0x
308};
309
310static llvm::cl::opt<LangStds>
311LangStd("std", llvm::cl::desc("Language standard to compile for"),
312 llvm::cl::init(lang_unspecified),
313 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
314 clEnumValN(lang_c89, "c90", "ISO C 1990"),
315 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
316 clEnumValN(lang_c94, "iso9899:199409",
317 "ISO C 1990 with amendment 1"),
318 clEnumValN(lang_c99, "c99", "ISO C 1999"),
319// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
320 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
321// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
322 clEnumValN(lang_gnu89, "gnu89",
323 "ISO C 1990 with GNU extensions (default for C)"),
324 clEnumValN(lang_gnu99, "gnu99",
325 "ISO C 1999 with GNU extensions"),
326 clEnumValN(lang_gnu99, "gnu9x",
327 "ISO C 1999 with GNU extensions"),
328 clEnumValN(lang_cxx98, "c++98",
329 "ISO C++ 1998 with amendments"),
330 clEnumValN(lang_gnucxx98, "gnu++98",
331 "ISO C++ 1998 with amendments and GNU "
332 "extensions (default for C++)"),
333 clEnumValN(lang_cxx0x, "c++0x",
334 "Upcoming ISO C++ 200x with amendments"),
335 clEnumValN(lang_gnucxx0x, "gnu++0x",
336 "Upcoming ISO C++ 200x with amendments and GNU "
337 "extensions (default for C++)"),
338 clEnumValEnd));
339
340static llvm::cl::opt<bool>
341NoOperatorNames("fno-operator-names",
342 llvm::cl::desc("Do not treat C++ operator name keywords as "
343 "synonyms for operators"));
344
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000345static llvm::cl::opt<bool>
346PascalStrings("fpascal-strings",
347 llvm::cl::desc("Recognize and construct Pascal-style "
348 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000349
350static llvm::cl::opt<bool>
351MSExtensions("fms-extensions",
352 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000353 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000354
355static llvm::cl::opt<bool>
356WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000357 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000358
359static llvm::cl::opt<bool>
360LaxVectorConversions("flax-vector-conversions",
361 llvm::cl::desc("Allow implicit conversions between vectors"
362 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000363 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000364
Chris Lattner4b009652007-07-25 00:24:17 +0000365// FIXME: add:
366// -ansi
367// -trigraphs
368// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000369// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000370static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000371 if (LangStd == lang_unspecified) {
372 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000373 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000374 default: assert(0 && "Unknown base language");
375 case langkind_c:
376 case langkind_c_cpp:
377 case langkind_objc:
378 case langkind_objc_cpp:
379 LangStd = lang_gnu99;
380 break;
381 case langkind_cxx:
382 case langkind_cxx_cpp:
383 case langkind_objcxx:
384 case langkind_objcxx_cpp:
385 LangStd = lang_gnucxx98;
386 break;
387 }
388 }
389
390 switch (LangStd) {
391 default: assert(0 && "Unknown language standard!");
392
393 // Fall through from newer standards to older ones. This isn't really right.
394 // FIXME: Enable specifically the right features based on the language stds.
395 case lang_gnucxx0x:
396 case lang_cxx0x:
397 Options.CPlusPlus0x = 1;
398 // FALL THROUGH
399 case lang_gnucxx98:
400 case lang_cxx98:
401 Options.CPlusPlus = 1;
402 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000403 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000404 // FALL THROUGH.
405 case lang_gnu99:
406 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000407 Options.C99 = 1;
408 Options.HexFloats = 1;
409 // FALL THROUGH.
410 case lang_gnu89:
411 Options.BCPLComment = 1; // Only for C99/C++.
412 // FALL THROUGH.
413 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000414 Options.Digraphs = 1; // C94, C99, C++.
415 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000416 case lang_c89:
417 break;
418 }
419
Chris Lattner6ab935b2008-04-05 06:32:51 +0000420 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
421 Options.ImplicitInt = 1;
422 else
423 Options.ImplicitInt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000424 Options.Trigraphs = 1; // -trigraphs or -ansi
425 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000426 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000427 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000428 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000429 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000430}
431
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000432static llvm::cl::opt<bool>
433ObjCExclusiveGC("fobjc-gc-only",
434 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000435 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000436
437static llvm::cl::opt<bool>
438ObjCEnableGC("fobjc-gc",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000439 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000440
441void InitializeGCMode(LangOptions &Options) {
442 if (ObjCExclusiveGC)
443 Options.setGCMode(LangOptions::GCOnly);
444 else if (ObjCEnableGC)
445 Options.setGCMode(LangOptions::HybridGC);
446}
447
448
Chris Lattner4b009652007-07-25 00:24:17 +0000449//===----------------------------------------------------------------------===//
450// Our DiagnosticClient implementation
451//===----------------------------------------------------------------------===//
452
453// FIXME: Werror should take a list of things, -Werror=foo,bar
454static llvm::cl::opt<bool>
455WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
456
457static llvm::cl::opt<bool>
458WarnOnExtensions("pedantic", llvm::cl::init(false),
459 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
460
461static llvm::cl::opt<bool>
462ErrorOnExtensions("pedantic-errors",
463 llvm::cl::desc("Issue an error on uses of GCC extensions"));
464
465static llvm::cl::opt<bool>
466WarnUnusedMacros("Wunused_macros",
467 llvm::cl::desc("Warn for unused macros in the main translation unit"));
468
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000469static llvm::cl::opt<bool>
470WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000471 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000472
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000473static llvm::cl::opt<bool>
474WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000475 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000476
Chris Lattnera616ee32008-01-23 17:19:46 +0000477static llvm::cl::opt<bool>
478WarnUndefMacros("Wundef",
479 llvm::cl::desc("Warn on use of undefined macros in #if's"));
480
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000481static llvm::cl::opt<bool>
482WarnImplicitFunctionDeclaration("Wimplicit-function-declaration"
483 "Warn about use of implicitly defined functions");
Chris Lattnera616ee32008-01-23 17:19:46 +0000484
Chris Lattner4b009652007-07-25 00:24:17 +0000485/// InitializeDiagnostics - Initialize the diagnostic object, based on the
486/// current command line option settings.
487static void InitializeDiagnostics(Diagnostic &Diags) {
488 Diags.setWarningsAsErrors(WarningsAsErrors);
489 Diags.setWarnOnExtensions(WarnOnExtensions);
490 Diags.setErrorOnExtensions(ErrorOnExtensions);
491
492 // Silence the "macro is not used" warning unless requested.
493 if (!WarnUnusedMacros)
494 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000495
496 // Silence "floating point comparison" warnings unless requested.
497 if (!WarnFloatEqual)
498 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000499
500 // Silence "format string is not a string literal" warnings if requested
501 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000502 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
503 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000504 if (!WarnUndefMacros)
505 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000506
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000507 if (!WarnImplicitFunctionDeclaration)
508 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
509 diag::MAP_IGNORE);
510
Steve Naroff606f7072008-02-11 22:40:08 +0000511 if (MSExtensions) // MS allows unnamed struct/union fields.
512 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000513
514 // If -pedantic-errors is set, turn extensions that warn by default into
515 // errors.
516 if (ErrorOnExtensions) {
517 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
518 diag::MAP_ERROR);
519 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
520 diag::MAP_ERROR);
521 }
Chris Lattner4b009652007-07-25 00:24:17 +0000522}
523
524//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000525// Analysis-specific options.
526//===----------------------------------------------------------------------===//
527
528static llvm::cl::opt<std::string>
529AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000530 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000531
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000532static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000533TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000534 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000535
Ted Kremenek0118bb52008-02-18 21:21:23 +0000536//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000537// Target Triple Processing.
538//===----------------------------------------------------------------------===//
539
540static llvm::cl::opt<std::string>
541TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000542 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000543
Chris Lattnerfc457002008-03-05 01:18:20 +0000544static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000545Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000546
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000547static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000548 // Initialize base triple. If a -triple option has been specified, use
549 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000550 std::string Triple = TargetTriple;
551 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000552
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000553 // If -arch foo was specified, remove the architecture from the triple we have
554 // so far and replace it with the specified one.
555 if (Arch.empty())
556 return Triple;
557
Ted Kremenek40499482007-12-03 22:06:55 +0000558 // Decompose the base triple into "arch" and suffix.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000559 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000560
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000561 if (FirstDashIdx == std::string::npos) {
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000562 fprintf(stderr,
563 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000564 Triple.c_str());
565 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000566 }
Ted Kremenek40499482007-12-03 22:06:55 +0000567
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000568 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenek40499482007-12-03 22:06:55 +0000569}
570
571//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000572// Preprocessor Initialization
573//===----------------------------------------------------------------------===//
574
575// FIXME: Preprocessor builtins to support.
576// -A... - Play with #assertions
577// -undef - Undefine all predefined macros
578
579static llvm::cl::list<std::string>
580D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
581 llvm::cl::desc("Predefine the specified macro"));
582static llvm::cl::list<std::string>
583U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
584 llvm::cl::desc("Undefine the specified macro"));
585
Chris Lattner008da782008-01-10 01:53:41 +0000586static llvm::cl::list<std::string>
587ImplicitIncludes("include", llvm::cl::value_desc("file"),
588 llvm::cl::desc("Include file before parsing"));
589
590
Chris Lattner4b009652007-07-25 00:24:17 +0000591// Append a #define line to Buf for Macro. Macro should be of the form XXX,
592// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
593// "#define XXX Y z W". To get a #define with no value, use "XXX=".
594static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
595 const char *Command = "#define ") {
596 Buf.insert(Buf.end(), Command, Command+strlen(Command));
597 if (const char *Equal = strchr(Macro, '=')) {
598 // Turn the = into ' '.
599 Buf.insert(Buf.end(), Macro, Equal);
600 Buf.push_back(' ');
601 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
602 } else {
603 // Push "macroname 1".
604 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
605 Buf.push_back(' ');
606 Buf.push_back('1');
607 }
608 Buf.push_back('\n');
609}
610
Chris Lattner008da782008-01-10 01:53:41 +0000611/// AddImplicitInclude - Add an implicit #include of the specified file to the
612/// predefines buffer.
613static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
614 const char *Inc = "#include \"";
615 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
616 Buf.insert(Buf.end(), File.begin(), File.end());
617 Buf.push_back('"');
618 Buf.push_back('\n');
619}
620
Chris Lattner4b009652007-07-25 00:24:17 +0000621
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000622/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000623/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000624///
Chris Lattner9d818a22008-04-19 23:25:44 +0000625static bool InitializePreprocessor(Preprocessor &PP,
626 bool InitializeSourceMgr,
627 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000628 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000629
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000630 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000631 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000632
633 if (InitializeSourceMgr) {
634 if (InFile != "-") {
635 const FileEntry *File = FileMgr.getFile(InFile);
636 if (File) SourceMgr.createMainFileID(File, SourceLocation());
637 if (SourceMgr.getMainFileID() == 0) {
638 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000639 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000640 }
641 } else {
642 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
643 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
644 if (SourceMgr.getMainFileID() == 0) {
645 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000646 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000647 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000648 }
Chris Lattner4b009652007-07-25 00:24:17 +0000649 }
Sam Bishop61a20782008-04-14 14:41:57 +0000650
Chris Lattner47b6a162008-04-19 23:09:31 +0000651 std::vector<char> PredefineBuffer;
652
Chris Lattner4b009652007-07-25 00:24:17 +0000653 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000654 unsigned d = 0, D = D_macros.size();
655 unsigned u = 0, U = U_macros.size();
656 while (d < D || u < U) {
657 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
658 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
659 else
660 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
661 }
662
Chris Lattner008da782008-01-10 01:53:41 +0000663 // FIXME: Read any files specified by -imacros.
664
665 // Add implicit #includes from -include.
666 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
667 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000668
Chris Lattner47b6a162008-04-19 23:09:31 +0000669 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000670 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000671 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000672
673 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000674 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000675}
676
677//===----------------------------------------------------------------------===//
678// Preprocessor include path information.
679//===----------------------------------------------------------------------===//
680
681// This tool exports a large number of command line options to control how the
682// preprocessor searches for header files. At root, however, the Preprocessor
683// object takes a very simple interface: a list of directories to search for
684//
685// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000686// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000687//
Chris Lattner008da782008-01-10 01:53:41 +0000688// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000689
690static llvm::cl::opt<bool>
691nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
692
693// Various command line options. These four add directories to each chain.
694static llvm::cl::list<std::string>
695F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
696 llvm::cl::desc("Add directory to framework include search path"));
697static llvm::cl::list<std::string>
698I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
699 llvm::cl::desc("Add directory to include search path"));
700static llvm::cl::list<std::string>
701idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
702 llvm::cl::desc("Add directory to AFTER include search path"));
703static llvm::cl::list<std::string>
704iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
705 llvm::cl::desc("Add directory to QUOTE include search path"));
706static llvm::cl::list<std::string>
707isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
708 llvm::cl::desc("Add directory to SYSTEM include search path"));
709
710// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
711static llvm::cl::list<std::string>
712iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
713 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
714static llvm::cl::list<std::string>
715iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
716 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
717static llvm::cl::list<std::string>
718iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
719 llvm::cl::Prefix,
720 llvm::cl::desc("Set directory to include search path with prefix"));
721
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000722static llvm::cl::opt<std::string>
723isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
724 llvm::cl::desc("Set the system root directory (usually /)"));
725
Chris Lattner4b009652007-07-25 00:24:17 +0000726// Finally, implement the code that groks the options above.
727enum IncludeDirGroup {
728 Quoted = 0,
729 Angled,
730 System,
731 After
732};
733
734static std::vector<DirectoryLookup> IncludeGroup[4];
735
736/// AddPath - Add the specified path to the specified group list.
737///
738static void AddPath(const std::string &Path, IncludeDirGroup Group,
739 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000740 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000741 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000742 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000743
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000744 // Compute the actual path, taking into consideration -isysroot.
745 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000746
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000747 // Handle isysroot.
748 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000749 // FIXME: Portability. This should be a sys::Path interface, this doesn't
750 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000751 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
752 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000753 }
754
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000755 MappedPath.append(Path.begin(), Path.end());
756
757 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000758 DirectoryLookup::DirType Type;
759 if (Group == Quoted || Group == Angled)
760 Type = DirectoryLookup::NormalHeaderDir;
761 else if (isCXXAware)
762 Type = DirectoryLookup::SystemHeaderDir;
763 else
764 Type = DirectoryLookup::ExternCSystemHeaderDir;
765
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000766
767 // If the directory exists, add it.
768 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
769 &MappedPath[0]+
770 MappedPath.size())) {
771 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
772 isFramework));
773 return;
774 }
775
Chris Lattnerb7426782007-12-17 07:52:39 +0000776 // Check to see if this is an apple-style headermap (which are not allowed to
777 // be frameworks).
778 if (!isFramework) {
779 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
780 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000781 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
782 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000783 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
784 return;
785 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000786 }
787 }
788
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000789 if (Verbose)
790 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000791}
792
793/// RemoveDuplicates - If there are duplicate directory entries in the specified
794/// search list, remove the later (dead) ones.
795static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000796 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000797 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000798 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000799 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000800 if (SearchList[i].isNormalDir()) {
801 // If this isn't the first time we've seen this dir, remove it.
802 if (SeenDirs.insert(SearchList[i].getDir()))
803 continue;
804
Chris Lattner4b009652007-07-25 00:24:17 +0000805 if (Verbose)
806 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
807 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000808 } else if (SearchList[i].isFramework()) {
809 // If this isn't the first time we've seen this framework dir, remove it.
810 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
811 continue;
812
813 if (Verbose)
814 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
815 SearchList[i].getFrameworkDir()->getName());
816
Chris Lattnercf33e932007-12-17 06:44:29 +0000817 } else {
818 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
819 // If this isn't the first time we've seen this headermap, remove it.
820 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
821 continue;
822
823 if (Verbose)
824 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
825 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000826 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000827
828 // This is reached if the current entry is a duplicate.
829 SearchList.erase(SearchList.begin()+i);
830 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000831 }
832}
833
Chris Lattner4f022a72008-03-01 08:07:28 +0000834// AddEnvVarPaths - Add a list of paths from an environment variable to a
835// header search list.
836//
837static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
838 const char* at = getenv(Name);
839 if (!at)
840 return;
841
842 const char* delim = strchr(at, llvm::sys::PathSeparator);
843 while (delim != 0) {
844 if (delim-at == 0)
845 AddPath(".", Angled, false, true, false, Headers);
846 else
847 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
848 true, false, Headers);
849 at = delim + 1;
850 delim = strchr(at, llvm::sys::PathSeparator);
851 }
852 if (*at == 0)
853 AddPath(".", Angled, false, true, false, Headers);
854 else
855 AddPath(at, Angled, false, true, false, Headers);
856}
857
Chris Lattner4b009652007-07-25 00:24:17 +0000858/// InitializeIncludePaths - Process the -I options and set them in the
859/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000860static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
861 FileManager &FM, const LangOptions &Lang) {
Chris Lattner4b009652007-07-25 00:24:17 +0000862 // Handle -F... options.
863 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000864 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000865
866 // Handle -I... options.
Chris Lattner45a56e02007-12-05 23:24:17 +0000867 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000868 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000869
870 // Handle -idirafter... options.
871 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000872 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000873
874 // Handle -iquote... options.
875 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000876 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000877
878 // Handle -isystem... options.
879 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000880 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000881
882 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
883 // parallel, processing the values in order of occurance to get the right
884 // prefixes.
885 {
886 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
887 unsigned iprefix_idx = 0;
888 unsigned iwithprefix_idx = 0;
889 unsigned iwithprefixbefore_idx = 0;
890 bool iprefix_done = iprefix_vals.empty();
891 bool iwithprefix_done = iwithprefix_vals.empty();
892 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
893 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
894 if (!iprefix_done &&
895 (iwithprefix_done ||
896 iprefix_vals.getPosition(iprefix_idx) <
897 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
898 (iwithprefixbefore_done ||
899 iprefix_vals.getPosition(iprefix_idx) <
900 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
901 Prefix = iprefix_vals[iprefix_idx];
902 ++iprefix_idx;
903 iprefix_done = iprefix_idx == iprefix_vals.size();
904 } else if (!iwithprefix_done &&
905 (iwithprefixbefore_done ||
906 iwithprefix_vals.getPosition(iwithprefix_idx) <
907 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
908 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000909 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000910 ++iwithprefix_idx;
911 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
912 } else {
913 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000914 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000915 ++iwithprefixbefore_idx;
916 iwithprefixbefore_done =
917 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
918 }
919 }
920 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000921
922 AddEnvVarPaths("CPATH", Headers);
923 if (Lang.CPlusPlus && Lang.ObjC1)
924 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
925 else if (Lang.CPlusPlus)
926 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
927 else if (Lang.ObjC1)
928 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
929 else
930 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
931
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000932 // Add the clang headers, which are relative to the clang driver.
933 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000934 llvm::sys::Path::GetMainExecutable(Argv0,
935 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000936 if (!MainExecutablePath.isEmpty()) {
937 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
938 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
939 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
940 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
941 }
942
Chris Lattner4b009652007-07-25 00:24:17 +0000943 // FIXME: temporary hack: hard-coded paths.
944 // FIXME: get these from the target?
945 if (!nostdinc) {
946 if (Lang.CPlusPlus) {
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000947 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000948 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000949 false, Headers);
950 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
951 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000952
953 // Ubuntu 7.10 - Gutsy Gibbon
954 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
955 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
956 false, Headers);
957 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
958 Headers);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000959
960 // Fedora 8
961 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner5fdcc302008-04-16 05:21:09 +0000962 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
963 false, Headers);
964 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
965 Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000966 }
967
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000968 AddPath("/usr/local/include", System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000969 // leopard
970 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000971 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000972 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000973 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000974 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
975 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000976 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000977
978 // tiger
979 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000980 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000981 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000982 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000983 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
984 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000985 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000986
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000987 // Ubuntu 7.10 - Gutsy Gibbon
988 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +0000989 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +0000990
Chris Lattner3e254fb2008-04-08 04:40:51 +0000991 // Fedora 8
992 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
993 false, false, false, Headers);
994
Andrew Lenharth6961ec42008-03-24 21:25:48 +0000995 //Debian testing/lenny x86
996 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
997 false, false, false, Headers);
Andrew Lenharthfccd7be2008-03-24 21:39:05 +0000998
999 //Debian testing/lenny amd64
1000 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1001 false, false, false, Headers);
Andrew Lenharth6961ec42008-03-24 21:25:48 +00001002
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001003 AddPath("/usr/include", System, false, false, false, Headers);
1004 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1005 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001006 }
1007
1008 // Now that we have collected all of the include paths, merge them all
1009 // together and tell the preprocessor about them.
1010
1011 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1012 std::vector<DirectoryLookup> SearchList;
1013 SearchList = IncludeGroup[Angled];
1014 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1015 IncludeGroup[System].end());
1016 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1017 IncludeGroup[After].end());
1018 RemoveDuplicates(SearchList);
1019 RemoveDuplicates(IncludeGroup[Quoted]);
1020
1021 // Prepend QUOTED list on the search list.
1022 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1023 IncludeGroup[Quoted].end());
1024
1025
1026 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1027 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1028 DontSearchCurDir);
1029
1030 // If verbose, print the list of directories that will be searched.
1031 if (Verbose) {
1032 fprintf(stderr, "#include \"...\" search starts here:\n");
1033 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1034 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1035 if (i == QuotedIdx)
1036 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +00001037 const char *Name = SearchList[i].getName();
1038 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +00001039 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +00001040 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +00001041 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +00001042 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001043 else {
1044 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +00001045 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001046 }
Chris Lattner1df68f92007-12-17 17:57:27 +00001047 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +00001048 }
Chris Lattnerac553842007-12-15 23:11:06 +00001049 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001050 }
1051}
1052
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001053//===----------------------------------------------------------------------===//
1054// Driver PreprocessorFactory - For lazily generating preprocessors ...
1055//===----------------------------------------------------------------------===//
1056
1057namespace {
1058class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001059 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001060 Diagnostic &Diags;
1061 const LangOptions &LangInfo;
1062 TargetInfo &Target;
1063 SourceManager &SourceMgr;
1064 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001065 bool InitializeSourceMgr;
1066
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001067public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001068 DriverPreprocessorFactory(const std::string &infile,
1069 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001070 TargetInfo &target, SourceManager &SM,
1071 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001072 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1073 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1074
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001075
1076 virtual ~DriverPreprocessorFactory() {}
1077
1078 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001079 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1080 SourceMgr, HeaderInfo);
1081
Chris Lattner9d818a22008-04-19 23:25:44 +00001082 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001083 delete PP;
1084 return NULL;
1085 }
1086
1087 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001088 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001089 }
1090};
1091}
Chris Lattner4b009652007-07-25 00:24:17 +00001092
Chris Lattner4b009652007-07-25 00:24:17 +00001093//===----------------------------------------------------------------------===//
1094// Basic Parser driver
1095//===----------------------------------------------------------------------===//
1096
Chris Lattner9d818a22008-04-19 23:25:44 +00001097static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001098 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001099 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001100
1101 // Parsing the specified input file.
1102 P.ParseTranslationUnit();
1103 delete PA;
1104}
1105
1106//===----------------------------------------------------------------------===//
1107// Main driver
1108//===----------------------------------------------------------------------===//
1109
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001110/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1111/// action. These consumers can operate on both ASTs that are freshly
1112/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001113static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001114 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001115 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001116 Preprocessor *PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001117 PreprocessorFactory *PPF,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001118 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001119 switch (ProgAction) {
1120 default:
1121 return NULL;
1122
1123 case ASTPrint:
1124 return CreateASTPrinter();
1125
1126 case ASTDump:
1127 return CreateASTDumper();
1128
1129 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001130 return CreateASTViewer();
1131
1132 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001133 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001134
1135 case ParseCFGDump:
1136 case ParseCFGView:
Ted Kremenek83390ec2008-02-22 20:00:31 +00001137 return CreateCFGDumper(ProgAction == ParseCFGView,
1138 AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001139
1140 case AnalysisLiveVariables:
Ted Kremenekb278abb2008-02-22 20:13:09 +00001141 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001142
1143 case WarnDeadStores:
1144 return CreateDeadStoreChecker(Diag);
1145
1146 case WarnUninitVals:
1147 return CreateUnitValsChecker(Diag);
1148
Ted Kremenek3862eb12008-02-14 22:36:46 +00001149 case AnalysisGRSimpleVals:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001150 return CreateGRSimpleVals(Diag, PP, PPF, AnalyzeSpecificFunction,
1151 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek1da5b142008-02-15 00:35:38 +00001152
Ted Kremenek827f93b2008-03-06 00:08:09 +00001153 case CheckerCFRef:
Ted Kremenek102d42e2008-04-29 05:13:59 +00001154 return CreateCFRefChecker(Diag, PP, PPF, LangOpts,
1155 AnalyzeSpecificFunction,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001156 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001157
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001158 case TestSerialization:
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001159 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001160
1161 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001162 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001163 DestModule = new llvm::Module(InFile);
1164 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001165
Ted Kremenekbde30332007-12-19 17:25:59 +00001166 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001167 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek6d1d3ac2007-12-19 23:48:45 +00001168 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek397de012007-12-13 00:37:31 +00001169
Steve Naroff44e81222008-04-14 22:03:09 +00001170 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001171 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001172 }
1173}
1174
Chris Lattner4b009652007-07-25 00:24:17 +00001175/// ProcessInputFile - Process a single input file with the specified state.
1176///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001177static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1178 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001179
1180 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001181 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001182 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001183
Chris Lattner4b009652007-07-25 00:24:17 +00001184 switch (ProgAction) {
1185 default:
Chris Lattner21f72d62008-04-16 06:11:58 +00001186 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1187 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001188 &PPF, CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001189
1190 if (!Consumer) {
1191 fprintf(stderr, "Unexpected program action!\n");
1192 return;
1193 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001194
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001195 break;
1196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 case DumpTokens: { // Token dump mode.
1198 Token Tok;
1199 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001200 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001201 do {
1202 PP.Lex(Tok);
1203 PP.DumpToken(Tok, true);
1204 fprintf(stderr, "\n");
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 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1210 Token Tok;
1211 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001212 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001213 do {
1214 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001215 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001216 ClearSourceMgr = true;
1217 break;
1218 }
1219
1220 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001221 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001222 ClearSourceMgr = true;
1223 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001224
Chris Lattner4b009652007-07-25 00:24:17 +00001225 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001226 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001227 ClearSourceMgr = true;
1228 break;
1229
1230 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001231 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001232 ClearSourceMgr = true;
1233 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001234
Ted Kremenek6856c632007-09-26 18:39:29 +00001235 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001236 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001237 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001238
1239 case RewriteMacros:
1240 RewriteMacrosInInput(PP, OutputFile);
1241 ClearSourceMgr = true;
1242 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001243 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001244
1245 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001246 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001247 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001248
1249 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001250 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001251 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001252
1253 // If running the code generator, finish up now.
1254 if (CodeGenModule) {
1255 std::ostream *Out;
1256 if (OutputFile == "-") {
1257 Out = llvm::cout.stream();
1258 } else if (!OutputFile.empty()) {
1259 Out = new std::ofstream(OutputFile.c_str(),
1260 std::ios_base::binary|std::ios_base::out);
1261 } else if (InFile == "-") {
1262 Out = llvm::cout.stream();
1263 } else {
1264 llvm::sys::Path Path(InFile);
1265 Path.eraseSuffix();
1266 if (ProgAction == EmitLLVM)
1267 Path.appendSuffix("ll");
1268 else if (ProgAction == EmitBC)
1269 Path.appendSuffix("bc");
1270 else
1271 assert(0 && "Unknown action");
1272 Out = new std::ofstream(Path.toString().c_str(),
1273 std::ios_base::binary|std::ios_base::out);
1274 }
1275
1276 if (ProgAction == EmitLLVM) {
1277 CodeGenModule->print(*Out);
1278 } else {
1279 assert(ProgAction == EmitBC);
1280 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1281 }
1282
1283 if (Out != llvm::cout.stream())
1284 delete Out;
1285 delete CodeGenModule;
1286 }
Chris Lattner4b009652007-07-25 00:24:17 +00001287
1288 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001289 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001290 PP.PrintStats();
1291 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001292 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001293 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001294 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001295 fprintf(stderr, "\n");
1296 }
1297
1298 // For a multi-file compilation, some things are ok with nuking the source
1299 // manager tables, other require stable fileid/macroid's across multiple
1300 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001301 if (ClearSourceMgr)
1302 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001303}
1304
Ted Kremenek80d53372007-12-12 23:41:08 +00001305static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1306 FileManager& FileMgr) {
1307
1308 if (VerifyDiagnostics) {
1309 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1310 exit (1);
1311 }
1312
1313 llvm::sys::Path Filename(InFile);
1314
1315 if (!Filename.isValid()) {
1316 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1317 exit (1);
1318 }
1319
Ted Kremenek863b01f2008-04-23 16:25:39 +00001320 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001321
1322 if (!TU) {
1323 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1324 InFile.c_str());
1325 exit (1);
1326 }
1327
Ted Kremenekab749372007-12-19 19:27:38 +00001328 // Observe that we use the source file name stored in the deserialized
1329 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001330 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001331 llvm::OwningPtr<ASTConsumer>
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001332 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(), 0, 0,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001333 DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001334
1335 if (!Consumer) {
1336 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1337 exit (1);
1338 }
1339
Ted Kremenek863b01f2008-04-23 16:25:39 +00001340 Consumer->Initialize(TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001341
Chris Lattner8d72ee02008-02-06 01:42:25 +00001342 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001343 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1344 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001345}
1346
1347
Chris Lattner4b009652007-07-25 00:24:17 +00001348static llvm::cl::list<std::string>
1349InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1350
Ted Kremenek80d53372007-12-12 23:41:08 +00001351static bool isSerializedFile(const std::string& InFile) {
1352 if (InFile.size() < 4)
1353 return false;
1354
1355 const char* s = InFile.c_str()+InFile.size()-4;
1356
1357 return s[0] == '.' &&
1358 s[1] == 'a' &&
1359 s[2] == 's' &&
1360 s[3] == 't';
1361}
1362
Chris Lattner4b009652007-07-25 00:24:17 +00001363
1364int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001365 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001366 llvm::sys::PrintStackTraceOnErrorSignal();
1367
1368 // If no input was specified, read from stdin.
1369 if (InputFilenames.empty())
1370 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001371
Chris Lattner4b009652007-07-25 00:24:17 +00001372 // Create a file manager object to provide access to and cache the filesystem.
1373 FileManager FileMgr;
1374
Ted Kremenekb240e822007-12-11 23:28:38 +00001375 // Create the diagnostic client for reporting errors or for
1376 // implementing -verify.
Ted Kremenekfd75e312008-03-27 06:17:42 +00001377 std::auto_ptr<DiagnosticClient> DiagClient;
1378 TextDiagnostics* TextDiagClient = NULL;
1379
1380 if (!HTMLDiag.empty()) {
Ted Kremenek675ac6f2008-04-16 16:53:18 +00001381
1382 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1383 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1384 // Fix this dependency later.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001385 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenekfd75e312008-03-27 06:17:42 +00001386 }
1387 else { // Use Text diagnostics.
1388 if (!VerifyDiagnostics) {
1389 // Print diagnostics to stderr by default.
1390 TextDiagClient = new TextDiagnosticPrinter();
1391 } else {
1392 // When checking diagnostics, just buffer them up.
1393 TextDiagClient = new TextDiagnosticBuffer();
1394
1395 if (InputFilenames.size() != 1) {
1396 fprintf(stderr,
1397 "-verify only works on single input files for now.\n");
1398 return 1;
1399 }
Chris Lattner4b009652007-07-25 00:24:17 +00001400 }
Ted Kremenekfd75e312008-03-27 06:17:42 +00001401
1402 assert (TextDiagClient);
1403 DiagClient.reset(TextDiagClient);
Chris Lattner4b009652007-07-25 00:24:17 +00001404 }
1405
1406 // Configure our handling of diagnostics.
1407 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001408 InitializeDiagnostics(Diags);
1409
Chris Lattner45a56e02007-12-05 23:24:17 +00001410 // -I- is a deprecated GCC feature, scan for it and reject it.
1411 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1412 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001413 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001414 I_dirs.erase(I_dirs.begin()+i);
1415 --i;
1416 }
1417 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001418
1419 // Get information about the target being compiled for.
1420 std::string Triple = CreateTargetTriple();
1421 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1422 if (Target == 0) {
1423 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1424 Triple.c_str());
1425 fprintf(stderr, "Please use -triple or -arch.\n");
1426 exit(1);
1427 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001428
Chris Lattner4b009652007-07-25 00:24:17 +00001429 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001430 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001431
Ted Kremenek80d53372007-12-12 23:41:08 +00001432 if (isSerializedFile(InFile))
1433 ProcessSerializedFile(InFile,Diags,FileMgr);
1434 else {
1435 /// Create a SourceManager object. This tracks and owns all the file
1436 /// buffers allocated to a translation unit.
1437 SourceManager SourceMgr;
Ted Kremenekb240e822007-12-11 23:28:38 +00001438
Ted Kremenek80d53372007-12-12 23:41:08 +00001439 // Initialize language options, inferring file types from input filenames.
1440 LangOptions LangInfo;
1441 InitializeBaseLanguage();
1442 LangKind LK = GetLanguage(InFile);
1443 InitializeLangOptions(LangInfo, LK);
1444 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001445 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001446
1447 // Process the -I options and set them in the HeaderInfo.
1448 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekfd75e312008-03-27 06:17:42 +00001449 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001450 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001451
Ted Kremenek80d53372007-12-12 23:41:08 +00001452 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001453 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001454 SourceMgr, HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001455
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001456 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1457
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001458 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001459 continue;
1460
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001461 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek80d53372007-12-12 23:41:08 +00001462 HeaderInfo.ClearFileInfo();
1463
1464 if (Stats)
1465 SourceMgr.PrintStats();
1466 }
Chris Lattner4b009652007-07-25 00:24:17 +00001467 }
1468
Chris Lattner2c77d852008-03-14 06:12:05 +00001469 delete Target;
1470
Chris Lattner4b009652007-07-25 00:24:17 +00001471 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1472
1473 if (NumDiagnostics)
1474 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1475 (NumDiagnostics == 1 ? "" : "s"));
1476
1477 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001478 FileMgr.PrintStats();
1479 fprintf(stderr, "\n");
1480 }
1481
1482 return Diags.getNumErrors() != 0;
1483}