blob: d92d5d62e6310c415e891b36d7cabbf2bbe49435 [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 Kremenek221bb8d2007-10-16 23:37:27 +000075 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000076 ParsePrintCallbacks, // Parse and print each callback.
77 ParseSyntaxOnly, // Parse and perform semantic analysis.
78 ParseNoop, // Parse with noop callbacks.
79 RunPreprocessorOnly, // Just lex, no output.
80 PrintPreprocessedInput, // -E mode.
Ted Kremenek81ea7992008-07-02 00:03:09 +000081 DumpTokens, // Token dump mode.
82 RunAnalysis // Run one or more source code analyses.
Chris Lattner4b009652007-07-25 00:24:17 +000083};
84
85static llvm::cl::opt<ProgActions>
86ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
87 llvm::cl::init(ParseSyntaxOnly),
88 llvm::cl::values(
89 clEnumValN(RunPreprocessorOnly, "Eonly",
90 "Just run preprocessor, no output (for timings)"),
91 clEnumValN(PrintPreprocessedInput, "E",
92 "Run preprocessor, emit preprocessed file"),
93 clEnumValN(DumpTokens, "dumptokens",
94 "Run preprocessor, dump internal rep of tokens"),
95 clEnumValN(ParseNoop, "parse-noop",
96 "Run parser with noop callbacks (for timings)"),
97 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
98 "Run parser and perform semantic analysis"),
99 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
100 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000101 clEnumValN(EmitHTML, "emit-html",
102 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000103 clEnumValN(ASTPrint, "ast-print",
104 "Build ASTs and then pretty-print them"),
105 clEnumValN(ASTDump, "ast-dump",
106 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000107 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000108 "Build ASTs and view them with GraphViz"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000109 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000110 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000111 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000112 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000113 clEnumValN(EmitBC, "emit-llvm-bc",
114 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000115 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000116 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000117 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000118 "Rewrite ObjC into C (code rewriter example)"),
119 clEnumValN(RewriteMacros, "rewrite-macros",
120 "Expand macros without full preprocessing"),
Chris Lattner4b009652007-07-25 00:24:17 +0000121 clEnumValEnd));
122
Ted Kremenekd01eae62007-12-19 19:47:59 +0000123
124static llvm::cl::opt<std::string>
125OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000126 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000127 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000128
129//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000130// Code Generator Options
131//===----------------------------------------------------------------------===//
132static llvm::cl::opt<bool>
133GenerateDebugInfo("g",
134 llvm::cl::desc("Generate source level debug information"));
135
136//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000137// Diagnostic Options
138//===----------------------------------------------------------------------===//
139
Ted Kremenek10389cf2007-09-26 19:42:19 +0000140static llvm::cl::opt<bool>
141VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000142 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000143
Ted Kremenekfd75e312008-03-27 06:17:42 +0000144static llvm::cl::opt<std::string>
145HTMLDiag("html-diags",
146 llvm::cl::desc("Generate HTML to report diagnostics"),
147 llvm::cl::value_desc("HTML directory"));
148
Chris Lattner4b009652007-07-25 00:24:17 +0000149//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000150// Analyzer Options
151//===----------------------------------------------------------------------===//
152
153static llvm::cl::opt<bool>
154VisualizeEG("visualize-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000155 llvm::cl::desc("Display static analysis Exploded Graph"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000156
157static llvm::cl::opt<bool>
158AnalyzeAll("checker-opt-analyze-headers",
159 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000160 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000161
Ted Kremenek81ea7992008-07-02 00:03:09 +0000162static llvm::cl::list<Analyses>
163AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
164llvm::cl::values(
Ted Kremeneke972d852008-07-02 18:23:21 +0000165clEnumValN(CFGDump, "cfg-dump", "Display Control-Flow Graphs"),
166clEnumValN(CFGView, "cfg-view", "View Control-Flow Graphs using GraphViz"),
Ted Kremenekd899b0f2008-07-02 18:11:29 +0000167clEnumValN(DisplayLiveVariables, "dump-live-variables",
168 "Print results of live variable analysis"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000169clEnumValN(WarnDeadStores, "warn-dead-stores",
170 "Flag warnings of stores to dead variables"),
171clEnumValN(WarnUninitVals, "warn-uninit-values",
172 "Flag warnings of uses of unitialized variables"),
Ted Kremenekd072b892008-07-11 22:40:47 +0000173clEnumValN(CheckObjCMethSigs, "check-objc-methodsigs",
174 "Check the Objective-C method signatures for type incompatibilities."),
Ted Kremenekc8a5fd42008-07-02 16:35:50 +0000175clEnumValN(CheckerSimple, "checker-simple",
176 "Perform simple path-sensitive checks."),
Ted Kremenek1c6cd212008-07-02 00:44:58 +0000177clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenekc8a5fd42008-07-02 16:35:50 +0000178 "Run the [Core] Foundation reference count checker"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000179clEnumValEnd));
180
Ted Kremenek517cb512008-04-14 18:40:58 +0000181//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000182// Language Options
183//===----------------------------------------------------------------------===//
184
185enum LangKind {
186 langkind_unspecified,
187 langkind_c,
188 langkind_c_cpp,
189 langkind_cxx,
190 langkind_cxx_cpp,
191 langkind_objc,
192 langkind_objc_cpp,
193 langkind_objcxx,
194 langkind_objcxx_cpp
195};
196
197/* TODO: GCC also accepts:
198 c-header c++-header objective-c-header objective-c++-header
199 assembler assembler-with-cpp
200 ada, f77*, ratfor (!), f95, java, treelang
201 */
202static llvm::cl::opt<LangKind>
203BaseLang("x", llvm::cl::desc("Base language to compile"),
204 llvm::cl::init(langkind_unspecified),
205 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
206 clEnumValN(langkind_cxx, "c++", "C++"),
207 clEnumValN(langkind_objc, "objective-c", "Objective C"),
208 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
209 clEnumValN(langkind_c_cpp, "c-cpp-output",
210 "Preprocessed C"),
211 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
212 "Preprocessed C++"),
213 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
214 "Preprocessed Objective C"),
215 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
216 "Preprocessed Objective C++"),
217 clEnumValEnd));
218
219static llvm::cl::opt<bool>
220LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
221 llvm::cl::Hidden);
222static llvm::cl::opt<bool>
223LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
224 llvm::cl::Hidden);
225
Ted Kremenek11ad8952007-12-05 23:49:08 +0000226/// InitializeBaseLanguage - Handle the -x foo options.
227static void InitializeBaseLanguage() {
228 if (LangObjC)
229 BaseLang = langkind_objc;
230 else if (LangObjCXX)
231 BaseLang = langkind_objcxx;
232}
233
234static LangKind GetLanguage(const std::string &Filename) {
235 if (BaseLang != langkind_unspecified)
236 return BaseLang;
237
238 std::string::size_type DotPos = Filename.rfind('.');
239
240 if (DotPos == std::string::npos) {
241 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000242 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000243 }
244
Ted Kremenek11ad8952007-12-05 23:49:08 +0000245 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
246 // C header: .h
247 // C++ header: .hh or .H;
248 // assembler no preprocessing: .s
249 // assembler: .S
250 if (Ext == "c")
251 return langkind_c;
252 else if (Ext == "i")
253 return langkind_c_cpp;
254 else if (Ext == "ii")
255 return langkind_cxx_cpp;
256 else if (Ext == "m")
257 return langkind_objc;
258 else if (Ext == "mi")
259 return langkind_objc_cpp;
260 else if (Ext == "mm" || Ext == "M")
261 return langkind_objcxx;
262 else if (Ext == "mii")
263 return langkind_objcxx_cpp;
264 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
265 Ext == "c++" || Ext == "cp" || Ext == "cxx")
266 return langkind_cxx;
267 else
268 return langkind_c;
269}
270
271
272static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000273 // FIXME: implement -fpreprocessed mode.
274 bool NoPreprocess = false;
275
Ted Kremenek11ad8952007-12-05 23:49:08 +0000276 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000277 default: assert(0 && "Unknown language kind!");
278 case langkind_c_cpp:
279 NoPreprocess = true;
280 // FALLTHROUGH
281 case langkind_c:
282 break;
283 case langkind_cxx_cpp:
284 NoPreprocess = true;
285 // FALLTHROUGH
286 case langkind_cxx:
287 Options.CPlusPlus = 1;
288 break;
289 case langkind_objc_cpp:
290 NoPreprocess = true;
291 // FALLTHROUGH
292 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000293 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000294 break;
295 case langkind_objcxx_cpp:
296 NoPreprocess = true;
297 // FALLTHROUGH
298 case langkind_objcxx:
299 Options.ObjC1 = Options.ObjC2 = 1;
300 Options.CPlusPlus = 1;
301 break;
302 }
303}
304
305/// LangStds - Language standards we support.
306enum LangStds {
307 lang_unspecified,
308 lang_c89, lang_c94, lang_c99,
309 lang_gnu89, lang_gnu99,
310 lang_cxx98, lang_gnucxx98,
311 lang_cxx0x, lang_gnucxx0x
312};
313
314static llvm::cl::opt<LangStds>
315LangStd("std", llvm::cl::desc("Language standard to compile for"),
316 llvm::cl::init(lang_unspecified),
317 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
318 clEnumValN(lang_c89, "c90", "ISO C 1990"),
319 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
320 clEnumValN(lang_c94, "iso9899:199409",
321 "ISO C 1990 with amendment 1"),
322 clEnumValN(lang_c99, "c99", "ISO C 1999"),
323// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
324 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
325// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
326 clEnumValN(lang_gnu89, "gnu89",
327 "ISO C 1990 with GNU extensions (default for C)"),
328 clEnumValN(lang_gnu99, "gnu99",
329 "ISO C 1999 with GNU extensions"),
330 clEnumValN(lang_gnu99, "gnu9x",
331 "ISO C 1999 with GNU extensions"),
332 clEnumValN(lang_cxx98, "c++98",
333 "ISO C++ 1998 with amendments"),
334 clEnumValN(lang_gnucxx98, "gnu++98",
335 "ISO C++ 1998 with amendments and GNU "
336 "extensions (default for C++)"),
337 clEnumValN(lang_cxx0x, "c++0x",
338 "Upcoming ISO C++ 200x with amendments"),
339 clEnumValN(lang_gnucxx0x, "gnu++0x",
340 "Upcoming ISO C++ 200x with amendments and GNU "
341 "extensions (default for C++)"),
342 clEnumValEnd));
343
344static llvm::cl::opt<bool>
345NoOperatorNames("fno-operator-names",
346 llvm::cl::desc("Do not treat C++ operator name keywords as "
347 "synonyms for operators"));
348
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000349static llvm::cl::opt<bool>
350PascalStrings("fpascal-strings",
351 llvm::cl::desc("Recognize and construct Pascal-style "
352 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000353
354static llvm::cl::opt<bool>
355MSExtensions("fms-extensions",
356 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000357 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000358
359static llvm::cl::opt<bool>
360WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000361 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000362
363static llvm::cl::opt<bool>
364LaxVectorConversions("flax-vector-conversions",
365 llvm::cl::desc("Allow implicit conversions between vectors"
366 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000367 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000368
Chris Lattner4b009652007-07-25 00:24:17 +0000369// FIXME: add:
370// -ansi
371// -trigraphs
372// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000373// -fpascal-strings
Ted Kremenek11ad8952007-12-05 23:49:08 +0000374static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000375 if (LangStd == lang_unspecified) {
376 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000377 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000378 default: assert(0 && "Unknown base language");
379 case langkind_c:
380 case langkind_c_cpp:
381 case langkind_objc:
382 case langkind_objc_cpp:
383 LangStd = lang_gnu99;
384 break;
385 case langkind_cxx:
386 case langkind_cxx_cpp:
387 case langkind_objcxx:
388 case langkind_objcxx_cpp:
389 LangStd = lang_gnucxx98;
390 break;
391 }
392 }
393
394 switch (LangStd) {
395 default: assert(0 && "Unknown language standard!");
396
397 // Fall through from newer standards to older ones. This isn't really right.
398 // FIXME: Enable specifically the right features based on the language stds.
399 case lang_gnucxx0x:
400 case lang_cxx0x:
401 Options.CPlusPlus0x = 1;
402 // FALL THROUGH
403 case lang_gnucxx98:
404 case lang_cxx98:
405 Options.CPlusPlus = 1;
406 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000407 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000408 // FALL THROUGH.
409 case lang_gnu99:
410 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000411 Options.C99 = 1;
412 Options.HexFloats = 1;
413 // FALL THROUGH.
414 case lang_gnu89:
415 Options.BCPLComment = 1; // Only for C99/C++.
416 // FALL THROUGH.
417 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000418 Options.Digraphs = 1; // C94, C99, C++.
419 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000420 case lang_c89:
421 break;
422 }
423
Chris Lattner6ab935b2008-04-05 06:32:51 +0000424 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
425 Options.ImplicitInt = 1;
426 else
427 Options.ImplicitInt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000428 Options.Trigraphs = 1; // -trigraphs or -ansi
429 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000430 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000431 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000432 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000433 Options.LaxVectorConversions = LaxVectorConversions;
Chris Lattner4b009652007-07-25 00:24:17 +0000434}
435
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000436static llvm::cl::opt<bool>
437ObjCExclusiveGC("fobjc-gc-only",
438 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000439 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000440
441static llvm::cl::opt<bool>
442ObjCEnableGC("fobjc-gc",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000443 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000444
445void InitializeGCMode(LangOptions &Options) {
446 if (ObjCExclusiveGC)
447 Options.setGCMode(LangOptions::GCOnly);
448 else if (ObjCEnableGC)
449 Options.setGCMode(LangOptions::HybridGC);
450}
451
452
Chris Lattner4b009652007-07-25 00:24:17 +0000453//===----------------------------------------------------------------------===//
454// Our DiagnosticClient implementation
455//===----------------------------------------------------------------------===//
456
457// FIXME: Werror should take a list of things, -Werror=foo,bar
458static llvm::cl::opt<bool>
459WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
460
461static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000462SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
463
464static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000465WarnOnExtensions("pedantic", llvm::cl::init(false),
466 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
467
468static llvm::cl::opt<bool>
469ErrorOnExtensions("pedantic-errors",
470 llvm::cl::desc("Issue an error on uses of GCC extensions"));
471
472static llvm::cl::opt<bool>
473WarnUnusedMacros("Wunused_macros",
474 llvm::cl::desc("Warn for unused macros in the main translation unit"));
475
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000476static llvm::cl::opt<bool>
477WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000478 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000479
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000480static llvm::cl::opt<bool>
481WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000482 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000483
Chris Lattnera616ee32008-01-23 17:19:46 +0000484static llvm::cl::opt<bool>
485WarnUndefMacros("Wundef",
486 llvm::cl::desc("Warn on use of undefined macros in #if's"));
487
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000488static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000489WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
490 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000491
Chris Lattner4b009652007-07-25 00:24:17 +0000492/// InitializeDiagnostics - Initialize the diagnostic object, based on the
493/// current command line option settings.
494static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000495 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000496 Diags.setWarningsAsErrors(WarningsAsErrors);
497 Diags.setWarnOnExtensions(WarnOnExtensions);
498 Diags.setErrorOnExtensions(ErrorOnExtensions);
499
500 // Silence the "macro is not used" warning unless requested.
501 if (!WarnUnusedMacros)
502 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000503
504 // Silence "floating point comparison" warnings unless requested.
505 if (!WarnFloatEqual)
506 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000507
508 // Silence "format string is not a string literal" warnings if requested
509 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000510 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
511 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000512 if (!WarnUndefMacros)
513 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000514
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000515 if (!WarnImplicitFunctionDeclaration)
516 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
517 diag::MAP_IGNORE);
518
Steve Naroff606f7072008-02-11 22:40:08 +0000519 if (MSExtensions) // MS allows unnamed struct/union fields.
520 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000521
522 // If -pedantic-errors is set, turn extensions that warn by default into
523 // errors.
524 if (ErrorOnExtensions) {
525 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
526 diag::MAP_ERROR);
527 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
528 diag::MAP_ERROR);
529 }
Chris Lattner4b009652007-07-25 00:24:17 +0000530}
531
532//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000533// Analysis-specific options.
534//===----------------------------------------------------------------------===//
535
536static llvm::cl::opt<std::string>
537AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000538 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000539
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000540static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000541TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000542 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000543
Ted Kremenek0118bb52008-02-18 21:21:23 +0000544//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000545// Target Triple Processing.
546//===----------------------------------------------------------------------===//
547
548static llvm::cl::opt<std::string>
549TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000550 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000551
Chris Lattnerfc457002008-03-05 01:18:20 +0000552static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000553Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000554
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000555static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000556 // Initialize base triple. If a -triple option has been specified, use
557 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000558 std::string Triple = TargetTriple;
559 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000560
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000561 // If -arch foo was specified, remove the architecture from the triple we have
562 // so far and replace it with the specified one.
563 if (Arch.empty())
564 return Triple;
565
Ted Kremenek40499482007-12-03 22:06:55 +0000566 // Decompose the base triple into "arch" and suffix.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000567 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenek40499482007-12-03 22:06:55 +0000568
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000569 if (FirstDashIdx == std::string::npos) {
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000570 fprintf(stderr,
571 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner210c0cc2007-12-12 05:01:48 +0000572 Triple.c_str());
573 exit(1);
Ted Kremenek0a8ce9d2007-12-03 22:11:31 +0000574 }
Ted Kremenek40499482007-12-03 22:06:55 +0000575
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000576 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenek40499482007-12-03 22:06:55 +0000577}
578
579//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000580// Preprocessor Initialization
581//===----------------------------------------------------------------------===//
582
583// FIXME: Preprocessor builtins to support.
584// -A... - Play with #assertions
585// -undef - Undefine all predefined macros
586
587static llvm::cl::list<std::string>
588D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
589 llvm::cl::desc("Predefine the specified macro"));
590static llvm::cl::list<std::string>
591U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
592 llvm::cl::desc("Undefine the specified macro"));
593
Chris Lattner008da782008-01-10 01:53:41 +0000594static llvm::cl::list<std::string>
595ImplicitIncludes("include", llvm::cl::value_desc("file"),
596 llvm::cl::desc("Include file before parsing"));
597
598
Chris Lattner4b009652007-07-25 00:24:17 +0000599// Append a #define line to Buf for Macro. Macro should be of the form XXX,
600// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
601// "#define XXX Y z W". To get a #define with no value, use "XXX=".
602static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
603 const char *Command = "#define ") {
604 Buf.insert(Buf.end(), Command, Command+strlen(Command));
605 if (const char *Equal = strchr(Macro, '=')) {
606 // Turn the = into ' '.
607 Buf.insert(Buf.end(), Macro, Equal);
608 Buf.push_back(' ');
609 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
610 } else {
611 // Push "macroname 1".
612 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
613 Buf.push_back(' ');
614 Buf.push_back('1');
615 }
616 Buf.push_back('\n');
617}
618
Chris Lattner008da782008-01-10 01:53:41 +0000619/// AddImplicitInclude - Add an implicit #include of the specified file to the
620/// predefines buffer.
621static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
622 const char *Inc = "#include \"";
623 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
624 Buf.insert(Buf.end(), File.begin(), File.end());
625 Buf.push_back('"');
626 Buf.push_back('\n');
627}
628
Chris Lattner4b009652007-07-25 00:24:17 +0000629
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000630/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000631/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000632///
Chris Lattner9d818a22008-04-19 23:25:44 +0000633static bool InitializePreprocessor(Preprocessor &PP,
634 bool InitializeSourceMgr,
635 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000636 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000637
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000638 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000639 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000640
641 if (InitializeSourceMgr) {
642 if (InFile != "-") {
643 const FileEntry *File = FileMgr.getFile(InFile);
644 if (File) SourceMgr.createMainFileID(File, SourceLocation());
645 if (SourceMgr.getMainFileID() == 0) {
646 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000647 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000648 }
649 } else {
650 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
651 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
652 if (SourceMgr.getMainFileID() == 0) {
653 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000654 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000655 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000656 }
Chris Lattner4b009652007-07-25 00:24:17 +0000657 }
Sam Bishop61a20782008-04-14 14:41:57 +0000658
Chris Lattner47b6a162008-04-19 23:09:31 +0000659 std::vector<char> PredefineBuffer;
660
Chris Lattner4b009652007-07-25 00:24:17 +0000661 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000662 unsigned d = 0, D = D_macros.size();
663 unsigned u = 0, U = U_macros.size();
664 while (d < D || u < U) {
665 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
666 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
667 else
668 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
669 }
670
Chris Lattner008da782008-01-10 01:53:41 +0000671 // FIXME: Read any files specified by -imacros.
672
673 // Add implicit #includes from -include.
674 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
675 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000676
Chris Lattner47b6a162008-04-19 23:09:31 +0000677 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000678 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000679 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000680
681 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000682 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000683}
684
685//===----------------------------------------------------------------------===//
686// Preprocessor include path information.
687//===----------------------------------------------------------------------===//
688
689// This tool exports a large number of command line options to control how the
690// preprocessor searches for header files. At root, however, the Preprocessor
691// object takes a very simple interface: a list of directories to search for
692//
693// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000694// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000695//
Chris Lattner008da782008-01-10 01:53:41 +0000696// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000697
698static llvm::cl::opt<bool>
699nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
700
701// Various command line options. These four add directories to each chain.
702static llvm::cl::list<std::string>
703F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
704 llvm::cl::desc("Add directory to framework include search path"));
705static llvm::cl::list<std::string>
706I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
707 llvm::cl::desc("Add directory to include search path"));
708static llvm::cl::list<std::string>
709idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
710 llvm::cl::desc("Add directory to AFTER include search path"));
711static llvm::cl::list<std::string>
712iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
713 llvm::cl::desc("Add directory to QUOTE include search path"));
714static llvm::cl::list<std::string>
715isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
716 llvm::cl::desc("Add directory to SYSTEM include search path"));
717
718// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
719static llvm::cl::list<std::string>
720iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
721 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
722static llvm::cl::list<std::string>
723iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
724 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
725static llvm::cl::list<std::string>
726iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
727 llvm::cl::Prefix,
728 llvm::cl::desc("Set directory to include search path with prefix"));
729
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000730static llvm::cl::opt<std::string>
731isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
732 llvm::cl::desc("Set the system root directory (usually /)"));
733
Chris Lattner4b009652007-07-25 00:24:17 +0000734// Finally, implement the code that groks the options above.
735enum IncludeDirGroup {
736 Quoted = 0,
737 Angled,
738 System,
739 After
740};
741
742static std::vector<DirectoryLookup> IncludeGroup[4];
743
744/// AddPath - Add the specified path to the specified group list.
745///
746static void AddPath(const std::string &Path, IncludeDirGroup Group,
747 bool isCXXAware, bool isUserSupplied,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000748 bool isFramework, HeaderSearch &HS) {
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000749 assert(!Path.empty() && "can't handle empty path here");
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000750 FileManager &FM = HS.getFileMgr();
Chris Lattnerc8d80bb2007-12-09 00:39:55 +0000751
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000752 // Compute the actual path, taking into consideration -isysroot.
753 llvm::SmallString<256> MappedPath;
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000754
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000755 // Handle isysroot.
756 if (Group == System) {
Chris Lattner2a2702a2007-12-17 06:51:34 +0000757 // FIXME: Portability. This should be a sys::Path interface, this doesn't
758 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000759 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
760 MappedPath.append(isysroot.begin(), isysroot.end());
Chris Lattner4b009652007-07-25 00:24:17 +0000761 }
762
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000763 MappedPath.append(Path.begin(), Path.end());
764
765 // Compute the DirectoryLookup type.
Chris Lattner4b009652007-07-25 00:24:17 +0000766 DirectoryLookup::DirType Type;
767 if (Group == Quoted || Group == Angled)
768 Type = DirectoryLookup::NormalHeaderDir;
769 else if (isCXXAware)
770 Type = DirectoryLookup::SystemHeaderDir;
771 else
772 Type = DirectoryLookup::ExternCSystemHeaderDir;
773
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000774
775 // If the directory exists, add it.
776 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
777 &MappedPath[0]+
778 MappedPath.size())) {
779 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
780 isFramework));
781 return;
782 }
783
Chris Lattnerb7426782007-12-17 07:52:39 +0000784 // Check to see if this is an apple-style headermap (which are not allowed to
785 // be frameworks).
786 if (!isFramework) {
787 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
788 &MappedPath[0]+MappedPath.size())) {
Chris Lattner9af36d32007-12-17 18:34:53 +0000789 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
790 // It is a headermap, add it to the search path.
Chris Lattnerb7426782007-12-17 07:52:39 +0000791 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
792 return;
793 }
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000794 }
795 }
796
Chris Lattner2a4e2ad2007-12-17 05:59:27 +0000797 if (Verbose)
798 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000799}
800
801/// RemoveDuplicates - If there are duplicate directory entries in the specified
802/// search list, remove the later (dead) ones.
803static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattnerac139d22007-12-15 23:20:07 +0000804 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerb7426782007-12-17 07:52:39 +0000805 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnercf33e932007-12-17 06:44:29 +0000806 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Chris Lattner4b009652007-07-25 00:24:17 +0000807 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnercf33e932007-12-17 06:44:29 +0000808 if (SearchList[i].isNormalDir()) {
809 // If this isn't the first time we've seen this dir, remove it.
810 if (SeenDirs.insert(SearchList[i].getDir()))
811 continue;
812
Chris Lattner4b009652007-07-25 00:24:17 +0000813 if (Verbose)
814 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
815 SearchList[i].getDir()->getName());
Chris Lattnerb7426782007-12-17 07:52:39 +0000816 } else if (SearchList[i].isFramework()) {
817 // If this isn't the first time we've seen this framework dir, remove it.
818 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
819 continue;
820
821 if (Verbose)
822 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
823 SearchList[i].getFrameworkDir()->getName());
824
Chris Lattnercf33e932007-12-17 06:44:29 +0000825 } else {
826 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
827 // If this isn't the first time we've seen this headermap, remove it.
828 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
829 continue;
830
831 if (Verbose)
832 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
833 SearchList[i].getDir()->getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000834 }
Chris Lattnercf33e932007-12-17 06:44:29 +0000835
836 // This is reached if the current entry is a duplicate.
837 SearchList.erase(SearchList.begin()+i);
838 --i;
Chris Lattner4b009652007-07-25 00:24:17 +0000839 }
840}
841
Chris Lattner4f022a72008-03-01 08:07:28 +0000842// AddEnvVarPaths - Add a list of paths from an environment variable to a
843// header search list.
844//
845static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
846 const char* at = getenv(Name);
847 if (!at)
848 return;
849
850 const char* delim = strchr(at, llvm::sys::PathSeparator);
851 while (delim != 0) {
852 if (delim-at == 0)
853 AddPath(".", Angled, false, true, false, Headers);
854 else
855 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
856 true, false, Headers);
857 at = delim + 1;
858 delim = strchr(at, llvm::sys::PathSeparator);
859 }
860 if (*at == 0)
861 AddPath(".", Angled, false, true, false, Headers);
862 else
863 AddPath(at, Angled, false, true, false, Headers);
864}
865
Chris Lattner4b009652007-07-25 00:24:17 +0000866/// InitializeIncludePaths - Process the -I options and set them in the
867/// HeaderSearch object.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000868static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
869 FileManager &FM, const LangOptions &Lang) {
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000870 // Handle -I... and -F... options, walking the lists in parallel.
871 unsigned Iidx = 0, Fidx = 0;
872 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
873 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
874 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
875 ++Iidx;
876 } else {
877 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
878 ++Fidx;
879 }
880 }
Chris Lattner4b009652007-07-25 00:24:17 +0000881
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000882 // Consume what's left from whatever list was longer.
883 for (; Iidx != I_dirs.size(); ++Iidx)
884 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
885 for (; Fidx != F_dirs.size(); ++Fidx)
886 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000887
888 // Handle -idirafter... options.
889 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000890 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000891
892 // Handle -iquote... options.
893 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000894 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000895
896 // Handle -isystem... options.
897 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000898 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000899
900 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
901 // parallel, processing the values in order of occurance to get the right
902 // prefixes.
903 {
904 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
905 unsigned iprefix_idx = 0;
906 unsigned iwithprefix_idx = 0;
907 unsigned iwithprefixbefore_idx = 0;
908 bool iprefix_done = iprefix_vals.empty();
909 bool iwithprefix_done = iwithprefix_vals.empty();
910 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
911 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
912 if (!iprefix_done &&
913 (iwithprefix_done ||
914 iprefix_vals.getPosition(iprefix_idx) <
915 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
916 (iwithprefixbefore_done ||
917 iprefix_vals.getPosition(iprefix_idx) <
918 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
919 Prefix = iprefix_vals[iprefix_idx];
920 ++iprefix_idx;
921 iprefix_done = iprefix_idx == iprefix_vals.size();
922 } else if (!iwithprefix_done &&
923 (iwithprefixbefore_done ||
924 iwithprefix_vals.getPosition(iwithprefix_idx) <
925 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
926 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000927 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000928 ++iwithprefix_idx;
929 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
930 } else {
931 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000932 Angled, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000933 ++iwithprefixbefore_idx;
934 iwithprefixbefore_done =
935 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
936 }
937 }
938 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000939
940 AddEnvVarPaths("CPATH", Headers);
941 if (Lang.CPlusPlus && Lang.ObjC1)
942 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
943 else if (Lang.CPlusPlus)
944 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
945 else if (Lang.ObjC1)
946 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
947 else
948 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
949
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000950 // Add the clang headers, which are relative to the clang driver.
951 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000952 llvm::sys::Path::GetMainExecutable(Argv0,
953 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000954 if (!MainExecutablePath.isEmpty()) {
955 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
956 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
957 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
958 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
959 }
960
Chris Lattner4b009652007-07-25 00:24:17 +0000961 // FIXME: temporary hack: hard-coded paths.
962 // FIXME: get these from the target?
963 if (!nostdinc) {
964 if (Lang.CPlusPlus) {
Ted Kremenek6032d722008-05-22 15:26:22 +0000965 AddPath("/usr/include/c++/4.2.1", System, true, false, false, Headers);
966 AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false,
967 false, Headers);
968 AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false,
969 Headers);
970
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000971 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000972 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattnerc2043bf2007-12-17 06:36:45 +0000973 false, Headers);
974 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
975 Headers);
Lauro Ramos Venanciof6a66272008-02-15 22:36:38 +0000976
977 // Ubuntu 7.10 - Gutsy Gibbon
978 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
979 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
980 false, Headers);
981 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
982 Headers);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000983
984 // Fedora 8
985 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner5fdcc302008-04-16 05:21:09 +0000986 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
987 false, Headers);
988 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
989 Headers);
Ted Kremenek0cb803a2008-06-24 03:33:47 +0000990
991 // Arch Linux 2008-06-24
992 AddPath("/usr/include/c++/4.3.1", System, true, false, false, Headers);
993 AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false,
994 false, Headers);
995 AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false,
996 Headers);
997 AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true,
998 false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +0000999 }
1000
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001001 AddPath("/usr/local/include", System, false, false, false, Headers);
Ted Kremenek6032d722008-05-22 15:26:22 +00001002
1003 AddPath("/usr/lib/gcc/i686-apple-darwin10/4.2.1/include", System,
1004 false, false, false, Headers);
1005 AddPath("/usr/lib/gcc/powerpc-apple-darwin10/4.2.1/include",
1006 System, false, false, false, Headers);
1007
Chris Lattner4b009652007-07-25 00:24:17 +00001008 // leopard
1009 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001010 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001011 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001012 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001013 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
1014 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001015 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001016
1017 // tiger
1018 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001019 false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001020 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001021 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001022 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
1023 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001024 System, false, false, false, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001025
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +00001026 // Ubuntu 7.10 - Gutsy Gibbon
1027 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattner43b885f2008-02-25 21:04:36 +00001028 false, false, false, Headers);
Lauro Ramos Venanciod0515f22008-01-21 23:08:35 +00001029
Chris Lattner3e254fb2008-04-08 04:40:51 +00001030 // Fedora 8
1031 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
1032 false, false, false, Headers);
1033
Andrew Lenharth6961ec42008-03-24 21:25:48 +00001034 //Debian testing/lenny x86
1035 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
1036 false, false, false, Headers);
Andrew Lenharthfccd7be2008-03-24 21:39:05 +00001037
1038 //Debian testing/lenny amd64
1039 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1040 false, false, false, Headers);
Andrew Lenharth6961ec42008-03-24 21:25:48 +00001041
Ted Kremenek0cb803a2008-06-24 03:33:47 +00001042 // Arch Linux 2008-06-24
1043 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include", System,
1044 false, false, false, Headers);
1045 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include-fixed", System,
1046 false, false, false, Headers);
1047 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include", System,
1048 false, false, false, Headers);
1049 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include-fixed",
1050 System, false, false, false, Headers);
1051
Matthijs Kooijman25349e42008-06-26 08:39:30 +00001052 // Debian testing/lenny ppc32
1053 AddPath("/usr/lib/gcc/powerpc-linux-gnu/4.2.3/include", System,
1054 false, false, false, Headers);
1055
Nuno Lopesbaf66722008-07-05 17:15:18 +00001056 // Gentoo x86 stable
1057 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include", System,
1058 false, false, false, Headers);
1059
Chris Lattnerc2043bf2007-12-17 06:36:45 +00001060 AddPath("/usr/include", System, false, false, false, Headers);
1061 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1062 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Chris Lattner4b009652007-07-25 00:24:17 +00001063 }
1064
1065 // Now that we have collected all of the include paths, merge them all
1066 // together and tell the preprocessor about them.
1067
1068 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1069 std::vector<DirectoryLookup> SearchList;
1070 SearchList = IncludeGroup[Angled];
1071 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1072 IncludeGroup[System].end());
1073 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1074 IncludeGroup[After].end());
1075 RemoveDuplicates(SearchList);
1076 RemoveDuplicates(IncludeGroup[Quoted]);
1077
1078 // Prepend QUOTED list on the search list.
1079 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1080 IncludeGroup[Quoted].end());
1081
1082
1083 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1084 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1085 DontSearchCurDir);
1086
1087 // If verbose, print the list of directories that will be searched.
1088 if (Verbose) {
1089 fprintf(stderr, "#include \"...\" search starts here:\n");
1090 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1091 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1092 if (i == QuotedIdx)
1093 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner1df68f92007-12-17 17:57:27 +00001094 const char *Name = SearchList[i].getName();
1095 const char *Suffix;
Chris Lattner0f64f652007-12-17 17:42:26 +00001096 if (SearchList[i].isNormalDir())
Chris Lattner1df68f92007-12-17 17:57:27 +00001097 Suffix = "";
Chris Lattner0f64f652007-12-17 17:42:26 +00001098 else if (SearchList[i].isFramework())
Chris Lattner1df68f92007-12-17 17:57:27 +00001099 Suffix = " (framework directory)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001100 else {
1101 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner1df68f92007-12-17 17:57:27 +00001102 Suffix = " (headermap)";
Chris Lattner0f64f652007-12-17 17:42:26 +00001103 }
Chris Lattner1df68f92007-12-17 17:57:27 +00001104 fprintf(stderr, " %s%s\n", Name, Suffix);
Chris Lattner4b009652007-07-25 00:24:17 +00001105 }
Chris Lattnerac553842007-12-15 23:11:06 +00001106 fprintf(stderr, "End of search list.\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001107 }
1108}
1109
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001110//===----------------------------------------------------------------------===//
1111// Driver PreprocessorFactory - For lazily generating preprocessors ...
1112//===----------------------------------------------------------------------===//
1113
1114namespace {
1115class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001116 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001117 Diagnostic &Diags;
1118 const LangOptions &LangInfo;
1119 TargetInfo &Target;
1120 SourceManager &SourceMgr;
1121 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001122 bool InitializeSourceMgr;
1123
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001124public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001125 DriverPreprocessorFactory(const std::string &infile,
1126 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001127 TargetInfo &target, SourceManager &SM,
1128 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001129 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1130 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1131
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001132
1133 virtual ~DriverPreprocessorFactory() {}
1134
1135 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001136 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1137 SourceMgr, HeaderInfo);
1138
Chris Lattner9d818a22008-04-19 23:25:44 +00001139 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001140 delete PP;
1141 return NULL;
1142 }
1143
1144 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001145 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001146 }
1147};
1148}
Chris Lattner4b009652007-07-25 00:24:17 +00001149
Chris Lattner4b009652007-07-25 00:24:17 +00001150//===----------------------------------------------------------------------===//
1151// Basic Parser driver
1152//===----------------------------------------------------------------------===//
1153
Chris Lattner9d818a22008-04-19 23:25:44 +00001154static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001155 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001156 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001157
1158 // Parsing the specified input file.
1159 P.ParseTranslationUnit();
1160 delete PA;
Argiris Kirtzidis8d833762008-06-13 12:15:34 +00001161
1162 if (VerifyDiagnostics)
1163 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001164}
1165
1166//===----------------------------------------------------------------------===//
1167// Main driver
1168//===----------------------------------------------------------------------===//
1169
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001170/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1171/// action. These consumers can operate on both ASTs that are freshly
1172/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001173static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001174 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001175 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001176 Preprocessor *PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001177 PreprocessorFactory *PPF,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001178 llvm::Module *&DestModule) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001179 switch (ProgAction) {
1180 default:
1181 return NULL;
1182
1183 case ASTPrint:
1184 return CreateASTPrinter();
1185
1186 case ASTDump:
1187 return CreateASTDumper();
1188
1189 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001190 return CreateASTViewer();
1191
1192 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001193 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001194
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001195 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001196 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001197
1198 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001199 case EmitBC:
Chris Lattner8d72ee02008-02-06 01:42:25 +00001200 DestModule = new llvm::Module(InFile);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +00001201 return CreateLLVMCodeGen(Diag, LangOpts, DestModule, GenerateDebugInfo);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001202
Ted Kremenekbde30332007-12-19 17:25:59 +00001203 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001204 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001205 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001206
Steve Naroff44e81222008-04-14 22:03:09 +00001207 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001208 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001209
1210 case RunAnalysis:
1211 assert (!AnalysisList.empty());
1212 return CreateAnalysisConsumer(&AnalysisList[0],
1213 &AnalysisList[0]+AnalysisList.size(),
1214 Diag, PP, PPF, LangOpts,
1215 AnalyzeSpecificFunction,
1216 OutputFile, VisualizeEG, TrimGraph,
1217 AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001218 }
1219}
1220
Chris Lattner4b009652007-07-25 00:24:17 +00001221/// ProcessInputFile - Process a single input file with the specified state.
1222///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001223static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1224 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001225
1226 ASTConsumer* Consumer = NULL;
Chris Lattner4b009652007-07-25 00:24:17 +00001227 bool ClearSourceMgr = false;
Chris Lattner8d72ee02008-02-06 01:42:25 +00001228 llvm::Module *CodeGenModule = 0;
Ted Kremenek6856c632007-09-26 18:39:29 +00001229
Chris Lattner4b009652007-07-25 00:24:17 +00001230 switch (ProgAction) {
1231 default:
Chris Lattner21f72d62008-04-16 06:11:58 +00001232 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1233 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001234 &PPF, CodeGenModule);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001235
1236 if (!Consumer) {
1237 fprintf(stderr, "Unexpected program action!\n");
1238 return;
1239 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001240
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001241 break;
1242
Chris Lattner4b009652007-07-25 00:24:17 +00001243 case DumpTokens: { // Token dump mode.
1244 Token Tok;
1245 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001246 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001247 do {
1248 PP.Lex(Tok);
1249 PP.DumpToken(Tok, true);
1250 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001251 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001252 ClearSourceMgr = true;
1253 break;
1254 }
1255 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1256 Token Tok;
1257 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001258 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001259 do {
1260 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001261 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001262 ClearSourceMgr = true;
1263 break;
1264 }
1265
1266 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001267 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001268 ClearSourceMgr = true;
1269 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001270
Chris Lattner4b009652007-07-25 00:24:17 +00001271 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001272 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001273 ClearSourceMgr = true;
1274 break;
1275
1276 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001277 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001278 ClearSourceMgr = true;
1279 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001280
Ted Kremenek6856c632007-09-26 18:39:29 +00001281 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek6856c632007-09-26 18:39:29 +00001282 Consumer = new ASTConsumer();
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001283 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001284
1285 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001286 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001287 ClearSourceMgr = true;
1288 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001289 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001290
1291 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001292 if (VerifyDiagnostics)
Ted Kremenek17861c52007-12-19 22:51:13 +00001293 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001294
1295 // This deletes Consumer.
Ted Kremenek17861c52007-12-19 22:51:13 +00001296 ParseAST(PP, Consumer, Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001297 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001298
1299 // If running the code generator, finish up now.
1300 if (CodeGenModule) {
1301 std::ostream *Out;
1302 if (OutputFile == "-") {
1303 Out = llvm::cout.stream();
1304 } else if (!OutputFile.empty()) {
1305 Out = new std::ofstream(OutputFile.c_str(),
1306 std::ios_base::binary|std::ios_base::out);
1307 } else if (InFile == "-") {
1308 Out = llvm::cout.stream();
1309 } else {
1310 llvm::sys::Path Path(InFile);
1311 Path.eraseSuffix();
1312 if (ProgAction == EmitLLVM)
1313 Path.appendSuffix("ll");
1314 else if (ProgAction == EmitBC)
1315 Path.appendSuffix("bc");
1316 else
1317 assert(0 && "Unknown action");
1318 Out = new std::ofstream(Path.toString().c_str(),
1319 std::ios_base::binary|std::ios_base::out);
1320 }
1321
1322 if (ProgAction == EmitLLVM) {
1323 CodeGenModule->print(*Out);
1324 } else {
1325 assert(ProgAction == EmitBC);
1326 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1327 }
1328
1329 if (Out != llvm::cout.stream())
1330 delete Out;
1331 delete CodeGenModule;
1332 }
Chris Lattner4b009652007-07-25 00:24:17 +00001333
1334 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001335 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001336 PP.PrintStats();
1337 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001338 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001339 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001340 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001341 fprintf(stderr, "\n");
1342 }
1343
1344 // For a multi-file compilation, some things are ok with nuking the source
1345 // manager tables, other require stable fileid/macroid's across multiple
1346 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001347 if (ClearSourceMgr)
1348 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001349}
1350
Ted Kremenek80d53372007-12-12 23:41:08 +00001351static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1352 FileManager& FileMgr) {
1353
1354 if (VerifyDiagnostics) {
1355 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1356 exit (1);
1357 }
1358
1359 llvm::sys::Path Filename(InFile);
1360
1361 if (!Filename.isValid()) {
1362 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1363 exit (1);
1364 }
1365
Ted Kremenek863b01f2008-04-23 16:25:39 +00001366 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001367
1368 if (!TU) {
1369 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1370 InFile.c_str());
1371 exit (1);
1372 }
1373
Ted Kremenekab749372007-12-19 19:27:38 +00001374 // Observe that we use the source file name stored in the deserialized
1375 // translation unit, rather than InFile.
Chris Lattner8d72ee02008-02-06 01:42:25 +00001376 llvm::Module *DestModule;
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001377 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001378 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
1379 0, 0, DestModule));
Ted Kremenek80d53372007-12-12 23:41:08 +00001380
1381 if (!Consumer) {
1382 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1383 exit (1);
1384 }
1385
Ted Kremenek863b01f2008-04-23 16:25:39 +00001386 Consumer->Initialize(TU->getContext());
Ted Kremenek80d53372007-12-12 23:41:08 +00001387
Chris Lattner8d72ee02008-02-06 01:42:25 +00001388 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001389 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1390 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001391}
1392
1393
Chris Lattner4b009652007-07-25 00:24:17 +00001394static llvm::cl::list<std::string>
1395InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1396
Ted Kremenek80d53372007-12-12 23:41:08 +00001397static bool isSerializedFile(const std::string& InFile) {
1398 if (InFile.size() < 4)
1399 return false;
1400
1401 const char* s = InFile.c_str()+InFile.size()-4;
1402
1403 return s[0] == '.' &&
1404 s[1] == 'a' &&
1405 s[2] == 's' &&
1406 s[3] == 't';
1407}
1408
Chris Lattner4b009652007-07-25 00:24:17 +00001409
1410int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001411 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001412 llvm::sys::PrintStackTraceOnErrorSignal();
1413
1414 // If no input was specified, read from stdin.
1415 if (InputFilenames.empty())
1416 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001417
Chris Lattner4b009652007-07-25 00:24:17 +00001418 // Create a file manager object to provide access to and cache the filesystem.
1419 FileManager FileMgr;
1420
Ted Kremenekb240e822007-12-11 23:28:38 +00001421 // Create the diagnostic client for reporting errors or for
1422 // implementing -verify.
Ted Kremenekfd75e312008-03-27 06:17:42 +00001423 std::auto_ptr<DiagnosticClient> DiagClient;
1424 TextDiagnostics* TextDiagClient = NULL;
1425
1426 if (!HTMLDiag.empty()) {
Ted Kremenek675ac6f2008-04-16 16:53:18 +00001427
1428 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1429 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1430 // Fix this dependency later.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001431 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenekfd75e312008-03-27 06:17:42 +00001432 }
1433 else { // Use Text diagnostics.
1434 if (!VerifyDiagnostics) {
1435 // Print diagnostics to stderr by default.
1436 TextDiagClient = new TextDiagnosticPrinter();
1437 } else {
1438 // When checking diagnostics, just buffer them up.
1439 TextDiagClient = new TextDiagnosticBuffer();
1440
1441 if (InputFilenames.size() != 1) {
1442 fprintf(stderr,
1443 "-verify only works on single input files for now.\n");
1444 return 1;
1445 }
Chris Lattner4b009652007-07-25 00:24:17 +00001446 }
Ted Kremenekfd75e312008-03-27 06:17:42 +00001447
1448 assert (TextDiagClient);
1449 DiagClient.reset(TextDiagClient);
Chris Lattner4b009652007-07-25 00:24:17 +00001450 }
1451
1452 // Configure our handling of diagnostics.
1453 Diagnostic Diags(*DiagClient);
Ted Kremenekb240e822007-12-11 23:28:38 +00001454 InitializeDiagnostics(Diags);
1455
Chris Lattner45a56e02007-12-05 23:24:17 +00001456 // -I- is a deprecated GCC feature, scan for it and reject it.
1457 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1458 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001459 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001460 I_dirs.erase(I_dirs.begin()+i);
1461 --i;
1462 }
1463 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001464
1465 // Get information about the target being compiled for.
1466 std::string Triple = CreateTargetTriple();
1467 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1468 if (Target == 0) {
1469 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1470 Triple.c_str());
1471 fprintf(stderr, "Please use -triple or -arch.\n");
1472 exit(1);
1473 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001474
Ted Kremenek81ea7992008-07-02 00:03:09 +00001475 // Are we invoking one or more source analyses?
1476 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1477 ProgAction = RunAnalysis;
1478
1479
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001480 llvm::OwningPtr<SourceManager> SourceMgr;
1481
Chris Lattner4b009652007-07-25 00:24:17 +00001482 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001483 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001484
Ted Kremenek80d53372007-12-12 23:41:08 +00001485 if (isSerializedFile(InFile))
1486 ProcessSerializedFile(InFile,Diags,FileMgr);
1487 else {
1488 /// Create a SourceManager object. This tracks and owns all the file
1489 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001490 if (!SourceMgr)
1491 SourceMgr.reset(new SourceManager());
1492 else
1493 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001494
Ted Kremenek80d53372007-12-12 23:41:08 +00001495 // Initialize language options, inferring file types from input filenames.
1496 LangOptions LangInfo;
1497 InitializeBaseLanguage();
1498 LangKind LK = GetLanguage(InFile);
1499 InitializeLangOptions(LangInfo, LK);
1500 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001501 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001502
1503 // Process the -I options and set them in the HeaderInfo.
1504 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekfd75e312008-03-27 06:17:42 +00001505 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Ted Kremenek649465c2008-06-06 01:47:30 +00001506
1507 // FIXME: Sink IncludeGroup into this loop.
1508 IncludeGroup[0].clear();
1509 IncludeGroup[1].clear();
1510 IncludeGroup[2].clear();
1511 IncludeGroup[3].clear();
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001512 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001513
Ted Kremenek80d53372007-12-12 23:41:08 +00001514 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001515 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001516 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001517
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001518 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1519
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001520 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001521 continue;
1522
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001523 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001524 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001525
1526 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001527 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001528 }
Chris Lattner4b009652007-07-25 00:24:17 +00001529 }
1530
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001531
Chris Lattner2c77d852008-03-14 06:12:05 +00001532 delete Target;
1533
Chris Lattner4b009652007-07-25 00:24:17 +00001534 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1535
1536 if (NumDiagnostics)
1537 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1538 (NumDiagnostics == 1 ? "" : "s"));
1539
1540 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001541 FileMgr.PrintStats();
1542 fprintf(stderr, "\n");
1543 }
1544
1545 return Diags.getNumErrors() != 0;
1546}