blob: 3ca5493d2cbd84df823c2919463f0845fb4569f3 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattnereb8c9632007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Zhongxing Xue7079442008-08-24 02:33:36 +000027#include "clang/Driver/HTMLDiagnostics.h"
Nico Weber770e3882008-08-22 09:25:22 +000028#include "clang/Driver/InitHeaderSearch.h"
Nico Weber0e13eaa2008-08-05 23:33:20 +000029#include "clang/Driver/TextDiagnosticBuffer.h"
30#include "clang/Driver/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000031#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000032#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000033#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000034#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000035#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000036#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000037#include "clang/Parse/Parser.h"
38#include "clang/Lex/HeaderSearch.h"
39#include "clang/Basic/FileManager.h"
40#include "clang/Basic/SourceManager.h"
41#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000042#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000043#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000044#include "llvm/ADT/StringExtras.h"
45#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000046#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000049#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000050using namespace clang;
51
52//===----------------------------------------------------------------------===//
53// Global options.
54//===----------------------------------------------------------------------===//
55
56static llvm::cl::opt<bool>
57Verbose("v", llvm::cl::desc("Enable verbose output"));
58static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000059Stats("print-stats",
60 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000061
62enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000063 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000064 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000065 RewriteMacros, // Expand macros but not #includes.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000066 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000067 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000068 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000069 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000070 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000071 ASTPrint, // Parse ASTs and print them.
72 ASTDump, // Parse ASTs and dump them.
73 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000074 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000075 ParsePrintCallbacks, // Parse and print each callback.
76 ParseSyntaxOnly, // Parse and perform semantic analysis.
77 ParseNoop, // Parse with noop callbacks.
78 RunPreprocessorOnly, // Just lex, no output.
79 PrintPreprocessedInput, // -E mode.
Ted Kremenek81ea7992008-07-02 00:03:09 +000080 DumpTokens, // Token dump mode.
81 RunAnalysis // Run one or more source code analyses.
Chris Lattner4b009652007-07-25 00:24:17 +000082};
83
84static llvm::cl::opt<ProgActions>
85ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
86 llvm::cl::init(ParseSyntaxOnly),
87 llvm::cl::values(
88 clEnumValN(RunPreprocessorOnly, "Eonly",
89 "Just run preprocessor, no output (for timings)"),
90 clEnumValN(PrintPreprocessedInput, "E",
91 "Run preprocessor, emit preprocessed file"),
92 clEnumValN(DumpTokens, "dumptokens",
93 "Run preprocessor, dump internal rep of tokens"),
94 clEnumValN(ParseNoop, "parse-noop",
95 "Run parser with noop callbacks (for timings)"),
96 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
97 "Run parser and perform semantic analysis"),
98 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
99 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000100 clEnumValN(EmitHTML, "emit-html",
101 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000102 clEnumValN(ASTPrint, "ast-print",
103 "Build ASTs and then pretty-print them"),
104 clEnumValN(ASTDump, "ast-dump",
105 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000106 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000107 "Build ASTs and view them with GraphViz"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000108 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000109 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000110 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000111 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000112 clEnumValN(EmitBC, "emit-llvm-bc",
113 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000114 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000115 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000116 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000117 "Rewrite ObjC into C (code rewriter example)"),
118 clEnumValN(RewriteMacros, "rewrite-macros",
119 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000120 clEnumValN(RewriteBlocks, "rewrite-blocks",
121 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000122 clEnumValEnd));
123
Ted Kremenekd01eae62007-12-19 19:47:59 +0000124
125static llvm::cl::opt<std::string>
126OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000127 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000128 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000129
130//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000131// Code Generator Options
132//===----------------------------------------------------------------------===//
133static llvm::cl::opt<bool>
134GenerateDebugInfo("g",
135 llvm::cl::desc("Generate source level debug information"));
136
137//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000138// Diagnostic Options
139//===----------------------------------------------------------------------===//
140
Ted Kremenek10389cf2007-09-26 19:42:19 +0000141static llvm::cl::opt<bool>
142VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000143 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000144
Ted Kremenekfd75e312008-03-27 06:17:42 +0000145static llvm::cl::opt<std::string>
146HTMLDiag("html-diags",
147 llvm::cl::desc("Generate HTML to report diagnostics"),
148 llvm::cl::value_desc("HTML directory"));
149
Nico Weber0e13eaa2008-08-05 23:33:20 +0000150static llvm::cl::opt<bool>
151NoShowColumn("fno-show-column",
152 llvm::cl::desc("Do not include column number on diagnostics"));
153
154static llvm::cl::opt<bool>
155NoCaretDiagnostics("fno-caret-diagnostics",
156 llvm::cl::desc("Do not include source line and caret with"
157 " diagnostics"));
158
159
Chris Lattner4b009652007-07-25 00:24:17 +0000160//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000161// Analyzer Options
162//===----------------------------------------------------------------------===//
163
164static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000165VisualizeEGDot("analyzer-viz-egraph-graphviz",
166 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000167
168static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000169VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
170 llvm::cl::desc("Display exploded graph using Ubigraph"));
171
172static llvm::cl::opt<bool>
173AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000174 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000175 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000176
Ted Kremenek81ea7992008-07-02 00:03:09 +0000177static llvm::cl::list<Analyses>
178AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
179llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000180#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000181clEnumValN(NAME, CMDFLAG, DESC),
182#include "Analyses.def"
183clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000184
Ted Kremenek517cb512008-04-14 18:40:58 +0000185//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000186// Language Options
187//===----------------------------------------------------------------------===//
188
189enum LangKind {
190 langkind_unspecified,
191 langkind_c,
192 langkind_c_cpp,
193 langkind_cxx,
194 langkind_cxx_cpp,
195 langkind_objc,
196 langkind_objc_cpp,
197 langkind_objcxx,
198 langkind_objcxx_cpp
199};
200
201/* TODO: GCC also accepts:
202 c-header c++-header objective-c-header objective-c++-header
203 assembler assembler-with-cpp
204 ada, f77*, ratfor (!), f95, java, treelang
205 */
206static llvm::cl::opt<LangKind>
207BaseLang("x", llvm::cl::desc("Base language to compile"),
208 llvm::cl::init(langkind_unspecified),
209 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
210 clEnumValN(langkind_cxx, "c++", "C++"),
211 clEnumValN(langkind_objc, "objective-c", "Objective C"),
212 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
213 clEnumValN(langkind_c_cpp, "c-cpp-output",
214 "Preprocessed C"),
215 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
216 "Preprocessed C++"),
217 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
218 "Preprocessed Objective C"),
219 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
220 "Preprocessed Objective C++"),
221 clEnumValEnd));
222
223static llvm::cl::opt<bool>
224LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
225 llvm::cl::Hidden);
226static llvm::cl::opt<bool>
227LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
228 llvm::cl::Hidden);
229
Ted Kremenek11ad8952007-12-05 23:49:08 +0000230/// InitializeBaseLanguage - Handle the -x foo options.
231static void InitializeBaseLanguage() {
232 if (LangObjC)
233 BaseLang = langkind_objc;
234 else if (LangObjCXX)
235 BaseLang = langkind_objcxx;
236}
237
238static LangKind GetLanguage(const std::string &Filename) {
239 if (BaseLang != langkind_unspecified)
240 return BaseLang;
241
242 std::string::size_type DotPos = Filename.rfind('.');
243
244 if (DotPos == std::string::npos) {
245 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000246 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000247 }
248
Ted Kremenek11ad8952007-12-05 23:49:08 +0000249 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
250 // C header: .h
251 // C++ header: .hh or .H;
252 // assembler no preprocessing: .s
253 // assembler: .S
254 if (Ext == "c")
255 return langkind_c;
256 else if (Ext == "i")
257 return langkind_c_cpp;
258 else if (Ext == "ii")
259 return langkind_cxx_cpp;
260 else if (Ext == "m")
261 return langkind_objc;
262 else if (Ext == "mi")
263 return langkind_objc_cpp;
264 else if (Ext == "mm" || Ext == "M")
265 return langkind_objcxx;
266 else if (Ext == "mii")
267 return langkind_objcxx_cpp;
268 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
269 Ext == "c++" || Ext == "cp" || Ext == "cxx")
270 return langkind_cxx;
271 else
272 return langkind_c;
273}
274
275
276static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000277 // FIXME: implement -fpreprocessed mode.
278 bool NoPreprocess = false;
279
Ted Kremenek11ad8952007-12-05 23:49:08 +0000280 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000281 default: assert(0 && "Unknown language kind!");
282 case langkind_c_cpp:
283 NoPreprocess = true;
284 // FALLTHROUGH
285 case langkind_c:
286 break;
287 case langkind_cxx_cpp:
288 NoPreprocess = true;
289 // FALLTHROUGH
290 case langkind_cxx:
291 Options.CPlusPlus = 1;
292 break;
293 case langkind_objc_cpp:
294 NoPreprocess = true;
295 // FALLTHROUGH
296 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000297 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000298 break;
299 case langkind_objcxx_cpp:
300 NoPreprocess = true;
301 // FALLTHROUGH
302 case langkind_objcxx:
303 Options.ObjC1 = Options.ObjC2 = 1;
304 Options.CPlusPlus = 1;
305 break;
306 }
307}
308
309/// LangStds - Language standards we support.
310enum LangStds {
311 lang_unspecified,
312 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000313 lang_gnu_START,
314 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000315 lang_cxx98, lang_gnucxx98,
316 lang_cxx0x, lang_gnucxx0x
317};
318
319static llvm::cl::opt<LangStds>
320LangStd("std", llvm::cl::desc("Language standard to compile for"),
321 llvm::cl::init(lang_unspecified),
322 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
323 clEnumValN(lang_c89, "c90", "ISO C 1990"),
324 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
325 clEnumValN(lang_c94, "iso9899:199409",
326 "ISO C 1990 with amendment 1"),
327 clEnumValN(lang_c99, "c99", "ISO C 1999"),
328// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
329 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
330// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
331 clEnumValN(lang_gnu89, "gnu89",
332 "ISO C 1990 with GNU extensions (default for C)"),
333 clEnumValN(lang_gnu99, "gnu99",
334 "ISO C 1999 with GNU extensions"),
335 clEnumValN(lang_gnu99, "gnu9x",
336 "ISO C 1999 with GNU extensions"),
337 clEnumValN(lang_cxx98, "c++98",
338 "ISO C++ 1998 with amendments"),
339 clEnumValN(lang_gnucxx98, "gnu++98",
340 "ISO C++ 1998 with amendments and GNU "
341 "extensions (default for C++)"),
342 clEnumValN(lang_cxx0x, "c++0x",
343 "Upcoming ISO C++ 200x with amendments"),
344 clEnumValN(lang_gnucxx0x, "gnu++0x",
345 "Upcoming ISO C++ 200x with amendments and GNU "
346 "extensions (default for C++)"),
347 clEnumValEnd));
348
349static llvm::cl::opt<bool>
350NoOperatorNames("fno-operator-names",
351 llvm::cl::desc("Do not treat C++ operator name keywords as "
352 "synonyms for operators"));
353
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000354static llvm::cl::opt<bool>
355PascalStrings("fpascal-strings",
356 llvm::cl::desc("Recognize and construct Pascal-style "
357 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000358
359static llvm::cl::opt<bool>
360MSExtensions("fms-extensions",
361 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000362 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000363
364static llvm::cl::opt<bool>
365WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000366 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000367
368static llvm::cl::opt<bool>
369LaxVectorConversions("flax-vector-conversions",
370 llvm::cl::desc("Allow implicit conversions between vectors"
371 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000372 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000373
Daniel Dunbar91692d92008-08-11 17:36:14 +0000374// FIXME: This (and all GCC -f options) really come in -f... and
375// -fno-... forms, and additionally support automagic behavior when
376// they are not defined. For example, -fexceptions defaults to on or
377// off depending on the language. We should support this behavior in
378// some form (perhaps just add a facility for distinguishing when an
379// has its default value from when it has been set to its default
380// value).
381static llvm::cl::opt<bool>
382Exceptions("fexceptions",
383 llvm::cl::desc("Enable support for exception handling."));
384
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000385static llvm::cl::opt<bool>
386GNURuntime("fgnu-runtime",
387 llvm::cl::desc("Generate output compatible with the standard GNU Objective-C runtime."));
388
389static llvm::cl::opt<bool>
390NeXTRuntime("fnext-runtime",
391 llvm::cl::desc("Generate output compatible with the NeXT runtime."));
392
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000393
394
395static llvm::cl::opt<bool>
396Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
397
398static llvm::cl::opt<bool>
399Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
400
Chris Lattner4b009652007-07-25 00:24:17 +0000401// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000402// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000403// -fpascal-strings
Daniel Dunbar34542952008-08-23 08:43:39 +0000404static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
405 TargetInfo *Target) {
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000406
407 if (Ansi) // "The -ansi option is equivalent to -std=c89."
408 LangStd = lang_c89;
409
Chris Lattner4b009652007-07-25 00:24:17 +0000410 if (LangStd == lang_unspecified) {
411 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000412 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000413 default: assert(0 && "Unknown base language");
414 case langkind_c:
415 case langkind_c_cpp:
416 case langkind_objc:
417 case langkind_objc_cpp:
418 LangStd = lang_gnu99;
419 break;
420 case langkind_cxx:
421 case langkind_cxx_cpp:
422 case langkind_objcxx:
423 case langkind_objcxx_cpp:
424 LangStd = lang_gnucxx98;
425 break;
426 }
427 }
428
429 switch (LangStd) {
430 default: assert(0 && "Unknown language standard!");
431
432 // Fall through from newer standards to older ones. This isn't really right.
433 // FIXME: Enable specifically the right features based on the language stds.
434 case lang_gnucxx0x:
435 case lang_cxx0x:
436 Options.CPlusPlus0x = 1;
437 // FALL THROUGH
438 case lang_gnucxx98:
439 case lang_cxx98:
440 Options.CPlusPlus = 1;
441 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000442 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000443 // FALL THROUGH.
444 case lang_gnu99:
445 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000446 Options.C99 = 1;
447 Options.HexFloats = 1;
448 // FALL THROUGH.
449 case lang_gnu89:
450 Options.BCPLComment = 1; // Only for C99/C++.
451 // FALL THROUGH.
452 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000453 Options.Digraphs = 1; // C94, C99, C++.
454 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000455 case lang_c89:
456 break;
457 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000458
459 if (Options.CPlusPlus) {
460 Options.C99 = 0;
461 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
462 }
Chris Lattner4b009652007-07-25 00:24:17 +0000463
Chris Lattner6ab935b2008-04-05 06:32:51 +0000464 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
465 Options.ImplicitInt = 1;
466 else
467 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000468
469 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
470 // is specified, or -std is set to a conforming mode.
471 Options.Trigraphs = LangStd < lang_gnu_START || Trigraphs ? 1 : 0;
472
Chris Lattner4b009652007-07-25 00:24:17 +0000473 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000474 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000475 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000476 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000477 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000478 Options.Exceptions = Exceptions;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000479
480 if (NeXTRuntime) {
481 Options.NeXTRuntime = 1;
482 } else if (GNURuntime) {
483 Options.NeXTRuntime = 0;
484 } else {
Daniel Dunbar34542952008-08-23 08:43:39 +0000485 Options.NeXTRuntime = Target->useNeXTRuntimeAsDefault();
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000486 }
Chris Lattner4b009652007-07-25 00:24:17 +0000487}
488
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000489static llvm::cl::opt<bool>
490ObjCExclusiveGC("fobjc-gc-only",
491 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000492 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000493
494static llvm::cl::opt<bool>
495ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000496 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000497
498void InitializeGCMode(LangOptions &Options) {
499 if (ObjCExclusiveGC)
500 Options.setGCMode(LangOptions::GCOnly);
501 else if (ObjCEnableGC)
502 Options.setGCMode(LangOptions::HybridGC);
503}
504
505
Chris Lattner4b009652007-07-25 00:24:17 +0000506//===----------------------------------------------------------------------===//
507// Our DiagnosticClient implementation
508//===----------------------------------------------------------------------===//
509
510// FIXME: Werror should take a list of things, -Werror=foo,bar
511static llvm::cl::opt<bool>
512WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
513
514static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000515SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
516
517static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000518WarnOnExtensions("pedantic", llvm::cl::init(false),
519 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
520
521static llvm::cl::opt<bool>
522ErrorOnExtensions("pedantic-errors",
523 llvm::cl::desc("Issue an error on uses of GCC extensions"));
524
525static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000526SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000527 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000528 llvm::cl::init(true));
529
530static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000531WarnUnusedMacros("Wunused_macros",
532 llvm::cl::desc("Warn for unused macros in the main translation unit"));
533
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000534static llvm::cl::opt<bool>
535WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000536 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000537
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000538static llvm::cl::opt<bool>
539WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000540 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000541
Chris Lattnera616ee32008-01-23 17:19:46 +0000542static llvm::cl::opt<bool>
543WarnUndefMacros("Wundef",
544 llvm::cl::desc("Warn on use of undefined macros in #if's"));
545
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000546static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000547WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
548 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000549
Chris Lattner4b009652007-07-25 00:24:17 +0000550/// InitializeDiagnostics - Initialize the diagnostic object, based on the
551/// current command line option settings.
552static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000553 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000554 Diags.setWarningsAsErrors(WarningsAsErrors);
555 Diags.setWarnOnExtensions(WarnOnExtensions);
556 Diags.setErrorOnExtensions(ErrorOnExtensions);
557
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000558 // Suppress warnings in system headers unless requested not to.
559 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
560
Chris Lattner4b009652007-07-25 00:24:17 +0000561 // Silence the "macro is not used" warning unless requested.
562 if (!WarnUnusedMacros)
563 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000564
565 // Silence "floating point comparison" warnings unless requested.
566 if (!WarnFloatEqual)
567 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000568
569 // Silence "format string is not a string literal" warnings if requested
570 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000571 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
572 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000573 if (!WarnUndefMacros)
574 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000575
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000576 if (!WarnImplicitFunctionDeclaration)
577 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
578 diag::MAP_IGNORE);
579
Steve Naroff606f7072008-02-11 22:40:08 +0000580 if (MSExtensions) // MS allows unnamed struct/union fields.
581 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000582
583 // If -pedantic-errors is set, turn extensions that warn by default into
584 // errors.
585 if (ErrorOnExtensions) {
586 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
587 diag::MAP_ERROR);
588 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
589 diag::MAP_ERROR);
590 }
Chris Lattner4b009652007-07-25 00:24:17 +0000591}
592
593//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000594// Analysis-specific options.
595//===----------------------------------------------------------------------===//
596
597static llvm::cl::opt<std::string>
598AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000599 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000600
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000601static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000602TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000603 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000604
Ted Kremenek0118bb52008-02-18 21:21:23 +0000605//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000606// Target Triple Processing.
607//===----------------------------------------------------------------------===//
608
609static llvm::cl::opt<std::string>
610TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000611 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000612
Chris Lattnerfc457002008-03-05 01:18:20 +0000613static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000614Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000615
Chris Lattner2b168e02008-09-30 01:13:12 +0000616static llvm::cl::opt<std::string>
617MacOSVersionMin("mmacosx-version-min",
618 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
619
Chris Lattner01de9c82008-09-30 20:16:56 +0000620// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
621// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
622static void HandleMacOSVersionMin(std::string &Triple) {
623 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
624 if (DarwinDashIdx == std::string::npos) {
625 fprintf(stderr,
626 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
627 exit(1);
628 }
629 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
630
Chris Lattner01de9c82008-09-30 20:16:56 +0000631 // Remove the number.
632 Triple.resize(DarwinNumIdx);
633
634 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
635 bool MacOSVersionMinIsInvalid = false;
636 int VersionNum = 0;
637 if (MacOSVersionMin.size() < 4 ||
638 MacOSVersionMin.substr(0, 3) != "10." ||
639 !isdigit(MacOSVersionMin[3])) {
640 MacOSVersionMinIsInvalid = true;
641 } else {
642 const char *Start = MacOSVersionMin.c_str()+3;
643 char *End = 0;
644 VersionNum = (int)strtol(Start, &End, 10);
645
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000646 // The version number must be in the range 0-9.
647 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
648
Chris Lattner01de9c82008-09-30 20:16:56 +0000649 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
650 Triple += llvm::itostr(VersionNum+4);
651
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000652 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
653 // Add the period piece (.7) to the end of the triple. This gives us
654 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000655 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000656 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
657 MacOSVersionMinIsInvalid = true;
658 }
659 }
660
661 if (MacOSVersionMinIsInvalid) {
662 fprintf(stderr,
663 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
664 MacOSVersionMin.c_str());
665 exit(1);
666 }
667}
668
669/// CreateTargetTriple - Process the various options that affect the target
670/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000671static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000672 // Initialize base triple. If a -triple option has been specified, use
673 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000674 std::string Triple = TargetTriple;
675 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenek40499482007-12-03 22:06:55 +0000676
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000677 // If -arch foo was specified, remove the architecture from the triple we have
678 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000679 if (!Arch.empty()) {
680 // Decompose the base triple into "arch" and suffix.
681 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000682
Chris Lattner2b168e02008-09-30 01:13:12 +0000683 if (FirstDashIdx == std::string::npos) {
684 fprintf(stderr,
685 "Malformed target triple: \"%s\" ('-' could not be found).\n",
686 Triple.c_str());
687 exit(1);
688 }
Ted Kremenek40499482007-12-03 22:06:55 +0000689
Chris Lattner2b168e02008-09-30 01:13:12 +0000690 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
691 }
692
693 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
694 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000695 if (!MacOSVersionMin.empty())
696 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000697
Chris Lattner2b168e02008-09-30 01:13:12 +0000698 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000699}
700
701//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000702// Preprocessor Initialization
703//===----------------------------------------------------------------------===//
704
705// FIXME: Preprocessor builtins to support.
706// -A... - Play with #assertions
707// -undef - Undefine all predefined macros
708
709static llvm::cl::list<std::string>
710D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
711 llvm::cl::desc("Predefine the specified macro"));
712static llvm::cl::list<std::string>
713U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
714 llvm::cl::desc("Undefine the specified macro"));
715
Chris Lattner008da782008-01-10 01:53:41 +0000716static llvm::cl::list<std::string>
717ImplicitIncludes("include", llvm::cl::value_desc("file"),
718 llvm::cl::desc("Include file before parsing"));
719
720
Chris Lattner4b009652007-07-25 00:24:17 +0000721// Append a #define line to Buf for Macro. Macro should be of the form XXX,
722// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
723// "#define XXX Y z W". To get a #define with no value, use "XXX=".
724static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
725 const char *Command = "#define ") {
726 Buf.insert(Buf.end(), Command, Command+strlen(Command));
727 if (const char *Equal = strchr(Macro, '=')) {
728 // Turn the = into ' '.
729 Buf.insert(Buf.end(), Macro, Equal);
730 Buf.push_back(' ');
731 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
732 } else {
733 // Push "macroname 1".
734 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
735 Buf.push_back(' ');
736 Buf.push_back('1');
737 }
738 Buf.push_back('\n');
739}
740
Chris Lattner008da782008-01-10 01:53:41 +0000741/// AddImplicitInclude - Add an implicit #include of the specified file to the
742/// predefines buffer.
743static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
744 const char *Inc = "#include \"";
745 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
746 Buf.insert(Buf.end(), File.begin(), File.end());
747 Buf.push_back('"');
748 Buf.push_back('\n');
749}
750
Chris Lattner4b009652007-07-25 00:24:17 +0000751
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000752/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000753/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000754///
Chris Lattner9d818a22008-04-19 23:25:44 +0000755static bool InitializePreprocessor(Preprocessor &PP,
756 bool InitializeSourceMgr,
757 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000758 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000759
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000760 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000761 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000762
763 if (InitializeSourceMgr) {
764 if (InFile != "-") {
765 const FileEntry *File = FileMgr.getFile(InFile);
766 if (File) SourceMgr.createMainFileID(File, SourceLocation());
767 if (SourceMgr.getMainFileID() == 0) {
768 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000769 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000770 }
771 } else {
772 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
773 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
774 if (SourceMgr.getMainFileID() == 0) {
775 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000776 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000777 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000778 }
Chris Lattner4b009652007-07-25 00:24:17 +0000779 }
Sam Bishop61a20782008-04-14 14:41:57 +0000780
Chris Lattner47b6a162008-04-19 23:09:31 +0000781 std::vector<char> PredefineBuffer;
782
Chris Lattner4b009652007-07-25 00:24:17 +0000783 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000784 unsigned d = 0, D = D_macros.size();
785 unsigned u = 0, U = U_macros.size();
786 while (d < D || u < U) {
787 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
788 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
789 else
790 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
791 }
792
Chris Lattner008da782008-01-10 01:53:41 +0000793 // FIXME: Read any files specified by -imacros.
794
795 // Add implicit #includes from -include.
796 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
797 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000798
Chris Lattner47b6a162008-04-19 23:09:31 +0000799 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000800 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000801 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000802
803 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000804 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000805}
806
807//===----------------------------------------------------------------------===//
808// Preprocessor include path information.
809//===----------------------------------------------------------------------===//
810
811// This tool exports a large number of command line options to control how the
812// preprocessor searches for header files. At root, however, the Preprocessor
813// object takes a very simple interface: a list of directories to search for
814//
815// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000816// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000817//
Chris Lattner008da782008-01-10 01:53:41 +0000818// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000819
820static llvm::cl::opt<bool>
821nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
822
823// Various command line options. These four add directories to each chain.
824static llvm::cl::list<std::string>
825F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
826 llvm::cl::desc("Add directory to framework include search path"));
827static llvm::cl::list<std::string>
828I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
829 llvm::cl::desc("Add directory to include search path"));
830static llvm::cl::list<std::string>
831idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
832 llvm::cl::desc("Add directory to AFTER include search path"));
833static llvm::cl::list<std::string>
834iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
835 llvm::cl::desc("Add directory to QUOTE include search path"));
836static llvm::cl::list<std::string>
837isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
838 llvm::cl::desc("Add directory to SYSTEM include search path"));
839
840// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
841static llvm::cl::list<std::string>
842iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
843 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
844static llvm::cl::list<std::string>
845iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
846 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
847static llvm::cl::list<std::string>
848iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
849 llvm::cl::Prefix,
850 llvm::cl::desc("Set directory to include search path with prefix"));
851
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000852static llvm::cl::opt<std::string>
853isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
854 llvm::cl::desc("Set the system root directory (usually /)"));
855
Chris Lattner4b009652007-07-25 00:24:17 +0000856// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000857
Chris Lattner4b009652007-07-25 00:24:17 +0000858/// InitializeIncludePaths - Process the -I options and set them in the
859/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000860void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
861 FileManager &FM, const LangOptions &Lang) {
862 InitHeaderSearch Init(Headers, Verbose, isysroot);
863
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000864 // Handle -I... and -F... options, walking the lists in parallel.
865 unsigned Iidx = 0, Fidx = 0;
866 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
867 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +0000868 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000869 ++Iidx;
870 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000871 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000872 ++Fidx;
873 }
874 }
Chris Lattner4b009652007-07-25 00:24:17 +0000875
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000876 // Consume what's left from whatever list was longer.
877 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +0000878 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000879 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +0000880 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000881
882 // Handle -idirafter... options.
883 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000884 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
885 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000886
887 // Handle -iquote... options.
888 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000889 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000890
891 // Handle -isystem... options.
892 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000893 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000894
895 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
896 // parallel, processing the values in order of occurance to get the right
897 // prefixes.
898 {
899 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
900 unsigned iprefix_idx = 0;
901 unsigned iwithprefix_idx = 0;
902 unsigned iwithprefixbefore_idx = 0;
903 bool iprefix_done = iprefix_vals.empty();
904 bool iwithprefix_done = iwithprefix_vals.empty();
905 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
906 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
907 if (!iprefix_done &&
908 (iwithprefix_done ||
909 iprefix_vals.getPosition(iprefix_idx) <
910 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
911 (iwithprefixbefore_done ||
912 iprefix_vals.getPosition(iprefix_idx) <
913 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
914 Prefix = iprefix_vals[iprefix_idx];
915 ++iprefix_idx;
916 iprefix_done = iprefix_idx == iprefix_vals.size();
917 } else if (!iwithprefix_done &&
918 (iwithprefixbefore_done ||
919 iwithprefix_vals.getPosition(iwithprefix_idx) <
920 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +0000921 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
922 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000923 ++iwithprefix_idx;
924 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
925 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000926 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
927 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000928 ++iwithprefixbefore_idx;
929 iwithprefixbefore_done =
930 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
931 }
932 }
933 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000934
Nico Weber770e3882008-08-22 09:25:22 +0000935 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +0000936
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000937 // Add the clang headers, which are relative to the clang driver.
938 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000939 llvm::sys::Path::GetMainExecutable(Argv0,
940 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000941 if (!MainExecutablePath.isEmpty()) {
942 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
943 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
944 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +0000945 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
946 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000947 }
948
Nico Weber770e3882008-08-22 09:25:22 +0000949 if (!nostdinc)
950 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +0000951
952 // Now that we have collected all of the include paths, merge them all
953 // together and tell the preprocessor about them.
954
Nico Weber770e3882008-08-22 09:25:22 +0000955 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +0000956}
957
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000958//===----------------------------------------------------------------------===//
959// Driver PreprocessorFactory - For lazily generating preprocessors ...
960//===----------------------------------------------------------------------===//
961
962namespace {
963class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000964 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000965 Diagnostic &Diags;
966 const LangOptions &LangInfo;
967 TargetInfo &Target;
968 SourceManager &SourceMgr;
969 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000970 bool InitializeSourceMgr;
971
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000972public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000973 DriverPreprocessorFactory(const std::string &infile,
974 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000975 TargetInfo &target, SourceManager &SM,
976 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000977 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
978 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
979
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000980
981 virtual ~DriverPreprocessorFactory() {}
982
983 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000984 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
985 SourceMgr, HeaderInfo);
986
Chris Lattner9d818a22008-04-19 23:25:44 +0000987 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000988 delete PP;
989 return NULL;
990 }
991
992 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000993 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000994 }
995};
996}
Chris Lattner4b009652007-07-25 00:24:17 +0000997
Chris Lattner4b009652007-07-25 00:24:17 +0000998//===----------------------------------------------------------------------===//
999// Basic Parser driver
1000//===----------------------------------------------------------------------===//
1001
Chris Lattner9d818a22008-04-19 23:25:44 +00001002static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001003 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001004 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001005
1006 // Parsing the specified input file.
1007 P.ParseTranslationUnit();
1008 delete PA;
Argiris Kirtzidis8d833762008-06-13 12:15:34 +00001009
1010 if (VerifyDiagnostics)
1011 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001012}
1013
1014//===----------------------------------------------------------------------===//
1015// Main driver
1016//===----------------------------------------------------------------------===//
1017
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001018/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1019/// action. These consumers can operate on both ASTs that are freshly
1020/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001021static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001022 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001023 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001024 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001025 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001026 switch (ProgAction) {
1027 default:
1028 return NULL;
1029
1030 case ASTPrint:
1031 return CreateASTPrinter();
1032
1033 case ASTDump:
1034 return CreateASTDumper();
1035
1036 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001037 return CreateASTViewer();
1038
1039 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001040 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001041
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001042 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001043 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001044
1045 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001046 case EmitBC:
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001047 return CreateLLVMCodeGenWriter(ProgAction == EmitBC, Diag, LangOpts,
1048 InFile, OutputFile, GenerateDebugInfo);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001049
Ted Kremenekbde30332007-12-19 17:25:59 +00001050 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001051 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001052 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001053
Steve Naroff44e81222008-04-14 22:03:09 +00001054 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001055 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001056
1057 case RewriteBlocks:
1058 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001059
1060 case RunAnalysis:
1061 assert (!AnalysisList.empty());
1062 return CreateAnalysisConsumer(&AnalysisList[0],
1063 &AnalysisList[0]+AnalysisList.size(),
1064 Diag, PP, PPF, LangOpts,
1065 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001066 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1067 TrimGraph, AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001068 }
1069}
1070
Chris Lattner4b009652007-07-25 00:24:17 +00001071/// ProcessInputFile - Process a single input file with the specified state.
1072///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001073static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1074 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001075
Ted Kremenek50aab982008-08-08 02:46:37 +00001076 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001077 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001078
Chris Lattner4b009652007-07-25 00:24:17 +00001079 switch (ProgAction) {
1080 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001081 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1082 PP.getFileManager(), PP.getLangOptions(),
1083 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001084
1085 if (!Consumer) {
1086 fprintf(stderr, "Unexpected program action!\n");
1087 return;
1088 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001089
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001090 break;
1091
Chris Lattner4b009652007-07-25 00:24:17 +00001092 case DumpTokens: { // Token dump mode.
1093 Token Tok;
1094 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001095 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001096 do {
1097 PP.Lex(Tok);
1098 PP.DumpToken(Tok, true);
1099 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001100 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001101 ClearSourceMgr = true;
1102 break;
1103 }
1104 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1105 Token Tok;
1106 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001107 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001108 do {
1109 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001110 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001111 ClearSourceMgr = true;
1112 break;
1113 }
1114
1115 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001116 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001117 ClearSourceMgr = true;
1118 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001119
Chris Lattner4b009652007-07-25 00:24:17 +00001120 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001121 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001122 ClearSourceMgr = true;
1123 break;
1124
1125 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001126 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001127 ClearSourceMgr = true;
1128 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001129
Ted Kremenek6856c632007-09-26 18:39:29 +00001130 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001131 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001132 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001133
1134 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001135 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001136 ClearSourceMgr = true;
1137 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001138 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001139
1140 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001141 if (VerifyDiagnostics)
Ted Kremenek50aab982008-08-08 02:46:37 +00001142 exit(CheckASTConsumer(PP, Consumer.get()));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001143
Ted Kremenek50aab982008-08-08 02:46:37 +00001144 ParseAST(PP, Consumer.get(), Stats);
Chris Lattner4b009652007-07-25 00:24:17 +00001145 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001146
Chris Lattner4b009652007-07-25 00:24:17 +00001147 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001148 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001149 PP.PrintStats();
1150 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001151 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001152 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001153 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001154 fprintf(stderr, "\n");
1155 }
1156
1157 // For a multi-file compilation, some things are ok with nuking the source
1158 // manager tables, other require stable fileid/macroid's across multiple
1159 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001160 if (ClearSourceMgr)
1161 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001162}
1163
Ted Kremenek80d53372007-12-12 23:41:08 +00001164static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1165 FileManager& FileMgr) {
1166
1167 if (VerifyDiagnostics) {
1168 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1169 exit (1);
1170 }
1171
1172 llvm::sys::Path Filename(InFile);
1173
1174 if (!Filename.isValid()) {
1175 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1176 exit (1);
1177 }
1178
Ted Kremenek863b01f2008-04-23 16:25:39 +00001179 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001180
1181 if (!TU) {
1182 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1183 InFile.c_str());
1184 exit (1);
1185 }
1186
Ted Kremenekab749372007-12-19 19:27:38 +00001187 // Observe that we use the source file name stored in the deserialized
1188 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001189 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001190 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001191 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001192
Ted Kremenek80d53372007-12-12 23:41:08 +00001193 if (!Consumer) {
1194 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1195 exit (1);
1196 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001197
Ted Kremenek863b01f2008-04-23 16:25:39 +00001198 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001199
Chris Lattner8d72ee02008-02-06 01:42:25 +00001200 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001201 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1202 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001203}
1204
1205
Chris Lattner4b009652007-07-25 00:24:17 +00001206static llvm::cl::list<std::string>
1207InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1208
Ted Kremenek80d53372007-12-12 23:41:08 +00001209static bool isSerializedFile(const std::string& InFile) {
1210 if (InFile.size() < 4)
1211 return false;
1212
1213 const char* s = InFile.c_str()+InFile.size()-4;
1214
1215 return s[0] == '.' &&
1216 s[1] == 'a' &&
1217 s[2] == 's' &&
1218 s[3] == 't';
1219}
1220
Chris Lattner4b009652007-07-25 00:24:17 +00001221
1222int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001223 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001224 llvm::sys::PrintStackTraceOnErrorSignal();
1225
1226 // If no input was specified, read from stdin.
1227 if (InputFilenames.empty())
1228 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001229
Chris Lattner4b009652007-07-25 00:24:17 +00001230 // Create a file manager object to provide access to and cache the filesystem.
1231 FileManager FileMgr;
1232
Ted Kremenekb240e822007-12-11 23:28:38 +00001233 // Create the diagnostic client for reporting errors or for
1234 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001235 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001236
Ted Kremenek5c341732008-08-07 17:49:57 +00001237 if (!VerifyDiagnostics) {
1238 // Print diagnostics to stderr by default.
1239 TextDiagClient = new TextDiagnosticPrinter(!NoShowColumn,
1240 !NoCaretDiagnostics);
1241 } else {
1242 // When checking diagnostics, just buffer them up.
1243 TextDiagClient = new TextDiagnosticBuffer();
1244
1245 if (InputFilenames.size() != 1) {
1246 fprintf(stderr,
1247 "-verify only works on single input files for now.\n");
1248 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001249 }
1250 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001251
Chris Lattner4b009652007-07-25 00:24:17 +00001252 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001253 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1254 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001255 InitializeDiagnostics(Diags);
1256
Chris Lattner45a56e02007-12-05 23:24:17 +00001257 // -I- is a deprecated GCC feature, scan for it and reject it.
1258 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1259 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001260 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001261 I_dirs.erase(I_dirs.begin()+i);
1262 --i;
1263 }
1264 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001265
1266 // Get information about the target being compiled for.
1267 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001268 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1269
Chris Lattner2c77d852008-03-14 06:12:05 +00001270 if (Target == 0) {
1271 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1272 Triple.c_str());
1273 fprintf(stderr, "Please use -triple or -arch.\n");
1274 exit(1);
1275 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001276
Ted Kremenek81ea7992008-07-02 00:03:09 +00001277 // Are we invoking one or more source analyses?
1278 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1279 ProgAction = RunAnalysis;
Ted Kremenek5c341732008-08-07 17:49:57 +00001280
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001281 llvm::OwningPtr<SourceManager> SourceMgr;
1282
Chris Lattner4b009652007-07-25 00:24:17 +00001283 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001284 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001285
Ted Kremenek5c341732008-08-07 17:49:57 +00001286 if (isSerializedFile(InFile)) {
1287 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001288 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001289 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001290 else {
1291 /// Create a SourceManager object. This tracks and owns all the file
1292 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001293 if (!SourceMgr)
1294 SourceMgr.reset(new SourceManager());
1295 else
1296 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001297
Ted Kremenek80d53372007-12-12 23:41:08 +00001298 // Initialize language options, inferring file types from input filenames.
1299 LangOptions LangInfo;
1300 InitializeBaseLanguage();
1301 LangKind LK = GetLanguage(InFile);
1302 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar34542952008-08-23 08:43:39 +00001303 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001304 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001305
1306 // Process the -I options and set them in the HeaderInfo.
1307 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001308
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001309 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001310
Ted Kremenek80d53372007-12-12 23:41:08 +00001311 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001312 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001313 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001314
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001315 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1316
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001317 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001318 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001319
1320 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1321 // always reset to using TextDiagClient.
1322 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001323
Ted Kremenek5c341732008-08-07 17:49:57 +00001324 if (!HTMLDiag.empty()) {
1325 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1326 &PPFactory));
1327 Diags.setClient(TmpClient.get());
1328 }
1329 else
1330 Diags.setClient(TextDiagClient);
1331
1332 // Process the source file.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001333 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001334 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001335
1336 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001337 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001338 }
Chris Lattner4b009652007-07-25 00:24:17 +00001339 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001340
Ted Kremenekec6c5252008-08-07 18:13:12 +00001341 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001342 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1343 (NumDiagnostics == 1 ? "" : "s"));
1344
1345 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001346 FileMgr.PrintStats();
1347 fprintf(stderr, "\n");
1348 }
1349
1350 return Diags.getNumErrors() != 0;
1351}