blob: c6ace84ea19be347c5a6de4c738e73d7660a80b9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Parse/Parser.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Basic/FileManager.h"
38#include "clang/Basic/SourceManager.h"
39#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000050#include <fstream>
Ted Kremenek339b9c22008-04-17 22:31:54 +000051#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +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 Begemanaabbb122007-12-30 01:38:50 +000061Stats("print-stats",
62 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000063
64enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000065 RewriteObjC, // ObjC->C Rewriter.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000066 RewriteMacros, // Expand macros but not #includes.
Ted Kremenek13e479b2008-03-19 07:53:42 +000067 HTMLTest, // HTML displayer testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000068 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000069 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000070 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000071 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-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 Kremenekfddd5182007-08-21 21:42:03 +000075 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000076 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000077 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000078 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
79 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek2fff37e2008-03-06 00:08:09 +000080 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremenek055c2752007-09-06 23:00:42 +000081 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000082 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000083 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000084 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek6a340832008-03-18 21:19:49 +0000109 clEnumValN(EmitHTML, "emit-html",
110 "Output input source as HTML"),
Chris Lattner3b427b32007-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 Lattnerea254db2007-10-11 00:37:43 +0000115 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000116 "Build ASTs and view them with GraphViz"),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000117 clEnumValN(ParseCFGDump, "dump-cfg",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000118 "Run parser, then build and print CFGs"),
Ted Kremenek7dba8602007-08-29 21:56:09 +0000119 clEnumValN(ParseCFGView, "view-cfg",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000120 "Run parser, then build and view CFGs with Graphviz"),
Ted Kremeneke4e63342007-09-06 00:17:54 +0000121 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000122 "Print results of live variable analysis"),
Ted Kremenek786d3372007-09-25 18:05:45 +0000123 clEnumValN(WarnDeadStores, "warn-dead-stores",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000124 "Flag warnings of stores to dead variables"),
Ted Kremenek786d3372007-09-25 18:05:45 +0000125 clEnumValN(WarnUninitVals, "warn-uninit-values",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000126 "Flag warnings of uses of unitialized variables"),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000127 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000128 "Perform path-sensitive constant propagation"),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000129 clEnumValN(CheckerCFRef, "checker-cfref",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000130 "Run the Core Foundation reference count checker"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000131 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000132 "Run prototype serialization code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000134 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000135 clEnumValN(EmitBC, "emit-llvm-bc",
136 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000137 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000138 "Build ASTs and emit .ast file"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000139 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000140 "Rewrite ObjC into C (code rewriter example)"),
141 clEnumValN(RewriteMacros, "rewrite-macros",
142 "Expand macros without full preprocessing"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 clEnumValEnd));
144
Ted Kremenekccc76472007-12-19 19:47:59 +0000145
146static llvm::cl::opt<std::string>
147OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000148 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000149 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000150
151//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000152// Code Generator Options
153//===----------------------------------------------------------------------===//
154static llvm::cl::opt<bool>
155GenerateDebugInfo("g",
156 llvm::cl::desc("Generate source level debug information"));
157
158//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000159// Diagnostic Options
160//===----------------------------------------------------------------------===//
161
Ted Kremenek41193e42007-09-26 19:42:19 +0000162static llvm::cl::opt<bool>
163VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000164 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000165
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000166static llvm::cl::opt<std::string>
167HTMLDiag("html-diags",
168 llvm::cl::desc("Generate HTML to report diagnostics"),
169 llvm::cl::value_desc("HTML directory"));
170
Reid Spencer5f016e22007-07-11 17:01:13 +0000171//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000172// Analyzer Options
173//===----------------------------------------------------------------------===//
174
175static llvm::cl::opt<bool>
176VisualizeEG("visualize-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000177 llvm::cl::desc("Display static analysis Exploded Graph"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000178
179static llvm::cl::opt<bool>
180AnalyzeAll("checker-opt-analyze-headers",
181 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000182 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000183
184//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000185// Language Options
186//===----------------------------------------------------------------------===//
187
188enum LangKind {
189 langkind_unspecified,
190 langkind_c,
191 langkind_c_cpp,
192 langkind_cxx,
193 langkind_cxx_cpp,
194 langkind_objc,
195 langkind_objc_cpp,
196 langkind_objcxx,
197 langkind_objcxx_cpp
198};
199
200/* TODO: GCC also accepts:
201 c-header c++-header objective-c-header objective-c++-header
202 assembler assembler-with-cpp
203 ada, f77*, ratfor (!), f95, java, treelang
204 */
205static llvm::cl::opt<LangKind>
206BaseLang("x", llvm::cl::desc("Base language to compile"),
207 llvm::cl::init(langkind_unspecified),
208 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
209 clEnumValN(langkind_cxx, "c++", "C++"),
210 clEnumValN(langkind_objc, "objective-c", "Objective C"),
211 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
212 clEnumValN(langkind_c_cpp, "c-cpp-output",
213 "Preprocessed C"),
214 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
215 "Preprocessed C++"),
216 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
217 "Preprocessed Objective C"),
218 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
219 "Preprocessed Objective C++"),
220 clEnumValEnd));
221
222static llvm::cl::opt<bool>
223LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
224 llvm::cl::Hidden);
225static llvm::cl::opt<bool>
226LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
227 llvm::cl::Hidden);
228
Ted Kremenek8904f152007-12-05 23:49:08 +0000229/// InitializeBaseLanguage - Handle the -x foo options.
230static void InitializeBaseLanguage() {
231 if (LangObjC)
232 BaseLang = langkind_objc;
233 else if (LangObjCXX)
234 BaseLang = langkind_objcxx;
235}
236
237static LangKind GetLanguage(const std::string &Filename) {
238 if (BaseLang != langkind_unspecified)
239 return BaseLang;
240
241 std::string::size_type DotPos = Filename.rfind('.');
242
243 if (DotPos == std::string::npos) {
244 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000245 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 }
247
Ted Kremenek8904f152007-12-05 23:49:08 +0000248 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
249 // C header: .h
250 // C++ header: .hh or .H;
251 // assembler no preprocessing: .s
252 // assembler: .S
253 if (Ext == "c")
254 return langkind_c;
255 else if (Ext == "i")
256 return langkind_c_cpp;
257 else if (Ext == "ii")
258 return langkind_cxx_cpp;
259 else if (Ext == "m")
260 return langkind_objc;
261 else if (Ext == "mi")
262 return langkind_objc_cpp;
263 else if (Ext == "mm" || Ext == "M")
264 return langkind_objcxx;
265 else if (Ext == "mii")
266 return langkind_objcxx_cpp;
267 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
268 Ext == "c++" || Ext == "cp" || Ext == "cxx")
269 return langkind_cxx;
270 else
271 return langkind_c;
272}
273
274
275static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 // FIXME: implement -fpreprocessed mode.
277 bool NoPreprocess = false;
278
Ted Kremenek8904f152007-12-05 23:49:08 +0000279 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 default: assert(0 && "Unknown language kind!");
281 case langkind_c_cpp:
282 NoPreprocess = true;
283 // FALLTHROUGH
284 case langkind_c:
285 break;
286 case langkind_cxx_cpp:
287 NoPreprocess = true;
288 // FALLTHROUGH
289 case langkind_cxx:
290 Options.CPlusPlus = 1;
291 break;
292 case langkind_objc_cpp:
293 NoPreprocess = true;
294 // FALLTHROUGH
295 case langkind_objc:
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000296 Options.ObjC1 = Options.ObjC2 = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 break;
298 case langkind_objcxx_cpp:
299 NoPreprocess = true;
300 // FALLTHROUGH
301 case langkind_objcxx:
302 Options.ObjC1 = Options.ObjC2 = 1;
303 Options.CPlusPlus = 1;
304 break;
305 }
306}
307
308/// LangStds - Language standards we support.
309enum LangStds {
310 lang_unspecified,
311 lang_c89, lang_c94, lang_c99,
312 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000313 lang_cxx98, lang_gnucxx98,
314 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000315};
316
317static llvm::cl::opt<LangStds>
318LangStd("std", llvm::cl::desc("Language standard to compile for"),
319 llvm::cl::init(lang_unspecified),
320 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
321 clEnumValN(lang_c89, "c90", "ISO C 1990"),
322 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
323 clEnumValN(lang_c94, "iso9899:199409",
324 "ISO C 1990 with amendment 1"),
325 clEnumValN(lang_c99, "c99", "ISO C 1999"),
326// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
327 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
328// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
329 clEnumValN(lang_gnu89, "gnu89",
330 "ISO C 1990 with GNU extensions (default for C)"),
331 clEnumValN(lang_gnu99, "gnu99",
332 "ISO C 1999 with GNU extensions"),
333 clEnumValN(lang_gnu99, "gnu9x",
334 "ISO C 1999 with GNU extensions"),
335 clEnumValN(lang_cxx98, "c++98",
336 "ISO C++ 1998 with amendments"),
337 clEnumValN(lang_gnucxx98, "gnu++98",
338 "ISO C++ 1998 with amendments and GNU "
339 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000340 clEnumValN(lang_cxx0x, "c++0x",
341 "Upcoming ISO C++ 200x with amendments"),
342 clEnumValN(lang_gnucxx0x, "gnu++0x",
343 "Upcoming ISO C++ 200x with amendments and GNU "
344 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 clEnumValEnd));
346
347static llvm::cl::opt<bool>
348NoOperatorNames("fno-operator-names",
349 llvm::cl::desc("Do not treat C++ operator name keywords as "
350 "synonyms for operators"));
351
Anders Carlssonee98ac52007-10-15 02:50:23 +0000352static llvm::cl::opt<bool>
353PascalStrings("fpascal-strings",
354 llvm::cl::desc("Recognize and construct Pascal-style "
355 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000356
357static llvm::cl::opt<bool>
358MSExtensions("fms-extensions",
359 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000360 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000361
362static llvm::cl::opt<bool>
363WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000364 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000365
366static llvm::cl::opt<bool>
367LaxVectorConversions("flax-vector-conversions",
368 llvm::cl::desc("Allow implicit conversions between vectors"
369 " with a different number of elements or "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000370 "different element types"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000371
Reid Spencer5f016e22007-07-11 17:01:13 +0000372// FIXME: add:
373// -ansi
374// -trigraphs
375// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000376// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000377static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 if (LangStd == lang_unspecified) {
379 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000380 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 default: assert(0 && "Unknown base language");
382 case langkind_c:
383 case langkind_c_cpp:
384 case langkind_objc:
385 case langkind_objc_cpp:
386 LangStd = lang_gnu99;
387 break;
388 case langkind_cxx:
389 case langkind_cxx_cpp:
390 case langkind_objcxx:
391 case langkind_objcxx_cpp:
392 LangStd = lang_gnucxx98;
393 break;
394 }
395 }
396
397 switch (LangStd) {
398 default: assert(0 && "Unknown language standard!");
399
400 // Fall through from newer standards to older ones. This isn't really right.
401 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000402 case lang_gnucxx0x:
403 case lang_cxx0x:
404 Options.CPlusPlus0x = 1;
405 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 case lang_gnucxx98:
407 case lang_cxx98:
408 Options.CPlusPlus = 1;
409 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000410 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 // FALL THROUGH.
412 case lang_gnu99:
413 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 Options.C99 = 1;
415 Options.HexFloats = 1;
416 // FALL THROUGH.
417 case lang_gnu89:
418 Options.BCPLComment = 1; // Only for C99/C++.
419 // FALL THROUGH.
420 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000421 Options.Digraphs = 1; // C94, C99, C++.
422 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 case lang_c89:
424 break;
425 }
426
Chris Lattnerd658b562008-04-05 06:32:51 +0000427 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
428 Options.ImplicitInt = 1;
429 else
430 Options.ImplicitInt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 Options.Trigraphs = 1; // -trigraphs or -ansi
432 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000433 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000434 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000435 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000436 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000437}
438
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000439static llvm::cl::opt<bool>
440ObjCExclusiveGC("fobjc-gc-only",
441 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000442 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000443
444static llvm::cl::opt<bool>
445ObjCEnableGC("fobjc-gc",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000446 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000447
448void InitializeGCMode(LangOptions &Options) {
449 if (ObjCExclusiveGC)
450 Options.setGCMode(LangOptions::GCOnly);
451 else if (ObjCEnableGC)
452 Options.setGCMode(LangOptions::HybridGC);
453}
454
455
Reid Spencer5f016e22007-07-11 17:01:13 +0000456//===----------------------------------------------------------------------===//
457// Our DiagnosticClient implementation
458//===----------------------------------------------------------------------===//
459
460// FIXME: Werror should take a list of things, -Werror=foo,bar
461static llvm::cl::opt<bool>
462WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
463
464static llvm::cl::opt<bool>
465WarnOnExtensions("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 Kremenekdb87bca2007-11-13 18:37:02 +0000476static llvm::cl::opt<bool>
477WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000478 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000479
Ted Kremenek73da5902007-12-17 17:50:07 +0000480static llvm::cl::opt<bool>
481WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000482 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000483
Chris Lattner116a4b12008-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 Lattner37d10842008-05-05 21:18:06 +0000488static llvm::cl::opt<bool>
489WarnImplicitFunctionDeclaration("Wimplicit-function-declaration"
490 "Warn about use of implicitly defined functions");
Chris Lattner116a4b12008-01-23 17:19:46 +0000491
Reid Spencer5f016e22007-07-11 17:01:13 +0000492/// InitializeDiagnostics - Initialize the diagnostic object, based on the
493/// current command line option settings.
494static void InitializeDiagnostics(Diagnostic &Diags) {
495 Diags.setWarningsAsErrors(WarningsAsErrors);
496 Diags.setWarnOnExtensions(WarnOnExtensions);
497 Diags.setErrorOnExtensions(ErrorOnExtensions);
498
499 // Silence the "macro is not used" warning unless requested.
500 if (!WarnUnusedMacros)
501 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000502
503 // Silence "floating point comparison" warnings unless requested.
504 if (!WarnFloatEqual)
505 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000506
507 // Silence "format string is not a string literal" warnings if requested
508 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000509 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
510 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000511 if (!WarnUndefMacros)
512 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000513
Chris Lattner37d10842008-05-05 21:18:06 +0000514 if (!WarnImplicitFunctionDeclaration)
515 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
516 diag::MAP_IGNORE);
517
Steve Naroffe7a37302008-02-11 22:40:08 +0000518 if (MSExtensions) // MS allows unnamed struct/union fields.
519 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner8aedf192008-05-04 23:52:02 +0000520
521 // If -pedantic-errors is set, turn extensions that warn by default into
522 // errors.
523 if (ErrorOnExtensions) {
524 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
525 diag::MAP_ERROR);
526 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
527 diag::MAP_ERROR);
528 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000529}
530
531//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000532// Analysis-specific options.
533//===----------------------------------------------------------------------===//
534
535static llvm::cl::opt<std::string>
536AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000537 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000538
Ted Kremenekffe0f432008-03-07 22:58:01 +0000539static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000540TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000541 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000542
Ted Kremenekcb330932008-02-18 21:21:23 +0000543//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000544// Target Triple Processing.
545//===----------------------------------------------------------------------===//
546
547static llvm::cl::opt<std::string>
548TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000549 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000550
Chris Lattner42e67372008-03-05 01:18:20 +0000551static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000552Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000553
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000554static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000555 // Initialize base triple. If a -triple option has been specified, use
556 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000557 std::string Triple = TargetTriple;
558 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000559
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000560 // If -arch foo was specified, remove the architecture from the triple we have
561 // so far and replace it with the specified one.
562 if (Arch.empty())
563 return Triple;
564
Ted Kremenekae360762007-12-03 22:06:55 +0000565 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000566 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000567
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000568 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000569 fprintf(stderr,
570 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000571 Triple.c_str());
572 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000573 }
Ted Kremenekae360762007-12-03 22:06:55 +0000574
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000575 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000576}
577
578//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000579// Preprocessor Initialization
580//===----------------------------------------------------------------------===//
581
582// FIXME: Preprocessor builtins to support.
583// -A... - Play with #assertions
584// -undef - Undefine all predefined macros
585
586static llvm::cl::list<std::string>
587D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
588 llvm::cl::desc("Predefine the specified macro"));
589static llvm::cl::list<std::string>
590U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
591 llvm::cl::desc("Undefine the specified macro"));
592
Chris Lattner64299f82008-01-10 01:53:41 +0000593static llvm::cl::list<std::string>
594ImplicitIncludes("include", llvm::cl::value_desc("file"),
595 llvm::cl::desc("Include file before parsing"));
596
597
Reid Spencer5f016e22007-07-11 17:01:13 +0000598// Append a #define line to Buf for Macro. Macro should be of the form XXX,
599// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
600// "#define XXX Y z W". To get a #define with no value, use "XXX=".
601static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
602 const char *Command = "#define ") {
603 Buf.insert(Buf.end(), Command, Command+strlen(Command));
604 if (const char *Equal = strchr(Macro, '=')) {
605 // Turn the = into ' '.
606 Buf.insert(Buf.end(), Macro, Equal);
607 Buf.push_back(' ');
608 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
609 } else {
610 // Push "macroname 1".
611 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
612 Buf.push_back(' ');
613 Buf.push_back('1');
614 }
615 Buf.push_back('\n');
616}
617
Chris Lattner64299f82008-01-10 01:53:41 +0000618/// AddImplicitInclude - Add an implicit #include of the specified file to the
619/// predefines buffer.
620static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
621 const char *Inc = "#include \"";
622 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
623 Buf.insert(Buf.end(), File.begin(), File.end());
624 Buf.push_back('"');
625 Buf.push_back('\n');
626}
627
Reid Spencer5f016e22007-07-11 17:01:13 +0000628
Chris Lattner53b0dab2007-10-09 22:10:18 +0000629/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000630/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000631///
Chris Lattner51574ea2008-04-19 23:25:44 +0000632static bool InitializePreprocessor(Preprocessor &PP,
633 bool InitializeSourceMgr,
634 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000635 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000636
Chris Lattner53b0dab2007-10-09 22:10:18 +0000637 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000638 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000639
640 if (InitializeSourceMgr) {
641 if (InFile != "-") {
642 const FileEntry *File = FileMgr.getFile(InFile);
643 if (File) SourceMgr.createMainFileID(File, SourceLocation());
644 if (SourceMgr.getMainFileID() == 0) {
645 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000646 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000647 }
648 } else {
649 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
650 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
651 if (SourceMgr.getMainFileID() == 0) {
652 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000653 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000654 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000655 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000657
Chris Lattneraa391972008-04-19 23:09:31 +0000658 std::vector<char> PredefineBuffer;
659
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000661 unsigned d = 0, D = D_macros.size();
662 unsigned u = 0, U = U_macros.size();
663 while (d < D || u < U) {
664 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
665 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
666 else
667 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
668 }
669
Chris Lattner64299f82008-01-10 01:53:41 +0000670 // FIXME: Read any files specified by -imacros.
671
672 // Add implicit #includes from -include.
673 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
674 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000675
Chris Lattneraa391972008-04-19 23:09:31 +0000676 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000677 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000678 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000679
680 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000681 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000682}
683
684//===----------------------------------------------------------------------===//
685// Preprocessor include path information.
686//===----------------------------------------------------------------------===//
687
688// This tool exports a large number of command line options to control how the
689// preprocessor searches for header files. At root, however, the Preprocessor
690// object takes a very simple interface: a list of directories to search for
691//
692// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000693// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000694//
Chris Lattner64299f82008-01-10 01:53:41 +0000695// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000696
697static llvm::cl::opt<bool>
698nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
699
700// Various command line options. These four add directories to each chain.
701static llvm::cl::list<std::string>
702F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
703 llvm::cl::desc("Add directory to framework include search path"));
704static llvm::cl::list<std::string>
705I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
706 llvm::cl::desc("Add directory to include search path"));
707static llvm::cl::list<std::string>
708idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
709 llvm::cl::desc("Add directory to AFTER include search path"));
710static llvm::cl::list<std::string>
711iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
712 llvm::cl::desc("Add directory to QUOTE include search path"));
713static llvm::cl::list<std::string>
714isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
715 llvm::cl::desc("Add directory to SYSTEM include search path"));
716
717// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
718static llvm::cl::list<std::string>
719iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
720 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
721static llvm::cl::list<std::string>
722iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
723 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
724static llvm::cl::list<std::string>
725iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
726 llvm::cl::Prefix,
727 llvm::cl::desc("Set directory to include search path with prefix"));
728
Chris Lattner0c946412007-08-26 17:47:35 +0000729static llvm::cl::opt<std::string>
730isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
731 llvm::cl::desc("Set the system root directory (usually /)"));
732
Reid Spencer5f016e22007-07-11 17:01:13 +0000733// Finally, implement the code that groks the options above.
734enum IncludeDirGroup {
735 Quoted = 0,
736 Angled,
737 System,
738 After
739};
740
741static std::vector<DirectoryLookup> IncludeGroup[4];
742
743/// AddPath - Add the specified path to the specified group list.
744///
745static void AddPath(const std::string &Path, IncludeDirGroup Group,
746 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000747 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000748 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000749 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000750
Chris Lattnerd6655272007-12-17 05:59:27 +0000751 // Compute the actual path, taking into consideration -isysroot.
752 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000753
Chris Lattnerd6655272007-12-17 05:59:27 +0000754 // Handle isysroot.
755 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000756 // FIXME: Portability. This should be a sys::Path interface, this doesn't
757 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000758 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
759 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 }
761
Chris Lattnerd6655272007-12-17 05:59:27 +0000762 MappedPath.append(Path.begin(), Path.end());
763
764 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 DirectoryLookup::DirType Type;
766 if (Group == Quoted || Group == Angled)
767 Type = DirectoryLookup::NormalHeaderDir;
768 else if (isCXXAware)
769 Type = DirectoryLookup::SystemHeaderDir;
770 else
771 Type = DirectoryLookup::ExternCSystemHeaderDir;
772
Chris Lattnerd6655272007-12-17 05:59:27 +0000773
774 // If the directory exists, add it.
775 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
776 &MappedPath[0]+
777 MappedPath.size())) {
778 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
779 isFramework));
780 return;
781 }
782
Chris Lattnerdf772332007-12-17 07:52:39 +0000783 // Check to see if this is an apple-style headermap (which are not allowed to
784 // be frameworks).
785 if (!isFramework) {
786 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
787 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000788 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
789 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000790 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
791 return;
792 }
Chris Lattner822da612007-12-17 06:36:45 +0000793 }
794 }
795
Chris Lattnerd6655272007-12-17 05:59:27 +0000796 if (Verbose)
797 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000798}
799
800/// RemoveDuplicates - If there are duplicate directory entries in the specified
801/// search list, remove the later (dead) ones.
802static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000803 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000804 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000805 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000807 if (SearchList[i].isNormalDir()) {
808 // If this isn't the first time we've seen this dir, remove it.
809 if (SeenDirs.insert(SearchList[i].getDir()))
810 continue;
811
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 if (Verbose)
813 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
814 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000815 } else if (SearchList[i].isFramework()) {
816 // If this isn't the first time we've seen this framework dir, remove it.
817 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
818 continue;
819
820 if (Verbose)
821 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
822 SearchList[i].getFrameworkDir()->getName());
823
Chris Lattnerb94c7072007-12-17 06:44:29 +0000824 } else {
825 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
826 // If this isn't the first time we've seen this headermap, remove it.
827 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
828 continue;
829
830 if (Verbose)
831 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
832 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000834
835 // This is reached if the current entry is a duplicate.
836 SearchList.erase(SearchList.begin()+i);
837 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 }
839}
840
Chris Lattner5f9eae52008-03-01 08:07:28 +0000841// AddEnvVarPaths - Add a list of paths from an environment variable to a
842// header search list.
843//
844static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
845 const char* at = getenv(Name);
846 if (!at)
847 return;
848
849 const char* delim = strchr(at, llvm::sys::PathSeparator);
850 while (delim != 0) {
851 if (delim-at == 0)
852 AddPath(".", Angled, false, true, false, Headers);
853 else
854 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
855 true, false, Headers);
856 at = delim + 1;
857 delim = strchr(at, llvm::sys::PathSeparator);
858 }
859 if (*at == 0)
860 AddPath(".", Angled, false, true, false, Headers);
861 else
862 AddPath(at, Angled, false, true, false, Headers);
863}
864
Reid Spencer5f016e22007-07-11 17:01:13 +0000865/// InitializeIncludePaths - Process the -I options and set them in the
866/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000867static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
868 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000869 // Handle -F... options.
870 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000871 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000872
873 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000874 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000875 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876
877 // Handle -idirafter... options.
878 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000879 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000880
881 // Handle -iquote... options.
882 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000883 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000884
885 // Handle -isystem... options.
886 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000887 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000888
889 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
890 // parallel, processing the values in order of occurance to get the right
891 // prefixes.
892 {
893 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
894 unsigned iprefix_idx = 0;
895 unsigned iwithprefix_idx = 0;
896 unsigned iwithprefixbefore_idx = 0;
897 bool iprefix_done = iprefix_vals.empty();
898 bool iwithprefix_done = iwithprefix_vals.empty();
899 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
900 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
901 if (!iprefix_done &&
902 (iwithprefix_done ||
903 iprefix_vals.getPosition(iprefix_idx) <
904 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
905 (iwithprefixbefore_done ||
906 iprefix_vals.getPosition(iprefix_idx) <
907 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
908 Prefix = iprefix_vals[iprefix_idx];
909 ++iprefix_idx;
910 iprefix_done = iprefix_idx == iprefix_vals.size();
911 } else if (!iwithprefix_done &&
912 (iwithprefixbefore_done ||
913 iwithprefix_vals.getPosition(iwithprefix_idx) <
914 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
915 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000916 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 ++iwithprefix_idx;
918 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
919 } else {
920 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000921 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 ++iwithprefixbefore_idx;
923 iwithprefixbefore_done =
924 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
925 }
926 }
927 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000928
929 AddEnvVarPaths("CPATH", Headers);
930 if (Lang.CPlusPlus && Lang.ObjC1)
931 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
932 else if (Lang.CPlusPlus)
933 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
934 else if (Lang.ObjC1)
935 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
936 else
937 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
938
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000939 // Add the clang headers, which are relative to the clang driver.
940 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000941 llvm::sys::Path::GetMainExecutable(Argv0,
942 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000943 if (!MainExecutablePath.isEmpty()) {
944 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
945 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
946 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
947 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
948 }
949
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 // FIXME: temporary hack: hard-coded paths.
951 // FIXME: get these from the target?
952 if (!nostdinc) {
953 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000954 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000956 false, Headers);
957 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
958 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000959
960 // Ubuntu 7.10 - Gutsy Gibbon
961 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
962 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
963 false, Headers);
964 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
965 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000966
967 // Fedora 8
968 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner8ac661c2008-04-16 05:21:09 +0000969 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
970 false, Headers);
971 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
972 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 }
974
Chris Lattner822da612007-12-17 06:36:45 +0000975 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 // leopard
977 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000978 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000980 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
982 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000983 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000984
985 // tiger
986 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000987 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000989 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
991 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000992 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000993
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000994 // Ubuntu 7.10 - Gutsy Gibbon
995 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000996 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000997
Chris Lattner04421082008-04-08 04:40:51 +0000998 // Fedora 8
999 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
1000 false, false, false, Headers);
1001
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001002 //Debian testing/lenny x86
1003 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
1004 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +00001005
1006 //Debian testing/lenny amd64
1007 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1008 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001009
Chris Lattner822da612007-12-17 06:36:45 +00001010 AddPath("/usr/include", System, false, false, false, Headers);
1011 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1012 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 }
1014
1015 // Now that we have collected all of the include paths, merge them all
1016 // together and tell the preprocessor about them.
1017
1018 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1019 std::vector<DirectoryLookup> SearchList;
1020 SearchList = IncludeGroup[Angled];
1021 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1022 IncludeGroup[System].end());
1023 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1024 IncludeGroup[After].end());
1025 RemoveDuplicates(SearchList);
1026 RemoveDuplicates(IncludeGroup[Quoted]);
1027
1028 // Prepend QUOTED list on the search list.
1029 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1030 IncludeGroup[Quoted].end());
1031
1032
1033 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1034 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1035 DontSearchCurDir);
1036
1037 // If verbose, print the list of directories that will be searched.
1038 if (Verbose) {
1039 fprintf(stderr, "#include \"...\" search starts here:\n");
1040 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1041 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1042 if (i == QuotedIdx)
1043 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +00001044 const char *Name = SearchList[i].getName();
1045 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +00001046 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +00001047 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +00001048 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +00001049 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +00001050 else {
1051 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +00001052 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +00001053 }
Chris Lattner3af66a92007-12-17 17:57:27 +00001054 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 }
Chris Lattner80e17152007-12-15 23:11:06 +00001056 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 }
1058}
1059
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001060//===----------------------------------------------------------------------===//
1061// Driver PreprocessorFactory - For lazily generating preprocessors ...
1062//===----------------------------------------------------------------------===//
1063
1064namespace {
1065class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001066 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001067 Diagnostic &Diags;
1068 const LangOptions &LangInfo;
1069 TargetInfo &Target;
1070 SourceManager &SourceMgr;
1071 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001072 bool InitializeSourceMgr;
1073
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001074public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001075 DriverPreprocessorFactory(const std::string &infile,
1076 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001077 TargetInfo &target, SourceManager &SM,
1078 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001079 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1080 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1081
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001082
1083 virtual ~DriverPreprocessorFactory() {}
1084
1085 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001086 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1087 SourceMgr, HeaderInfo);
1088
Chris Lattner51574ea2008-04-19 23:25:44 +00001089 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001090 delete PP;
1091 return NULL;
1092 }
1093
1094 InitializeSourceMgr = false;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001095 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001096 }
1097};
1098}
Reid Spencer5f016e22007-07-11 17:01:13 +00001099
Reid Spencer5f016e22007-07-11 17:01:13 +00001100//===----------------------------------------------------------------------===//
1101// Basic Parser driver
1102//===----------------------------------------------------------------------===//
1103
Chris Lattner51574ea2008-04-19 23:25:44 +00001104static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001106 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001107
1108 // Parsing the specified input file.
1109 P.ParseTranslationUnit();
1110 delete PA;
1111}
1112
1113//===----------------------------------------------------------------------===//
1114// Main driver
1115//===----------------------------------------------------------------------===//
1116
Ted Kremenekdb094a22007-12-05 18:27:04 +00001117/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1118/// action. These consumers can operate on both ASTs that are freshly
1119/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001120static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001121 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001122 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001123 Preprocessor *PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001124 PreprocessorFactory *PPF,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001125 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001126 switch (ProgAction) {
1127 default:
1128 return NULL;
1129
1130 case ASTPrint:
1131 return CreateASTPrinter();
1132
1133 case ASTDump:
1134 return CreateASTDumper();
1135
1136 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001137 return CreateASTViewer();
1138
1139 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001140 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001141
1142 case ParseCFGDump:
1143 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001144 return CreateCFGDumper(ProgAction == ParseCFGView,
1145 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001146
1147 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001148 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001149
1150 case WarnDeadStores:
1151 return CreateDeadStoreChecker(Diag);
1152
1153 case WarnUninitVals:
1154 return CreateUnitValsChecker(Diag);
1155
Ted Kremeneke01c9872008-02-14 22:36:46 +00001156 case AnalysisGRSimpleVals:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001157 return CreateGRSimpleVals(Diag, PP, PPF, AnalyzeSpecificFunction,
1158 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001159
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001160 case CheckerCFRef:
Ted Kremeneke5c30122008-04-29 05:13:59 +00001161 return CreateCFRefChecker(Diag, PP, PPF, LangOpts,
1162 AnalyzeSpecificFunction,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001163 OutputFile, VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001164
Ted Kremenekdb094a22007-12-05 18:27:04 +00001165 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001166 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001167
1168 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001169 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001170 DestModule = new llvm::Module(InFile);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +00001171 return CreateLLVMCodeGen(Diag, LangOpts, DestModule, GenerateDebugInfo);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001172
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001173 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001174 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001175 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001176
Steve Naroffb29b4272008-04-14 22:03:09 +00001177 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001178 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001179 }
1180}
1181
Reid Spencer5f016e22007-07-11 17:01:13 +00001182/// ProcessInputFile - Process a single input file with the specified state.
1183///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001184static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1185 const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001186
1187 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001188 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001189 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 switch (ProgAction) {
1192 default:
Chris Lattner3245a0a2008-04-16 06:11:58 +00001193 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1194 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001195 &PPF, CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001196
1197 if (!Consumer) {
1198 fprintf(stderr, "Unexpected program action!\n");
1199 return;
1200 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001201
Ted Kremenekdb094a22007-12-05 18:27:04 +00001202 break;
1203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001205 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001207 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 do {
1209 PP.Lex(Tok);
1210 PP.DumpToken(Tok, true);
1211 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001212 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001213 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 break;
1215 }
1216 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001217 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001219 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 do {
1221 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001222 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001223 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 break;
1225 }
1226
1227 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001228 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001229 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001231
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001233 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001234 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 break;
1236
1237 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001238 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001239 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001241
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001242 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001243 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001244 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001245
1246 case RewriteMacros:
1247 RewriteMacrosInInput(PP, OutputFile);
1248 ClearSourceMgr = true;
1249 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001250 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001251
1252 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001253 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001254 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001255
1256 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001257 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001259
1260 // If running the code generator, finish up now.
1261 if (CodeGenModule) {
1262 std::ostream *Out;
1263 if (OutputFile == "-") {
1264 Out = llvm::cout.stream();
1265 } else if (!OutputFile.empty()) {
1266 Out = new std::ofstream(OutputFile.c_str(),
1267 std::ios_base::binary|std::ios_base::out);
1268 } else if (InFile == "-") {
1269 Out = llvm::cout.stream();
1270 } else {
1271 llvm::sys::Path Path(InFile);
1272 Path.eraseSuffix();
1273 if (ProgAction == EmitLLVM)
1274 Path.appendSuffix("ll");
1275 else if (ProgAction == EmitBC)
1276 Path.appendSuffix("bc");
1277 else
1278 assert(0 && "Unknown action");
1279 Out = new std::ofstream(Path.toString().c_str(),
1280 std::ios_base::binary|std::ios_base::out);
1281 }
1282
1283 if (ProgAction == EmitLLVM) {
1284 CodeGenModule->print(*Out);
1285 } else {
1286 assert(ProgAction == EmitBC);
1287 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1288 }
1289
1290 if (Out != llvm::cout.stream())
1291 delete Out;
1292 delete CodeGenModule;
1293 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001294
1295 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001296 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 PP.PrintStats();
1298 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001299 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001300 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001301 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 fprintf(stderr, "\n");
1303 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001304
1305 // For a multi-file compilation, some things are ok with nuking the source
1306 // manager tables, other require stable fileid/macroid's across multiple
1307 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001308 if (ClearSourceMgr)
1309 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001310}
1311
Ted Kremenek20e97482007-12-12 23:41:08 +00001312static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1313 FileManager& FileMgr) {
1314
1315 if (VerifyDiagnostics) {
1316 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1317 exit (1);
1318 }
1319
1320 llvm::sys::Path Filename(InFile);
1321
1322 if (!Filename.isValid()) {
1323 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1324 exit (1);
1325 }
1326
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001327 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001328
1329 if (!TU) {
1330 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1331 InFile.c_str());
1332 exit (1);
1333 }
1334
Ted Kremenek63ea8632007-12-19 19:27:38 +00001335 // Observe that we use the source file name stored in the deserialized
1336 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001337 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001338 llvm::OwningPtr<ASTConsumer>
Ted Kremenek339b9c22008-04-17 22:31:54 +00001339 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(), 0, 0,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001340 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001341
1342 if (!Consumer) {
1343 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1344 exit (1);
1345 }
1346
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001347 Consumer->Initialize(TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001348
Chris Lattnere66b65c2008-02-06 01:42:25 +00001349 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001350 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1351 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001352}
1353
1354
Reid Spencer5f016e22007-07-11 17:01:13 +00001355static llvm::cl::list<std::string>
1356InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1357
Ted Kremenek20e97482007-12-12 23:41:08 +00001358static bool isSerializedFile(const std::string& InFile) {
1359 if (InFile.size() < 4)
1360 return false;
1361
1362 const char* s = InFile.c_str()+InFile.size()-4;
1363
1364 return s[0] == '.' &&
1365 s[1] == 'a' &&
1366 s[2] == 's' &&
1367 s[3] == 't';
1368}
1369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370
1371int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001372 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 llvm::sys::PrintStackTraceOnErrorSignal();
1374
1375 // If no input was specified, read from stdin.
1376 if (InputFilenames.empty())
1377 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001378
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 // Create a file manager object to provide access to and cache the filesystem.
1380 FileManager FileMgr;
1381
Ted Kremenek31e703b2007-12-11 23:28:38 +00001382 // Create the diagnostic client for reporting errors or for
1383 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001384 std::auto_ptr<DiagnosticClient> DiagClient;
1385 TextDiagnostics* TextDiagClient = NULL;
1386
1387 if (!HTMLDiag.empty()) {
Ted Kremeneka760f5f2008-04-16 16:53:18 +00001388
1389 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1390 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1391 // Fix this dependency later.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001392 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001393 }
1394 else { // Use Text diagnostics.
1395 if (!VerifyDiagnostics) {
1396 // Print diagnostics to stderr by default.
1397 TextDiagClient = new TextDiagnosticPrinter();
1398 } else {
1399 // When checking diagnostics, just buffer them up.
1400 TextDiagClient = new TextDiagnosticBuffer();
1401
1402 if (InputFilenames.size() != 1) {
1403 fprintf(stderr,
1404 "-verify only works on single input files for now.\n");
1405 return 1;
1406 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001408
1409 assert (TextDiagClient);
1410 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 }
1412
1413 // Configure our handling of diagnostics.
1414 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001415 InitializeDiagnostics(Diags);
1416
Chris Lattner4f037832007-12-05 23:24:17 +00001417 // -I- is a deprecated GCC feature, scan for it and reject it.
1418 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1419 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001420 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001421 I_dirs.erase(I_dirs.begin()+i);
1422 --i;
1423 }
1424 }
Chris Lattner11215192008-03-14 06:12:05 +00001425
1426 // Get information about the target being compiled for.
1427 std::string Triple = CreateTargetTriple();
1428 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1429 if (Target == 0) {
1430 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1431 Triple.c_str());
1432 fprintf(stderr, "Please use -triple or -arch.\n");
1433 exit(1);
1434 }
Chris Lattner4f037832007-12-05 23:24:17 +00001435
Reid Spencer5f016e22007-07-11 17:01:13 +00001436 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001437 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001438
Ted Kremenek20e97482007-12-12 23:41:08 +00001439 if (isSerializedFile(InFile))
1440 ProcessSerializedFile(InFile,Diags,FileMgr);
1441 else {
1442 /// Create a SourceManager object. This tracks and owns all the file
1443 /// buffers allocated to a translation unit.
1444 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001445
Ted Kremenek20e97482007-12-12 23:41:08 +00001446 // Initialize language options, inferring file types from input filenames.
1447 LangOptions LangInfo;
1448 InitializeBaseLanguage();
1449 LangKind LK = GetLanguage(InFile);
1450 InitializeLangOptions(LangInfo, LK);
1451 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001452 InitializeGCMode(LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001453
1454 // Process the -I options and set them in the HeaderInfo.
1455 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001456 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001457 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001458
Ted Kremenek20e97482007-12-12 23:41:08 +00001459 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001460 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001461 SourceMgr, HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001462
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001463 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1464
Ted Kremenek339b9c22008-04-17 22:31:54 +00001465 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001466 continue;
1467
Ted Kremenek339b9c22008-04-17 22:31:54 +00001468 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001469 HeaderInfo.ClearFileInfo();
1470
1471 if (Stats)
1472 SourceMgr.PrintStats();
1473 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 }
1475
Chris Lattner11215192008-03-14 06:12:05 +00001476 delete Target;
1477
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1479
1480 if (NumDiagnostics)
1481 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1482 (NumDiagnostics == 1 ? "" : "s"));
1483
1484 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 FileMgr.PrintStats();
1486 fprintf(stderr, "\n");
1487 }
1488
Chris Lattner96f1a642007-07-21 05:40:53 +00001489 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490}