blob: 09140c942e0dfba21d6ccabbd9accc24ec335a9d [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
1012
Reid Spencer5f016e22007-07-11 17:01:13 +00001013//===----------------------------------------------------------------------===//
1014// Basic Parser driver
1015//===----------------------------------------------------------------------===//
1016
Ted Kremenek95041a22007-12-19 22:51:13 +00001017static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001019 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001020
1021 // Parsing the specified input file.
1022 P.ParseTranslationUnit();
1023 delete PA;
1024}
1025
1026//===----------------------------------------------------------------------===//
1027// Main driver
1028//===----------------------------------------------------------------------===//
1029
Ted Kremenekdb094a22007-12-05 18:27:04 +00001030/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1031/// action. These consumers can operate on both ASTs that are freshly
1032/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001033static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001034 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001035 const LangOptions& LangOpts,
1036 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001037 switch (ProgAction) {
1038 default:
1039 return NULL;
1040
1041 case ASTPrint:
1042 return CreateASTPrinter();
1043
1044 case ASTDump:
1045 return CreateASTDumper();
1046
1047 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001048 return CreateASTViewer();
1049
1050 case EmitHTML:
Chris Lattner8ac661c2008-04-16 05:21:09 +00001051 return CreateHTMLPrinter(OutputFile, Diag);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001052
1053 case ParseCFGDump:
1054 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001055 return CreateCFGDumper(ProgAction == ParseCFGView,
1056 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001057
1058 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001059 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001060
1061 case WarnDeadStores:
1062 return CreateDeadStoreChecker(Diag);
1063
1064 case WarnUninitVals:
1065 return CreateUnitValsChecker(Diag);
1066
Ted Kremeneke01c9872008-02-14 22:36:46 +00001067 case AnalysisGRSimpleVals:
Ted Kremenek4dc41cc2008-03-31 18:26:32 +00001068 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, OutputFile,
Ted Kremenek55af98c2008-04-14 18:40:58 +00001069 VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001070
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001071 case CheckerCFRef:
Ted Kremenekd71ed262008-04-10 22:16:52 +00001072 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction, OutputFile,
Ted Kremenek55af98c2008-04-14 18:40:58 +00001073 VisualizeEG, TrimGraph, AnalyzeAll);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001074
Ted Kremenekdb094a22007-12-05 18:27:04 +00001075 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001076 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001077
1078 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001079 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001080 DestModule = new llvm::Module(InFile);
1081 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001082
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001083 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001084 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001085 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001086
Steve Naroffb29b4272008-04-14 22:03:09 +00001087 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001088 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001089 }
1090}
1091
Reid Spencer5f016e22007-07-11 17:01:13 +00001092/// ProcessInputFile - Process a single input file with the specified state.
1093///
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001094static void ProcessInputFile(Preprocessor &PP, const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001095
1096 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001097 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001098 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001099
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 switch (ProgAction) {
1101 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001102 Consumer = CreateASTConsumer(InFile,
1103 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001104 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001105 PP.getLangOptions(),
1106 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001107
1108 if (!Consumer) {
1109 fprintf(stderr, "Unexpected program action!\n");
1110 return;
1111 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001112
Ted Kremenekdb094a22007-12-05 18:27:04 +00001113 break;
1114
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001116 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001118 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 do {
1120 PP.Lex(Tok);
1121 PP.DumpToken(Tok, true);
1122 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001123 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001124 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 break;
1126 }
1127 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001128 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001130 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 do {
1132 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001133 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001134 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 break;
1136 }
1137
1138 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001139 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001140 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 break;
1142
1143 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001144 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001145 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 break;
1147
1148 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001149 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001150 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001152
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001153 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001154 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001155 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001156 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001157
1158 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001159 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001160 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001161
1162 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001163 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001165
1166 // If running the code generator, finish up now.
1167 if (CodeGenModule) {
1168 std::ostream *Out;
1169 if (OutputFile == "-") {
1170 Out = llvm::cout.stream();
1171 } else if (!OutputFile.empty()) {
1172 Out = new std::ofstream(OutputFile.c_str(),
1173 std::ios_base::binary|std::ios_base::out);
1174 } else if (InFile == "-") {
1175 Out = llvm::cout.stream();
1176 } else {
1177 llvm::sys::Path Path(InFile);
1178 Path.eraseSuffix();
1179 if (ProgAction == EmitLLVM)
1180 Path.appendSuffix("ll");
1181 else if (ProgAction == EmitBC)
1182 Path.appendSuffix("bc");
1183 else
1184 assert(0 && "Unknown action");
1185 Out = new std::ofstream(Path.toString().c_str(),
1186 std::ios_base::binary|std::ios_base::out);
1187 }
1188
1189 if (ProgAction == EmitLLVM) {
1190 CodeGenModule->print(*Out);
1191 } else {
1192 assert(ProgAction == EmitBC);
1193 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1194 }
1195
1196 if (Out != llvm::cout.stream())
1197 delete Out;
1198 delete CodeGenModule;
1199 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001200
1201 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001202 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 PP.PrintStats();
1204 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001205 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001206 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001207 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 fprintf(stderr, "\n");
1209 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001210
1211 // For a multi-file compilation, some things are ok with nuking the source
1212 // manager tables, other require stable fileid/macroid's across multiple
1213 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001214 if (ClearSourceMgr)
1215 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001216}
1217
Ted Kremenek20e97482007-12-12 23:41:08 +00001218static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1219 FileManager& FileMgr) {
1220
1221 if (VerifyDiagnostics) {
1222 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1223 exit (1);
1224 }
1225
1226 llvm::sys::Path Filename(InFile);
1227
1228 if (!Filename.isValid()) {
1229 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1230 exit (1);
1231 }
1232
Ted Kremenekee533642007-12-20 19:47:16 +00001233 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001234
1235 if (!TU) {
1236 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1237 InFile.c_str());
1238 exit (1);
1239 }
1240
Ted Kremenek63ea8632007-12-19 19:27:38 +00001241 // Observe that we use the source file name stored in the deserialized
1242 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001243 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001244 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001245 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1246 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001247
1248 if (!Consumer) {
1249 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1250 exit (1);
1251 }
1252
Ted Kremenek95041a22007-12-19 22:51:13 +00001253 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001254
Chris Lattnere66b65c2008-02-06 01:42:25 +00001255 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001256 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1257 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001258}
1259
1260
Reid Spencer5f016e22007-07-11 17:01:13 +00001261static llvm::cl::list<std::string>
1262InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1263
Ted Kremenek20e97482007-12-12 23:41:08 +00001264static bool isSerializedFile(const std::string& InFile) {
1265 if (InFile.size() < 4)
1266 return false;
1267
1268 const char* s = InFile.c_str()+InFile.size()-4;
1269
1270 return s[0] == '.' &&
1271 s[1] == 'a' &&
1272 s[2] == 's' &&
1273 s[3] == 't';
1274}
1275
Reid Spencer5f016e22007-07-11 17:01:13 +00001276
1277int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001278 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 llvm::sys::PrintStackTraceOnErrorSignal();
1280
1281 // If no input was specified, read from stdin.
1282 if (InputFilenames.empty())
1283 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 // Create a file manager object to provide access to and cache the filesystem.
1286 FileManager FileMgr;
1287
Ted Kremenek31e703b2007-12-11 23:28:38 +00001288 // Create the diagnostic client for reporting errors or for
1289 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001290 std::auto_ptr<DiagnosticClient> DiagClient;
1291 TextDiagnostics* TextDiagClient = NULL;
1292
1293 if (!HTMLDiag.empty()) {
1294 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
1295 }
1296 else { // Use Text diagnostics.
1297 if (!VerifyDiagnostics) {
1298 // Print diagnostics to stderr by default.
1299 TextDiagClient = new TextDiagnosticPrinter();
1300 } else {
1301 // When checking diagnostics, just buffer them up.
1302 TextDiagClient = new TextDiagnosticBuffer();
1303
1304 if (InputFilenames.size() != 1) {
1305 fprintf(stderr,
1306 "-verify only works on single input files for now.\n");
1307 return 1;
1308 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001310
1311 assert (TextDiagClient);
1312 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 }
1314
1315 // Configure our handling of diagnostics.
1316 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001317 InitializeDiagnostics(Diags);
1318
Chris Lattner4f037832007-12-05 23:24:17 +00001319 // -I- is a deprecated GCC feature, scan for it and reject it.
1320 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1321 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001322 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001323 I_dirs.erase(I_dirs.begin()+i);
1324 --i;
1325 }
1326 }
Chris Lattner11215192008-03-14 06:12:05 +00001327
1328 // Get information about the target being compiled for.
1329 std::string Triple = CreateTargetTriple();
1330 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1331 if (Target == 0) {
1332 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1333 Triple.c_str());
1334 fprintf(stderr, "Please use -triple or -arch.\n");
1335 exit(1);
1336 }
Chris Lattner4f037832007-12-05 23:24:17 +00001337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001339 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001340
Ted Kremenek20e97482007-12-12 23:41:08 +00001341 if (isSerializedFile(InFile))
1342 ProcessSerializedFile(InFile,Diags,FileMgr);
1343 else {
1344 /// Create a SourceManager object. This tracks and owns all the file
1345 /// buffers allocated to a translation unit.
1346 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001347
Ted Kremenek20e97482007-12-12 23:41:08 +00001348 // Initialize language options, inferring file types from input filenames.
1349 LangOptions LangInfo;
1350 InitializeBaseLanguage();
1351 LangKind LK = GetLanguage(InFile);
1352 InitializeLangOptions(LangInfo, LK);
1353 InitializeLanguageStandard(LangInfo, LK);
1354
1355 // Process the -I options and set them in the HeaderInfo.
1356 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001357 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001358 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001359
Ted Kremenek20e97482007-12-12 23:41:08 +00001360 // Set up the preprocessor with these options.
1361 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1362
1363 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001364 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001365 continue;
1366
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001367 ProcessInputFile(PP, InFile);
Ted Kremenek20e97482007-12-12 23:41:08 +00001368 HeaderInfo.ClearFileInfo();
1369
1370 if (Stats)
1371 SourceMgr.PrintStats();
1372 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 }
1374
Chris Lattner11215192008-03-14 06:12:05 +00001375 delete Target;
1376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1378
1379 if (NumDiagnostics)
1380 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1381 (NumDiagnostics == 1 ? "" : "s"));
1382
1383 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 FileMgr.PrintStats();
1385 fprintf(stderr, "\n");
1386 }
1387
Chris Lattner96f1a642007-07-21 05:40:53 +00001388 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001389}