blob: 741eddc3a45ae91286e60bff95aaf2715339a134 [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"
Ted Kremenek21b88b72008-11-03 22:31:48 +000028#include "clang/Driver/PathDiagnosticClients.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"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000048#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000050#include "llvm/Support/PluginLoader.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000051#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000052#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000053#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000054using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Global options.
58//===----------------------------------------------------------------------===//
59
Daniel Dunbar4efedde2008-10-16 16:54:18 +000060static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000061
Chris Lattner4b009652007-07-25 00:24:17 +000062static llvm::cl::opt<bool>
63Verbose("v", llvm::cl::desc("Enable verbose output"));
64static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000065Stats("print-stats",
66 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000067static llvm::cl::opt<bool>
68DisableFree("disable-free",
69 llvm::cl::desc("Disable freeing of memory on exit"),
70 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000071
72enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000073 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000074 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000075 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000076 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000077 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000078 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000079 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000080 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000081 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000082 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000083 ASTPrint, // Parse ASTs and print them.
84 ASTDump, // Parse ASTs and dump them.
85 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000086 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000087 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000088 ParsePrintCallbacks, // Parse and print each callback.
89 ParseSyntaxOnly, // Parse and perform semantic analysis.
90 ParseNoop, // Parse with noop callbacks.
91 RunPreprocessorOnly, // Just lex, no output.
92 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000093 DumpTokens, // Dump out preprocessed tokens.
94 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +000095 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +000096 GeneratePCH, // Generate precompiled header.
97 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +000098};
99
100static llvm::cl::opt<ProgActions>
101ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
102 llvm::cl::init(ParseSyntaxOnly),
103 llvm::cl::values(
104 clEnumValN(RunPreprocessorOnly, "Eonly",
105 "Just run preprocessor, no output (for timings)"),
106 clEnumValN(PrintPreprocessedInput, "E",
107 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000108 clEnumValN(DumpRawTokens, "dump-raw-tokens",
109 "Lex file in raw mode and dump raw tokens"),
110 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000111 "Run preprocessor, dump internal rep of tokens"),
112 clEnumValN(ParseNoop, "parse-noop",
113 "Run parser with noop callbacks (for timings)"),
114 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
115 "Run parser and perform semantic analysis"),
116 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
117 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000118 clEnumValN(EmitHTML, "emit-html",
119 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000120 clEnumValN(ASTPrint, "ast-print",
121 "Build ASTs and then pretty-print them"),
122 clEnumValN(ASTDump, "ast-dump",
123 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000124 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000125 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000126 clEnumValN(PrintDeclContext, "print-decl-contexts",
127 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000128 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000129 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000130 clEnumValN(EmitAssembly, "S",
131 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000132 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000133 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000134 clEnumValN(EmitBC, "emit-llvm-bc",
135 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000136 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000137 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000138 clEnumValN(RewriteTest, "rewrite-test",
139 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000140 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000141 "Rewrite ObjC into C (code rewriter example)"),
142 clEnumValN(RewriteMacros, "rewrite-macros",
143 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000144 clEnumValN(RewriteBlocks, "rewrite-blocks",
145 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000146 clEnumValEnd));
147
Ted Kremenekd01eae62007-12-19 19:47:59 +0000148
149static llvm::cl::opt<std::string>
150OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000151 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000152 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000153
154//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000155// Code Generator Options
156//===----------------------------------------------------------------------===//
157static llvm::cl::opt<bool>
158GenerateDebugInfo("g",
159 llvm::cl::desc("Generate source level debug information"));
160
Ted Kremenek57f25b22008-12-02 19:57:31 +0000161
162//===----------------------------------------------------------------------===//
163// PTH.
164//===----------------------------------------------------------------------===//
165
166static llvm::cl::opt<std::string>
167TokenCache("token-cache", llvm::cl::value_desc("path"),
168 llvm::cl::desc("Use specified token cache file"));
169
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000170//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000171// Diagnostic Options
172//===----------------------------------------------------------------------===//
173
Ted Kremenek10389cf2007-09-26 19:42:19 +0000174static llvm::cl::opt<bool>
175VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000176 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000177
Ted Kremenekfd75e312008-03-27 06:17:42 +0000178static llvm::cl::opt<std::string>
179HTMLDiag("html-diags",
180 llvm::cl::desc("Generate HTML to report diagnostics"),
181 llvm::cl::value_desc("HTML directory"));
182
Nico Weber0e13eaa2008-08-05 23:33:20 +0000183static llvm::cl::opt<bool>
184NoShowColumn("fno-show-column",
185 llvm::cl::desc("Do not include column number on diagnostics"));
186
187static llvm::cl::opt<bool>
188NoCaretDiagnostics("fno-caret-diagnostics",
189 llvm::cl::desc("Do not include source line and caret with"
190 " diagnostics"));
191
192
Chris Lattner4b009652007-07-25 00:24:17 +0000193//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000194// C++ Visualization.
195//===----------------------------------------------------------------------===//
196
197static llvm::cl::opt<std::string>
198InheritanceViewCls("cxx-inheritance-view",
199 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000200 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000201
202//===----------------------------------------------------------------------===//
203// Analyzer Options.
Ted Kremenek517cb512008-04-14 18:40:58 +0000204//===----------------------------------------------------------------------===//
205
206static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000207VisualizeEGDot("analyzer-viz-egraph-graphviz",
208 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000209
210static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000211VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
212 llvm::cl::desc("Display exploded graph using Ubigraph"));
213
214static llvm::cl::opt<bool>
215AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000216 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000217 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000218
Ted Kremenek81ea7992008-07-02 00:03:09 +0000219static llvm::cl::list<Analyses>
Ted Kremenekc3803992008-10-24 01:04:59 +0000220AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000221llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000222#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000223clEnumValN(NAME, CMDFLAG, DESC),
224#include "Analyses.def"
225clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000226
Ted Kremenekc3803992008-10-24 01:04:59 +0000227static llvm::cl::opt<AnalysisStores>
228AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
229 llvm::cl::init(BasicStoreModel),
230 llvm::cl::values(
231#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
232clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
233#include "Analyses.def"
234clEnumValEnd));
235
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000236static llvm::cl::opt<AnalysisDiagClients>
237AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
238 llvm::cl::init(PD_HTML),
239 llvm::cl::values(
240#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)\
241clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
242#include "Analyses.def"
243clEnumValEnd));
244
Ted Kremenek517cb512008-04-14 18:40:58 +0000245//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000246// Language Options
247//===----------------------------------------------------------------------===//
248
249enum LangKind {
250 langkind_unspecified,
251 langkind_c,
252 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000253 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000254 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000255 langkind_cxx,
256 langkind_cxx_cpp,
257 langkind_objc,
258 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000259 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000260 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000261 langkind_objcxx_cpp,
262 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000263};
264
265/* TODO: GCC also accepts:
266 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera19689a2008-10-22 17:29:21 +0000267 assembler
Chris Lattner4b009652007-07-25 00:24:17 +0000268 ada, f77*, ratfor (!), f95, java, treelang
269 */
270static llvm::cl::opt<LangKind>
271BaseLang("x", llvm::cl::desc("Base language to compile"),
272 llvm::cl::init(langkind_unspecified),
273 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
274 clEnumValN(langkind_cxx, "c++", "C++"),
275 clEnumValN(langkind_objc, "objective-c", "Objective C"),
276 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
277 clEnumValN(langkind_c_cpp, "c-cpp-output",
278 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000279 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
280 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000281 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000282 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000283 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
284 "Preprocessed Objective C"),
285 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
286 "Preprocessed Objective C++"),
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000287 clEnumValN(langkind_c_pch,"c-header",
288 "Precompiled C header"),
289 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000290 "Precompiled Objective-C header"),
291 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
292 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000293 clEnumValEnd));
294
295static llvm::cl::opt<bool>
296LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
297 llvm::cl::Hidden);
298static llvm::cl::opt<bool>
299LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
300 llvm::cl::Hidden);
301
Ted Kremenek11ad8952007-12-05 23:49:08 +0000302/// InitializeBaseLanguage - Handle the -x foo options.
303static void InitializeBaseLanguage() {
304 if (LangObjC)
305 BaseLang = langkind_objc;
306 else if (LangObjCXX)
307 BaseLang = langkind_objcxx;
308}
309
310static LangKind GetLanguage(const std::string &Filename) {
311 if (BaseLang != langkind_unspecified)
312 return BaseLang;
313
314 std::string::size_type DotPos = Filename.rfind('.');
315
316 if (DotPos == std::string::npos) {
317 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000318 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000319 }
320
Ted Kremenek11ad8952007-12-05 23:49:08 +0000321 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
322 // C header: .h
323 // C++ header: .hh or .H;
324 // assembler no preprocessing: .s
325 // assembler: .S
326 if (Ext == "c")
327 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000328 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000329 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000330 else if (Ext == "i")
331 return langkind_c_cpp;
332 else if (Ext == "ii")
333 return langkind_cxx_cpp;
334 else if (Ext == "m")
335 return langkind_objc;
336 else if (Ext == "mi")
337 return langkind_objc_cpp;
338 else if (Ext == "mm" || Ext == "M")
339 return langkind_objcxx;
340 else if (Ext == "mii")
341 return langkind_objcxx_cpp;
342 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
343 Ext == "c++" || Ext == "cp" || Ext == "cxx")
344 return langkind_cxx;
345 else
346 return langkind_c;
347}
348
349
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000350static void InitializeCOptions(LangOptions &Options) {
351 // Do nothing.
352}
353
354static void InitializeObjCOptions(LangOptions &Options) {
355 Options.ObjC1 = Options.ObjC2 = 1;
356}
357
358
359static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000360 // FIXME: implement -fpreprocessed mode.
361 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000362 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000363
364 // Test for 'PCH'.
365 switch (LK) {
366 default:
367 break;
368 case langkind_c_pch:
369 LK = langkind_c;
370 PCH = true;
371 break;
372 case langkind_objc_pch:
373 LK = langkind_objc;
374 PCH = true;
375 break;
376 case langkind_objcxx_pch:
377 LK = langkind_objcxx;
378 PCH = true;
379 break;
380 }
Chris Lattner4b009652007-07-25 00:24:17 +0000381
Ted Kremenek11ad8952007-12-05 23:49:08 +0000382 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000383 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000384 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000385 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000386 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000387 case langkind_c_cpp:
388 NoPreprocess = true;
389 // FALLTHROUGH
390 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000391 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000392 break;
393 case langkind_cxx_cpp:
394 NoPreprocess = true;
395 // FALLTHROUGH
396 case langkind_cxx:
397 Options.CPlusPlus = 1;
398 break;
399 case langkind_objc_cpp:
400 NoPreprocess = true;
401 // FALLTHROUGH
402 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000403 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000404 break;
405 case langkind_objcxx_cpp:
406 NoPreprocess = true;
407 // FALLTHROUGH
408 case langkind_objcxx:
409 Options.ObjC1 = Options.ObjC2 = 1;
410 Options.CPlusPlus = 1;
411 break;
412 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000413
414 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000415}
416
417/// LangStds - Language standards we support.
418enum LangStds {
419 lang_unspecified,
420 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000421 lang_gnu_START,
422 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000423 lang_cxx98, lang_gnucxx98,
424 lang_cxx0x, lang_gnucxx0x
425};
426
427static llvm::cl::opt<LangStds>
428LangStd("std", llvm::cl::desc("Language standard to compile for"),
429 llvm::cl::init(lang_unspecified),
430 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
431 clEnumValN(lang_c89, "c90", "ISO C 1990"),
432 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
433 clEnumValN(lang_c94, "iso9899:199409",
434 "ISO C 1990 with amendment 1"),
435 clEnumValN(lang_c99, "c99", "ISO C 1999"),
436// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
437 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
438// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
439 clEnumValN(lang_gnu89, "gnu89",
440 "ISO C 1990 with GNU extensions (default for C)"),
441 clEnumValN(lang_gnu99, "gnu99",
442 "ISO C 1999 with GNU extensions"),
443 clEnumValN(lang_gnu99, "gnu9x",
444 "ISO C 1999 with GNU extensions"),
445 clEnumValN(lang_cxx98, "c++98",
446 "ISO C++ 1998 with amendments"),
447 clEnumValN(lang_gnucxx98, "gnu++98",
448 "ISO C++ 1998 with amendments and GNU "
449 "extensions (default for C++)"),
450 clEnumValN(lang_cxx0x, "c++0x",
451 "Upcoming ISO C++ 200x with amendments"),
452 clEnumValN(lang_gnucxx0x, "gnu++0x",
453 "Upcoming ISO C++ 200x with amendments and GNU "
454 "extensions (default for C++)"),
455 clEnumValEnd));
456
457static llvm::cl::opt<bool>
458NoOperatorNames("fno-operator-names",
459 llvm::cl::desc("Do not treat C++ operator name keywords as "
460 "synonyms for operators"));
461
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000462static llvm::cl::opt<bool>
463PascalStrings("fpascal-strings",
464 llvm::cl::desc("Recognize and construct Pascal-style "
465 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000466
467static llvm::cl::opt<bool>
468MSExtensions("fms-extensions",
469 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000470 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000471
472static llvm::cl::opt<bool>
473WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000474 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000475
476static llvm::cl::opt<bool>
477LaxVectorConversions("flax-vector-conversions",
478 llvm::cl::desc("Allow implicit conversions between vectors"
479 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000480 "different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000481static llvm::cl::opt<bool>
482EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
483
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000484
Daniel Dunbar91692d92008-08-11 17:36:14 +0000485// FIXME: This (and all GCC -f options) really come in -f... and
486// -fno-... forms, and additionally support automagic behavior when
487// they are not defined. For example, -fexceptions defaults to on or
488// off depending on the language. We should support this behavior in
489// some form (perhaps just add a facility for distinguishing when an
490// has its default value from when it has been set to its default
491// value).
492static llvm::cl::opt<bool>
493Exceptions("fexceptions",
494 llvm::cl::desc("Enable support for exception handling."));
495
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000496static llvm::cl::opt<bool>
497GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000498 llvm::cl::desc("Generate output compatible with the standard GNU "
499 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000500
501static llvm::cl::opt<bool>
502NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000503 llvm::cl::desc("Generate output compatible with the NeXT "
504 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000505
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000506
507
508static llvm::cl::opt<bool>
509Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
510
511static llvm::cl::opt<bool>
512Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
513
Chris Lattner4b009652007-07-25 00:24:17 +0000514// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000515// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000516static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
517 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000518 // Allow the target to set the default the langauge options as it sees fit.
519 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000520
521 if (Ansi) // "The -ansi option is equivalent to -std=c89."
522 LangStd = lang_c89;
523
Chris Lattner4b009652007-07-25 00:24:17 +0000524 if (LangStd == lang_unspecified) {
525 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000526 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000527 default: assert(0 && "Unknown base language");
528 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000529 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000530 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000531 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000532 case langkind_objc:
533 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000534 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000535 LangStd = lang_gnu99;
536 break;
537 case langkind_cxx:
538 case langkind_cxx_cpp:
539 case langkind_objcxx:
540 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000541 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000542 LangStd = lang_gnucxx98;
543 break;
544 }
545 }
546
547 switch (LangStd) {
548 default: assert(0 && "Unknown language standard!");
549
550 // Fall through from newer standards to older ones. This isn't really right.
551 // FIXME: Enable specifically the right features based on the language stds.
552 case lang_gnucxx0x:
553 case lang_cxx0x:
554 Options.CPlusPlus0x = 1;
555 // FALL THROUGH
556 case lang_gnucxx98:
557 case lang_cxx98:
558 Options.CPlusPlus = 1;
559 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000560 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000561 // FALL THROUGH.
562 case lang_gnu99:
563 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000564 Options.C99 = 1;
565 Options.HexFloats = 1;
566 // FALL THROUGH.
567 case lang_gnu89:
568 Options.BCPLComment = 1; // Only for C99/C++.
569 // FALL THROUGH.
570 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000571 Options.Digraphs = 1; // C94, C99, C++.
572 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000573 case lang_c89:
574 break;
575 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000576
577 if (Options.CPlusPlus) {
578 Options.C99 = 0;
579 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
580 }
Chris Lattner4b009652007-07-25 00:24:17 +0000581
Chris Lattner6ab935b2008-04-05 06:32:51 +0000582 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
583 Options.ImplicitInt = 1;
584 else
585 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000586
587 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
588 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000589 Options.Trigraphs = LangStd < lang_gnu_START;
590 if (Trigraphs.getPosition())
591 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000592
Chris Lattner58d5ba52008-12-05 00:10:44 +0000593 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
594 // even if they are normally on for the target. In GNU modes (e.g.
595 // -std=gnu99) the default for blocks depends on the target settings.
596 if (LangStd < lang_gnu_START)
597 Options.Blocks = 0;
598
Chris Lattner4b009652007-07-25 00:24:17 +0000599 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000600 if (PascalStrings.getPosition())
601 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000602 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000603 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000604 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000605 Options.Exceptions = Exceptions;
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000606 if (EnableBlocks.getPosition())
607 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000608
Chris Lattnerddae7102008-12-04 22:54:33 +0000609 // Override the default runtime if the user requested it.
610 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000611 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000612 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000613 Options.NeXTRuntime = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000614}
615
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000616static llvm::cl::opt<bool>
617ObjCExclusiveGC("fobjc-gc-only",
618 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000619 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000620
621static llvm::cl::opt<bool>
622ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000623 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000624
625void InitializeGCMode(LangOptions &Options) {
626 if (ObjCExclusiveGC)
627 Options.setGCMode(LangOptions::GCOnly);
628 else if (ObjCEnableGC)
629 Options.setGCMode(LangOptions::HybridGC);
630}
631
632
Chris Lattner4b009652007-07-25 00:24:17 +0000633//===----------------------------------------------------------------------===//
634// Our DiagnosticClient implementation
635//===----------------------------------------------------------------------===//
636
637// FIXME: Werror should take a list of things, -Werror=foo,bar
638static llvm::cl::opt<bool>
639WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
640
641static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000642SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
643
644static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000645WarnOnExtensions("pedantic", llvm::cl::init(false),
646 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
647
648static llvm::cl::opt<bool>
649ErrorOnExtensions("pedantic-errors",
650 llvm::cl::desc("Issue an error on uses of GCC extensions"));
651
652static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000653SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000654 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000655 llvm::cl::init(true));
656
657static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000658WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000659 llvm::cl::desc("Warn for unused macros in the main translation unit"));
660
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000661static llvm::cl::opt<bool>
662WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000663 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000664
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000665static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000666WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
667 llvm::cl::desc("Warn about readonly properties with writable attributes"));
668
669static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000670WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000671 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000672
Chris Lattnera616ee32008-01-23 17:19:46 +0000673static llvm::cl::opt<bool>
674WarnUndefMacros("Wundef",
675 llvm::cl::desc("Warn on use of undefined macros in #if's"));
676
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000677static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000678WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
679 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000680
Steve Naroffb91afca2008-10-21 10:37:50 +0000681static llvm::cl::opt<bool>
682WarnNoStrictSelectorMatch("Wno-strict-selector-match",
683 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
684 llvm::cl::init(true));
685
Chris Lattner4b009652007-07-25 00:24:17 +0000686/// InitializeDiagnostics - Initialize the diagnostic object, based on the
687/// current command line option settings.
688static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000689 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000690 Diags.setWarningsAsErrors(WarningsAsErrors);
691 Diags.setWarnOnExtensions(WarnOnExtensions);
692 Diags.setErrorOnExtensions(ErrorOnExtensions);
693
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000694 // Suppress warnings in system headers unless requested not to.
695 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
696
Chris Lattner4b009652007-07-25 00:24:17 +0000697 // Silence the "macro is not used" warning unless requested.
698 if (!WarnUnusedMacros)
699 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000700
701 // Silence "floating point comparison" warnings unless requested.
702 if (!WarnFloatEqual)
703 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000704
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000705 if (!WarnPropertyReadonlyAttrs)
706 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
707 diag::MAP_IGNORE);
708
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000709 // Silence "format string is not a string literal" warnings if requested
710 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000711 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
712 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000713 if (!WarnUndefMacros)
714 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000715
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000716 if (!WarnImplicitFunctionDeclaration)
717 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
718 diag::MAP_IGNORE);
719
Chris Lattner057a2f52008-05-04 23:52:02 +0000720 // If -pedantic-errors is set, turn extensions that warn by default into
721 // errors.
722 if (ErrorOnExtensions) {
723 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
724 diag::MAP_ERROR);
725 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
726 diag::MAP_ERROR);
727 }
Chris Lattner4b009652007-07-25 00:24:17 +0000728}
729
730//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000731// Analysis-specific options.
732//===----------------------------------------------------------------------===//
733
734static llvm::cl::opt<std::string>
735AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000736 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000737
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000738static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000739TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000740 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000741
Ted Kremenek0118bb52008-02-18 21:21:23 +0000742//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000743// Target Triple Processing.
744//===----------------------------------------------------------------------===//
745
746static llvm::cl::opt<std::string>
747TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000748 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000749
Chris Lattnerfc457002008-03-05 01:18:20 +0000750static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000751Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000752
Chris Lattner2b168e02008-09-30 01:13:12 +0000753static llvm::cl::opt<std::string>
754MacOSVersionMin("mmacosx-version-min",
755 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
756
Chris Lattner01de9c82008-09-30 20:16:56 +0000757// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
758// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
759static void HandleMacOSVersionMin(std::string &Triple) {
760 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
761 if (DarwinDashIdx == std::string::npos) {
762 fprintf(stderr,
763 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
764 exit(1);
765 }
766 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
767
Chris Lattner01de9c82008-09-30 20:16:56 +0000768 // Remove the number.
769 Triple.resize(DarwinNumIdx);
770
771 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
772 bool MacOSVersionMinIsInvalid = false;
773 int VersionNum = 0;
774 if (MacOSVersionMin.size() < 4 ||
775 MacOSVersionMin.substr(0, 3) != "10." ||
776 !isdigit(MacOSVersionMin[3])) {
777 MacOSVersionMinIsInvalid = true;
778 } else {
779 const char *Start = MacOSVersionMin.c_str()+3;
780 char *End = 0;
781 VersionNum = (int)strtol(Start, &End, 10);
782
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000783 // The version number must be in the range 0-9.
784 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
785
Chris Lattner01de9c82008-09-30 20:16:56 +0000786 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
787 Triple += llvm::itostr(VersionNum+4);
788
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000789 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
790 // Add the period piece (.7) to the end of the triple. This gives us
791 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000792 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000793 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
794 MacOSVersionMinIsInvalid = true;
795 }
796 }
797
798 if (MacOSVersionMinIsInvalid) {
799 fprintf(stderr,
800 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
801 MacOSVersionMin.c_str());
802 exit(1);
803 }
804}
805
806/// CreateTargetTriple - Process the various options that affect the target
807/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000808static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000809 // Initialize base triple. If a -triple option has been specified, use
810 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000811 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000812 if (Triple.empty()) {
813 Triple = LLVM_HOSTTRIPLE;
814
Daniel Dunbar81caece2008-12-12 18:34:35 +0000815 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
816 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
817 Triple[2] == '8' && Triple[3] == '6')
818 Triple[1] = '3';
819
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000820 // On darwin, we want to update the version to match that of the
821 // host.
822 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
823 if (DarwinDashIdx != std::string::npos) {
824 Triple.resize(DarwinDashIdx + strlen("-darwin"));
825
Daniel Dunbar81caece2008-12-12 18:34:35 +0000826 // Only add the major part of the os version.
827 std::string Version = llvm::sys::osVersion();
828 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000829 }
830 }
Ted Kremenek40499482007-12-03 22:06:55 +0000831
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000832 // If -arch foo was specified, remove the architecture from the triple we have
833 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000834 if (!Arch.empty()) {
835 // Decompose the base triple into "arch" and suffix.
836 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000837
Chris Lattner2b168e02008-09-30 01:13:12 +0000838 if (FirstDashIdx == std::string::npos) {
839 fprintf(stderr,
840 "Malformed target triple: \"%s\" ('-' could not be found).\n",
841 Triple.c_str());
842 exit(1);
843 }
Ted Kremenek40499482007-12-03 22:06:55 +0000844
Chris Lattner2b168e02008-09-30 01:13:12 +0000845 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
846 }
847
848 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
849 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000850 if (!MacOSVersionMin.empty())
851 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000852
Chris Lattner2b168e02008-09-30 01:13:12 +0000853 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000854}
855
856//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000857// Preprocessor Initialization
858//===----------------------------------------------------------------------===//
859
860// FIXME: Preprocessor builtins to support.
861// -A... - Play with #assertions
862// -undef - Undefine all predefined macros
863
864static llvm::cl::list<std::string>
865D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
866 llvm::cl::desc("Predefine the specified macro"));
867static llvm::cl::list<std::string>
868U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
869 llvm::cl::desc("Undefine the specified macro"));
870
Chris Lattner008da782008-01-10 01:53:41 +0000871static llvm::cl::list<std::string>
872ImplicitIncludes("include", llvm::cl::value_desc("file"),
873 llvm::cl::desc("Include file before parsing"));
874
875
Chris Lattner4b009652007-07-25 00:24:17 +0000876// Append a #define line to Buf for Macro. Macro should be of the form XXX,
877// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
878// "#define XXX Y z W". To get a #define with no value, use "XXX=".
879static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
880 const char *Command = "#define ") {
881 Buf.insert(Buf.end(), Command, Command+strlen(Command));
882 if (const char *Equal = strchr(Macro, '=')) {
883 // Turn the = into ' '.
884 Buf.insert(Buf.end(), Macro, Equal);
885 Buf.push_back(' ');
886 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
887 } else {
888 // Push "macroname 1".
889 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
890 Buf.push_back(' ');
891 Buf.push_back('1');
892 }
893 Buf.push_back('\n');
894}
895
Chris Lattner008da782008-01-10 01:53:41 +0000896/// AddImplicitInclude - Add an implicit #include of the specified file to the
897/// predefines buffer.
898static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
899 const char *Inc = "#include \"";
900 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
901 Buf.insert(Buf.end(), File.begin(), File.end());
902 Buf.push_back('"');
903 Buf.push_back('\n');
904}
905
Chris Lattner4b009652007-07-25 00:24:17 +0000906
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000907/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000908/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000909///
Chris Lattner9d818a22008-04-19 23:25:44 +0000910static bool InitializePreprocessor(Preprocessor &PP,
911 bool InitializeSourceMgr,
912 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000913 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000914
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000915 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000916 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000917
918 if (InitializeSourceMgr) {
919 if (InFile != "-") {
920 const FileEntry *File = FileMgr.getFile(InFile);
921 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000922 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000923 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000924 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000925 }
926 } else {
927 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
928 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000929 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000930 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000931 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000932 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000933 }
Chris Lattner4b009652007-07-25 00:24:17 +0000934 }
Sam Bishop61a20782008-04-14 14:41:57 +0000935
Chris Lattner47b6a162008-04-19 23:09:31 +0000936 std::vector<char> PredefineBuffer;
937
Chris Lattner4b009652007-07-25 00:24:17 +0000938 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000939 unsigned d = 0, D = D_macros.size();
940 unsigned u = 0, U = U_macros.size();
941 while (d < D || u < U) {
942 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
943 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
944 else
945 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
946 }
947
Chris Lattner008da782008-01-10 01:53:41 +0000948 // FIXME: Read any files specified by -imacros.
949
950 // Add implicit #includes from -include.
951 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
952 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000953
Chris Lattner47b6a162008-04-19 23:09:31 +0000954 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000955 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000956 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000957
958 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000959 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000960}
961
962//===----------------------------------------------------------------------===//
963// Preprocessor include path information.
964//===----------------------------------------------------------------------===//
965
966// This tool exports a large number of command line options to control how the
967// preprocessor searches for header files. At root, however, the Preprocessor
968// object takes a very simple interface: a list of directories to search for
969//
970// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000971// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000972//
Chris Lattner008da782008-01-10 01:53:41 +0000973// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000974
975static llvm::cl::opt<bool>
976nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
977
978// Various command line options. These four add directories to each chain.
979static llvm::cl::list<std::string>
980F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
981 llvm::cl::desc("Add directory to framework include search path"));
982static llvm::cl::list<std::string>
983I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
984 llvm::cl::desc("Add directory to include search path"));
985static llvm::cl::list<std::string>
986idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
987 llvm::cl::desc("Add directory to AFTER include search path"));
988static llvm::cl::list<std::string>
989iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
990 llvm::cl::desc("Add directory to QUOTE include search path"));
991static llvm::cl::list<std::string>
992isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
993 llvm::cl::desc("Add directory to SYSTEM include search path"));
994
995// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
996static llvm::cl::list<std::string>
997iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
998 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
999static llvm::cl::list<std::string>
1000iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1001 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1002static llvm::cl::list<std::string>
1003iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1004 llvm::cl::Prefix,
1005 llvm::cl::desc("Set directory to include search path with prefix"));
1006
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001007static llvm::cl::opt<std::string>
1008isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1009 llvm::cl::desc("Set the system root directory (usually /)"));
1010
Chris Lattner4b009652007-07-25 00:24:17 +00001011// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001012
Chris Lattner4b009652007-07-25 00:24:17 +00001013/// InitializeIncludePaths - Process the -I options and set them in the
1014/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001015void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1016 FileManager &FM, const LangOptions &Lang) {
1017 InitHeaderSearch Init(Headers, Verbose, isysroot);
1018
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001019 // Handle -I... and -F... options, walking the lists in parallel.
1020 unsigned Iidx = 0, Fidx = 0;
1021 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1022 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001023 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001024 ++Iidx;
1025 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001026 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001027 ++Fidx;
1028 }
1029 }
Chris Lattner4b009652007-07-25 00:24:17 +00001030
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001031 // Consume what's left from whatever list was longer.
1032 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001033 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001034 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001035 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001036
1037 // Handle -idirafter... options.
1038 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001039 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1040 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001041
1042 // Handle -iquote... options.
1043 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001044 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001045
1046 // Handle -isystem... options.
1047 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001048 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001049
1050 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1051 // parallel, processing the values in order of occurance to get the right
1052 // prefixes.
1053 {
1054 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1055 unsigned iprefix_idx = 0;
1056 unsigned iwithprefix_idx = 0;
1057 unsigned iwithprefixbefore_idx = 0;
1058 bool iprefix_done = iprefix_vals.empty();
1059 bool iwithprefix_done = iwithprefix_vals.empty();
1060 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1061 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1062 if (!iprefix_done &&
1063 (iwithprefix_done ||
1064 iprefix_vals.getPosition(iprefix_idx) <
1065 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1066 (iwithprefixbefore_done ||
1067 iprefix_vals.getPosition(iprefix_idx) <
1068 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1069 Prefix = iprefix_vals[iprefix_idx];
1070 ++iprefix_idx;
1071 iprefix_done = iprefix_idx == iprefix_vals.size();
1072 } else if (!iwithprefix_done &&
1073 (iwithprefixbefore_done ||
1074 iwithprefix_vals.getPosition(iwithprefix_idx) <
1075 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001076 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1077 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001078 ++iwithprefix_idx;
1079 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1080 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001081 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1082 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001083 ++iwithprefixbefore_idx;
1084 iwithprefixbefore_done =
1085 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1086 }
1087 }
1088 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001089
Nico Weber770e3882008-08-22 09:25:22 +00001090 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001091
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001092 // Add the clang headers, which are relative to the clang driver.
1093 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001094 llvm::sys::Path::GetMainExecutable(Argv0,
1095 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001096 if (!MainExecutablePath.isEmpty()) {
1097 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1098 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1099 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001100 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1101 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001102 }
1103
Nico Weber770e3882008-08-22 09:25:22 +00001104 if (!nostdinc)
1105 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001106
1107 // Now that we have collected all of the include paths, merge them all
1108 // together and tell the preprocessor about them.
1109
Nico Weber770e3882008-08-22 09:25:22 +00001110 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001111}
1112
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001113//===----------------------------------------------------------------------===//
1114// Driver PreprocessorFactory - For lazily generating preprocessors ...
1115//===----------------------------------------------------------------------===//
1116
1117namespace {
1118class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001119 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001120 Diagnostic &Diags;
1121 const LangOptions &LangInfo;
1122 TargetInfo &Target;
1123 SourceManager &SourceMgr;
1124 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001125 bool InitializeSourceMgr;
1126
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001127public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001128 DriverPreprocessorFactory(const std::string &infile,
1129 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001130 TargetInfo &target, SourceManager &SM,
1131 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001132 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1133 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1134
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001135
1136 virtual ~DriverPreprocessorFactory() {}
1137
1138 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001139 llvm::OwningPtr<PTHManager> PTHMgr;
1140
1141 // Use PTH?
1142 if (!TokenCache.empty())
1143 PTHMgr.reset(PTHManager::Create(TokenCache));
1144
1145 // Create the Preprocessor.
1146 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1147 SourceMgr, HeaderInfo,
1148 PTHMgr.get()));
1149
1150 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1151 // That argument is used as the IdentifierInfoLookup argument to
1152 // IdentifierTable's ctor.
1153 if (PTHMgr) {
1154 PTHMgr->setPreprocessor(PP.get());
1155 PP->setPTHManager(PTHMgr.take());
1156 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001157
Chris Lattner9d818a22008-04-19 23:25:44 +00001158 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001159 return NULL;
1160 }
1161
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001162 /// FIXME: PP can only handle one callback
1163 if (ProgAction != PrintPreprocessedInput) {
1164 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001165 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001166 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001167 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001168 return NULL;
1169 }
1170 }
1171
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001172 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001173 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001174 }
1175};
1176}
Chris Lattner4b009652007-07-25 00:24:17 +00001177
Chris Lattner4b009652007-07-25 00:24:17 +00001178//===----------------------------------------------------------------------===//
1179// Basic Parser driver
1180//===----------------------------------------------------------------------===//
1181
Chris Lattner9d818a22008-04-19 23:25:44 +00001182static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001183 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001184 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001185
1186 // Parsing the specified input file.
1187 P.ParseTranslationUnit();
1188 delete PA;
1189}
1190
1191//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001192// Code generation options
1193//===----------------------------------------------------------------------===//
1194
1195static llvm::cl::opt<bool>
1196OptSize("Os",
1197 llvm::cl::desc("Optimize for size"));
1198
1199// It might be nice to add bounds to the CommandLine library directly.
1200struct OptLevelParser : public llvm::cl::parser<unsigned> {
1201 bool parse(llvm::cl::Option &O, const char *ArgName,
1202 const std::string &Arg, unsigned &Val) {
1203 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1204 return true;
1205 // FIXME: Support -O4.
1206 if (Val > 3)
1207 return O.error(": '" + Arg + "' invalid optimization level!");
1208 return false;
1209 }
1210};
1211static llvm::cl::opt<unsigned, false, OptLevelParser>
1212OptLevel("O", llvm::cl::Prefix,
1213 llvm::cl::desc("Optimization level"),
1214 llvm::cl::init(0));
1215
1216static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001217 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001218 if (OptSize) {
1219 // -Os implies -O2
1220 // FIXME: Diagnose conflicting options.
1221 Opts.OptimizationLevel = 2;
1222 } else {
1223 Opts.OptimizationLevel = OptLevel;
1224 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001225
1226 // FIXME: There are llvm-gcc options to control these selectively.
1227 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1228 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1229 Opts.SimplifyLibCalls = 1;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001230
1231#ifdef NDEBUG
1232 Opts.VerifyModule = 0;
1233#endif
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001234}
1235
1236//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001237// Main driver
1238//===----------------------------------------------------------------------===//
1239
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001240/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1241/// action. These consumers can operate on both ASTs that are freshly
1242/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001243static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001244 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001245 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001246 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001247 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001248 switch (ProgAction) {
1249 default:
1250 return NULL;
1251
1252 case ASTPrint:
1253 return CreateASTPrinter();
1254
1255 case ASTDump:
1256 return CreateASTDumper();
1257
1258 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001259 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001260
1261 case PrintDeclContext:
1262 return CreateDeclContextPrinter();
Ted Kremenek24612ae2008-03-18 21:19:49 +00001263
1264 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001265 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001266
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001267 case InheritanceView:
1268 return CreateInheritanceViewer(InheritanceViewCls);
1269
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001270 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001271 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001272
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001273 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001274 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001275 case EmitBC: {
1276 BackendAction Act;
1277 if (ProgAction == EmitAssembly) {
1278 Act = Backend_EmitAssembly;
1279 } else if (ProgAction == EmitLLVM) {
1280 Act = Backend_EmitLL;
1281 } else {
1282 Act = Backend_EmitBC;
1283 }
1284 CompileOptions Opts;
1285 InitializeCompileOptions(Opts);
1286 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001287 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001288 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001289
Ted Kremenekbde30332007-12-19 17:25:59 +00001290 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001291 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001292 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001293
Steve Naroff44e81222008-04-14 22:03:09 +00001294 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001295 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001296
1297 case RewriteBlocks:
1298 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001299
1300 case RunAnalysis:
1301 assert (!AnalysisList.empty());
1302 return CreateAnalysisConsumer(&AnalysisList[0],
1303 &AnalysisList[0]+AnalysisList.size(),
Ted Kremeneka3f825e2008-11-03 23:18:07 +00001304 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenek81ea7992008-07-02 00:03:09 +00001305 Diag, PP, PPF, LangOpts,
1306 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001307 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1308 TrimGraph, AnalyzeAll);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001309 }
1310}
1311
Chris Lattner4b009652007-07-25 00:24:17 +00001312/// ProcessInputFile - Process a single input file with the specified state.
1313///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001314static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001315 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001316 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001317 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001318
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001319 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001320 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001321 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1322 PP.getFileManager(), PP.getLangOptions(),
1323 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001324
1325 if (!Consumer) {
1326 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001327 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001328 return;
1329 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001330
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001331 break;
1332
Chris Lattneraf669fb2008-10-12 05:03:36 +00001333 case DumpRawTokens: {
1334 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001335 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001336 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001337 RawLex.SetKeepWhitespaceMode(true);
1338
1339 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001340 RawLex.LexFromRawLexer(RawTok);
1341 while (RawTok.isNot(tok::eof)) {
1342 PP.DumpToken(RawTok, true);
1343 fprintf(stderr, "\n");
1344 RawLex.LexFromRawLexer(RawTok);
1345 }
1346 ClearSourceMgr = true;
1347 break;
1348 }
Chris Lattner4b009652007-07-25 00:24:17 +00001349 case DumpTokens: { // Token dump mode.
1350 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001351 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001352 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001353 do {
1354 PP.Lex(Tok);
1355 PP.DumpToken(Tok, true);
1356 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001357 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001358 ClearSourceMgr = true;
1359 break;
1360 }
1361 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1362 Token Tok;
1363 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001364 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001365 do {
1366 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001367 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001368 ClearSourceMgr = true;
1369 break;
1370 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001371
1372 case GeneratePCH: {
1373 CacheTokens(PP, OutputFile);
1374 ClearSourceMgr = true;
1375 break;
1376 }
Chris Lattner4b009652007-07-25 00:24:17 +00001377
1378 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001379 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001380 ClearSourceMgr = true;
1381 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001382
Chris Lattner4b009652007-07-25 00:24:17 +00001383 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001384 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001385 ClearSourceMgr = true;
1386 break;
1387
1388 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001389 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001390 ClearSourceMgr = true;
1391 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001392
Ted Kremenek6856c632007-09-26 18:39:29 +00001393 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001394 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001395 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001396
1397 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001398 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001399 ClearSourceMgr = true;
1400 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001401
1402 case RewriteTest:
1403 DoRewriteTest(PP, InFile, OutputFile);
1404 ClearSourceMgr = true;
1405 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001406 }
Ted Kremenek6856c632007-09-26 18:39:29 +00001407
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001408 if (Consumer)
Daniel Dunbar4efedde2008-10-16 16:54:18 +00001409 ParseAST(PP, Consumer.get(), Stats, !DisableFree);
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001410
1411 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001412 if (CheckDiagnostics(PP))
1413 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001414
Chris Lattner4b009652007-07-25 00:24:17 +00001415 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001416 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001417 PP.PrintStats();
1418 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001419 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001420 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001421 fprintf(stderr, "\n");
1422 }
1423
1424 // For a multi-file compilation, some things are ok with nuking the source
1425 // manager tables, other require stable fileid/macroid's across multiple
1426 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001427 if (ClearSourceMgr)
1428 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001429
1430 if (DisableFree)
1431 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001432}
1433
Ted Kremenek80d53372007-12-12 23:41:08 +00001434static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1435 FileManager& FileMgr) {
1436
1437 if (VerifyDiagnostics) {
1438 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1439 exit (1);
1440 }
1441
1442 llvm::sys::Path Filename(InFile);
1443
1444 if (!Filename.isValid()) {
1445 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1446 exit (1);
1447 }
1448
Ted Kremenek863b01f2008-04-23 16:25:39 +00001449 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001450
1451 if (!TU) {
1452 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1453 InFile.c_str());
1454 exit (1);
1455 }
1456
Ted Kremenekab749372007-12-19 19:27:38 +00001457 // Observe that we use the source file name stored in the deserialized
1458 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001459 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001460 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001461 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001462
Ted Kremenek80d53372007-12-12 23:41:08 +00001463 if (!Consumer) {
1464 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1465 exit (1);
1466 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001467
Ted Kremenek863b01f2008-04-23 16:25:39 +00001468 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001469
Chris Lattner8d72ee02008-02-06 01:42:25 +00001470 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001471 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1472 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001473}
1474
1475
Chris Lattner4b009652007-07-25 00:24:17 +00001476static llvm::cl::list<std::string>
1477InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1478
Ted Kremenek80d53372007-12-12 23:41:08 +00001479static bool isSerializedFile(const std::string& InFile) {
1480 if (InFile.size() < 4)
1481 return false;
1482
1483 const char* s = InFile.c_str()+InFile.size()-4;
1484
1485 return s[0] == '.' &&
1486 s[1] == 'a' &&
1487 s[2] == 's' &&
1488 s[3] == 't';
1489}
1490
Chris Lattner4b009652007-07-25 00:24:17 +00001491
1492int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001493 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001494 llvm::sys::PrintStackTraceOnErrorSignal();
1495
1496 // If no input was specified, read from stdin.
1497 if (InputFilenames.empty())
1498 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001499
Chris Lattner4b009652007-07-25 00:24:17 +00001500 // Create a file manager object to provide access to and cache the filesystem.
1501 FileManager FileMgr;
1502
Ted Kremenekb240e822007-12-11 23:28:38 +00001503 // Create the diagnostic client for reporting errors or for
1504 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001505 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001506
Ted Kremenek5c341732008-08-07 17:49:57 +00001507 if (!VerifyDiagnostics) {
1508 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001509 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1510 !NoShowColumn,
Ted Kremenek5c341732008-08-07 17:49:57 +00001511 !NoCaretDiagnostics);
1512 } else {
1513 // When checking diagnostics, just buffer them up.
1514 TextDiagClient = new TextDiagnosticBuffer();
1515
1516 if (InputFilenames.size() != 1) {
1517 fprintf(stderr,
1518 "-verify only works on single input files for now.\n");
1519 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001520 }
1521 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001522
Chris Lattner4b009652007-07-25 00:24:17 +00001523 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001524 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1525 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001526 InitializeDiagnostics(Diags);
1527
Chris Lattner45a56e02007-12-05 23:24:17 +00001528 // -I- is a deprecated GCC feature, scan for it and reject it.
1529 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1530 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001531 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001532 I_dirs.erase(I_dirs.begin()+i);
1533 --i;
1534 }
1535 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001536
1537 // Get information about the target being compiled for.
1538 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001539 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1540
Chris Lattner2c77d852008-03-14 06:12:05 +00001541 if (Target == 0) {
1542 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1543 Triple.c_str());
1544 fprintf(stderr, "Please use -triple or -arch.\n");
1545 exit(1);
1546 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001547
Ted Kremenek81ea7992008-07-02 00:03:09 +00001548 // Are we invoking one or more source analyses?
1549 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1550 ProgAction = RunAnalysis;
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001551 else if (!InheritanceViewCls.empty()) // C++ visualization?
1552 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001553
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001554 llvm::OwningPtr<SourceManager> SourceMgr;
1555
Chris Lattner4b009652007-07-25 00:24:17 +00001556 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001557 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001558
Ted Kremenek5c341732008-08-07 17:49:57 +00001559 if (isSerializedFile(InFile)) {
1560 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001561 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001562 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001563 else {
1564 /// Create a SourceManager object. This tracks and owns all the file
1565 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001566 if (!SourceMgr)
1567 SourceMgr.reset(new SourceManager());
1568 else
1569 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001570
Ted Kremenek80d53372007-12-12 23:41:08 +00001571 // Initialize language options, inferring file types from input filenames.
1572 LangOptions LangInfo;
1573 InitializeBaseLanguage();
1574 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001575 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001576 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001577 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001578
Ted Kremenek80d53372007-12-12 23:41:08 +00001579 // Process the -I options and set them in the HeaderInfo.
1580 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001581
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001582 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001583
Ted Kremenek80d53372007-12-12 23:41:08 +00001584 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001585 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001586 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001587
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001588 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1589
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001590 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001591 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001592
1593 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1594 // always reset to using TextDiagClient.
1595 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001596
Ted Kremenek5c341732008-08-07 17:49:57 +00001597 if (!HTMLDiag.empty()) {
1598 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1599 &PPFactory));
1600 Diags.setClient(TmpClient.get());
1601 }
1602 else
1603 Diags.setClient(TextDiagClient);
1604
1605 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001606 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1607
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001608 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001609 }
Chris Lattner4b009652007-07-25 00:24:17 +00001610 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001611
Ted Kremenekec6c5252008-08-07 18:13:12 +00001612 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001613 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1614 (NumDiagnostics == 1 ? "" : "s"));
1615
1616 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001617 FileMgr.PrintStats();
1618 fprintf(stderr, "\n");
1619 }
1620
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001621 // If verifying diagnostics and we reached here, all is well.
1622 if (VerifyDiagnostics)
1623 return 0;
1624
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001625 // Managed static deconstruction. Useful for making things like
1626 // -time-passes usable.
1627 llvm::llvm_shutdown();
1628
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001629 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001630}