blob: cbd27259d752f1d3a087bb898d212710b44043d0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Parse/Parser.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Basic/FileManager.h"
38#include "clang/Basic/SourceManager.h"
39#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000050#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Global options.
55//===----------------------------------------------------------------------===//
56
57static llvm::cl::opt<bool>
58Verbose("v", llvm::cl::desc("Enable verbose output"));
59static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000060Stats("print-stats",
61 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000062
63enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000064 RewriteObjC, // ObjC->C Rewriter.
Ted Kremenek13e479b2008-03-19 07:53:42 +000065 HTMLTest, // HTML displayer testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000066 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000067 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000068 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000069 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000070 ASTPrint, // Parse ASTs and print them.
71 ASTDump, // Parse ASTs and dump them.
72 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000073 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000074 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000075 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000076 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
77 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek2fff37e2008-03-06 00:08:09 +000078 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremenek055c2752007-09-06 23:00:42 +000079 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000080 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000081 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000082 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000083 ParsePrintCallbacks, // Parse and print each callback.
84 ParseSyntaxOnly, // Parse and perform semantic analysis.
85 ParseNoop, // Parse with noop callbacks.
86 RunPreprocessorOnly, // Just lex, no output.
87 PrintPreprocessedInput, // -E mode.
88 DumpTokens // Token dump mode.
89};
90
91static llvm::cl::opt<ProgActions>
92ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
93 llvm::cl::init(ParseSyntaxOnly),
94 llvm::cl::values(
95 clEnumValN(RunPreprocessorOnly, "Eonly",
96 "Just run preprocessor, no output (for timings)"),
97 clEnumValN(PrintPreprocessedInput, "E",
98 "Run preprocessor, emit preprocessed file"),
99 clEnumValN(DumpTokens, "dumptokens",
100 "Run preprocessor, dump internal rep of tokens"),
101 clEnumValN(ParseNoop, "parse-noop",
102 "Run parser with noop callbacks (for timings)"),
103 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
104 "Run parser and perform semantic analysis"),
105 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
106 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000107 clEnumValN(EmitHTML, "emit-html",
108 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000109 clEnumValN(ASTPrint, "ast-print",
110 "Build ASTs and then pretty-print them"),
111 clEnumValN(ASTDump, "ast-dump",
112 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000113 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000114 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000115 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000116 "Run parser, then build and print CFGs."),
117 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000118 "Run parser, then build and view CFGs with Graphviz."),
119 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000120 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000121 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000122 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000123 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000124 "Flag warnings of uses of unitialized variables."),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000125 clEnumValN(AnalysisGRSimpleVals, "checker-simple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000126 "Perform path-sensitive constant propagation."),
Ted Kremenekd71ed262008-04-10 22:16:52 +0000127 clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000128 "Run the Core Foundation reference count checker."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000129 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerf3dabbd2008-03-09 05:25:01 +0000130 "Run prototype serialization code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000132 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000133 clEnumValN(EmitBC, "emit-llvm-bc",
134 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000135 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000136 "Build ASTs and emit .ast file"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000137 clEnumValN(RewriteObjC, "rewrite-objc",
Ted Kremenekfdbe6792008-04-16 04:38:45 +0000138 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 clEnumValEnd));
140
Ted Kremenekccc76472007-12-19 19:47:59 +0000141
142static llvm::cl::opt<std::string>
143OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000144 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000145 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000146
147//===----------------------------------------------------------------------===//
148// Diagnostic Options
149//===----------------------------------------------------------------------===//
150
Ted Kremenek41193e42007-09-26 19:42:19 +0000151static llvm::cl::opt<bool>
152VerifyDiagnostics("verify",
153 llvm::cl::desc("Verify emitted diagnostics and warnings."));
154
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000155static llvm::cl::opt<std::string>
156HTMLDiag("html-diags",
157 llvm::cl::desc("Generate HTML to report diagnostics"),
158 llvm::cl::value_desc("HTML directory"));
159
Reid Spencer5f016e22007-07-11 17:01:13 +0000160//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000161// Analyzer Options
162//===----------------------------------------------------------------------===//
163
164static llvm::cl::opt<bool>
165VisualizeEG("visualize-egraph",
166 llvm::cl::desc("Display static analysis Exploded Graph."));
167
168static llvm::cl::opt<bool>
169AnalyzeAll("checker-opt-analyze-headers",
170 llvm::cl::desc("Force the static analyzer to analyze "
171 "functions defined in header files."));
172
173//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000174// Language Options
175//===----------------------------------------------------------------------===//
176
177enum LangKind {
178 langkind_unspecified,
179 langkind_c,
180 langkind_c_cpp,
181 langkind_cxx,
182 langkind_cxx_cpp,
183 langkind_objc,
184 langkind_objc_cpp,
185 langkind_objcxx,
186 langkind_objcxx_cpp
187};
188
189/* TODO: GCC also accepts:
190 c-header c++-header objective-c-header objective-c++-header
191 assembler assembler-with-cpp
192 ada, f77*, ratfor (!), f95, java, treelang
193 */
194static llvm::cl::opt<LangKind>
195BaseLang("x", llvm::cl::desc("Base language to compile"),
196 llvm::cl::init(langkind_unspecified),
197 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
198 clEnumValN(langkind_cxx, "c++", "C++"),
199 clEnumValN(langkind_objc, "objective-c", "Objective C"),
200 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
201 clEnumValN(langkind_c_cpp, "c-cpp-output",
202 "Preprocessed C"),
203 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
204 "Preprocessed C++"),
205 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
206 "Preprocessed Objective C"),
207 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
208 "Preprocessed Objective C++"),
209 clEnumValEnd));
210
211static llvm::cl::opt<bool>
212LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
213 llvm::cl::Hidden);
214static llvm::cl::opt<bool>
215LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
216 llvm::cl::Hidden);
217
Ted Kremenek8904f152007-12-05 23:49:08 +0000218/// InitializeBaseLanguage - Handle the -x foo options.
219static void InitializeBaseLanguage() {
220 if (LangObjC)
221 BaseLang = langkind_objc;
222 else if (LangObjCXX)
223 BaseLang = langkind_objcxx;
224}
225
226static LangKind GetLanguage(const std::string &Filename) {
227 if (BaseLang != langkind_unspecified)
228 return BaseLang;
229
230 std::string::size_type DotPos = Filename.rfind('.');
231
232 if (DotPos == std::string::npos) {
233 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000234 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 }
236
Ted Kremenek8904f152007-12-05 23:49:08 +0000237 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
238 // C header: .h
239 // C++ header: .hh or .H;
240 // assembler no preprocessing: .s
241 // assembler: .S
242 if (Ext == "c")
243 return langkind_c;
244 else if (Ext == "i")
245 return langkind_c_cpp;
246 else if (Ext == "ii")
247 return langkind_cxx_cpp;
248 else if (Ext == "m")
249 return langkind_objc;
250 else if (Ext == "mi")
251 return langkind_objc_cpp;
252 else if (Ext == "mm" || Ext == "M")
253 return langkind_objcxx;
254 else if (Ext == "mii")
255 return langkind_objcxx_cpp;
256 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
257 Ext == "c++" || Ext == "cp" || Ext == "cxx")
258 return langkind_cxx;
259 else
260 return langkind_c;
261}
262
263
264static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000265 // FIXME: implement -fpreprocessed mode.
266 bool NoPreprocess = false;
267
Ted Kremenek8904f152007-12-05 23:49:08 +0000268 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000269 default: assert(0 && "Unknown language kind!");
270 case langkind_c_cpp:
271 NoPreprocess = true;
272 // FALLTHROUGH
273 case langkind_c:
274 break;
275 case langkind_cxx_cpp:
276 NoPreprocess = true;
277 // FALLTHROUGH
278 case langkind_cxx:
279 Options.CPlusPlus = 1;
280 break;
281 case langkind_objc_cpp:
282 NoPreprocess = true;
283 // FALLTHROUGH
284 case langkind_objc:
285 Options.ObjC1 = Options.ObjC2 = 1;
286 break;
287 case langkind_objcxx_cpp:
288 NoPreprocess = true;
289 // FALLTHROUGH
290 case langkind_objcxx:
291 Options.ObjC1 = Options.ObjC2 = 1;
292 Options.CPlusPlus = 1;
293 break;
294 }
295}
296
297/// LangStds - Language standards we support.
298enum LangStds {
299 lang_unspecified,
300 lang_c89, lang_c94, lang_c99,
301 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000302 lang_cxx98, lang_gnucxx98,
303 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000304};
305
306static llvm::cl::opt<LangStds>
307LangStd("std", llvm::cl::desc("Language standard to compile for"),
308 llvm::cl::init(lang_unspecified),
309 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
310 clEnumValN(lang_c89, "c90", "ISO C 1990"),
311 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
312 clEnumValN(lang_c94, "iso9899:199409",
313 "ISO C 1990 with amendment 1"),
314 clEnumValN(lang_c99, "c99", "ISO C 1999"),
315// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
316 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
317// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
318 clEnumValN(lang_gnu89, "gnu89",
319 "ISO C 1990 with GNU extensions (default for C)"),
320 clEnumValN(lang_gnu99, "gnu99",
321 "ISO C 1999 with GNU extensions"),
322 clEnumValN(lang_gnu99, "gnu9x",
323 "ISO C 1999 with GNU extensions"),
324 clEnumValN(lang_cxx98, "c++98",
325 "ISO C++ 1998 with amendments"),
326 clEnumValN(lang_gnucxx98, "gnu++98",
327 "ISO C++ 1998 with amendments and GNU "
328 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000329 clEnumValN(lang_cxx0x, "c++0x",
330 "Upcoming ISO C++ 200x with amendments"),
331 clEnumValN(lang_gnucxx0x, "gnu++0x",
332 "Upcoming ISO C++ 200x with amendments and GNU "
333 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 clEnumValEnd));
335
336static llvm::cl::opt<bool>
337NoOperatorNames("fno-operator-names",
338 llvm::cl::desc("Do not treat C++ operator name keywords as "
339 "synonyms for operators"));
340
Anders Carlssonee98ac52007-10-15 02:50:23 +0000341static llvm::cl::opt<bool>
342PascalStrings("fpascal-strings",
343 llvm::cl::desc("Recognize and construct Pascal-style "
344 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000345
346static llvm::cl::opt<bool>
347MSExtensions("fms-extensions",
348 llvm::cl::desc("Accept some non-standard constructs used in "
349 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000350
351static llvm::cl::opt<bool>
352WritableStrings("fwritable-strings",
353 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000354
355static llvm::cl::opt<bool>
356LaxVectorConversions("flax-vector-conversions",
357 llvm::cl::desc("Allow implicit conversions between vectors"
358 " with a different number of elements or "
359 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000360// FIXME: add:
361// -ansi
362// -trigraphs
363// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000364// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000365static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 if (LangStd == lang_unspecified) {
367 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000368 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 default: assert(0 && "Unknown base language");
370 case langkind_c:
371 case langkind_c_cpp:
372 case langkind_objc:
373 case langkind_objc_cpp:
374 LangStd = lang_gnu99;
375 break;
376 case langkind_cxx:
377 case langkind_cxx_cpp:
378 case langkind_objcxx:
379 case langkind_objcxx_cpp:
380 LangStd = lang_gnucxx98;
381 break;
382 }
383 }
384
385 switch (LangStd) {
386 default: assert(0 && "Unknown language standard!");
387
388 // Fall through from newer standards to older ones. This isn't really right.
389 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000390 case lang_gnucxx0x:
391 case lang_cxx0x:
392 Options.CPlusPlus0x = 1;
393 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 case lang_gnucxx98:
395 case lang_cxx98:
396 Options.CPlusPlus = 1;
397 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000398 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 // FALL THROUGH.
400 case lang_gnu99:
401 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 Options.C99 = 1;
403 Options.HexFloats = 1;
404 // FALL THROUGH.
405 case lang_gnu89:
406 Options.BCPLComment = 1; // Only for C99/C++.
407 // FALL THROUGH.
408 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000409 Options.Digraphs = 1; // C94, C99, C++.
410 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 case lang_c89:
412 break;
413 }
414
Chris Lattnerd658b562008-04-05 06:32:51 +0000415 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
416 Options.ImplicitInt = 1;
417 else
418 Options.ImplicitInt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 Options.Trigraphs = 1; // -trigraphs or -ansi
420 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000421 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000422 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000423 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000424 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000425}
426
427//===----------------------------------------------------------------------===//
428// Our DiagnosticClient implementation
429//===----------------------------------------------------------------------===//
430
431// FIXME: Werror should take a list of things, -Werror=foo,bar
432static llvm::cl::opt<bool>
433WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
434
435static llvm::cl::opt<bool>
436WarnOnExtensions("pedantic", llvm::cl::init(false),
437 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
438
439static llvm::cl::opt<bool>
440ErrorOnExtensions("pedantic-errors",
441 llvm::cl::desc("Issue an error on uses of GCC extensions"));
442
443static llvm::cl::opt<bool>
444WarnUnusedMacros("Wunused_macros",
445 llvm::cl::desc("Warn for unused macros in the main translation unit"));
446
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000447static llvm::cl::opt<bool>
448WarnFloatEqual("Wfloat-equal",
449 llvm::cl::desc("Warn about equality comparisons of floating point values."));
450
Ted Kremenek73da5902007-12-17 17:50:07 +0000451static llvm::cl::opt<bool>
452WarnNoFormatNonLiteral("Wno-format-nonliteral",
453 llvm::cl::desc("Do not warn about non-literal format strings."));
454
Chris Lattner116a4b12008-01-23 17:19:46 +0000455static llvm::cl::opt<bool>
456WarnUndefMacros("Wundef",
457 llvm::cl::desc("Warn on use of undefined macros in #if's"));
458
459
Reid Spencer5f016e22007-07-11 17:01:13 +0000460/// InitializeDiagnostics - Initialize the diagnostic object, based on the
461/// current command line option settings.
462static void InitializeDiagnostics(Diagnostic &Diags) {
463 Diags.setWarningsAsErrors(WarningsAsErrors);
464 Diags.setWarnOnExtensions(WarnOnExtensions);
465 Diags.setErrorOnExtensions(ErrorOnExtensions);
466
467 // Silence the "macro is not used" warning unless requested.
468 if (!WarnUnusedMacros)
469 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000470
471 // Silence "floating point comparison" warnings unless requested.
472 if (!WarnFloatEqual)
473 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000474
475 // Silence "format string is not a string literal" warnings if requested
476 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000477 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
478 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000479 if (!WarnUndefMacros)
480 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000481
482 if (MSExtensions) // MS allows unnamed struct/union fields.
483 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000484}
485
486//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000487// Analysis-specific options.
488//===----------------------------------------------------------------------===//
489
490static llvm::cl::opt<std::string>
491AnalyzeSpecificFunction("analyze-function",
492 llvm::cl::desc("Run analysis on specific function."));
493
Ted Kremenekffe0f432008-03-07 22:58:01 +0000494static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000495TrimGraph("trim-egraph",
Ted Kremenekffe0f432008-03-07 22:58:01 +0000496 llvm::cl::desc("Only show error-related paths in the analysis graph."));
497
Ted Kremenekcb330932008-02-18 21:21:23 +0000498//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000499// Target Triple Processing.
500//===----------------------------------------------------------------------===//
501
502static llvm::cl::opt<std::string>
503TargetTriple("triple",
504 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
505
Chris Lattner42e67372008-03-05 01:18:20 +0000506static llvm::cl::opt<std::string>
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000507Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenekae360762007-12-03 22:06:55 +0000508
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000509static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000510 // Initialize base triple. If a -triple option has been specified, use
511 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000512 std::string Triple = TargetTriple;
513 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000514
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000515 // If -arch foo was specified, remove the architecture from the triple we have
516 // so far and replace it with the specified one.
517 if (Arch.empty())
518 return Triple;
519
Ted Kremenekae360762007-12-03 22:06:55 +0000520 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000521 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000522
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000523 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000524 fprintf(stderr,
525 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000526 Triple.c_str());
527 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000528 }
Ted Kremenekae360762007-12-03 22:06:55 +0000529
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000530 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000531}
532
533//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000534// Preprocessor Initialization
535//===----------------------------------------------------------------------===//
536
537// FIXME: Preprocessor builtins to support.
538// -A... - Play with #assertions
539// -undef - Undefine all predefined macros
540
541static llvm::cl::list<std::string>
542D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
543 llvm::cl::desc("Predefine the specified macro"));
544static llvm::cl::list<std::string>
545U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
546 llvm::cl::desc("Undefine the specified macro"));
547
Chris Lattner64299f82008-01-10 01:53:41 +0000548static llvm::cl::list<std::string>
549ImplicitIncludes("include", llvm::cl::value_desc("file"),
550 llvm::cl::desc("Include file before parsing"));
551
552
Reid Spencer5f016e22007-07-11 17:01:13 +0000553// Append a #define line to Buf for Macro. Macro should be of the form XXX,
554// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
555// "#define XXX Y z W". To get a #define with no value, use "XXX=".
556static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
557 const char *Command = "#define ") {
558 Buf.insert(Buf.end(), Command, Command+strlen(Command));
559 if (const char *Equal = strchr(Macro, '=')) {
560 // Turn the = into ' '.
561 Buf.insert(Buf.end(), Macro, Equal);
562 Buf.push_back(' ');
563 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
564 } else {
565 // Push "macroname 1".
566 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
567 Buf.push_back(' ');
568 Buf.push_back('1');
569 }
570 Buf.push_back('\n');
571}
572
Chris Lattner64299f82008-01-10 01:53:41 +0000573/// AddImplicitInclude - Add an implicit #include of the specified file to the
574/// predefines buffer.
575static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
576 const char *Inc = "#include \"";
577 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
578 Buf.insert(Buf.end(), File.begin(), File.end());
579 Buf.push_back('"');
580 Buf.push_back('\n');
581}
582
Reid Spencer5f016e22007-07-11 17:01:13 +0000583
Chris Lattner53b0dab2007-10-09 22:10:18 +0000584/// InitializePreprocessor - Initialize the preprocessor getting it and the
585/// environment ready to process a single file. This returns the file ID for the
586/// input file. If a failure happens, it returns 0.
587///
588static unsigned InitializePreprocessor(Preprocessor &PP,
589 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000590 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000591
Chris Lattnerdee73592007-12-15 20:48:40 +0000592 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000593
Chris Lattner53b0dab2007-10-09 22:10:18 +0000594 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000595 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000596 if (InFile != "-") {
597 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000598 if (File) SourceMgr.createMainFileID(File, SourceLocation());
599 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000600 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
601 return 0;
602 }
603 } else {
604 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000605 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
606 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000607 fprintf(stderr, "Error reading standard input! Empty?\n");
608 return 0;
609 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000611
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000613 unsigned d = 0, D = D_macros.size();
614 unsigned u = 0, U = U_macros.size();
615 while (d < D || u < U) {
616 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
617 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
618 else
619 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
620 }
621
Chris Lattner64299f82008-01-10 01:53:41 +0000622 // FIXME: Read any files specified by -imacros.
623
624 // Add implicit #includes from -include.
625 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
626 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000627
628 // Null terminate PredefinedBuffer and add it.
629 PredefineBuffer.push_back(0);
630 PP.setPredefines(&PredefineBuffer[0]);
631
632 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000633 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000634}
635
636//===----------------------------------------------------------------------===//
637// Preprocessor include path information.
638//===----------------------------------------------------------------------===//
639
640// This tool exports a large number of command line options to control how the
641// preprocessor searches for header files. At root, however, the Preprocessor
642// object takes a very simple interface: a list of directories to search for
643//
644// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000645// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000646//
Chris Lattner64299f82008-01-10 01:53:41 +0000647// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000648
649static llvm::cl::opt<bool>
650nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
651
652// Various command line options. These four add directories to each chain.
653static llvm::cl::list<std::string>
654F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
655 llvm::cl::desc("Add directory to framework include search path"));
656static llvm::cl::list<std::string>
657I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
658 llvm::cl::desc("Add directory to include search path"));
659static llvm::cl::list<std::string>
660idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
661 llvm::cl::desc("Add directory to AFTER include search path"));
662static llvm::cl::list<std::string>
663iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
664 llvm::cl::desc("Add directory to QUOTE include search path"));
665static llvm::cl::list<std::string>
666isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
667 llvm::cl::desc("Add directory to SYSTEM include search path"));
668
669// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
670static llvm::cl::list<std::string>
671iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
672 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
673static llvm::cl::list<std::string>
674iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
675 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
676static llvm::cl::list<std::string>
677iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
678 llvm::cl::Prefix,
679 llvm::cl::desc("Set directory to include search path with prefix"));
680
Chris Lattner0c946412007-08-26 17:47:35 +0000681static llvm::cl::opt<std::string>
682isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
683 llvm::cl::desc("Set the system root directory (usually /)"));
684
Reid Spencer5f016e22007-07-11 17:01:13 +0000685// Finally, implement the code that groks the options above.
686enum IncludeDirGroup {
687 Quoted = 0,
688 Angled,
689 System,
690 After
691};
692
693static std::vector<DirectoryLookup> IncludeGroup[4];
694
695/// AddPath - Add the specified path to the specified group list.
696///
697static void AddPath(const std::string &Path, IncludeDirGroup Group,
698 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000699 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000700 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000701 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000702
Chris Lattnerd6655272007-12-17 05:59:27 +0000703 // Compute the actual path, taking into consideration -isysroot.
704 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000705
Chris Lattnerd6655272007-12-17 05:59:27 +0000706 // Handle isysroot.
707 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000708 // FIXME: Portability. This should be a sys::Path interface, this doesn't
709 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000710 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
711 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 }
713
Chris Lattnerd6655272007-12-17 05:59:27 +0000714 MappedPath.append(Path.begin(), Path.end());
715
716 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 DirectoryLookup::DirType Type;
718 if (Group == Quoted || Group == Angled)
719 Type = DirectoryLookup::NormalHeaderDir;
720 else if (isCXXAware)
721 Type = DirectoryLookup::SystemHeaderDir;
722 else
723 Type = DirectoryLookup::ExternCSystemHeaderDir;
724
Chris Lattnerd6655272007-12-17 05:59:27 +0000725
726 // If the directory exists, add it.
727 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
728 &MappedPath[0]+
729 MappedPath.size())) {
730 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
731 isFramework));
732 return;
733 }
734
Chris Lattnerdf772332007-12-17 07:52:39 +0000735 // Check to see if this is an apple-style headermap (which are not allowed to
736 // be frameworks).
737 if (!isFramework) {
738 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
739 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000740 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
741 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000742 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
743 return;
744 }
Chris Lattner822da612007-12-17 06:36:45 +0000745 }
746 }
747
Chris Lattnerd6655272007-12-17 05:59:27 +0000748 if (Verbose)
749 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000750}
751
752/// RemoveDuplicates - If there are duplicate directory entries in the specified
753/// search list, remove the later (dead) ones.
754static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000755 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000756 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000757 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000759 if (SearchList[i].isNormalDir()) {
760 // If this isn't the first time we've seen this dir, remove it.
761 if (SeenDirs.insert(SearchList[i].getDir()))
762 continue;
763
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 if (Verbose)
765 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
766 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000767 } else if (SearchList[i].isFramework()) {
768 // If this isn't the first time we've seen this framework dir, remove it.
769 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
770 continue;
771
772 if (Verbose)
773 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
774 SearchList[i].getFrameworkDir()->getName());
775
Chris Lattnerb94c7072007-12-17 06:44:29 +0000776 } else {
777 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
778 // If this isn't the first time we've seen this headermap, remove it.
779 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
780 continue;
781
782 if (Verbose)
783 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
784 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000786
787 // This is reached if the current entry is a duplicate.
788 SearchList.erase(SearchList.begin()+i);
789 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 }
791}
792
Chris Lattner5f9eae52008-03-01 08:07:28 +0000793// AddEnvVarPaths - Add a list of paths from an environment variable to a
794// header search list.
795//
796static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
797 const char* at = getenv(Name);
798 if (!at)
799 return;
800
801 const char* delim = strchr(at, llvm::sys::PathSeparator);
802 while (delim != 0) {
803 if (delim-at == 0)
804 AddPath(".", Angled, false, true, false, Headers);
805 else
806 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
807 true, false, Headers);
808 at = delim + 1;
809 delim = strchr(at, llvm::sys::PathSeparator);
810 }
811 if (*at == 0)
812 AddPath(".", Angled, false, true, false, Headers);
813 else
814 AddPath(at, Angled, false, true, false, Headers);
815}
816
Reid Spencer5f016e22007-07-11 17:01:13 +0000817/// InitializeIncludePaths - Process the -I options and set them in the
818/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000819static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
820 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 // Handle -F... options.
822 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000823 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000824
825 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000826 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000827 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000828
829 // Handle -idirafter... options.
830 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000831 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000832
833 // Handle -iquote... options.
834 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000835 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000836
837 // Handle -isystem... options.
838 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000839 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000840
841 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
842 // parallel, processing the values in order of occurance to get the right
843 // prefixes.
844 {
845 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
846 unsigned iprefix_idx = 0;
847 unsigned iwithprefix_idx = 0;
848 unsigned iwithprefixbefore_idx = 0;
849 bool iprefix_done = iprefix_vals.empty();
850 bool iwithprefix_done = iwithprefix_vals.empty();
851 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
852 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
853 if (!iprefix_done &&
854 (iwithprefix_done ||
855 iprefix_vals.getPosition(iprefix_idx) <
856 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
857 (iwithprefixbefore_done ||
858 iprefix_vals.getPosition(iprefix_idx) <
859 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
860 Prefix = iprefix_vals[iprefix_idx];
861 ++iprefix_idx;
862 iprefix_done = iprefix_idx == iprefix_vals.size();
863 } else if (!iwithprefix_done &&
864 (iwithprefixbefore_done ||
865 iwithprefix_vals.getPosition(iwithprefix_idx) <
866 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
867 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000868 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000869 ++iwithprefix_idx;
870 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
871 } else {
872 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000873 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 ++iwithprefixbefore_idx;
875 iwithprefixbefore_done =
876 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
877 }
878 }
879 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000880
881 AddEnvVarPaths("CPATH", Headers);
882 if (Lang.CPlusPlus && Lang.ObjC1)
883 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
884 else if (Lang.CPlusPlus)
885 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
886 else if (Lang.ObjC1)
887 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
888 else
889 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
890
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000891 // Add the clang headers, which are relative to the clang driver.
892 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000893 llvm::sys::Path::GetMainExecutable(Argv0,
894 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000895 if (!MainExecutablePath.isEmpty()) {
896 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
897 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
898 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
899 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
900 }
901
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 // FIXME: temporary hack: hard-coded paths.
903 // FIXME: get these from the target?
904 if (!nostdinc) {
905 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000906 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000908 false, Headers);
909 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
910 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000911
912 // Ubuntu 7.10 - Gutsy Gibbon
913 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
914 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
915 false, Headers);
916 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
917 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000918
919 // Fedora 8
920 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner8ac661c2008-04-16 05:21:09 +0000921 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
922 false, Headers);
923 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
924 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 }
926
Chris Lattner822da612007-12-17 06:36:45 +0000927 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 // leopard
929 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000930 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000932 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000933 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
934 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000935 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000936
937 // tiger
938 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000939 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000941 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000942 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
943 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000944 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000945
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000946 // Ubuntu 7.10 - Gutsy Gibbon
947 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000948 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000949
Chris Lattner04421082008-04-08 04:40:51 +0000950 // Fedora 8
951 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
952 false, false, false, Headers);
953
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000954 //Debian testing/lenny x86
955 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
956 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +0000957
958 //Debian testing/lenny amd64
959 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
960 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +0000961
Chris Lattner822da612007-12-17 06:36:45 +0000962 AddPath("/usr/include", System, false, false, false, Headers);
963 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
964 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 }
966
967 // Now that we have collected all of the include paths, merge them all
968 // together and tell the preprocessor about them.
969
970 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
971 std::vector<DirectoryLookup> SearchList;
972 SearchList = IncludeGroup[Angled];
973 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
974 IncludeGroup[System].end());
975 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
976 IncludeGroup[After].end());
977 RemoveDuplicates(SearchList);
978 RemoveDuplicates(IncludeGroup[Quoted]);
979
980 // Prepend QUOTED list on the search list.
981 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
982 IncludeGroup[Quoted].end());
983
984
985 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
986 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
987 DontSearchCurDir);
988
989 // If verbose, print the list of directories that will be searched.
990 if (Verbose) {
991 fprintf(stderr, "#include \"...\" search starts here:\n");
992 unsigned QuotedIdx = IncludeGroup[Quoted].size();
993 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
994 if (i == QuotedIdx)
995 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000996 const char *Name = SearchList[i].getName();
997 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000998 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000999 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +00001000 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +00001001 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +00001002 else {
1003 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +00001004 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +00001005 }
Chris Lattner3af66a92007-12-17 17:57:27 +00001006 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 }
Chris Lattner80e17152007-12-15 23:11:06 +00001008 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001009 }
1010}
1011
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001012//===----------------------------------------------------------------------===//
1013// Driver PreprocessorFactory - For lazily generating preprocessors ...
1014//===----------------------------------------------------------------------===//
1015
1016namespace {
1017class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1018 Diagnostic &Diags;
1019 const LangOptions &LangInfo;
1020 TargetInfo &Target;
1021 SourceManager &SourceMgr;
1022 HeaderSearch &HeaderInfo;
1023
1024public:
1025 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
1026 TargetInfo &target, SourceManager &SM,
1027 HeaderSearch &Headers)
1028 : Diags(diags), LangInfo(opts), Target(target),
1029 SourceMgr(SM), HeaderInfo(Headers) {}
1030
1031 virtual ~DriverPreprocessorFactory() {}
1032
1033 virtual Preprocessor* CreatePreprocessor() {
1034 return new Preprocessor(Diags, LangInfo, Target, SourceMgr, HeaderInfo);
1035 }
1036};
1037}
Reid Spencer5f016e22007-07-11 17:01:13 +00001038
Reid Spencer5f016e22007-07-11 17:01:13 +00001039//===----------------------------------------------------------------------===//
1040// Basic Parser driver
1041//===----------------------------------------------------------------------===//
1042
Ted Kremenek95041a22007-12-19 22:51:13 +00001043static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +00001044 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001045 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001046
1047 // Parsing the specified input file.
1048 P.ParseTranslationUnit();
1049 delete PA;
1050}
1051
1052//===----------------------------------------------------------------------===//
1053// Main driver
1054//===----------------------------------------------------------------------===//
1055
Ted Kremenekdb094a22007-12-05 18:27:04 +00001056/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1057/// action. These consumers can operate on both ASTs that are freshly
1058/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001059static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001060 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001061 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001062 Preprocessor *PP,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001063 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001064 switch (ProgAction) {
1065 default:
1066 return NULL;
1067
1068 case ASTPrint:
1069 return CreateASTPrinter();
1070
1071 case ASTDump:
1072 return CreateASTDumper();
1073
1074 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001075 return CreateASTViewer();
1076
1077 case EmitHTML:
Chris Lattner3245a0a2008-04-16 06:11:58 +00001078 return CreateHTMLPrinter(OutputFile, Diag, PP);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001079
1080 case ParseCFGDump:
1081 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001082 return CreateCFGDumper(ProgAction == ParseCFGView,
1083 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001084
1085 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001086 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001087
1088 case WarnDeadStores:
1089 return CreateDeadStoreChecker(Diag);
1090
1091 case WarnUninitVals:
1092 return CreateUnitValsChecker(Diag);
1093
Ted Kremeneke01c9872008-02-14 22:36:46 +00001094 case AnalysisGRSimpleVals:
Ted Kremenek47abe762008-04-16 16:39:56 +00001095 return CreateGRSimpleVals(Diag, PP, AnalyzeSpecificFunction, OutputFile,
Ted Kremenek55af98c2008-04-14 18:40:58 +00001096 VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001097
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001098 case CheckerCFRef:
Ted Kremenek47abe762008-04-16 16:39:56 +00001099 return CreateCFRefChecker(Diag, PP, AnalyzeSpecificFunction, OutputFile,
Ted Kremenek55af98c2008-04-14 18:40:58 +00001100 VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001101
Ted Kremenekdb094a22007-12-05 18:27:04 +00001102 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001103 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001104
1105 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001106 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001107 DestModule = new llvm::Module(InFile);
1108 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001109
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001110 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001111 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001112 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001113
Steve Naroffb29b4272008-04-14 22:03:09 +00001114 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001115 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001116 }
1117}
1118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119/// ProcessInputFile - Process a single input file with the specified state.
1120///
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001121static void ProcessInputFile(Preprocessor &PP, const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001122
1123 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001124 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001125 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001126
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 switch (ProgAction) {
1128 default:
Chris Lattner3245a0a2008-04-16 06:11:58 +00001129 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1130 PP.getFileManager(), PP.getLangOptions(), &PP,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001131 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001132
1133 if (!Consumer) {
1134 fprintf(stderr, "Unexpected program action!\n");
1135 return;
1136 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001137
Ted Kremenekdb094a22007-12-05 18:27:04 +00001138 break;
1139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001141 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001143 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 do {
1145 PP.Lex(Tok);
1146 PP.DumpToken(Tok, true);
1147 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001148 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001149 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 break;
1151 }
1152 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001153 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001154 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001155 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 do {
1157 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001158 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001159 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 break;
1161 }
1162
1163 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001164 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001165 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 break;
1167
1168 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001169 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001170 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 break;
1172
1173 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001174 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001175 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001177
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001178 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001179 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001180 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001181 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001182
1183 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001184 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001185 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001186
1187 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001188 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001190
1191 // If running the code generator, finish up now.
1192 if (CodeGenModule) {
1193 std::ostream *Out;
1194 if (OutputFile == "-") {
1195 Out = llvm::cout.stream();
1196 } else if (!OutputFile.empty()) {
1197 Out = new std::ofstream(OutputFile.c_str(),
1198 std::ios_base::binary|std::ios_base::out);
1199 } else if (InFile == "-") {
1200 Out = llvm::cout.stream();
1201 } else {
1202 llvm::sys::Path Path(InFile);
1203 Path.eraseSuffix();
1204 if (ProgAction == EmitLLVM)
1205 Path.appendSuffix("ll");
1206 else if (ProgAction == EmitBC)
1207 Path.appendSuffix("bc");
1208 else
1209 assert(0 && "Unknown action");
1210 Out = new std::ofstream(Path.toString().c_str(),
1211 std::ios_base::binary|std::ios_base::out);
1212 }
1213
1214 if (ProgAction == EmitLLVM) {
1215 CodeGenModule->print(*Out);
1216 } else {
1217 assert(ProgAction == EmitBC);
1218 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1219 }
1220
1221 if (Out != llvm::cout.stream())
1222 delete Out;
1223 delete CodeGenModule;
1224 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001225
1226 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001227 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 PP.PrintStats();
1229 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001230 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001231 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001232 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 fprintf(stderr, "\n");
1234 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001235
1236 // For a multi-file compilation, some things are ok with nuking the source
1237 // manager tables, other require stable fileid/macroid's across multiple
1238 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001239 if (ClearSourceMgr)
1240 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001241}
1242
Ted Kremenek20e97482007-12-12 23:41:08 +00001243static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1244 FileManager& FileMgr) {
1245
1246 if (VerifyDiagnostics) {
1247 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1248 exit (1);
1249 }
1250
1251 llvm::sys::Path Filename(InFile);
1252
1253 if (!Filename.isValid()) {
1254 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1255 exit (1);
1256 }
1257
Ted Kremenekee533642007-12-20 19:47:16 +00001258 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001259
1260 if (!TU) {
1261 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1262 InFile.c_str());
1263 exit (1);
1264 }
1265
Ted Kremenek63ea8632007-12-19 19:27:38 +00001266 // Observe that we use the source file name stored in the deserialized
1267 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001268 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001269 llvm::OwningPtr<ASTConsumer>
Chris Lattner3245a0a2008-04-16 06:11:58 +00001270 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(), 0,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001271 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001272
1273 if (!Consumer) {
1274 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1275 exit (1);
1276 }
1277
Ted Kremenek95041a22007-12-19 22:51:13 +00001278 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001279
Chris Lattnere66b65c2008-02-06 01:42:25 +00001280 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001281 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1282 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001283}
1284
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286static llvm::cl::list<std::string>
1287InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1288
Ted Kremenek20e97482007-12-12 23:41:08 +00001289static bool isSerializedFile(const std::string& InFile) {
1290 if (InFile.size() < 4)
1291 return false;
1292
1293 const char* s = InFile.c_str()+InFile.size()-4;
1294
1295 return s[0] == '.' &&
1296 s[1] == 'a' &&
1297 s[2] == 's' &&
1298 s[3] == 't';
1299}
1300
Reid Spencer5f016e22007-07-11 17:01:13 +00001301
1302int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001303 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 llvm::sys::PrintStackTraceOnErrorSignal();
1305
1306 // If no input was specified, read from stdin.
1307 if (InputFilenames.empty())
1308 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001309
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 // Create a file manager object to provide access to and cache the filesystem.
1311 FileManager FileMgr;
1312
Ted Kremenek31e703b2007-12-11 23:28:38 +00001313 // Create the diagnostic client for reporting errors or for
1314 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001315 std::auto_ptr<DiagnosticClient> DiagClient;
1316 TextDiagnostics* TextDiagClient = NULL;
1317
1318 if (!HTMLDiag.empty()) {
Ted Kremeneka760f5f2008-04-16 16:53:18 +00001319
1320 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1321 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1322 // Fix this dependency later.
Ted Kremenek47abe762008-04-16 16:39:56 +00001323 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, NULL));
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001324 }
1325 else { // Use Text diagnostics.
1326 if (!VerifyDiagnostics) {
1327 // Print diagnostics to stderr by default.
1328 TextDiagClient = new TextDiagnosticPrinter();
1329 } else {
1330 // When checking diagnostics, just buffer them up.
1331 TextDiagClient = new TextDiagnosticBuffer();
1332
1333 if (InputFilenames.size() != 1) {
1334 fprintf(stderr,
1335 "-verify only works on single input files for now.\n");
1336 return 1;
1337 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001339
1340 assert (TextDiagClient);
1341 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 }
1343
1344 // Configure our handling of diagnostics.
1345 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001346 InitializeDiagnostics(Diags);
1347
Chris Lattner4f037832007-12-05 23:24:17 +00001348 // -I- is a deprecated GCC feature, scan for it and reject it.
1349 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1350 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001351 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001352 I_dirs.erase(I_dirs.begin()+i);
1353 --i;
1354 }
1355 }
Chris Lattner11215192008-03-14 06:12:05 +00001356
1357 // Get information about the target being compiled for.
1358 std::string Triple = CreateTargetTriple();
1359 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1360 if (Target == 0) {
1361 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1362 Triple.c_str());
1363 fprintf(stderr, "Please use -triple or -arch.\n");
1364 exit(1);
1365 }
Chris Lattner4f037832007-12-05 23:24:17 +00001366
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001368 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001369
Ted Kremenek20e97482007-12-12 23:41:08 +00001370 if (isSerializedFile(InFile))
1371 ProcessSerializedFile(InFile,Diags,FileMgr);
1372 else {
1373 /// Create a SourceManager object. This tracks and owns all the file
1374 /// buffers allocated to a translation unit.
1375 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001376
Ted Kremenek20e97482007-12-12 23:41:08 +00001377 // Initialize language options, inferring file types from input filenames.
1378 LangOptions LangInfo;
1379 InitializeBaseLanguage();
1380 LangKind LK = GetLanguage(InFile);
1381 InitializeLangOptions(LangInfo, LK);
1382 InitializeLanguageStandard(LangInfo, LK);
1383
1384 // Process the -I options and set them in the HeaderInfo.
1385 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001386 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001387 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001388
Ted Kremenek20e97482007-12-12 23:41:08 +00001389 // Set up the preprocessor with these options.
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001390 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
1391 SourceMgr, HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001392
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001393 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1394
Ted Kremenek20e97482007-12-12 23:41:08 +00001395 std::vector<char> PredefineBuffer;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001396 if (!InitializePreprocessor(*PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001397 continue;
1398
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001399 ProcessInputFile(*PP, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001400 HeaderInfo.ClearFileInfo();
1401
1402 if (Stats)
1403 SourceMgr.PrintStats();
1404 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 }
1406
Chris Lattner11215192008-03-14 06:12:05 +00001407 delete Target;
1408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1410
1411 if (NumDiagnostics)
1412 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1413 (NumDiagnostics == 1 ? "" : "s"));
1414
1415 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 FileMgr.PrintStats();
1417 fprintf(stderr, "\n");
1418 }
1419
Chris Lattner96f1a642007-07-21 05:40:53 +00001420 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001421}