blob: 91d521246ab3e464f5a8078f2239420f6dce2bfa [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"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000048#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000049#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000050#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000051using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Global options.
55//===----------------------------------------------------------------------===//
56
Daniel Dunbar70a66b12008-10-04 23:42:49 +000057bool HadErrors = false;
58
Chris Lattner4b009652007-07-25 00:24:17 +000059static llvm::cl::opt<bool>
60Verbose("v", llvm::cl::desc("Enable verbose output"));
61static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000062Stats("print-stats",
63 llvm::cl::desc("Print performance metrics and statistics"));
Chris Lattner4b009652007-07-25 00:24:17 +000064
65enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000066 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000067 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000068 RewriteMacros, // Expand macros but not #includes.
Ted Kremeneke1a79d82008-03-19 07:53:42 +000069 HTMLTest, // HTML displayer testing stuff.
Chris Lattner4b009652007-07-25 00:24:17 +000070 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000071 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000072 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000073 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000074 ASTPrint, // Parse ASTs and print them.
75 ASTDump, // Parse ASTs and dump them.
76 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000077 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000078 ParsePrintCallbacks, // Parse and print each callback.
79 ParseSyntaxOnly, // Parse and perform semantic analysis.
80 ParseNoop, // Parse with noop callbacks.
81 RunPreprocessorOnly, // Just lex, no output.
82 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000083 DumpTokens, // Dump out preprocessed tokens.
84 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek81ea7992008-07-02 00:03:09 +000085 RunAnalysis // Run one or more source code analyses.
Chris Lattner4b009652007-07-25 00:24:17 +000086};
87
88static llvm::cl::opt<ProgActions>
89ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
90 llvm::cl::init(ParseSyntaxOnly),
91 llvm::cl::values(
92 clEnumValN(RunPreprocessorOnly, "Eonly",
93 "Just run preprocessor, no output (for timings)"),
94 clEnumValN(PrintPreprocessedInput, "E",
95 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +000096 clEnumValN(DumpRawTokens, "dump-raw-tokens",
97 "Lex file in raw mode and dump raw tokens"),
98 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +000099 "Run preprocessor, dump internal rep of tokens"),
100 clEnumValN(ParseNoop, "parse-noop",
101 "Run parser with noop callbacks (for timings)"),
102 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
103 "Run parser and perform semantic analysis"),
104 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
105 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000106 clEnumValN(EmitHTML, "emit-html",
107 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000108 clEnumValN(ASTPrint, "ast-print",
109 "Build ASTs and then pretty-print them"),
110 clEnumValN(ASTDump, "ast-dump",
111 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000112 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000113 "Build ASTs and view them with GraphViz"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000114 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000115 "Run prototype serialization code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000116 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000117 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000118 clEnumValN(EmitBC, "emit-llvm-bc",
119 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000120 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000121 "Build ASTs and emit .ast file"),
Steve Naroff44e81222008-04-14 22:03:09 +0000122 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000123 "Rewrite ObjC into C (code rewriter example)"),
124 clEnumValN(RewriteMacros, "rewrite-macros",
125 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000126 clEnumValN(RewriteBlocks, "rewrite-blocks",
127 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000128 clEnumValEnd));
129
Ted Kremenekd01eae62007-12-19 19:47:59 +0000130
131static llvm::cl::opt<std::string>
132OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000133 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000134 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000135
136//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000137// Code Generator Options
138//===----------------------------------------------------------------------===//
139static llvm::cl::opt<bool>
140GenerateDebugInfo("g",
141 llvm::cl::desc("Generate source level debug information"));
142
143//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000144// Diagnostic Options
145//===----------------------------------------------------------------------===//
146
Ted Kremenek10389cf2007-09-26 19:42:19 +0000147static llvm::cl::opt<bool>
148VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000149 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000150
Ted Kremenekfd75e312008-03-27 06:17:42 +0000151static llvm::cl::opt<std::string>
152HTMLDiag("html-diags",
153 llvm::cl::desc("Generate HTML to report diagnostics"),
154 llvm::cl::value_desc("HTML directory"));
155
Nico Weber0e13eaa2008-08-05 23:33:20 +0000156static llvm::cl::opt<bool>
157NoShowColumn("fno-show-column",
158 llvm::cl::desc("Do not include column number on diagnostics"));
159
160static llvm::cl::opt<bool>
161NoCaretDiagnostics("fno-caret-diagnostics",
162 llvm::cl::desc("Do not include source line and caret with"
163 " diagnostics"));
164
165
Chris Lattner4b009652007-07-25 00:24:17 +0000166//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000167// Analyzer Options
168//===----------------------------------------------------------------------===//
169
170static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000171VisualizeEGDot("analyzer-viz-egraph-graphviz",
172 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000173
174static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000175VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
176 llvm::cl::desc("Display exploded graph using Ubigraph"));
177
178static llvm::cl::opt<bool>
179AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000180 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000181 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000182
Ted Kremenek81ea7992008-07-02 00:03:09 +0000183static llvm::cl::list<Analyses>
184AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
185llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000186#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000187clEnumValN(NAME, CMDFLAG, DESC),
188#include "Analyses.def"
189clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000190
Ted Kremenek517cb512008-04-14 18:40:58 +0000191//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000192// Language Options
193//===----------------------------------------------------------------------===//
194
195enum LangKind {
196 langkind_unspecified,
197 langkind_c,
198 langkind_c_cpp,
199 langkind_cxx,
200 langkind_cxx_cpp,
201 langkind_objc,
202 langkind_objc_cpp,
203 langkind_objcxx,
204 langkind_objcxx_cpp
205};
206
207/* TODO: GCC also accepts:
208 c-header c++-header objective-c-header objective-c++-header
209 assembler assembler-with-cpp
210 ada, f77*, ratfor (!), f95, java, treelang
211 */
212static llvm::cl::opt<LangKind>
213BaseLang("x", llvm::cl::desc("Base language to compile"),
214 llvm::cl::init(langkind_unspecified),
215 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
216 clEnumValN(langkind_cxx, "c++", "C++"),
217 clEnumValN(langkind_objc, "objective-c", "Objective C"),
218 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
219 clEnumValN(langkind_c_cpp, "c-cpp-output",
220 "Preprocessed C"),
221 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
222 "Preprocessed C++"),
223 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
224 "Preprocessed Objective C"),
225 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
226 "Preprocessed Objective C++"),
227 clEnumValEnd));
228
229static llvm::cl::opt<bool>
230LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
231 llvm::cl::Hidden);
232static llvm::cl::opt<bool>
233LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
234 llvm::cl::Hidden);
235
Ted Kremenek11ad8952007-12-05 23:49:08 +0000236/// InitializeBaseLanguage - Handle the -x foo options.
237static void InitializeBaseLanguage() {
238 if (LangObjC)
239 BaseLang = langkind_objc;
240 else if (LangObjCXX)
241 BaseLang = langkind_objcxx;
242}
243
244static LangKind GetLanguage(const std::string &Filename) {
245 if (BaseLang != langkind_unspecified)
246 return BaseLang;
247
248 std::string::size_type DotPos = Filename.rfind('.');
249
250 if (DotPos == std::string::npos) {
251 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000252 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000253 }
254
Ted Kremenek11ad8952007-12-05 23:49:08 +0000255 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
256 // C header: .h
257 // C++ header: .hh or .H;
258 // assembler no preprocessing: .s
259 // assembler: .S
260 if (Ext == "c")
261 return langkind_c;
262 else if (Ext == "i")
263 return langkind_c_cpp;
264 else if (Ext == "ii")
265 return langkind_cxx_cpp;
266 else if (Ext == "m")
267 return langkind_objc;
268 else if (Ext == "mi")
269 return langkind_objc_cpp;
270 else if (Ext == "mm" || Ext == "M")
271 return langkind_objcxx;
272 else if (Ext == "mii")
273 return langkind_objcxx_cpp;
274 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
275 Ext == "c++" || Ext == "cp" || Ext == "cxx")
276 return langkind_cxx;
277 else
278 return langkind_c;
279}
280
281
282static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000283 // FIXME: implement -fpreprocessed mode.
284 bool NoPreprocess = false;
285
Ted Kremenek11ad8952007-12-05 23:49:08 +0000286 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000287 default: assert(0 && "Unknown language kind!");
288 case langkind_c_cpp:
289 NoPreprocess = true;
290 // FALLTHROUGH
291 case langkind_c:
292 break;
293 case langkind_cxx_cpp:
294 NoPreprocess = true;
295 // FALLTHROUGH
296 case langkind_cxx:
297 Options.CPlusPlus = 1;
298 break;
299 case langkind_objc_cpp:
300 NoPreprocess = true;
301 // FALLTHROUGH
302 case langkind_objc:
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000303 Options.ObjC1 = Options.ObjC2 = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000304 break;
305 case langkind_objcxx_cpp:
306 NoPreprocess = true;
307 // FALLTHROUGH
308 case langkind_objcxx:
309 Options.ObjC1 = Options.ObjC2 = 1;
310 Options.CPlusPlus = 1;
311 break;
312 }
313}
314
315/// LangStds - Language standards we support.
316enum LangStds {
317 lang_unspecified,
318 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000319 lang_gnu_START,
320 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000321 lang_cxx98, lang_gnucxx98,
322 lang_cxx0x, lang_gnucxx0x
323};
324
325static llvm::cl::opt<LangStds>
326LangStd("std", llvm::cl::desc("Language standard to compile for"),
327 llvm::cl::init(lang_unspecified),
328 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
329 clEnumValN(lang_c89, "c90", "ISO C 1990"),
330 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
331 clEnumValN(lang_c94, "iso9899:199409",
332 "ISO C 1990 with amendment 1"),
333 clEnumValN(lang_c99, "c99", "ISO C 1999"),
334// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
335 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
336// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
337 clEnumValN(lang_gnu89, "gnu89",
338 "ISO C 1990 with GNU extensions (default for C)"),
339 clEnumValN(lang_gnu99, "gnu99",
340 "ISO C 1999 with GNU extensions"),
341 clEnumValN(lang_gnu99, "gnu9x",
342 "ISO C 1999 with GNU extensions"),
343 clEnumValN(lang_cxx98, "c++98",
344 "ISO C++ 1998 with amendments"),
345 clEnumValN(lang_gnucxx98, "gnu++98",
346 "ISO C++ 1998 with amendments and GNU "
347 "extensions (default for C++)"),
348 clEnumValN(lang_cxx0x, "c++0x",
349 "Upcoming ISO C++ 200x with amendments"),
350 clEnumValN(lang_gnucxx0x, "gnu++0x",
351 "Upcoming ISO C++ 200x with amendments and GNU "
352 "extensions (default for C++)"),
353 clEnumValEnd));
354
355static llvm::cl::opt<bool>
356NoOperatorNames("fno-operator-names",
357 llvm::cl::desc("Do not treat C++ operator name keywords as "
358 "synonyms for operators"));
359
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000360static llvm::cl::opt<bool>
361PascalStrings("fpascal-strings",
362 llvm::cl::desc("Recognize and construct Pascal-style "
363 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000364
365static llvm::cl::opt<bool>
366MSExtensions("fms-extensions",
367 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000368 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000369
370static llvm::cl::opt<bool>
371WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000372 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000373
374static llvm::cl::opt<bool>
375LaxVectorConversions("flax-vector-conversions",
376 llvm::cl::desc("Allow implicit conversions between vectors"
377 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000378 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000379
Daniel Dunbar91692d92008-08-11 17:36:14 +0000380// FIXME: This (and all GCC -f options) really come in -f... and
381// -fno-... forms, and additionally support automagic behavior when
382// they are not defined. For example, -fexceptions defaults to on or
383// off depending on the language. We should support this behavior in
384// some form (perhaps just add a facility for distinguishing when an
385// has its default value from when it has been set to its default
386// value).
387static llvm::cl::opt<bool>
388Exceptions("fexceptions",
389 llvm::cl::desc("Enable support for exception handling."));
390
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000391static llvm::cl::opt<bool>
392GNURuntime("fgnu-runtime",
393 llvm::cl::desc("Generate output compatible with the standard GNU Objective-C runtime."));
394
395static llvm::cl::opt<bool>
396NeXTRuntime("fnext-runtime",
397 llvm::cl::desc("Generate output compatible with the NeXT runtime."));
398
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000399
400
401static llvm::cl::opt<bool>
402Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
403
404static llvm::cl::opt<bool>
405Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
406
Chris Lattner4b009652007-07-25 00:24:17 +0000407// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000408// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000409// -fpascal-strings
Daniel Dunbar34542952008-08-23 08:43:39 +0000410static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
411 TargetInfo *Target) {
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000412
413 if (Ansi) // "The -ansi option is equivalent to -std=c89."
414 LangStd = lang_c89;
415
Chris Lattner4b009652007-07-25 00:24:17 +0000416 if (LangStd == lang_unspecified) {
417 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000418 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000419 default: assert(0 && "Unknown base language");
420 case langkind_c:
421 case langkind_c_cpp:
422 case langkind_objc:
423 case langkind_objc_cpp:
424 LangStd = lang_gnu99;
425 break;
426 case langkind_cxx:
427 case langkind_cxx_cpp:
428 case langkind_objcxx:
429 case langkind_objcxx_cpp:
430 LangStd = lang_gnucxx98;
431 break;
432 }
433 }
434
435 switch (LangStd) {
436 default: assert(0 && "Unknown language standard!");
437
438 // Fall through from newer standards to older ones. This isn't really right.
439 // FIXME: Enable specifically the right features based on the language stds.
440 case lang_gnucxx0x:
441 case lang_cxx0x:
442 Options.CPlusPlus0x = 1;
443 // FALL THROUGH
444 case lang_gnucxx98:
445 case lang_cxx98:
446 Options.CPlusPlus = 1;
447 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000448 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000449 // FALL THROUGH.
450 case lang_gnu99:
451 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000452 Options.C99 = 1;
453 Options.HexFloats = 1;
454 // FALL THROUGH.
455 case lang_gnu89:
456 Options.BCPLComment = 1; // Only for C99/C++.
457 // FALL THROUGH.
458 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000459 Options.Digraphs = 1; // C94, C99, C++.
460 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000461 case lang_c89:
462 break;
463 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000464
465 if (Options.CPlusPlus) {
466 Options.C99 = 0;
467 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
468 }
Chris Lattner4b009652007-07-25 00:24:17 +0000469
Chris Lattner6ab935b2008-04-05 06:32:51 +0000470 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
471 Options.ImplicitInt = 1;
472 else
473 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000474
475 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
476 // is specified, or -std is set to a conforming mode.
477 Options.Trigraphs = LangStd < lang_gnu_START || Trigraphs ? 1 : 0;
478
Chris Lattner4b009652007-07-25 00:24:17 +0000479 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000480 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000481 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000482 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000483 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000484 Options.Exceptions = Exceptions;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000485
486 if (NeXTRuntime) {
487 Options.NeXTRuntime = 1;
488 } else if (GNURuntime) {
489 Options.NeXTRuntime = 0;
490 } else {
Daniel Dunbar34542952008-08-23 08:43:39 +0000491 Options.NeXTRuntime = Target->useNeXTRuntimeAsDefault();
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000492 }
Daniel Dunbar7744d4a2008-10-10 00:20:52 +0000493
494 if (Options.CPlusPlus)
495 Options.Blocks = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000496}
497
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000498static llvm::cl::opt<bool>
499ObjCExclusiveGC("fobjc-gc-only",
500 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000501 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000502
503static llvm::cl::opt<bool>
504ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000505 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000506
507void InitializeGCMode(LangOptions &Options) {
508 if (ObjCExclusiveGC)
509 Options.setGCMode(LangOptions::GCOnly);
510 else if (ObjCEnableGC)
511 Options.setGCMode(LangOptions::HybridGC);
512}
513
514
Chris Lattner4b009652007-07-25 00:24:17 +0000515//===----------------------------------------------------------------------===//
516// Our DiagnosticClient implementation
517//===----------------------------------------------------------------------===//
518
519// FIXME: Werror should take a list of things, -Werror=foo,bar
520static llvm::cl::opt<bool>
521WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
522
523static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000524SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
525
526static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000527WarnOnExtensions("pedantic", llvm::cl::init(false),
528 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
529
530static llvm::cl::opt<bool>
531ErrorOnExtensions("pedantic-errors",
532 llvm::cl::desc("Issue an error on uses of GCC extensions"));
533
534static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000535SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000536 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000537 llvm::cl::init(true));
538
539static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000540WarnUnusedMacros("Wunused_macros",
541 llvm::cl::desc("Warn for unused macros in the main translation unit"));
542
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000543static llvm::cl::opt<bool>
544WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000545 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000546
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000547static llvm::cl::opt<bool>
548WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000549 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000550
Chris Lattnera616ee32008-01-23 17:19:46 +0000551static llvm::cl::opt<bool>
552WarnUndefMacros("Wundef",
553 llvm::cl::desc("Warn on use of undefined macros in #if's"));
554
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000555static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000556WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
557 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000558
Chris Lattner4b009652007-07-25 00:24:17 +0000559/// InitializeDiagnostics - Initialize the diagnostic object, based on the
560/// current command line option settings.
561static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000562 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000563 Diags.setWarningsAsErrors(WarningsAsErrors);
564 Diags.setWarnOnExtensions(WarnOnExtensions);
565 Diags.setErrorOnExtensions(ErrorOnExtensions);
566
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000567 // Suppress warnings in system headers unless requested not to.
568 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
569
Chris Lattner4b009652007-07-25 00:24:17 +0000570 // Silence the "macro is not used" warning unless requested.
571 if (!WarnUnusedMacros)
572 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000573
574 // Silence "floating point comparison" warnings unless requested.
575 if (!WarnFloatEqual)
576 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000577
578 // Silence "format string is not a string literal" warnings if requested
579 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000580 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
581 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000582 if (!WarnUndefMacros)
583 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000584
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000585 if (!WarnImplicitFunctionDeclaration)
586 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
587 diag::MAP_IGNORE);
588
Steve Naroff606f7072008-02-11 22:40:08 +0000589 if (MSExtensions) // MS allows unnamed struct/union fields.
590 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000591
592 // If -pedantic-errors is set, turn extensions that warn by default into
593 // errors.
594 if (ErrorOnExtensions) {
595 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
596 diag::MAP_ERROR);
597 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
598 diag::MAP_ERROR);
599 }
Chris Lattner4b009652007-07-25 00:24:17 +0000600}
601
602//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000603// Analysis-specific options.
604//===----------------------------------------------------------------------===//
605
606static llvm::cl::opt<std::string>
607AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000608 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000609
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000610static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000611TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000612 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000613
Ted Kremenek0118bb52008-02-18 21:21:23 +0000614//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000615// Target Triple Processing.
616//===----------------------------------------------------------------------===//
617
618static llvm::cl::opt<std::string>
619TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000620 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000621
Chris Lattnerfc457002008-03-05 01:18:20 +0000622static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000623Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000624
Chris Lattner2b168e02008-09-30 01:13:12 +0000625static llvm::cl::opt<std::string>
626MacOSVersionMin("mmacosx-version-min",
627 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
628
Chris Lattner01de9c82008-09-30 20:16:56 +0000629// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
630// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
631static void HandleMacOSVersionMin(std::string &Triple) {
632 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
633 if (DarwinDashIdx == std::string::npos) {
634 fprintf(stderr,
635 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
636 exit(1);
637 }
638 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
639
Chris Lattner01de9c82008-09-30 20:16:56 +0000640 // Remove the number.
641 Triple.resize(DarwinNumIdx);
642
643 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
644 bool MacOSVersionMinIsInvalid = false;
645 int VersionNum = 0;
646 if (MacOSVersionMin.size() < 4 ||
647 MacOSVersionMin.substr(0, 3) != "10." ||
648 !isdigit(MacOSVersionMin[3])) {
649 MacOSVersionMinIsInvalid = true;
650 } else {
651 const char *Start = MacOSVersionMin.c_str()+3;
652 char *End = 0;
653 VersionNum = (int)strtol(Start, &End, 10);
654
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000655 // The version number must be in the range 0-9.
656 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
657
Chris Lattner01de9c82008-09-30 20:16:56 +0000658 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
659 Triple += llvm::itostr(VersionNum+4);
660
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000661 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
662 // Add the period piece (.7) to the end of the triple. This gives us
663 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000664 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000665 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
666 MacOSVersionMinIsInvalid = true;
667 }
668 }
669
670 if (MacOSVersionMinIsInvalid) {
671 fprintf(stderr,
672 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
673 MacOSVersionMin.c_str());
674 exit(1);
675 }
676}
677
678/// CreateTargetTriple - Process the various options that affect the target
679/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000680static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000681 // Initialize base triple. If a -triple option has been specified, use
682 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000683 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000684 if (Triple.empty()) {
685 Triple = LLVM_HOSTTRIPLE;
686
687 // On darwin, we want to update the version to match that of the
688 // host.
689 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
690 if (DarwinDashIdx != std::string::npos) {
691 Triple.resize(DarwinDashIdx + strlen("-darwin"));
692
693 Triple += llvm::sys::osVersion();
694 }
695 }
Ted Kremenek40499482007-12-03 22:06:55 +0000696
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000697 // If -arch foo was specified, remove the architecture from the triple we have
698 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000699 if (!Arch.empty()) {
700 // Decompose the base triple into "arch" and suffix.
701 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000702
Chris Lattner2b168e02008-09-30 01:13:12 +0000703 if (FirstDashIdx == std::string::npos) {
704 fprintf(stderr,
705 "Malformed target triple: \"%s\" ('-' could not be found).\n",
706 Triple.c_str());
707 exit(1);
708 }
Ted Kremenek40499482007-12-03 22:06:55 +0000709
Chris Lattner2b168e02008-09-30 01:13:12 +0000710 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
711 }
712
713 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
714 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000715 if (!MacOSVersionMin.empty())
716 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000717
Chris Lattner2b168e02008-09-30 01:13:12 +0000718 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000719}
720
721//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000722// Preprocessor Initialization
723//===----------------------------------------------------------------------===//
724
725// FIXME: Preprocessor builtins to support.
726// -A... - Play with #assertions
727// -undef - Undefine all predefined macros
728
729static llvm::cl::list<std::string>
730D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
731 llvm::cl::desc("Predefine the specified macro"));
732static llvm::cl::list<std::string>
733U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
734 llvm::cl::desc("Undefine the specified macro"));
735
Chris Lattner008da782008-01-10 01:53:41 +0000736static llvm::cl::list<std::string>
737ImplicitIncludes("include", llvm::cl::value_desc("file"),
738 llvm::cl::desc("Include file before parsing"));
739
740
Chris Lattner4b009652007-07-25 00:24:17 +0000741// Append a #define line to Buf for Macro. Macro should be of the form XXX,
742// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
743// "#define XXX Y z W". To get a #define with no value, use "XXX=".
744static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
745 const char *Command = "#define ") {
746 Buf.insert(Buf.end(), Command, Command+strlen(Command));
747 if (const char *Equal = strchr(Macro, '=')) {
748 // Turn the = into ' '.
749 Buf.insert(Buf.end(), Macro, Equal);
750 Buf.push_back(' ');
751 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
752 } else {
753 // Push "macroname 1".
754 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
755 Buf.push_back(' ');
756 Buf.push_back('1');
757 }
758 Buf.push_back('\n');
759}
760
Chris Lattner008da782008-01-10 01:53:41 +0000761/// AddImplicitInclude - Add an implicit #include of the specified file to the
762/// predefines buffer.
763static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
764 const char *Inc = "#include \"";
765 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
766 Buf.insert(Buf.end(), File.begin(), File.end());
767 Buf.push_back('"');
768 Buf.push_back('\n');
769}
770
Chris Lattner4b009652007-07-25 00:24:17 +0000771
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000772/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000773/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000774///
Chris Lattner9d818a22008-04-19 23:25:44 +0000775static bool InitializePreprocessor(Preprocessor &PP,
776 bool InitializeSourceMgr,
777 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000778 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000779
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000780 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000781 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000782
783 if (InitializeSourceMgr) {
784 if (InFile != "-") {
785 const FileEntry *File = FileMgr.getFile(InFile);
786 if (File) SourceMgr.createMainFileID(File, SourceLocation());
787 if (SourceMgr.getMainFileID() == 0) {
788 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000789 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000790 }
791 } else {
792 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
793 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
794 if (SourceMgr.getMainFileID() == 0) {
795 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000796 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000797 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000798 }
Chris Lattner4b009652007-07-25 00:24:17 +0000799 }
Sam Bishop61a20782008-04-14 14:41:57 +0000800
Chris Lattner47b6a162008-04-19 23:09:31 +0000801 std::vector<char> PredefineBuffer;
802
Chris Lattner4b009652007-07-25 00:24:17 +0000803 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000804 unsigned d = 0, D = D_macros.size();
805 unsigned u = 0, U = U_macros.size();
806 while (d < D || u < U) {
807 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
808 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
809 else
810 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
811 }
812
Chris Lattner008da782008-01-10 01:53:41 +0000813 // FIXME: Read any files specified by -imacros.
814
815 // Add implicit #includes from -include.
816 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
817 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000818
Chris Lattner47b6a162008-04-19 23:09:31 +0000819 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000820 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000821 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000822
823 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000824 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000825}
826
827//===----------------------------------------------------------------------===//
828// Preprocessor include path information.
829//===----------------------------------------------------------------------===//
830
831// This tool exports a large number of command line options to control how the
832// preprocessor searches for header files. At root, however, the Preprocessor
833// object takes a very simple interface: a list of directories to search for
834//
835// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000836// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000837//
Chris Lattner008da782008-01-10 01:53:41 +0000838// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000839
840static llvm::cl::opt<bool>
841nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
842
843// Various command line options. These four add directories to each chain.
844static llvm::cl::list<std::string>
845F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
846 llvm::cl::desc("Add directory to framework include search path"));
847static llvm::cl::list<std::string>
848I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
849 llvm::cl::desc("Add directory to include search path"));
850static llvm::cl::list<std::string>
851idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
852 llvm::cl::desc("Add directory to AFTER include search path"));
853static llvm::cl::list<std::string>
854iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
855 llvm::cl::desc("Add directory to QUOTE include search path"));
856static llvm::cl::list<std::string>
857isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
858 llvm::cl::desc("Add directory to SYSTEM include search path"));
859
860// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
861static llvm::cl::list<std::string>
862iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
863 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
864static llvm::cl::list<std::string>
865iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
866 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
867static llvm::cl::list<std::string>
868iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
869 llvm::cl::Prefix,
870 llvm::cl::desc("Set directory to include search path with prefix"));
871
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000872static llvm::cl::opt<std::string>
873isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
874 llvm::cl::desc("Set the system root directory (usually /)"));
875
Chris Lattner4b009652007-07-25 00:24:17 +0000876// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000877
Chris Lattner4b009652007-07-25 00:24:17 +0000878/// InitializeIncludePaths - Process the -I options and set them in the
879/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000880void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
881 FileManager &FM, const LangOptions &Lang) {
882 InitHeaderSearch Init(Headers, Verbose, isysroot);
883
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000884 // Handle -I... and -F... options, walking the lists in parallel.
885 unsigned Iidx = 0, Fidx = 0;
886 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
887 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +0000888 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000889 ++Iidx;
890 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000891 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000892 ++Fidx;
893 }
894 }
Chris Lattner4b009652007-07-25 00:24:17 +0000895
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000896 // Consume what's left from whatever list was longer.
897 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +0000898 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000899 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +0000900 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000901
902 // Handle -idirafter... options.
903 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000904 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
905 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000906
907 // Handle -iquote... options.
908 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000909 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000910
911 // Handle -isystem... options.
912 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000913 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000914
915 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
916 // parallel, processing the values in order of occurance to get the right
917 // prefixes.
918 {
919 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
920 unsigned iprefix_idx = 0;
921 unsigned iwithprefix_idx = 0;
922 unsigned iwithprefixbefore_idx = 0;
923 bool iprefix_done = iprefix_vals.empty();
924 bool iwithprefix_done = iwithprefix_vals.empty();
925 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
926 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
927 if (!iprefix_done &&
928 (iwithprefix_done ||
929 iprefix_vals.getPosition(iprefix_idx) <
930 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
931 (iwithprefixbefore_done ||
932 iprefix_vals.getPosition(iprefix_idx) <
933 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
934 Prefix = iprefix_vals[iprefix_idx];
935 ++iprefix_idx;
936 iprefix_done = iprefix_idx == iprefix_vals.size();
937 } else if (!iwithprefix_done &&
938 (iwithprefixbefore_done ||
939 iwithprefix_vals.getPosition(iwithprefix_idx) <
940 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +0000941 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
942 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000943 ++iwithprefix_idx;
944 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
945 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000946 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
947 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000948 ++iwithprefixbefore_idx;
949 iwithprefixbefore_done =
950 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
951 }
952 }
953 }
Chris Lattner4f022a72008-03-01 08:07:28 +0000954
Nico Weber770e3882008-08-22 09:25:22 +0000955 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +0000956
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000957 // Add the clang headers, which are relative to the clang driver.
958 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +0000959 llvm::sys::Path::GetMainExecutable(Argv0,
960 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000961 if (!MainExecutablePath.isEmpty()) {
962 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
963 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
964 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +0000965 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
966 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +0000967 }
968
Nico Weber770e3882008-08-22 09:25:22 +0000969 if (!nostdinc)
970 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +0000971
972 // Now that we have collected all of the include paths, merge them all
973 // together and tell the preprocessor about them.
974
Nico Weber770e3882008-08-22 09:25:22 +0000975 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +0000976}
977
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000978//===----------------------------------------------------------------------===//
979// Driver PreprocessorFactory - For lazily generating preprocessors ...
980//===----------------------------------------------------------------------===//
981
982namespace {
983class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000984 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000985 Diagnostic &Diags;
986 const LangOptions &LangInfo;
987 TargetInfo &Target;
988 SourceManager &SourceMgr;
989 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000990 bool InitializeSourceMgr;
991
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000992public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000993 DriverPreprocessorFactory(const std::string &infile,
994 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +0000995 TargetInfo &target, SourceManager &SM,
996 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000997 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
998 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
999
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001000
1001 virtual ~DriverPreprocessorFactory() {}
1002
1003 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001004 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1005 SourceMgr, HeaderInfo);
1006
Chris Lattner9d818a22008-04-19 23:25:44 +00001007 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001008 delete PP;
1009 return NULL;
1010 }
1011
1012 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001013 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001014 }
1015};
1016}
Chris Lattner4b009652007-07-25 00:24:17 +00001017
Chris Lattner4b009652007-07-25 00:24:17 +00001018//===----------------------------------------------------------------------===//
1019// Basic Parser driver
1020//===----------------------------------------------------------------------===//
1021
Chris Lattner9d818a22008-04-19 23:25:44 +00001022static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001023 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001024 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001025
1026 // Parsing the specified input file.
1027 P.ParseTranslationUnit();
1028 delete PA;
1029}
1030
1031//===----------------------------------------------------------------------===//
1032// Main driver
1033//===----------------------------------------------------------------------===//
1034
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001035/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1036/// action. These consumers can operate on both ASTs that are freshly
1037/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001038static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001039 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001040 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001041 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001042 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001043 switch (ProgAction) {
1044 default:
1045 return NULL;
1046
1047 case ASTPrint:
1048 return CreateASTPrinter();
1049
1050 case ASTDump:
1051 return CreateASTDumper();
1052
1053 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001054 return CreateASTViewer();
1055
1056 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001057 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001058
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001059 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001060 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001061
1062 case EmitLLVM:
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001063 case EmitBC:
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001064 return CreateLLVMCodeGenWriter(ProgAction == EmitBC, Diag, LangOpts,
1065 InFile, OutputFile, GenerateDebugInfo);
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001066
Ted Kremenekbde30332007-12-19 17:25:59 +00001067 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001068 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001069 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001070
Steve Naroff44e81222008-04-14 22:03:09 +00001071 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001072 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001073
1074 case RewriteBlocks:
1075 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001076
1077 case RunAnalysis:
1078 assert (!AnalysisList.empty());
1079 return CreateAnalysisConsumer(&AnalysisList[0],
1080 &AnalysisList[0]+AnalysisList.size(),
1081 Diag, PP, PPF, LangOpts,
1082 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001083 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1084 TrimGraph, AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001085 }
1086}
1087
Chris Lattner4b009652007-07-25 00:24:17 +00001088/// ProcessInputFile - Process a single input file with the specified state.
1089///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001090static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1091 const std::string &InFile) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001092
Ted Kremenek50aab982008-08-08 02:46:37 +00001093 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001094 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001095
Chris Lattner4b009652007-07-25 00:24:17 +00001096 switch (ProgAction) {
1097 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001098 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1099 PP.getFileManager(), PP.getLangOptions(),
1100 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001101
1102 if (!Consumer) {
1103 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001104 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001105 return;
1106 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001107
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001108 break;
1109
Chris Lattneraf669fb2008-10-12 05:03:36 +00001110 case DumpRawTokens: {
1111 SourceManager &SM = PP.getSourceManager();
1112 std::pair<const char*,const char*> File =
1113 SM.getBufferData(SM.getMainFileID());
1114 // Start lexing the specified input file.
1115 Lexer RawLex(SourceLocation::getFileLoc(SM.getMainFileID(), 0),
1116 PP.getLangOptions(), File.first, File.second);
1117 RawLex.SetKeepWhitespaceMode(true);
1118
1119 Token RawTok;
1120
1121 RawLex.LexFromRawLexer(RawTok);
1122 while (RawTok.isNot(tok::eof)) {
1123 PP.DumpToken(RawTok, true);
1124 fprintf(stderr, "\n");
1125 RawLex.LexFromRawLexer(RawTok);
1126 }
1127 ClearSourceMgr = true;
1128 break;
1129 }
Chris Lattner4b009652007-07-25 00:24:17 +00001130 case DumpTokens: { // Token dump mode.
1131 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001132 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001133 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001134 do {
1135 PP.Lex(Tok);
1136 PP.DumpToken(Tok, true);
1137 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001138 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001139 ClearSourceMgr = true;
1140 break;
1141 }
1142 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1143 Token Tok;
1144 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001145 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001146 do {
1147 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001148 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001149 ClearSourceMgr = true;
1150 break;
1151 }
1152
1153 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001154 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001155 ClearSourceMgr = true;
1156 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001157
Chris Lattner4b009652007-07-25 00:24:17 +00001158 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001159 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001160 ClearSourceMgr = true;
1161 break;
1162
1163 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001164 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001165 ClearSourceMgr = true;
1166 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001167
Ted Kremenek6856c632007-09-26 18:39:29 +00001168 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001169 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001170 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001171
1172 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001173 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001174 ClearSourceMgr = true;
1175 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001176 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001177
1178 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001179 if (VerifyDiagnostics)
Ted Kremenek50aab982008-08-08 02:46:37 +00001180 exit(CheckASTConsumer(PP, Consumer.get()));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001181
Ted Kremenek50aab982008-08-08 02:46:37 +00001182 ParseAST(PP, Consumer.get(), Stats);
Daniel Dunbarab3288e2008-10-05 01:38:39 +00001183 } else {
1184 if (VerifyDiagnostics)
1185 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001186 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001187
Chris Lattner4b009652007-07-25 00:24:17 +00001188 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001189 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001190 PP.PrintStats();
1191 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001192 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001193 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001194 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001195 fprintf(stderr, "\n");
1196 }
1197
1198 // For a multi-file compilation, some things are ok with nuking the source
1199 // manager tables, other require stable fileid/macroid's across multiple
1200 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001201 if (ClearSourceMgr)
1202 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001203}
1204
Ted Kremenek80d53372007-12-12 23:41:08 +00001205static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1206 FileManager& FileMgr) {
1207
1208 if (VerifyDiagnostics) {
1209 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1210 exit (1);
1211 }
1212
1213 llvm::sys::Path Filename(InFile);
1214
1215 if (!Filename.isValid()) {
1216 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1217 exit (1);
1218 }
1219
Ted Kremenek863b01f2008-04-23 16:25:39 +00001220 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001221
1222 if (!TU) {
1223 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1224 InFile.c_str());
1225 exit (1);
1226 }
1227
Ted Kremenekab749372007-12-19 19:27:38 +00001228 // Observe that we use the source file name stored in the deserialized
1229 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001230 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001231 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001232 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001233
Ted Kremenek80d53372007-12-12 23:41:08 +00001234 if (!Consumer) {
1235 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1236 exit (1);
1237 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001238
Ted Kremenek863b01f2008-04-23 16:25:39 +00001239 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001240
Chris Lattner8d72ee02008-02-06 01:42:25 +00001241 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001242 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1243 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001244}
1245
1246
Chris Lattner4b009652007-07-25 00:24:17 +00001247static llvm::cl::list<std::string>
1248InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1249
Ted Kremenek80d53372007-12-12 23:41:08 +00001250static bool isSerializedFile(const std::string& InFile) {
1251 if (InFile.size() < 4)
1252 return false;
1253
1254 const char* s = InFile.c_str()+InFile.size()-4;
1255
1256 return s[0] == '.' &&
1257 s[1] == 'a' &&
1258 s[2] == 's' &&
1259 s[3] == 't';
1260}
1261
Chris Lattner4b009652007-07-25 00:24:17 +00001262
1263int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001264 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001265 llvm::sys::PrintStackTraceOnErrorSignal();
1266
1267 // If no input was specified, read from stdin.
1268 if (InputFilenames.empty())
1269 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001270
Chris Lattner4b009652007-07-25 00:24:17 +00001271 // Create a file manager object to provide access to and cache the filesystem.
1272 FileManager FileMgr;
1273
Ted Kremenekb240e822007-12-11 23:28:38 +00001274 // Create the diagnostic client for reporting errors or for
1275 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001276 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001277
Ted Kremenek5c341732008-08-07 17:49:57 +00001278 if (!VerifyDiagnostics) {
1279 // Print diagnostics to stderr by default.
1280 TextDiagClient = new TextDiagnosticPrinter(!NoShowColumn,
1281 !NoCaretDiagnostics);
1282 } else {
1283 // When checking diagnostics, just buffer them up.
1284 TextDiagClient = new TextDiagnosticBuffer();
1285
1286 if (InputFilenames.size() != 1) {
1287 fprintf(stderr,
1288 "-verify only works on single input files for now.\n");
1289 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001290 }
1291 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001292
Chris Lattner4b009652007-07-25 00:24:17 +00001293 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001294 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1295 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001296 InitializeDiagnostics(Diags);
1297
Chris Lattner45a56e02007-12-05 23:24:17 +00001298 // -I- is a deprecated GCC feature, scan for it and reject it.
1299 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1300 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001301 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001302 I_dirs.erase(I_dirs.begin()+i);
1303 --i;
1304 }
1305 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001306
1307 // Get information about the target being compiled for.
1308 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001309 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1310
Chris Lattner2c77d852008-03-14 06:12:05 +00001311 if (Target == 0) {
1312 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1313 Triple.c_str());
1314 fprintf(stderr, "Please use -triple or -arch.\n");
1315 exit(1);
1316 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001317
Ted Kremenek81ea7992008-07-02 00:03:09 +00001318 // Are we invoking one or more source analyses?
1319 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1320 ProgAction = RunAnalysis;
Ted Kremenek5c341732008-08-07 17:49:57 +00001321
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001322 llvm::OwningPtr<SourceManager> SourceMgr;
1323
Chris Lattner4b009652007-07-25 00:24:17 +00001324 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001325 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001326
Ted Kremenek5c341732008-08-07 17:49:57 +00001327 if (isSerializedFile(InFile)) {
1328 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001329 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001330 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001331 else {
1332 /// Create a SourceManager object. This tracks and owns all the file
1333 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001334 if (!SourceMgr)
1335 SourceMgr.reset(new SourceManager());
1336 else
1337 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001338
Ted Kremenek80d53372007-12-12 23:41:08 +00001339 // Initialize language options, inferring file types from input filenames.
1340 LangOptions LangInfo;
1341 InitializeBaseLanguage();
1342 LangKind LK = GetLanguage(InFile);
1343 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar34542952008-08-23 08:43:39 +00001344 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001345 InitializeGCMode(LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001346
1347 // Process the -I options and set them in the HeaderInfo.
1348 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001349
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001350 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001351
Ted Kremenek80d53372007-12-12 23:41:08 +00001352 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001353 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001354 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001355
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001356 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1357
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001358 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001359 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001360
1361 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1362 // always reset to using TextDiagClient.
1363 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001364
Ted Kremenek5c341732008-08-07 17:49:57 +00001365 if (!HTMLDiag.empty()) {
1366 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1367 &PPFactory));
1368 Diags.setClient(TmpClient.get());
1369 }
1370 else
1371 Diags.setClient(TextDiagClient);
1372
1373 // Process the source file.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001374 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001375 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001376
1377 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001378 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001379 }
Chris Lattner4b009652007-07-25 00:24:17 +00001380 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001381
Ted Kremenekec6c5252008-08-07 18:13:12 +00001382 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001383 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1384 (NumDiagnostics == 1 ? "" : "s"));
1385
1386 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001387 FileMgr.PrintStats();
1388 fprintf(stderr, "\n");
1389 }
1390
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001391 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001392}