blob: 6d3f0b38435780aebf2be511742003d3d7e84fba [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"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000027#include "clang/Driver/CompileOptions.h"
Zhongxing Xue7079442008-08-24 02:33:36 +000028#include "clang/Driver/HTMLDiagnostics.h"
Nico Weber770e3882008-08-22 09:25:22 +000029#include "clang/Driver/InitHeaderSearch.h"
Nico Weber0e13eaa2008-08-05 23:33:20 +000030#include "clang/Driver/TextDiagnosticBuffer.h"
31#include "clang/Driver/TextDiagnosticPrinter.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000037#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000038#include "clang/Parse/Parser.h"
39#include "clang/Lex/HeaderSearch.h"
40#include "clang/Basic/FileManager.h"
41#include "clang/Basic/SourceManager.h"
42#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000043#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000044#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000047#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000049#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000050#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000051#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Global options.
56//===----------------------------------------------------------------------===//
57
Daniel Dunbar4efedde2008-10-16 16:54:18 +000058static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000059
Chris Lattner4b009652007-07-25 00:24:17 +000060static llvm::cl::opt<bool>
61Verbose("v", llvm::cl::desc("Enable verbose output"));
62static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000063Stats("print-stats",
64 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000065static llvm::cl::opt<bool>
66DisableFree("disable-free",
67 llvm::cl::desc("Disable freeing of memory on exit"),
68 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000069
70enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000071 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000072 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000073 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000074 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000075 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000076 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000077 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000078 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000079 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000080 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000081 ASTPrint, // Parse ASTs and print them.
82 ASTDump, // Parse ASTs and dump them.
83 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000084 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000085 ParsePrintCallbacks, // Parse and print each callback.
86 ParseSyntaxOnly, // Parse and perform semantic analysis.
87 ParseNoop, // Parse with noop callbacks.
88 RunPreprocessorOnly, // Just lex, no output.
89 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000090 DumpTokens, // Dump out preprocessed tokens.
91 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +000092 RunAnalysis, // Run one or more source code analyses.
93 GeneratePCH // Generate precompiled header.
Chris Lattner4b009652007-07-25 00:24:17 +000094};
95
96static llvm::cl::opt<ProgActions>
97ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
98 llvm::cl::init(ParseSyntaxOnly),
99 llvm::cl::values(
100 clEnumValN(RunPreprocessorOnly, "Eonly",
101 "Just run preprocessor, no output (for timings)"),
102 clEnumValN(PrintPreprocessedInput, "E",
103 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000104 clEnumValN(DumpRawTokens, "dump-raw-tokens",
105 "Lex file in raw mode and dump raw tokens"),
106 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000107 "Run preprocessor, dump internal rep of tokens"),
108 clEnumValN(ParseNoop, "parse-noop",
109 "Run parser with noop callbacks (for timings)"),
110 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
111 "Run parser and perform semantic analysis"),
112 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
113 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000114 clEnumValN(EmitHTML, "emit-html",
115 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000116 clEnumValN(ASTPrint, "ast-print",
117 "Build ASTs and then pretty-print them"),
118 clEnumValN(ASTDump, "ast-dump",
119 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000120 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000121 "Build ASTs and view them with GraphViz"),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000122 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000123 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000124 clEnumValN(EmitAssembly, "S",
125 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000126 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000127 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000128 clEnumValN(EmitBC, "emit-llvm-bc",
129 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000130 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000131 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000132 clEnumValN(RewriteTest, "rewrite-test",
133 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000134 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000135 "Rewrite ObjC into C (code rewriter example)"),
136 clEnumValN(RewriteMacros, "rewrite-macros",
137 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000138 clEnumValN(RewriteBlocks, "rewrite-blocks",
139 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000140 clEnumValEnd));
141
Ted Kremenekd01eae62007-12-19 19:47:59 +0000142
143static llvm::cl::opt<std::string>
144OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000145 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000146 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000147
148//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000149// Code Generator Options
150//===----------------------------------------------------------------------===//
151static llvm::cl::opt<bool>
152GenerateDebugInfo("g",
153 llvm::cl::desc("Generate source level debug information"));
154
155//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000156// Diagnostic Options
157//===----------------------------------------------------------------------===//
158
Ted Kremenek10389cf2007-09-26 19:42:19 +0000159static llvm::cl::opt<bool>
160VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000161 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000162
Ted Kremenekfd75e312008-03-27 06:17:42 +0000163static llvm::cl::opt<std::string>
164HTMLDiag("html-diags",
165 llvm::cl::desc("Generate HTML to report diagnostics"),
166 llvm::cl::value_desc("HTML directory"));
167
Nico Weber0e13eaa2008-08-05 23:33:20 +0000168static llvm::cl::opt<bool>
169NoShowColumn("fno-show-column",
170 llvm::cl::desc("Do not include column number on diagnostics"));
171
172static llvm::cl::opt<bool>
173NoCaretDiagnostics("fno-caret-diagnostics",
174 llvm::cl::desc("Do not include source line and caret with"
175 " diagnostics"));
176
177
Chris Lattner4b009652007-07-25 00:24:17 +0000178//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000179// Analyzer Options
180//===----------------------------------------------------------------------===//
181
182static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000183VisualizeEGDot("analyzer-viz-egraph-graphviz",
184 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000185
186static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000187VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
188 llvm::cl::desc("Display exploded graph using Ubigraph"));
189
190static llvm::cl::opt<bool>
191AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000192 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000193 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000194
Ted Kremenek81ea7992008-07-02 00:03:09 +0000195static llvm::cl::list<Analyses>
196AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
197llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000198#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000199clEnumValN(NAME, CMDFLAG, DESC),
200#include "Analyses.def"
201clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000202
Ted Kremenek517cb512008-04-14 18:40:58 +0000203//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000204// Language Options
205//===----------------------------------------------------------------------===//
206
207enum LangKind {
208 langkind_unspecified,
209 langkind_c,
210 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000211 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000212 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000213 langkind_cxx,
214 langkind_cxx_cpp,
215 langkind_objc,
216 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000217 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000218 langkind_objcxx,
219 langkind_objcxx_cpp
220};
221
222/* TODO: GCC also accepts:
223 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera19689a2008-10-22 17:29:21 +0000224 assembler
Chris Lattner4b009652007-07-25 00:24:17 +0000225 ada, f77*, ratfor (!), f95, java, treelang
226 */
227static llvm::cl::opt<LangKind>
228BaseLang("x", llvm::cl::desc("Base language to compile"),
229 llvm::cl::init(langkind_unspecified),
230 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
231 clEnumValN(langkind_cxx, "c++", "C++"),
232 clEnumValN(langkind_objc, "objective-c", "Objective C"),
233 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
234 clEnumValN(langkind_c_cpp, "c-cpp-output",
235 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000236 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
237 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000238 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000239 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000240 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
241 "Preprocessed Objective C"),
242 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
243 "Preprocessed Objective C++"),
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000244 clEnumValN(langkind_c_pch,"c-header",
245 "Precompiled C header"),
246 clEnumValN(langkind_objc_pch, "objective-c-header",
247 "Precompiled Objective C header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000248 clEnumValEnd));
249
250static llvm::cl::opt<bool>
251LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
252 llvm::cl::Hidden);
253static llvm::cl::opt<bool>
254LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
255 llvm::cl::Hidden);
256
Ted Kremenek11ad8952007-12-05 23:49:08 +0000257/// InitializeBaseLanguage - Handle the -x foo options.
258static void InitializeBaseLanguage() {
259 if (LangObjC)
260 BaseLang = langkind_objc;
261 else if (LangObjCXX)
262 BaseLang = langkind_objcxx;
263}
264
265static LangKind GetLanguage(const std::string &Filename) {
266 if (BaseLang != langkind_unspecified)
267 return BaseLang;
268
269 std::string::size_type DotPos = Filename.rfind('.');
270
271 if (DotPos == std::string::npos) {
272 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000273 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000274 }
275
Ted Kremenek11ad8952007-12-05 23:49:08 +0000276 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
277 // C header: .h
278 // C++ header: .hh or .H;
279 // assembler no preprocessing: .s
280 // assembler: .S
281 if (Ext == "c")
282 return langkind_c;
Chris Lattnera19689a2008-10-22 17:29:21 +0000283 else if (Ext == "S" || Ext == "s")
284 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000285 else if (Ext == "i")
286 return langkind_c_cpp;
287 else if (Ext == "ii")
288 return langkind_cxx_cpp;
289 else if (Ext == "m")
290 return langkind_objc;
291 else if (Ext == "mi")
292 return langkind_objc_cpp;
293 else if (Ext == "mm" || Ext == "M")
294 return langkind_objcxx;
295 else if (Ext == "mii")
296 return langkind_objcxx_cpp;
297 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
298 Ext == "c++" || Ext == "cp" || Ext == "cxx")
299 return langkind_cxx;
300 else
301 return langkind_c;
302}
303
304
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000305static void InitializeCOptions(LangOptions &Options) {
306 // Do nothing.
307}
308
309static void InitializeObjCOptions(LangOptions &Options) {
310 Options.ObjC1 = Options.ObjC2 = 1;
311}
312
313
314static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000315 // FIXME: implement -fpreprocessed mode.
316 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000317 bool PCH = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000318
Ted Kremenek11ad8952007-12-05 23:49:08 +0000319 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000320 default: assert(0 && "Unknown language kind!");
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000321 case langkind_c_pch:
322 InitializeCOptions(Options);
323 PCH = true;
324 break;
Chris Lattnera19689a2008-10-22 17:29:21 +0000325 case langkind_asm_cpp:
326 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000327 case langkind_c_cpp:
328 NoPreprocess = true;
329 // FALLTHROUGH
330 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000331 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000332 break;
333 case langkind_cxx_cpp:
334 NoPreprocess = true;
335 // FALLTHROUGH
336 case langkind_cxx:
337 Options.CPlusPlus = 1;
338 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000339 case langkind_objc_pch:
340 InitializeObjCOptions(Options);
341 PCH = true;
342 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000343 case langkind_objc_cpp:
344 NoPreprocess = true;
345 // FALLTHROUGH
346 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000347 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000348 break;
349 case langkind_objcxx_cpp:
350 NoPreprocess = true;
351 // FALLTHROUGH
352 case langkind_objcxx:
353 Options.ObjC1 = Options.ObjC2 = 1;
354 Options.CPlusPlus = 1;
355 break;
356 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000357
358 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000359}
360
361/// LangStds - Language standards we support.
362enum LangStds {
363 lang_unspecified,
364 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000365 lang_gnu_START,
366 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000367 lang_cxx98, lang_gnucxx98,
368 lang_cxx0x, lang_gnucxx0x
369};
370
371static llvm::cl::opt<LangStds>
372LangStd("std", llvm::cl::desc("Language standard to compile for"),
373 llvm::cl::init(lang_unspecified),
374 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
375 clEnumValN(lang_c89, "c90", "ISO C 1990"),
376 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
377 clEnumValN(lang_c94, "iso9899:199409",
378 "ISO C 1990 with amendment 1"),
379 clEnumValN(lang_c99, "c99", "ISO C 1999"),
380// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
381 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
382// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
383 clEnumValN(lang_gnu89, "gnu89",
384 "ISO C 1990 with GNU extensions (default for C)"),
385 clEnumValN(lang_gnu99, "gnu99",
386 "ISO C 1999 with GNU extensions"),
387 clEnumValN(lang_gnu99, "gnu9x",
388 "ISO C 1999 with GNU extensions"),
389 clEnumValN(lang_cxx98, "c++98",
390 "ISO C++ 1998 with amendments"),
391 clEnumValN(lang_gnucxx98, "gnu++98",
392 "ISO C++ 1998 with amendments and GNU "
393 "extensions (default for C++)"),
394 clEnumValN(lang_cxx0x, "c++0x",
395 "Upcoming ISO C++ 200x with amendments"),
396 clEnumValN(lang_gnucxx0x, "gnu++0x",
397 "Upcoming ISO C++ 200x with amendments and GNU "
398 "extensions (default for C++)"),
399 clEnumValEnd));
400
401static llvm::cl::opt<bool>
402NoOperatorNames("fno-operator-names",
403 llvm::cl::desc("Do not treat C++ operator name keywords as "
404 "synonyms for operators"));
405
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000406static llvm::cl::opt<bool>
407PascalStrings("fpascal-strings",
408 llvm::cl::desc("Recognize and construct Pascal-style "
409 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000410
411static llvm::cl::opt<bool>
412MSExtensions("fms-extensions",
413 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000414 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000415
416static llvm::cl::opt<bool>
417WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000418 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000419
420static llvm::cl::opt<bool>
421LaxVectorConversions("flax-vector-conversions",
422 llvm::cl::desc("Allow implicit conversions between vectors"
423 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000424 "different element types"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000425
Daniel Dunbar91692d92008-08-11 17:36:14 +0000426// FIXME: This (and all GCC -f options) really come in -f... and
427// -fno-... forms, and additionally support automagic behavior when
428// they are not defined. For example, -fexceptions defaults to on or
429// off depending on the language. We should support this behavior in
430// some form (perhaps just add a facility for distinguishing when an
431// has its default value from when it has been set to its default
432// value).
433static llvm::cl::opt<bool>
434Exceptions("fexceptions",
435 llvm::cl::desc("Enable support for exception handling."));
436
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000437static llvm::cl::opt<bool>
438GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000439 llvm::cl::desc("Generate output compatible with the standard GNU "
440 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000441
442static llvm::cl::opt<bool>
443NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000444 llvm::cl::desc("Generate output compatible with the NeXT "
445 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000446
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000447
448
449static llvm::cl::opt<bool>
450Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
451
452static llvm::cl::opt<bool>
453Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
454
Chris Lattner4b009652007-07-25 00:24:17 +0000455// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000456// -fdollars-in-identifiers
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000457// -fpascal-strings
Daniel Dunbar34542952008-08-23 08:43:39 +0000458static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
459 TargetInfo *Target) {
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000460
461 if (Ansi) // "The -ansi option is equivalent to -std=c89."
462 LangStd = lang_c89;
463
Chris Lattner4b009652007-07-25 00:24:17 +0000464 if (LangStd == lang_unspecified) {
465 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000466 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000467 default: assert(0 && "Unknown base language");
468 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000469 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000470 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000471 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000472 case langkind_objc:
473 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000474 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000475 LangStd = lang_gnu99;
476 break;
477 case langkind_cxx:
478 case langkind_cxx_cpp:
479 case langkind_objcxx:
480 case langkind_objcxx_cpp:
481 LangStd = lang_gnucxx98;
482 break;
483 }
484 }
485
486 switch (LangStd) {
487 default: assert(0 && "Unknown language standard!");
488
489 // Fall through from newer standards to older ones. This isn't really right.
490 // FIXME: Enable specifically the right features based on the language stds.
491 case lang_gnucxx0x:
492 case lang_cxx0x:
493 Options.CPlusPlus0x = 1;
494 // FALL THROUGH
495 case lang_gnucxx98:
496 case lang_cxx98:
497 Options.CPlusPlus = 1;
498 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000499 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000500 // FALL THROUGH.
501 case lang_gnu99:
502 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000503 Options.C99 = 1;
504 Options.HexFloats = 1;
505 // FALL THROUGH.
506 case lang_gnu89:
507 Options.BCPLComment = 1; // Only for C99/C++.
508 // FALL THROUGH.
509 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000510 Options.Digraphs = 1; // C94, C99, C++.
511 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000512 case lang_c89:
513 break;
514 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000515
516 if (Options.CPlusPlus) {
517 Options.C99 = 0;
518 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
519 }
Chris Lattner4b009652007-07-25 00:24:17 +0000520
Chris Lattner6ab935b2008-04-05 06:32:51 +0000521 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
522 Options.ImplicitInt = 1;
523 else
524 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000525
526 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
527 // is specified, or -std is set to a conforming mode.
528 Options.Trigraphs = LangStd < lang_gnu_START || Trigraphs ? 1 : 0;
529
Chris Lattner4b009652007-07-25 00:24:17 +0000530 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000531 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000532 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000533 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000534 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000535 Options.Exceptions = Exceptions;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000536
537 if (NeXTRuntime) {
538 Options.NeXTRuntime = 1;
539 } else if (GNURuntime) {
540 Options.NeXTRuntime = 0;
541 } else {
Daniel Dunbar34542952008-08-23 08:43:39 +0000542 Options.NeXTRuntime = Target->useNeXTRuntimeAsDefault();
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000543 }
Daniel Dunbar7744d4a2008-10-10 00:20:52 +0000544
545 if (Options.CPlusPlus)
546 Options.Blocks = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000547}
548
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000549static llvm::cl::opt<bool>
550ObjCExclusiveGC("fobjc-gc-only",
551 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000552 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000553
554static llvm::cl::opt<bool>
555ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000556 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000557
558void InitializeGCMode(LangOptions &Options) {
559 if (ObjCExclusiveGC)
560 Options.setGCMode(LangOptions::GCOnly);
561 else if (ObjCEnableGC)
562 Options.setGCMode(LangOptions::HybridGC);
563}
564
565
Chris Lattner4b009652007-07-25 00:24:17 +0000566//===----------------------------------------------------------------------===//
567// Our DiagnosticClient implementation
568//===----------------------------------------------------------------------===//
569
570// FIXME: Werror should take a list of things, -Werror=foo,bar
571static llvm::cl::opt<bool>
572WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
573
574static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000575SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
576
577static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000578WarnOnExtensions("pedantic", llvm::cl::init(false),
579 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
580
581static llvm::cl::opt<bool>
582ErrorOnExtensions("pedantic-errors",
583 llvm::cl::desc("Issue an error on uses of GCC extensions"));
584
585static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000586SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000587 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000588 llvm::cl::init(true));
589
590static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000591WarnUnusedMacros("Wunused_macros",
592 llvm::cl::desc("Warn for unused macros in the main translation unit"));
593
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000594static llvm::cl::opt<bool>
595WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000596 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000597
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000598static llvm::cl::opt<bool>
599WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000600 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000601
Chris Lattnera616ee32008-01-23 17:19:46 +0000602static llvm::cl::opt<bool>
603WarnUndefMacros("Wundef",
604 llvm::cl::desc("Warn on use of undefined macros in #if's"));
605
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000606static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000607WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
608 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000609
Steve Naroffb91afca2008-10-21 10:37:50 +0000610static llvm::cl::opt<bool>
611WarnNoStrictSelectorMatch("Wno-strict-selector-match",
612 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
613 llvm::cl::init(true));
614
Chris Lattner4b009652007-07-25 00:24:17 +0000615/// InitializeDiagnostics - Initialize the diagnostic object, based on the
616/// current command line option settings.
617static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000618 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000619 Diags.setWarningsAsErrors(WarningsAsErrors);
620 Diags.setWarnOnExtensions(WarnOnExtensions);
621 Diags.setErrorOnExtensions(ErrorOnExtensions);
622
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000623 // Suppress warnings in system headers unless requested not to.
624 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
625
Chris Lattner4b009652007-07-25 00:24:17 +0000626 // Silence the "macro is not used" warning unless requested.
627 if (!WarnUnusedMacros)
628 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000629
630 // Silence "floating point comparison" warnings unless requested.
631 if (!WarnFloatEqual)
632 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000633
634 // Silence "format string is not a string literal" warnings if requested
635 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000636 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
637 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000638 if (!WarnUndefMacros)
639 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000640
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000641 if (!WarnImplicitFunctionDeclaration)
642 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
643 diag::MAP_IGNORE);
644
Steve Naroff606f7072008-02-11 22:40:08 +0000645 if (MSExtensions) // MS allows unnamed struct/union fields.
646 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner057a2f52008-05-04 23:52:02 +0000647
648 // If -pedantic-errors is set, turn extensions that warn by default into
649 // errors.
650 if (ErrorOnExtensions) {
651 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
652 diag::MAP_ERROR);
653 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
654 diag::MAP_ERROR);
655 }
Chris Lattner4b009652007-07-25 00:24:17 +0000656}
657
658//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000659// Analysis-specific options.
660//===----------------------------------------------------------------------===//
661
662static llvm::cl::opt<std::string>
663AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000664 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000665
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000666static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000667TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000668 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000669
Ted Kremenek0118bb52008-02-18 21:21:23 +0000670//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000671// Target Triple Processing.
672//===----------------------------------------------------------------------===//
673
674static llvm::cl::opt<std::string>
675TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000676 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000677
Chris Lattnerfc457002008-03-05 01:18:20 +0000678static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000679Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000680
Chris Lattner2b168e02008-09-30 01:13:12 +0000681static llvm::cl::opt<std::string>
682MacOSVersionMin("mmacosx-version-min",
683 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
684
Chris Lattner01de9c82008-09-30 20:16:56 +0000685// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
686// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
687static void HandleMacOSVersionMin(std::string &Triple) {
688 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
689 if (DarwinDashIdx == std::string::npos) {
690 fprintf(stderr,
691 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
692 exit(1);
693 }
694 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
695
Chris Lattner01de9c82008-09-30 20:16:56 +0000696 // Remove the number.
697 Triple.resize(DarwinNumIdx);
698
699 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
700 bool MacOSVersionMinIsInvalid = false;
701 int VersionNum = 0;
702 if (MacOSVersionMin.size() < 4 ||
703 MacOSVersionMin.substr(0, 3) != "10." ||
704 !isdigit(MacOSVersionMin[3])) {
705 MacOSVersionMinIsInvalid = true;
706 } else {
707 const char *Start = MacOSVersionMin.c_str()+3;
708 char *End = 0;
709 VersionNum = (int)strtol(Start, &End, 10);
710
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000711 // The version number must be in the range 0-9.
712 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
713
Chris Lattner01de9c82008-09-30 20:16:56 +0000714 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
715 Triple += llvm::itostr(VersionNum+4);
716
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000717 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
718 // Add the period piece (.7) to the end of the triple. This gives us
719 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000720 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000721 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
722 MacOSVersionMinIsInvalid = true;
723 }
724 }
725
726 if (MacOSVersionMinIsInvalid) {
727 fprintf(stderr,
728 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
729 MacOSVersionMin.c_str());
730 exit(1);
731 }
732}
733
734/// CreateTargetTriple - Process the various options that affect the target
735/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000736static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000737 // Initialize base triple. If a -triple option has been specified, use
738 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000739 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000740 if (Triple.empty()) {
741 Triple = LLVM_HOSTTRIPLE;
742
743 // On darwin, we want to update the version to match that of the
744 // host.
745 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
746 if (DarwinDashIdx != std::string::npos) {
747 Triple.resize(DarwinDashIdx + strlen("-darwin"));
748
749 Triple += llvm::sys::osVersion();
750 }
751 }
Ted Kremenek40499482007-12-03 22:06:55 +0000752
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000753 // If -arch foo was specified, remove the architecture from the triple we have
754 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000755 if (!Arch.empty()) {
756 // Decompose the base triple into "arch" and suffix.
757 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000758
Chris Lattner2b168e02008-09-30 01:13:12 +0000759 if (FirstDashIdx == std::string::npos) {
760 fprintf(stderr,
761 "Malformed target triple: \"%s\" ('-' could not be found).\n",
762 Triple.c_str());
763 exit(1);
764 }
Ted Kremenek40499482007-12-03 22:06:55 +0000765
Chris Lattner2b168e02008-09-30 01:13:12 +0000766 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
767 }
768
769 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
770 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000771 if (!MacOSVersionMin.empty())
772 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000773
Chris Lattner2b168e02008-09-30 01:13:12 +0000774 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000775}
776
777//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000778// Preprocessor Initialization
779//===----------------------------------------------------------------------===//
780
781// FIXME: Preprocessor builtins to support.
782// -A... - Play with #assertions
783// -undef - Undefine all predefined macros
784
785static llvm::cl::list<std::string>
786D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
787 llvm::cl::desc("Predefine the specified macro"));
788static llvm::cl::list<std::string>
789U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
790 llvm::cl::desc("Undefine the specified macro"));
791
Chris Lattner008da782008-01-10 01:53:41 +0000792static llvm::cl::list<std::string>
793ImplicitIncludes("include", llvm::cl::value_desc("file"),
794 llvm::cl::desc("Include file before parsing"));
795
796
Chris Lattner4b009652007-07-25 00:24:17 +0000797// Append a #define line to Buf for Macro. Macro should be of the form XXX,
798// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
799// "#define XXX Y z W". To get a #define with no value, use "XXX=".
800static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
801 const char *Command = "#define ") {
802 Buf.insert(Buf.end(), Command, Command+strlen(Command));
803 if (const char *Equal = strchr(Macro, '=')) {
804 // Turn the = into ' '.
805 Buf.insert(Buf.end(), Macro, Equal);
806 Buf.push_back(' ');
807 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
808 } else {
809 // Push "macroname 1".
810 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
811 Buf.push_back(' ');
812 Buf.push_back('1');
813 }
814 Buf.push_back('\n');
815}
816
Chris Lattner008da782008-01-10 01:53:41 +0000817/// AddImplicitInclude - Add an implicit #include of the specified file to the
818/// predefines buffer.
819static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
820 const char *Inc = "#include \"";
821 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
822 Buf.insert(Buf.end(), File.begin(), File.end());
823 Buf.push_back('"');
824 Buf.push_back('\n');
825}
826
Chris Lattner4b009652007-07-25 00:24:17 +0000827
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000828/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000829/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000830///
Chris Lattner9d818a22008-04-19 23:25:44 +0000831static bool InitializePreprocessor(Preprocessor &PP,
832 bool InitializeSourceMgr,
833 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000834 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000835
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000836 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000837 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000838
839 if (InitializeSourceMgr) {
840 if (InFile != "-") {
841 const FileEntry *File = FileMgr.getFile(InFile);
842 if (File) SourceMgr.createMainFileID(File, SourceLocation());
843 if (SourceMgr.getMainFileID() == 0) {
844 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000845 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000846 }
847 } else {
848 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
849 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
850 if (SourceMgr.getMainFileID() == 0) {
851 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000852 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000853 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000854 }
Chris Lattner4b009652007-07-25 00:24:17 +0000855 }
Sam Bishop61a20782008-04-14 14:41:57 +0000856
Chris Lattner47b6a162008-04-19 23:09:31 +0000857 std::vector<char> PredefineBuffer;
858
Chris Lattner4b009652007-07-25 00:24:17 +0000859 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000860 unsigned d = 0, D = D_macros.size();
861 unsigned u = 0, U = U_macros.size();
862 while (d < D || u < U) {
863 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
864 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
865 else
866 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
867 }
868
Chris Lattner008da782008-01-10 01:53:41 +0000869 // FIXME: Read any files specified by -imacros.
870
871 // Add implicit #includes from -include.
872 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
873 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000874
Chris Lattner47b6a162008-04-19 23:09:31 +0000875 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000876 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000877 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000878
879 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000880 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000881}
882
883//===----------------------------------------------------------------------===//
884// Preprocessor include path information.
885//===----------------------------------------------------------------------===//
886
887// This tool exports a large number of command line options to control how the
888// preprocessor searches for header files. At root, however, the Preprocessor
889// object takes a very simple interface: a list of directories to search for
890//
891// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000892// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000893//
Chris Lattner008da782008-01-10 01:53:41 +0000894// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000895
896static llvm::cl::opt<bool>
897nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
898
899// Various command line options. These four add directories to each chain.
900static llvm::cl::list<std::string>
901F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
902 llvm::cl::desc("Add directory to framework include search path"));
903static llvm::cl::list<std::string>
904I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
905 llvm::cl::desc("Add directory to include search path"));
906static llvm::cl::list<std::string>
907idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
908 llvm::cl::desc("Add directory to AFTER include search path"));
909static llvm::cl::list<std::string>
910iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
911 llvm::cl::desc("Add directory to QUOTE include search path"));
912static llvm::cl::list<std::string>
913isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
914 llvm::cl::desc("Add directory to SYSTEM include search path"));
915
916// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
917static llvm::cl::list<std::string>
918iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
919 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
920static llvm::cl::list<std::string>
921iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
922 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
923static llvm::cl::list<std::string>
924iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
925 llvm::cl::Prefix,
926 llvm::cl::desc("Set directory to include search path with prefix"));
927
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000928static llvm::cl::opt<std::string>
929isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
930 llvm::cl::desc("Set the system root directory (usually /)"));
931
Chris Lattner4b009652007-07-25 00:24:17 +0000932// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +0000933
Chris Lattner4b009652007-07-25 00:24:17 +0000934/// InitializeIncludePaths - Process the -I options and set them in the
935/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +0000936void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
937 FileManager &FM, const LangOptions &Lang) {
938 InitHeaderSearch Init(Headers, Verbose, isysroot);
939
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000940 // Handle -I... and -F... options, walking the lists in parallel.
941 unsigned Iidx = 0, Fidx = 0;
942 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
943 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +0000944 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000945 ++Iidx;
946 } else {
Nico Weber770e3882008-08-22 09:25:22 +0000947 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000948 ++Fidx;
949 }
950 }
Chris Lattner4b009652007-07-25 00:24:17 +0000951
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000952 // Consume what's left from whatever list was longer.
953 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +0000954 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +0000955 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +0000956 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000957
958 // Handle -idirafter... options.
959 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000960 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
961 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000962
963 // Handle -iquote... options.
964 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000965 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000966
967 // Handle -isystem... options.
968 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +0000969 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000970
971 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
972 // parallel, processing the values in order of occurance to get the right
973 // prefixes.
974 {
975 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
976 unsigned iprefix_idx = 0;
977 unsigned iwithprefix_idx = 0;
978 unsigned iwithprefixbefore_idx = 0;
979 bool iprefix_done = iprefix_vals.empty();
980 bool iwithprefix_done = iwithprefix_vals.empty();
981 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
982 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
983 if (!iprefix_done &&
984 (iwithprefix_done ||
985 iprefix_vals.getPosition(iprefix_idx) <
986 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
987 (iwithprefixbefore_done ||
988 iprefix_vals.getPosition(iprefix_idx) <
989 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
990 Prefix = iprefix_vals[iprefix_idx];
991 ++iprefix_idx;
992 iprefix_done = iprefix_idx == iprefix_vals.size();
993 } else if (!iwithprefix_done &&
994 (iwithprefixbefore_done ||
995 iwithprefix_vals.getPosition(iwithprefix_idx) <
996 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +0000997 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
998 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000999 ++iwithprefix_idx;
1000 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1001 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001002 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1003 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001004 ++iwithprefixbefore_idx;
1005 iwithprefixbefore_done =
1006 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1007 }
1008 }
1009 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001010
Nico Weber770e3882008-08-22 09:25:22 +00001011 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001012
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001013 // Add the clang headers, which are relative to the clang driver.
1014 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001015 llvm::sys::Path::GetMainExecutable(Argv0,
1016 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001017 if (!MainExecutablePath.isEmpty()) {
1018 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1019 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1020 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001021 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1022 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001023 }
1024
Nico Weber770e3882008-08-22 09:25:22 +00001025 if (!nostdinc)
1026 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001027
1028 // Now that we have collected all of the include paths, merge them all
1029 // together and tell the preprocessor about them.
1030
Nico Weber770e3882008-08-22 09:25:22 +00001031 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001032}
1033
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001034//===----------------------------------------------------------------------===//
1035// Driver PreprocessorFactory - For lazily generating preprocessors ...
1036//===----------------------------------------------------------------------===//
1037
1038namespace {
1039class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001040 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001041 Diagnostic &Diags;
1042 const LangOptions &LangInfo;
1043 TargetInfo &Target;
1044 SourceManager &SourceMgr;
1045 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001046 bool InitializeSourceMgr;
1047
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001048public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001049 DriverPreprocessorFactory(const std::string &infile,
1050 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001051 TargetInfo &target, SourceManager &SM,
1052 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001053 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1054 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1055
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001056
1057 virtual ~DriverPreprocessorFactory() {}
1058
1059 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001060 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1061 SourceMgr, HeaderInfo);
1062
Chris Lattner9d818a22008-04-19 23:25:44 +00001063 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001064 delete PP;
1065 return NULL;
1066 }
1067
1068 InitializeSourceMgr = false;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001069 return PP;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001070 }
1071};
1072}
Chris Lattner4b009652007-07-25 00:24:17 +00001073
Chris Lattner4b009652007-07-25 00:24:17 +00001074//===----------------------------------------------------------------------===//
1075// Basic Parser driver
1076//===----------------------------------------------------------------------===//
1077
Chris Lattner9d818a22008-04-19 23:25:44 +00001078static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001079 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001080 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001081
1082 // Parsing the specified input file.
1083 P.ParseTranslationUnit();
1084 delete PA;
1085}
1086
1087//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001088// Code generation options
1089//===----------------------------------------------------------------------===//
1090
1091static llvm::cl::opt<bool>
1092OptSize("Os",
1093 llvm::cl::desc("Optimize for size"));
1094
1095// It might be nice to add bounds to the CommandLine library directly.
1096struct OptLevelParser : public llvm::cl::parser<unsigned> {
1097 bool parse(llvm::cl::Option &O, const char *ArgName,
1098 const std::string &Arg, unsigned &Val) {
1099 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1100 return true;
1101 // FIXME: Support -O4.
1102 if (Val > 3)
1103 return O.error(": '" + Arg + "' invalid optimization level!");
1104 return false;
1105 }
1106};
1107static llvm::cl::opt<unsigned, false, OptLevelParser>
1108OptLevel("O", llvm::cl::Prefix,
1109 llvm::cl::desc("Optimization level"),
1110 llvm::cl::init(0));
1111
1112static void InitializeCompileOptions(CompileOptions &Opts) {
1113 Opts.OptimizationLevel = OptLevel;
1114 Opts.OptimizeSize = OptSize;
1115 // FIXME: Wire other options.
1116}
1117
1118//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001119// Main driver
1120//===----------------------------------------------------------------------===//
1121
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001122/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1123/// action. These consumers can operate on both ASTs that are freshly
1124/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001125static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001126 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001127 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001128 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001129 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001130 switch (ProgAction) {
1131 default:
1132 return NULL;
1133
1134 case ASTPrint:
1135 return CreateASTPrinter();
1136
1137 case ASTDump:
1138 return CreateASTDumper();
1139
1140 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001141 return CreateASTViewer();
1142
1143 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001144 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001145
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001146 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001147 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001148
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001149 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001150 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001151 case EmitBC: {
1152 BackendAction Act;
1153 if (ProgAction == EmitAssembly) {
1154 Act = Backend_EmitAssembly;
1155 } else if (ProgAction == EmitLLVM) {
1156 Act = Backend_EmitLL;
1157 } else {
1158 Act = Backend_EmitBC;
1159 }
1160 CompileOptions Opts;
1161 InitializeCompileOptions(Opts);
1162 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001163 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001164 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001165
Ted Kremenekbde30332007-12-19 17:25:59 +00001166 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001167 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001168 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001169
Steve Naroff44e81222008-04-14 22:03:09 +00001170 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001171 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001172
1173 case RewriteBlocks:
1174 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001175
1176 case RunAnalysis:
1177 assert (!AnalysisList.empty());
1178 return CreateAnalysisConsumer(&AnalysisList[0],
1179 &AnalysisList[0]+AnalysisList.size(),
1180 Diag, PP, PPF, LangOpts,
1181 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001182 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1183 TrimGraph, AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001184 }
1185}
1186
Chris Lattner4b009652007-07-25 00:24:17 +00001187/// ProcessInputFile - Process a single input file with the specified state.
1188///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001189static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001190 const std::string &InFile, ProgActions PA) {
Ted Kremenek6856c632007-09-26 18:39:29 +00001191
Ted Kremenek50aab982008-08-08 02:46:37 +00001192 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001193 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001194
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001195 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001196 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001197 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1198 PP.getFileManager(), PP.getLangOptions(),
1199 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001200
1201 if (!Consumer) {
1202 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001203 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001204 return;
1205 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001206
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001207 break;
1208
Chris Lattneraf669fb2008-10-12 05:03:36 +00001209 case DumpRawTokens: {
1210 SourceManager &SM = PP.getSourceManager();
1211 std::pair<const char*,const char*> File =
1212 SM.getBufferData(SM.getMainFileID());
1213 // Start lexing the specified input file.
1214 Lexer RawLex(SourceLocation::getFileLoc(SM.getMainFileID(), 0),
1215 PP.getLangOptions(), File.first, File.second);
1216 RawLex.SetKeepWhitespaceMode(true);
1217
1218 Token RawTok;
1219
1220 RawLex.LexFromRawLexer(RawTok);
1221 while (RawTok.isNot(tok::eof)) {
1222 PP.DumpToken(RawTok, true);
1223 fprintf(stderr, "\n");
1224 RawLex.LexFromRawLexer(RawTok);
1225 }
1226 ClearSourceMgr = true;
1227 break;
1228 }
Chris Lattner4b009652007-07-25 00:24:17 +00001229 case DumpTokens: { // Token dump mode.
1230 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001231 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001232 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001233 do {
1234 PP.Lex(Tok);
1235 PP.DumpToken(Tok, true);
1236 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001237 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001238 ClearSourceMgr = true;
1239 break;
1240 }
1241 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1242 Token Tok;
1243 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001244 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001245 do {
1246 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001247 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001248 ClearSourceMgr = true;
1249 break;
1250 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001251
1252 case GeneratePCH: {
1253 CacheTokens(PP, OutputFile);
1254 ClearSourceMgr = true;
1255 break;
1256 }
Chris Lattner4b009652007-07-25 00:24:17 +00001257
1258 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001259 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001260 ClearSourceMgr = true;
1261 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001262
Chris Lattner4b009652007-07-25 00:24:17 +00001263 case ParseNoop: // -parse-noop
Ted Kremenek17861c52007-12-19 22:51:13 +00001264 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001265 ClearSourceMgr = true;
1266 break;
1267
1268 case ParsePrintCallbacks:
Ted Kremenek17861c52007-12-19 22:51:13 +00001269 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattner4b009652007-07-25 00:24:17 +00001270 ClearSourceMgr = true;
1271 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001272
Ted Kremenek6856c632007-09-26 18:39:29 +00001273 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001274 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001275 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001276
1277 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001278 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001279 ClearSourceMgr = true;
1280 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001281
1282 case RewriteTest:
1283 DoRewriteTest(PP, InFile, OutputFile);
1284 ClearSourceMgr = true;
1285 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001286 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001287
1288 if (Consumer) {
Ted Kremenek56b70862007-09-26 20:14:22 +00001289 if (VerifyDiagnostics)
Ted Kremenek50aab982008-08-08 02:46:37 +00001290 exit(CheckASTConsumer(PP, Consumer.get()));
Chris Lattner8593cbf2007-11-03 06:24:16 +00001291
Daniel Dunbar4efedde2008-10-16 16:54:18 +00001292 ParseAST(PP, Consumer.get(), Stats, !DisableFree);
Daniel Dunbarab3288e2008-10-05 01:38:39 +00001293 } else {
1294 if (VerifyDiagnostics)
1295 exit(CheckDiagnostics(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001296 }
Chris Lattner8d72ee02008-02-06 01:42:25 +00001297
Chris Lattner4b009652007-07-25 00:24:17 +00001298 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001299 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001300 PP.PrintStats();
1301 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001302 PP.getHeaderSearchInfo().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001303 if (ClearSourceMgr)
Chris Lattner968982d2007-12-15 20:48:40 +00001304 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001305 fprintf(stderr, "\n");
1306 }
1307
1308 // For a multi-file compilation, some things are ok with nuking the source
1309 // manager tables, other require stable fileid/macroid's across multiple
1310 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001311 if (ClearSourceMgr)
1312 PP.getSourceManager().clearIDTables();
Chris Lattner4b009652007-07-25 00:24:17 +00001313}
1314
Ted Kremenek80d53372007-12-12 23:41:08 +00001315static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1316 FileManager& FileMgr) {
1317
1318 if (VerifyDiagnostics) {
1319 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1320 exit (1);
1321 }
1322
1323 llvm::sys::Path Filename(InFile);
1324
1325 if (!Filename.isValid()) {
1326 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1327 exit (1);
1328 }
1329
Ted Kremenek863b01f2008-04-23 16:25:39 +00001330 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001331
1332 if (!TU) {
1333 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1334 InFile.c_str());
1335 exit (1);
1336 }
1337
Ted Kremenekab749372007-12-19 19:27:38 +00001338 // Observe that we use the source file name stored in the deserialized
1339 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001340 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001341 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001342 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001343
Ted Kremenek80d53372007-12-12 23:41:08 +00001344 if (!Consumer) {
1345 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1346 exit (1);
1347 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001348
Ted Kremenek863b01f2008-04-23 16:25:39 +00001349 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001350
Chris Lattner8d72ee02008-02-06 01:42:25 +00001351 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001352 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1353 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001354}
1355
1356
Chris Lattner4b009652007-07-25 00:24:17 +00001357static llvm::cl::list<std::string>
1358InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1359
Ted Kremenek80d53372007-12-12 23:41:08 +00001360static bool isSerializedFile(const std::string& InFile) {
1361 if (InFile.size() < 4)
1362 return false;
1363
1364 const char* s = InFile.c_str()+InFile.size()-4;
1365
1366 return s[0] == '.' &&
1367 s[1] == 'a' &&
1368 s[2] == 's' &&
1369 s[3] == 't';
1370}
1371
Chris Lattner4b009652007-07-25 00:24:17 +00001372
1373int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001374 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001375 llvm::sys::PrintStackTraceOnErrorSignal();
1376
1377 // If no input was specified, read from stdin.
1378 if (InputFilenames.empty())
1379 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001380
Chris Lattner4b009652007-07-25 00:24:17 +00001381 // Create a file manager object to provide access to and cache the filesystem.
1382 FileManager FileMgr;
1383
Ted Kremenekb240e822007-12-11 23:28:38 +00001384 // Create the diagnostic client for reporting errors or for
1385 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001386 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001387
Ted Kremenek5c341732008-08-07 17:49:57 +00001388 if (!VerifyDiagnostics) {
1389 // Print diagnostics to stderr by default.
1390 TextDiagClient = new TextDiagnosticPrinter(!NoShowColumn,
1391 !NoCaretDiagnostics);
1392 } else {
1393 // When checking diagnostics, just buffer them up.
1394 TextDiagClient = new TextDiagnosticBuffer();
1395
1396 if (InputFilenames.size() != 1) {
1397 fprintf(stderr,
1398 "-verify only works on single input files for now.\n");
1399 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001400 }
1401 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001402
Chris Lattner4b009652007-07-25 00:24:17 +00001403 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001404 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1405 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001406 InitializeDiagnostics(Diags);
1407
Chris Lattner45a56e02007-12-05 23:24:17 +00001408 // -I- is a deprecated GCC feature, scan for it and reject it.
1409 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1410 if (I_dirs[i] == "-") {
Ted Kremenekde79f792007-12-11 22:57:35 +00001411 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001412 I_dirs.erase(I_dirs.begin()+i);
1413 --i;
1414 }
1415 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001416
1417 // Get information about the target being compiled for.
1418 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001419 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1420
Chris Lattner2c77d852008-03-14 06:12:05 +00001421 if (Target == 0) {
1422 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1423 Triple.c_str());
1424 fprintf(stderr, "Please use -triple or -arch.\n");
1425 exit(1);
1426 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001427
Ted Kremenek81ea7992008-07-02 00:03:09 +00001428 // Are we invoking one or more source analyses?
1429 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1430 ProgAction = RunAnalysis;
Ted Kremenek5c341732008-08-07 17:49:57 +00001431
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001432 llvm::OwningPtr<SourceManager> SourceMgr;
1433
Chris Lattner4b009652007-07-25 00:24:17 +00001434 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001435 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001436
Ted Kremenek5c341732008-08-07 17:49:57 +00001437 if (isSerializedFile(InFile)) {
1438 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001439 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001440 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001441 else {
1442 /// Create a SourceManager object. This tracks and owns all the file
1443 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001444 if (!SourceMgr)
1445 SourceMgr.reset(new SourceManager());
1446 else
1447 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001448
Ted Kremenek80d53372007-12-12 23:41:08 +00001449 // Initialize language options, inferring file types from input filenames.
1450 LangOptions LangInfo;
1451 InitializeBaseLanguage();
1452 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001453 bool PCH = InitializeLangOptions(LangInfo, LK);
Daniel Dunbar34542952008-08-23 08:43:39 +00001454 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001455 InitializeGCMode(LangInfo);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001456
Ted Kremenek80d53372007-12-12 23:41:08 +00001457 // Process the -I options and set them in the HeaderInfo.
1458 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001459
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001460 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001461
Ted Kremenek80d53372007-12-12 23:41:08 +00001462 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001463 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001464 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001465
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001466 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1467
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001468 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001469 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001470
1471 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1472 // always reset to using TextDiagClient.
1473 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001474
Ted Kremenek5c341732008-08-07 17:49:57 +00001475 if (!HTMLDiag.empty()) {
1476 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1477 &PPFactory));
1478 Diags.setClient(TmpClient.get());
1479 }
1480 else
1481 Diags.setClient(TextDiagClient);
1482
1483 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001484 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1485
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001486 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001487
1488 if (Stats)
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001489 SourceMgr->PrintStats();
Ted Kremenek80d53372007-12-12 23:41:08 +00001490 }
Chris Lattner4b009652007-07-25 00:24:17 +00001491 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001492
Ted Kremenekec6c5252008-08-07 18:13:12 +00001493 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001494 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1495 (NumDiagnostics == 1 ? "" : "s"));
1496
1497 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001498 FileMgr.PrintStats();
1499 fprintf(stderr, "\n");
1500 }
1501
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001502 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001503}