blob: ca91fc682ba3faf858210307314ba7d11f41ddbc [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"
Chris Lattner545f39e2009-01-29 05:15:15 +000032#include "clang/Driver/DriverDiagnostic.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000033#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000034#include "clang/AST/Decl.h"
Ted Kremenekac881932007-12-18 21:34:28 +000035#include "clang/AST/TranslationUnit.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000036#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000037#include "clang/Sema/ParseAST.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000039#include "clang/Parse/Parser.h"
40#include "clang/Lex/HeaderSearch.h"
41#include "clang/Basic/FileManager.h"
42#include "clang/Basic/SourceManager.h"
43#include "clang/Basic/TargetInfo.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000044#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000045#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000046#include "llvm/ADT/StringExtras.h"
47#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000048#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000049#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000050#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000051#include "llvm/Support/PluginLoader.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000052#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000053#include "llvm/System/Path.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000054#include "llvm/System/Signals.h"
Chris Lattner4b009652007-07-25 00:24:17 +000055using namespace clang;
56
57//===----------------------------------------------------------------------===//
58// Global options.
59//===----------------------------------------------------------------------===//
60
Daniel Dunbar4efedde2008-10-16 16:54:18 +000061static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +000062
Chris Lattner4b009652007-07-25 00:24:17 +000063static llvm::cl::opt<bool>
64Verbose("v", llvm::cl::desc("Enable verbose output"));
65static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +000066Stats("print-stats",
67 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +000068static llvm::cl::opt<bool>
69DisableFree("disable-free",
70 llvm::cl::desc("Disable freeing of memory on exit"),
71 llvm::cl::init(false));
Chris Lattner4b009652007-07-25 00:24:17 +000072
73enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +000074 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +000075 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +000076 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +000077 RewriteTest, // Rewriter playground
Ted Kremeneke1a79d82008-03-19 07:53:42 +000078 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +000079 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +000080 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +000081 EmitBC, // Emit a .bc file.
Ted Kremenek397de012007-12-13 00:37:31 +000082 SerializeAST, // Emit a .ast file.
Ted Kremenek24612ae2008-03-18 21:19:49 +000083 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +000084 ASTPrint, // Parse ASTs and print them.
85 ASTDump, // Parse ASTs and dump them.
86 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +000087 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenek221bb8d2007-10-16 23:37:27 +000088 TestSerialization, // Run experimental serialization code.
Chris Lattner4b009652007-07-25 00:24:17 +000089 ParsePrintCallbacks, // Parse and print each callback.
90 ParseSyntaxOnly, // Parse and perform semantic analysis.
91 ParseNoop, // Parse with noop callbacks.
92 RunPreprocessorOnly, // Just lex, no output.
93 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +000094 DumpTokens, // Dump out preprocessed tokens.
95 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +000096 RunAnalysis, // Run one or more source code analyses.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +000097 GeneratePCH, // Generate precompiled header.
98 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +000099};
100
101static llvm::cl::opt<ProgActions>
102ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
103 llvm::cl::init(ParseSyntaxOnly),
104 llvm::cl::values(
105 clEnumValN(RunPreprocessorOnly, "Eonly",
106 "Just run preprocessor, no output (for timings)"),
107 clEnumValN(PrintPreprocessedInput, "E",
108 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000109 clEnumValN(DumpRawTokens, "dump-raw-tokens",
110 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000111 clEnumValN(RunAnalysis, "analyze",
112 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000113 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000114 "Run preprocessor, dump internal rep of tokens"),
115 clEnumValN(ParseNoop, "parse-noop",
116 "Run parser with noop callbacks (for timings)"),
117 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
118 "Run parser and perform semantic analysis"),
119 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
120 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000121 clEnumValN(EmitHTML, "emit-html",
122 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000123 clEnumValN(ASTPrint, "ast-print",
124 "Build ASTs and then pretty-print them"),
125 clEnumValN(ASTDump, "ast-dump",
126 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000127 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000128 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000129 clEnumValN(PrintDeclContext, "print-decl-contexts",
130 "Print DeclContexts and their Decls."),
Ted Kremenek221bb8d2007-10-16 23:37:27 +0000131 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000132 "Run prototype serialization code"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000133 clEnumValN(EmitAssembly, "S",
134 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000135 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000136 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000137 clEnumValN(EmitBC, "emit-llvm-bc",
138 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000139 clEnumValN(SerializeAST, "serialize",
Ted Kremenek397de012007-12-13 00:37:31 +0000140 "Build ASTs and emit .ast file"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000141 clEnumValN(RewriteTest, "rewrite-test",
142 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000143 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000144 "Rewrite ObjC into C (code rewriter example)"),
145 clEnumValN(RewriteMacros, "rewrite-macros",
146 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000147 clEnumValN(RewriteBlocks, "rewrite-blocks",
148 "Rewrite Blocks to C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000149 clEnumValEnd));
150
Ted Kremenekd01eae62007-12-19 19:47:59 +0000151
152static llvm::cl::opt<std::string>
153OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000154 llvm::cl::value_desc("path"),
Ted Kremenekd01eae62007-12-19 19:47:59 +0000155 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000156
157//===----------------------------------------------------------------------===//
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000158// Code Generator Options
159//===----------------------------------------------------------------------===//
160static llvm::cl::opt<bool>
161GenerateDebugInfo("g",
162 llvm::cl::desc("Generate source level debug information"));
163
Ted Kremenek57f25b22008-12-02 19:57:31 +0000164
165//===----------------------------------------------------------------------===//
166// PTH.
167//===----------------------------------------------------------------------===//
168
169static llvm::cl::opt<std::string>
170TokenCache("token-cache", llvm::cl::value_desc("path"),
171 llvm::cl::desc("Use specified token cache file"));
172
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000173//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000174// Diagnostic Options
175//===----------------------------------------------------------------------===//
176
Ted Kremenek10389cf2007-09-26 19:42:19 +0000177static llvm::cl::opt<bool>
178VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000179 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000180
Ted Kremenekfd75e312008-03-27 06:17:42 +0000181static llvm::cl::opt<std::string>
182HTMLDiag("html-diags",
183 llvm::cl::desc("Generate HTML to report diagnostics"),
184 llvm::cl::value_desc("HTML directory"));
185
Nico Weber0e13eaa2008-08-05 23:33:20 +0000186static llvm::cl::opt<bool>
187NoShowColumn("fno-show-column",
188 llvm::cl::desc("Do not include column number on diagnostics"));
189
190static llvm::cl::opt<bool>
191NoCaretDiagnostics("fno-caret-diagnostics",
192 llvm::cl::desc("Do not include source line and caret with"
193 " diagnostics"));
194
195
Chris Lattner4b009652007-07-25 00:24:17 +0000196//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000197// C++ Visualization.
198//===----------------------------------------------------------------------===//
199
200static llvm::cl::opt<std::string>
201InheritanceViewCls("cxx-inheritance-view",
202 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000203 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000204
205//===----------------------------------------------------------------------===//
206// Analyzer Options.
Ted Kremenek517cb512008-04-14 18:40:58 +0000207//===----------------------------------------------------------------------===//
208
209static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000210VisualizeEGDot("analyzer-viz-egraph-graphviz",
211 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000212
213static llvm::cl::opt<bool>
Ted Kremenekcf262252008-08-27 22:31:43 +0000214VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
215 llvm::cl::desc("Display exploded graph using Ubigraph"));
216
217static llvm::cl::opt<bool>
218AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek517cb512008-04-14 18:40:58 +0000219 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000220 "functions defined in header files"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000221
Ted Kremenek60feb282009-01-23 20:52:26 +0000222static llvm::cl::opt<bool>
223AnalyzerDisplayProgress("analyzer-display-progress",
224 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
225
Ted Kremenek81ea7992008-07-02 00:03:09 +0000226static llvm::cl::list<Analyses>
Ted Kremenekc3803992008-10-24 01:04:59 +0000227AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenek81ea7992008-07-02 00:03:09 +0000228llvm::cl::values(
Ted Kremenekfbda0ef2008-07-15 00:46:02 +0000229#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenek8ce61b32008-07-14 23:41:13 +0000230clEnumValN(NAME, CMDFLAG, DESC),
231#include "Analyses.def"
232clEnumValEnd));
Ted Kremenek81ea7992008-07-02 00:03:09 +0000233
Ted Kremenekc3803992008-10-24 01:04:59 +0000234static llvm::cl::opt<AnalysisStores>
235AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
236 llvm::cl::init(BasicStoreModel),
237 llvm::cl::values(
238#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
239clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
240#include "Analyses.def"
241clEnumValEnd));
242
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000243static llvm::cl::opt<AnalysisDiagClients>
244AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
245 llvm::cl::init(PD_HTML),
246 llvm::cl::values(
Ted Kremenekdd485cb2009-01-23 20:06:20 +0000247#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
Ted Kremeneka3f825e2008-11-03 23:18:07 +0000248clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
249#include "Analyses.def"
250clEnumValEnd));
251
Ted Kremenek517cb512008-04-14 18:40:58 +0000252//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000253// Language Options
254//===----------------------------------------------------------------------===//
255
256enum LangKind {
257 langkind_unspecified,
258 langkind_c,
259 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000260 langkind_asm_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000261 langkind_c_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000262 langkind_cxx,
263 langkind_cxx_cpp,
264 langkind_objc,
265 langkind_objc_cpp,
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000266 langkind_objc_pch,
Chris Lattner4b009652007-07-25 00:24:17 +0000267 langkind_objcxx,
Ted Kremenekceacc812009-01-09 00:38:08 +0000268 langkind_objcxx_cpp,
269 langkind_objcxx_pch
Chris Lattner4b009652007-07-25 00:24:17 +0000270};
271
272/* TODO: GCC also accepts:
273 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera19689a2008-10-22 17:29:21 +0000274 assembler
Chris Lattner4b009652007-07-25 00:24:17 +0000275 ada, f77*, ratfor (!), f95, java, treelang
276 */
277static llvm::cl::opt<LangKind>
278BaseLang("x", llvm::cl::desc("Base language to compile"),
279 llvm::cl::init(langkind_unspecified),
280 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
281 clEnumValN(langkind_cxx, "c++", "C++"),
282 clEnumValN(langkind_objc, "objective-c", "Objective C"),
283 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
284 clEnumValN(langkind_c_cpp, "c-cpp-output",
285 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000286 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
287 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000288 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000289 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000290 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
291 "Preprocessed Objective C"),
292 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
293 "Preprocessed Objective C++"),
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000294 clEnumValN(langkind_c_pch,"c-header",
295 "Precompiled C header"),
296 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekceacc812009-01-09 00:38:08 +0000297 "Precompiled Objective-C header"),
298 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
299 "Precompiled Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000300 clEnumValEnd));
301
302static llvm::cl::opt<bool>
303LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
304 llvm::cl::Hidden);
305static llvm::cl::opt<bool>
306LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
307 llvm::cl::Hidden);
308
Ted Kremenek11ad8952007-12-05 23:49:08 +0000309/// InitializeBaseLanguage - Handle the -x foo options.
310static void InitializeBaseLanguage() {
311 if (LangObjC)
312 BaseLang = langkind_objc;
313 else if (LangObjCXX)
314 BaseLang = langkind_objcxx;
315}
316
317static LangKind GetLanguage(const std::string &Filename) {
318 if (BaseLang != langkind_unspecified)
319 return BaseLang;
320
321 std::string::size_type DotPos = Filename.rfind('.');
322
323 if (DotPos == std::string::npos) {
324 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000325 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000326 }
327
Ted Kremenek11ad8952007-12-05 23:49:08 +0000328 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
329 // C header: .h
330 // C++ header: .hh or .H;
331 // assembler no preprocessing: .s
332 // assembler: .S
333 if (Ext == "c")
334 return langkind_c;
Chris Lattner1cbb3032008-10-28 20:33:42 +0000335 else if (Ext == "S")
Chris Lattnera19689a2008-10-22 17:29:21 +0000336 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000337 else if (Ext == "i")
338 return langkind_c_cpp;
339 else if (Ext == "ii")
340 return langkind_cxx_cpp;
341 else if (Ext == "m")
342 return langkind_objc;
343 else if (Ext == "mi")
344 return langkind_objc_cpp;
345 else if (Ext == "mm" || Ext == "M")
346 return langkind_objcxx;
347 else if (Ext == "mii")
348 return langkind_objcxx_cpp;
349 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
350 Ext == "c++" || Ext == "cp" || Ext == "cxx")
351 return langkind_cxx;
352 else
353 return langkind_c;
354}
355
356
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000357static void InitializeCOptions(LangOptions &Options) {
358 // Do nothing.
359}
360
361static void InitializeObjCOptions(LangOptions &Options) {
362 Options.ObjC1 = Options.ObjC2 = 1;
363}
364
365
366static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000367 // FIXME: implement -fpreprocessed mode.
368 bool NoPreprocess = false;
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000369 bool PCH = false;
Ted Kremenekceacc812009-01-09 00:38:08 +0000370
371 // Test for 'PCH'.
372 switch (LK) {
373 default:
374 break;
375 case langkind_c_pch:
376 LK = langkind_c;
377 PCH = true;
378 break;
379 case langkind_objc_pch:
380 LK = langkind_objc;
381 PCH = true;
382 break;
383 case langkind_objcxx_pch:
384 LK = langkind_objcxx;
385 PCH = true;
386 break;
387 }
Chris Lattner4b009652007-07-25 00:24:17 +0000388
Ted Kremenek11ad8952007-12-05 23:49:08 +0000389 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000390 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000391 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000392 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000393 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000394 case langkind_c_cpp:
395 NoPreprocess = true;
396 // FALLTHROUGH
397 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000398 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000399 break;
400 case langkind_cxx_cpp:
401 NoPreprocess = true;
402 // FALLTHROUGH
403 case langkind_cxx:
404 Options.CPlusPlus = 1;
405 break;
406 case langkind_objc_cpp:
407 NoPreprocess = true;
408 // FALLTHROUGH
409 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000410 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000411 break;
412 case langkind_objcxx_cpp:
413 NoPreprocess = true;
414 // FALLTHROUGH
415 case langkind_objcxx:
416 Options.ObjC1 = Options.ObjC2 = 1;
417 Options.CPlusPlus = 1;
418 break;
419 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000420
421 return PCH;
Chris Lattner4b009652007-07-25 00:24:17 +0000422}
423
424/// LangStds - Language standards we support.
425enum LangStds {
426 lang_unspecified,
427 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000428 lang_gnu_START,
429 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000430 lang_cxx98, lang_gnucxx98,
431 lang_cxx0x, lang_gnucxx0x
432};
433
434static llvm::cl::opt<LangStds>
435LangStd("std", llvm::cl::desc("Language standard to compile for"),
436 llvm::cl::init(lang_unspecified),
437 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
438 clEnumValN(lang_c89, "c90", "ISO C 1990"),
439 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
440 clEnumValN(lang_c94, "iso9899:199409",
441 "ISO C 1990 with amendment 1"),
442 clEnumValN(lang_c99, "c99", "ISO C 1999"),
443// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
444 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
445// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
446 clEnumValN(lang_gnu89, "gnu89",
447 "ISO C 1990 with GNU extensions (default for C)"),
448 clEnumValN(lang_gnu99, "gnu99",
449 "ISO C 1999 with GNU extensions"),
450 clEnumValN(lang_gnu99, "gnu9x",
451 "ISO C 1999 with GNU extensions"),
452 clEnumValN(lang_cxx98, "c++98",
453 "ISO C++ 1998 with amendments"),
454 clEnumValN(lang_gnucxx98, "gnu++98",
455 "ISO C++ 1998 with amendments and GNU "
456 "extensions (default for C++)"),
457 clEnumValN(lang_cxx0x, "c++0x",
458 "Upcoming ISO C++ 200x with amendments"),
459 clEnumValN(lang_gnucxx0x, "gnu++0x",
460 "Upcoming ISO C++ 200x with amendments and GNU "
461 "extensions (default for C++)"),
462 clEnumValEnd));
463
464static llvm::cl::opt<bool>
465NoOperatorNames("fno-operator-names",
466 llvm::cl::desc("Do not treat C++ operator name keywords as "
467 "synonyms for operators"));
468
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000469static llvm::cl::opt<bool>
470PascalStrings("fpascal-strings",
471 llvm::cl::desc("Recognize and construct Pascal-style "
472 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000473
474static llvm::cl::opt<bool>
475MSExtensions("fms-extensions",
476 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000477 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000478
479static llvm::cl::opt<bool>
480WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000481 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000482
483static llvm::cl::opt<bool>
484LaxVectorConversions("flax-vector-conversions",
485 llvm::cl::desc("Allow implicit conversions between vectors"
486 " with a different number of elements or "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000487 "different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000488static llvm::cl::opt<bool>
489EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
490
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000491static llvm::cl::opt<bool>
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000492ObjCNonFragileABI("fobjc-nonfragile-abi", llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000493
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000494
Daniel Dunbar91692d92008-08-11 17:36:14 +0000495// FIXME: This (and all GCC -f options) really come in -f... and
496// -fno-... forms, and additionally support automagic behavior when
497// they are not defined. For example, -fexceptions defaults to on or
498// off depending on the language. We should support this behavior in
499// some form (perhaps just add a facility for distinguishing when an
500// has its default value from when it has been set to its default
501// value).
502static llvm::cl::opt<bool>
503Exceptions("fexceptions",
504 llvm::cl::desc("Enable support for exception handling."));
505
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000506static llvm::cl::opt<bool>
507GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000508 llvm::cl::desc("Generate output compatible with the standard GNU "
509 "Objective-C runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000510
511static llvm::cl::opt<bool>
512NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000513 llvm::cl::desc("Generate output compatible with the NeXT "
514 "runtime."));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000515
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000516
517
518static llvm::cl::opt<bool>
519Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
520
521static llvm::cl::opt<bool>
522Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
523
Chris Lattner4b009652007-07-25 00:24:17 +0000524// FIXME: add:
Chris Lattner4b009652007-07-25 00:24:17 +0000525// -fdollars-in-identifiers
Daniel Dunbar34542952008-08-23 08:43:39 +0000526static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
527 TargetInfo *Target) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000528 // Allow the target to set the default the langauge options as it sees fit.
529 Target->getDefaultLangOptions(Options);
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000530
531 if (Ansi) // "The -ansi option is equivalent to -std=c89."
532 LangStd = lang_c89;
533
Chris Lattner4b009652007-07-25 00:24:17 +0000534 if (LangStd == lang_unspecified) {
535 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000536 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000537 default: assert(0 && "Unknown base language");
538 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000539 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000540 case langkind_c_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000541 case langkind_c_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000542 case langkind_objc:
543 case langkind_objc_cpp:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000544 case langkind_objc_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000545 LangStd = lang_gnu99;
546 break;
547 case langkind_cxx:
548 case langkind_cxx_cpp:
549 case langkind_objcxx:
550 case langkind_objcxx_cpp:
Ted Kremenekceacc812009-01-09 00:38:08 +0000551 case langkind_objcxx_pch:
Chris Lattner4b009652007-07-25 00:24:17 +0000552 LangStd = lang_gnucxx98;
553 break;
554 }
555 }
556
557 switch (LangStd) {
558 default: assert(0 && "Unknown language standard!");
559
560 // Fall through from newer standards to older ones. This isn't really right.
561 // FIXME: Enable specifically the right features based on the language stds.
562 case lang_gnucxx0x:
563 case lang_cxx0x:
564 Options.CPlusPlus0x = 1;
565 // FALL THROUGH
566 case lang_gnucxx98:
567 case lang_cxx98:
568 Options.CPlusPlus = 1;
569 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begemanca893342007-11-15 07:30:50 +0000570 Options.Boolean = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000571 // FALL THROUGH.
572 case lang_gnu99:
573 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000574 Options.C99 = 1;
575 Options.HexFloats = 1;
576 // FALL THROUGH.
577 case lang_gnu89:
578 Options.BCPLComment = 1; // Only for C99/C++.
579 // FALL THROUGH.
580 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000581 Options.Digraphs = 1; // C94, C99, C++.
582 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000583 case lang_c89:
584 break;
585 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000586
587 if (Options.CPlusPlus) {
588 Options.C99 = 0;
589 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
590 }
Chris Lattner4b009652007-07-25 00:24:17 +0000591
Chris Lattner6ab935b2008-04-05 06:32:51 +0000592 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
593 Options.ImplicitInt = 1;
594 else
595 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000596
597 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
598 // is specified, or -std is set to a conforming mode.
Chris Lattner58d5ba52008-12-05 00:10:44 +0000599 Options.Trigraphs = LangStd < lang_gnu_START;
600 if (Trigraphs.getPosition())
601 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000602
Chris Lattner58d5ba52008-12-05 00:10:44 +0000603 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
604 // even if they are normally on for the target. In GNU modes (e.g.
605 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000606 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
607 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000608 Options.Blocks = 0;
609
Chris Lattner4b009652007-07-25 00:24:17 +0000610 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000611 if (PascalStrings.getPosition())
612 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000613 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000614 Options.WritableStrings = WritableStrings;
Anders Carlssone87cd982007-11-30 04:21:22 +0000615 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000616 Options.Exceptions = Exceptions;
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000617 if (EnableBlocks.getPosition())
618 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000619
Chris Lattnerddae7102008-12-04 22:54:33 +0000620 // Override the default runtime if the user requested it.
621 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000622 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000623 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000624 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000625
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000626 if (ObjCNonFragileABI)
627 Options.ObjCNonFragileABI = 1;
Chris Lattner4b009652007-07-25 00:24:17 +0000628}
629
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000630static llvm::cl::opt<bool>
631ObjCExclusiveGC("fobjc-gc-only",
632 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000633 "memory management"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000634
635static llvm::cl::opt<bool>
636ObjCEnableGC("fobjc-gc",
Nico Weber0e13eaa2008-08-05 23:33:20 +0000637 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000638
639void InitializeGCMode(LangOptions &Options) {
640 if (ObjCExclusiveGC)
641 Options.setGCMode(LangOptions::GCOnly);
642 else if (ObjCEnableGC)
643 Options.setGCMode(LangOptions::HybridGC);
644}
645
646
Chris Lattner4b009652007-07-25 00:24:17 +0000647//===----------------------------------------------------------------------===//
648// Our DiagnosticClient implementation
649//===----------------------------------------------------------------------===//
650
651// FIXME: Werror should take a list of things, -Werror=foo,bar
652static llvm::cl::opt<bool>
653WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
654
655static llvm::cl::opt<bool>
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000656SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
657
658static llvm::cl::opt<bool>
Chris Lattner4b009652007-07-25 00:24:17 +0000659WarnOnExtensions("pedantic", llvm::cl::init(false),
660 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
661
662static llvm::cl::opt<bool>
663ErrorOnExtensions("pedantic-errors",
664 llvm::cl::desc("Issue an error on uses of GCC extensions"));
665
666static llvm::cl::opt<bool>
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000667SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar35e50942008-09-30 20:49:53 +0000668 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000669 llvm::cl::init(true));
670
671static llvm::cl::opt<bool>
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000672WarnUnusedMacros("Wunused-macros",
Chris Lattner4b009652007-07-25 00:24:17 +0000673 llvm::cl::desc("Warn for unused macros in the main translation unit"));
674
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000675static llvm::cl::opt<bool>
676WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000677 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000678
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000679static llvm::cl::opt<bool>
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000680WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
681 llvm::cl::desc("Warn about readonly properties with writable attributes"));
682
683static llvm::cl::opt<bool>
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000684WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000685 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000686
Chris Lattnera616ee32008-01-23 17:19:46 +0000687static llvm::cl::opt<bool>
688WarnUndefMacros("Wundef",
689 llvm::cl::desc("Warn on use of undefined macros in #if's"));
690
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000691static llvm::cl::opt<bool>
Ted Kremenekc6e16692008-05-30 16:42:02 +0000692WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
693 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattnera616ee32008-01-23 17:19:46 +0000694
Steve Naroffb91afca2008-10-21 10:37:50 +0000695static llvm::cl::opt<bool>
696WarnNoStrictSelectorMatch("Wno-strict-selector-match",
697 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
698 llvm::cl::init(true));
699
Chris Lattner4b009652007-07-25 00:24:17 +0000700/// InitializeDiagnostics - Initialize the diagnostic object, based on the
701/// current command line option settings.
702static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner3a22b7c2008-05-29 15:36:45 +0000703 Diags.setIgnoreAllWarnings(SilenceWarnings);
Chris Lattner4b009652007-07-25 00:24:17 +0000704 Diags.setWarningsAsErrors(WarningsAsErrors);
705 Diags.setWarnOnExtensions(WarnOnExtensions);
706 Diags.setErrorOnExtensions(ErrorOnExtensions);
707
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000708 // Suppress warnings in system headers unless requested not to.
709 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
710
Chris Lattner4b009652007-07-25 00:24:17 +0000711 // Silence the "macro is not used" warning unless requested.
712 if (!WarnUnusedMacros)
713 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenek24f59fb2007-11-13 18:37:02 +0000714
715 // Silence "floating point comparison" warnings unless requested.
716 if (!WarnFloatEqual)
717 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000718
Fariborz Jahanian4fb265c2009-01-08 23:23:10 +0000719 if (!WarnPropertyReadonlyAttrs)
720 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
721 diag::MAP_IGNORE);
722
Ted Kremenek4b57bc72007-12-17 17:50:07 +0000723 // Silence "format string is not a string literal" warnings if requested
724 if (WarnNoFormatNonLiteral)
Ted Kremenekf0a6ae02007-12-17 17:50:39 +0000725 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
726 diag::MAP_IGNORE);
Chris Lattnera616ee32008-01-23 17:19:46 +0000727 if (!WarnUndefMacros)
728 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroff606f7072008-02-11 22:40:08 +0000729
Chris Lattnerdea31bf2008-05-05 21:18:06 +0000730 if (!WarnImplicitFunctionDeclaration)
731 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
732 diag::MAP_IGNORE);
Chris Lattner4b009652007-07-25 00:24:17 +0000733}
734
735//===----------------------------------------------------------------------===//
Ted Kremenek0118bb52008-02-18 21:21:23 +0000736// Analysis-specific options.
737//===----------------------------------------------------------------------===//
738
739static llvm::cl::opt<std::string>
740AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000741 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenek0118bb52008-02-18 21:21:23 +0000742
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000743static llvm::cl::opt<bool>
Ted Kremenekb1983ba2008-04-10 22:16:52 +0000744TrimGraph("trim-egraph",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000745 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenek5e1e05c2008-03-07 22:58:01 +0000746
Ted Kremenek0118bb52008-02-18 21:21:23 +0000747//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000748// Target Triple Processing.
749//===----------------------------------------------------------------------===//
750
751static llvm::cl::opt<std::string>
752TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000753 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000754
Chris Lattnerfc457002008-03-05 01:18:20 +0000755static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000756Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000757
Chris Lattner2b168e02008-09-30 01:13:12 +0000758static llvm::cl::opt<std::string>
759MacOSVersionMin("mmacosx-version-min",
760 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
761
Chris Lattner01de9c82008-09-30 20:16:56 +0000762// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
763// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
764static void HandleMacOSVersionMin(std::string &Triple) {
765 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
766 if (DarwinDashIdx == std::string::npos) {
767 fprintf(stderr,
768 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
769 exit(1);
770 }
771 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
772
Chris Lattner01de9c82008-09-30 20:16:56 +0000773 // Remove the number.
774 Triple.resize(DarwinNumIdx);
775
776 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
777 bool MacOSVersionMinIsInvalid = false;
778 int VersionNum = 0;
779 if (MacOSVersionMin.size() < 4 ||
780 MacOSVersionMin.substr(0, 3) != "10." ||
781 !isdigit(MacOSVersionMin[3])) {
782 MacOSVersionMinIsInvalid = true;
783 } else {
784 const char *Start = MacOSVersionMin.c_str()+3;
785 char *End = 0;
786 VersionNum = (int)strtol(Start, &End, 10);
787
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000788 // The version number must be in the range 0-9.
789 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
790
Chris Lattner01de9c82008-09-30 20:16:56 +0000791 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
792 Triple += llvm::itostr(VersionNum+4);
793
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000794 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
795 // Add the period piece (.7) to the end of the triple. This gives us
796 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000797 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000798 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
799 MacOSVersionMinIsInvalid = true;
800 }
801 }
802
803 if (MacOSVersionMinIsInvalid) {
804 fprintf(stderr,
805 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
806 MacOSVersionMin.c_str());
807 exit(1);
808 }
809}
810
811/// CreateTargetTriple - Process the various options that affect the target
812/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000813static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000814 // Initialize base triple. If a -triple option has been specified, use
815 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000816 std::string Triple = TargetTriple;
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000817 if (Triple.empty()) {
818 Triple = LLVM_HOSTTRIPLE;
819
Daniel Dunbar81caece2008-12-12 18:34:35 +0000820 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
821 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
822 Triple[2] == '8' && Triple[3] == '6')
823 Triple[1] = '3';
824
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000825 // On darwin, we want to update the version to match that of the
826 // host.
827 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
828 if (DarwinDashIdx != std::string::npos) {
829 Triple.resize(DarwinDashIdx + strlen("-darwin"));
830
Daniel Dunbar81caece2008-12-12 18:34:35 +0000831 // Only add the major part of the os version.
Chris Lattner7bddf6d2009-01-22 20:57:52 +0000832 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbar81caece2008-12-12 18:34:35 +0000833 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbarabe2e542008-10-02 01:21:33 +0000834 }
835 }
Ted Kremenek40499482007-12-03 22:06:55 +0000836
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000837 // If -arch foo was specified, remove the architecture from the triple we have
838 // so far and replace it with the specified one.
Chris Lattner2b168e02008-09-30 01:13:12 +0000839 if (!Arch.empty()) {
840 // Decompose the base triple into "arch" and suffix.
841 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000842
Chris Lattner2b168e02008-09-30 01:13:12 +0000843 if (FirstDashIdx == std::string::npos) {
844 fprintf(stderr,
845 "Malformed target triple: \"%s\" ('-' could not be found).\n",
846 Triple.c_str());
847 exit(1);
848 }
Ted Kremenek40499482007-12-03 22:06:55 +0000849
Chris Lattner2b168e02008-09-30 01:13:12 +0000850 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
851 }
852
853 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
854 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000855 if (!MacOSVersionMin.empty())
856 HandleMacOSVersionMin(Triple);
Ted Kremenek40499482007-12-03 22:06:55 +0000857
Chris Lattner2b168e02008-09-30 01:13:12 +0000858 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000859}
860
861//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000862// Preprocessor Initialization
863//===----------------------------------------------------------------------===//
864
865// FIXME: Preprocessor builtins to support.
866// -A... - Play with #assertions
867// -undef - Undefine all predefined macros
868
869static llvm::cl::list<std::string>
870D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
871 llvm::cl::desc("Predefine the specified macro"));
872static llvm::cl::list<std::string>
873U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
874 llvm::cl::desc("Undefine the specified macro"));
875
Chris Lattner008da782008-01-10 01:53:41 +0000876static llvm::cl::list<std::string>
877ImplicitIncludes("include", llvm::cl::value_desc("file"),
878 llvm::cl::desc("Include file before parsing"));
879
880
Chris Lattner4b009652007-07-25 00:24:17 +0000881// Append a #define line to Buf for Macro. Macro should be of the form XXX,
882// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
883// "#define XXX Y z W". To get a #define with no value, use "XXX=".
884static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
885 const char *Command = "#define ") {
886 Buf.insert(Buf.end(), Command, Command+strlen(Command));
887 if (const char *Equal = strchr(Macro, '=')) {
888 // Turn the = into ' '.
889 Buf.insert(Buf.end(), Macro, Equal);
890 Buf.push_back(' ');
891 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
892 } else {
893 // Push "macroname 1".
894 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
895 Buf.push_back(' ');
896 Buf.push_back('1');
897 }
898 Buf.push_back('\n');
899}
900
Chris Lattner008da782008-01-10 01:53:41 +0000901/// AddImplicitInclude - Add an implicit #include of the specified file to the
902/// predefines buffer.
903static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
904 const char *Inc = "#include \"";
905 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
906 Buf.insert(Buf.end(), File.begin(), File.end());
907 Buf.push_back('"');
908 Buf.push_back('\n');
909}
910
Chris Lattner4b009652007-07-25 00:24:17 +0000911
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000912/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner9d818a22008-04-19 23:25:44 +0000913/// environment ready to process a single file. This returns true on error.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000914///
Chris Lattner9d818a22008-04-19 23:25:44 +0000915static bool InitializePreprocessor(Preprocessor &PP,
916 bool InitializeSourceMgr,
917 const std::string &InFile) {
Chris Lattner968982d2007-12-15 20:48:40 +0000918 FileManager &FileMgr = PP.getFileManager();
Chris Lattner4b009652007-07-25 00:24:17 +0000919
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000920 // Figure out where to get and map in the main file.
Chris Lattner968982d2007-12-15 20:48:40 +0000921 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000922
923 if (InitializeSourceMgr) {
924 if (InFile != "-") {
925 const FileEntry *File = FileMgr.getFile(InFile);
926 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000927 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000928 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner9d818a22008-04-19 23:25:44 +0000929 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000930 }
931 } else {
932 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
933 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000934 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000935 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner9d818a22008-04-19 23:25:44 +0000936 return true;
Ted Kremenek4e9899f2008-04-17 22:31:54 +0000937 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000938 }
Chris Lattner4b009652007-07-25 00:24:17 +0000939 }
Sam Bishop61a20782008-04-14 14:41:57 +0000940
Chris Lattner47b6a162008-04-19 23:09:31 +0000941 std::vector<char> PredefineBuffer;
942
Chris Lattner4b009652007-07-25 00:24:17 +0000943 // Add macros from the command line.
Sam Bishop61a20782008-04-14 14:41:57 +0000944 unsigned d = 0, D = D_macros.size();
945 unsigned u = 0, U = U_macros.size();
946 while (d < D || u < U) {
947 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
948 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
949 else
950 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
951 }
952
Chris Lattner008da782008-01-10 01:53:41 +0000953 // FIXME: Read any files specified by -imacros.
954
955 // Add implicit #includes from -include.
956 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
957 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000958
Chris Lattner47b6a162008-04-19 23:09:31 +0000959 // Null terminate PredefinedBuffer and add it.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000960 PredefineBuffer.push_back(0);
Chris Lattner47b6a162008-04-19 23:09:31 +0000961 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000962
963 // Once we've read this, we're done.
Chris Lattner9d818a22008-04-19 23:25:44 +0000964 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000965}
966
967//===----------------------------------------------------------------------===//
968// Preprocessor include path information.
969//===----------------------------------------------------------------------===//
970
971// This tool exports a large number of command line options to control how the
972// preprocessor searches for header files. At root, however, the Preprocessor
973// object takes a very simple interface: a list of directories to search for
974//
975// FIXME: -nostdinc,-nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +0000976// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +0000977//
Chris Lattner008da782008-01-10 01:53:41 +0000978// FIXME: -imacros
Chris Lattner4b009652007-07-25 00:24:17 +0000979
980static llvm::cl::opt<bool>
981nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
982
983// Various command line options. These four add directories to each chain.
984static llvm::cl::list<std::string>
985F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
986 llvm::cl::desc("Add directory to framework include search path"));
987static llvm::cl::list<std::string>
988I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
989 llvm::cl::desc("Add directory to include search path"));
990static llvm::cl::list<std::string>
991idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
992 llvm::cl::desc("Add directory to AFTER include search path"));
993static llvm::cl::list<std::string>
994iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
995 llvm::cl::desc("Add directory to QUOTE include search path"));
996static llvm::cl::list<std::string>
997isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
998 llvm::cl::desc("Add directory to SYSTEM include search path"));
999
1000// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1001static llvm::cl::list<std::string>
1002iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1003 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1004static llvm::cl::list<std::string>
1005iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1006 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1007static llvm::cl::list<std::string>
1008iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1009 llvm::cl::Prefix,
1010 llvm::cl::desc("Set directory to include search path with prefix"));
1011
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001012static llvm::cl::opt<std::string>
1013isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1014 llvm::cl::desc("Set the system root directory (usually /)"));
1015
Chris Lattner4b009652007-07-25 00:24:17 +00001016// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001017
Chris Lattner4b009652007-07-25 00:24:17 +00001018/// InitializeIncludePaths - Process the -I options and set them in the
1019/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001020void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1021 FileManager &FM, const LangOptions &Lang) {
1022 InitHeaderSearch Init(Headers, Verbose, isysroot);
1023
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001024 // Handle -I... and -F... options, walking the lists in parallel.
1025 unsigned Iidx = 0, Fidx = 0;
1026 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1027 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001028 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001029 ++Iidx;
1030 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001031 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001032 ++Fidx;
1033 }
1034 }
Chris Lattner4b009652007-07-25 00:24:17 +00001035
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001036 // Consume what's left from whatever list was longer.
1037 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001038 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001039 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001040 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001041
1042 // Handle -idirafter... options.
1043 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001044 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1045 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001046
1047 // Handle -iquote... options.
1048 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001049 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001050
1051 // Handle -isystem... options.
1052 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001053 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001054
1055 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1056 // parallel, processing the values in order of occurance to get the right
1057 // prefixes.
1058 {
1059 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1060 unsigned iprefix_idx = 0;
1061 unsigned iwithprefix_idx = 0;
1062 unsigned iwithprefixbefore_idx = 0;
1063 bool iprefix_done = iprefix_vals.empty();
1064 bool iwithprefix_done = iwithprefix_vals.empty();
1065 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1066 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1067 if (!iprefix_done &&
1068 (iwithprefix_done ||
1069 iprefix_vals.getPosition(iprefix_idx) <
1070 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1071 (iwithprefixbefore_done ||
1072 iprefix_vals.getPosition(iprefix_idx) <
1073 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1074 Prefix = iprefix_vals[iprefix_idx];
1075 ++iprefix_idx;
1076 iprefix_done = iprefix_idx == iprefix_vals.size();
1077 } else if (!iwithprefix_done &&
1078 (iwithprefixbefore_done ||
1079 iwithprefix_vals.getPosition(iwithprefix_idx) <
1080 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001081 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1082 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001083 ++iwithprefix_idx;
1084 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1085 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001086 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1087 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001088 ++iwithprefixbefore_idx;
1089 iwithprefixbefore_done =
1090 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1091 }
1092 }
1093 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001094
Nico Weber770e3882008-08-22 09:25:22 +00001095 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001096
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001097 // Add the clang headers, which are relative to the clang driver.
1098 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001099 llvm::sys::Path::GetMainExecutable(Argv0,
1100 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001101 if (!MainExecutablePath.isEmpty()) {
1102 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1103 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1104 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber770e3882008-08-22 09:25:22 +00001105 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1106 false, false, false);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001107 }
1108
Nico Weber770e3882008-08-22 09:25:22 +00001109 if (!nostdinc)
1110 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001111
1112 // Now that we have collected all of the include paths, merge them all
1113 // together and tell the preprocessor about them.
1114
Nico Weber770e3882008-08-22 09:25:22 +00001115 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001116}
1117
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001118//===----------------------------------------------------------------------===//
1119// Driver PreprocessorFactory - For lazily generating preprocessors ...
1120//===----------------------------------------------------------------------===//
1121
1122namespace {
1123class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001124 const std::string &InFile;
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001125 Diagnostic &Diags;
1126 const LangOptions &LangInfo;
1127 TargetInfo &Target;
1128 SourceManager &SourceMgr;
1129 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001130 bool InitializeSourceMgr;
1131
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001132public:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001133 DriverPreprocessorFactory(const std::string &infile,
1134 Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001135 TargetInfo &target, SourceManager &SM,
1136 HeaderSearch &Headers)
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001137 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1138 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1139
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001140
1141 virtual ~DriverPreprocessorFactory() {}
1142
1143 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001144 llvm::OwningPtr<PTHManager> PTHMgr;
1145
1146 // Use PTH?
1147 if (!TokenCache.empty())
Ted Kremenek3d145552009-01-28 20:49:33 +00001148 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001149
1150 // Create the Preprocessor.
1151 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1152 SourceMgr, HeaderInfo,
1153 PTHMgr.get()));
1154
1155 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1156 // That argument is used as the IdentifierInfoLookup argument to
1157 // IdentifierTable's ctor.
1158 if (PTHMgr) {
1159 PTHMgr->setPreprocessor(PP.get());
1160 PP->setPTHManager(PTHMgr.take());
1161 }
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001162
Chris Lattner9d818a22008-04-19 23:25:44 +00001163 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001164 return NULL;
1165 }
1166
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001167 /// FIXME: PP can only handle one callback
1168 if (ProgAction != PrintPreprocessedInput) {
1169 const char* ErrStr;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001170 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001171 if (!DFG && ErrStr) {
Ted Kremenekdf349f32008-10-25 20:19:34 +00001172 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar35fe5de2008-10-24 22:12:41 +00001173 return NULL;
1174 }
1175 }
1176
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001177 InitializeSourceMgr = false;
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001178 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001179 }
1180};
1181}
Chris Lattner4b009652007-07-25 00:24:17 +00001182
Chris Lattner4b009652007-07-25 00:24:17 +00001183//===----------------------------------------------------------------------===//
1184// Basic Parser driver
1185//===----------------------------------------------------------------------===//
1186
Chris Lattner9d818a22008-04-19 23:25:44 +00001187static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001188 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001189 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001190
1191 // Parsing the specified input file.
1192 P.ParseTranslationUnit();
1193 delete PA;
1194}
1195
1196//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001197// Code generation options
1198//===----------------------------------------------------------------------===//
1199
1200static llvm::cl::opt<bool>
1201OptSize("Os",
1202 llvm::cl::desc("Optimize for size"));
1203
1204// It might be nice to add bounds to the CommandLine library directly.
1205struct OptLevelParser : public llvm::cl::parser<unsigned> {
1206 bool parse(llvm::cl::Option &O, const char *ArgName,
1207 const std::string &Arg, unsigned &Val) {
1208 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1209 return true;
1210 // FIXME: Support -O4.
1211 if (Val > 3)
1212 return O.error(": '" + Arg + "' invalid optimization level!");
1213 return false;
1214 }
1215};
1216static llvm::cl::opt<unsigned, false, OptLevelParser>
1217OptLevel("O", llvm::cl::Prefix,
1218 llvm::cl::desc("Optimization level"),
1219 llvm::cl::init(0));
1220
1221static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001222 Opts.OptimizeSize = OptSize;
Daniel Dunbard725b162008-10-29 07:56:11 +00001223 if (OptSize) {
1224 // -Os implies -O2
1225 // FIXME: Diagnose conflicting options.
1226 Opts.OptimizationLevel = 2;
1227 } else {
1228 Opts.OptimizationLevel = OptLevel;
1229 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001230
1231 // FIXME: There are llvm-gcc options to control these selectively.
1232 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1233 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1234 Opts.SimplifyLibCalls = 1;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001235
1236#ifdef NDEBUG
1237 Opts.VerifyModule = 0;
1238#endif
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001239}
1240
1241//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001242// Main driver
1243//===----------------------------------------------------------------------===//
1244
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001245/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1246/// action. These consumers can operate on both ASTs that are freshly
1247/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001248static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremenek397de012007-12-13 00:37:31 +00001249 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattner8d72ee02008-02-06 01:42:25 +00001250 const LangOptions& LangOpts,
Chris Lattner21f72d62008-04-16 06:11:58 +00001251 Preprocessor *PP,
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001252 PreprocessorFactory *PPF) {
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001253 switch (ProgAction) {
1254 default:
1255 return NULL;
1256
1257 case ASTPrint:
1258 return CreateASTPrinter();
1259
1260 case ASTDump:
1261 return CreateASTDumper();
1262
1263 case ASTView:
Ted Kremenek24612ae2008-03-18 21:19:49 +00001264 return CreateASTViewer();
Zhongxing Xu6036bbe2009-01-13 01:29:24 +00001265
1266 case PrintDeclContext:
1267 return CreateDeclContextPrinter();
Ted Kremenek24612ae2008-03-18 21:19:49 +00001268
1269 case EmitHTML:
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001270 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremeneke972d852008-07-02 18:23:21 +00001271
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001272 case InheritanceView:
1273 return CreateInheritanceViewer(InheritanceViewCls);
1274
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001275 case TestSerialization:
Ted Kremenek842126e2008-06-04 15:55:15 +00001276 return CreateSerializationTest(Diag, FileMgr);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001277
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001278 case EmitAssembly:
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001279 case EmitLLVM:
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001280 case EmitBC: {
1281 BackendAction Act;
1282 if (ProgAction == EmitAssembly) {
1283 Act = Backend_EmitAssembly;
1284 } else if (ProgAction == EmitLLVM) {
1285 Act = Backend_EmitLL;
1286 } else {
1287 Act = Backend_EmitBC;
1288 }
1289 CompileOptions Opts;
1290 InitializeCompileOptions(Opts);
1291 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +00001292 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001293 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001294
Ted Kremenekbde30332007-12-19 17:25:59 +00001295 case SerializeAST:
Ted Kremenek397de012007-12-13 00:37:31 +00001296 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek842126e2008-06-04 15:55:15 +00001297 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremenek397de012007-12-13 00:37:31 +00001298
Steve Naroff44e81222008-04-14 22:03:09 +00001299 case RewriteObjC:
Chris Lattner673f2bd2008-03-22 00:08:40 +00001300 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff93c18352008-09-18 14:10:13 +00001301
1302 case RewriteBlocks:
1303 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenek81ea7992008-07-02 00:03:09 +00001304
1305 case RunAnalysis:
Ted Kremenek81ea7992008-07-02 00:03:09 +00001306 return CreateAnalysisConsumer(&AnalysisList[0],
1307 &AnalysisList[0]+AnalysisList.size(),
Ted Kremeneka3f825e2008-11-03 23:18:07 +00001308 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenek81ea7992008-07-02 00:03:09 +00001309 Diag, PP, PPF, LangOpts,
1310 AnalyzeSpecificFunction,
Ted Kremenekcf262252008-08-27 22:31:43 +00001311 OutputFile, VisualizeEGDot, VisualizeEGUbi,
Ted Kremenek60feb282009-01-23 20:52:26 +00001312 TrimGraph, AnalyzeAll,
1313 AnalyzerDisplayProgress);
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001314 }
1315}
1316
Chris Lattner4b009652007-07-25 00:24:17 +00001317/// ProcessInputFile - Process a single input file with the specified state.
1318///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001319static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001320 const std::string &InFile, ProgActions PA) {
Ted Kremenek50aab982008-08-08 02:46:37 +00001321 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001322 bool ClearSourceMgr = false;
Ted Kremenek6856c632007-09-26 18:39:29 +00001323
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001324 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001325 default:
Ted Kremenek50aab982008-08-08 02:46:37 +00001326 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1327 PP.getFileManager(), PP.getLangOptions(),
1328 &PP, &PPF));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001329
1330 if (!Consumer) {
1331 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001332 HadErrors = true;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001333 return;
1334 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001335
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001336 break;
1337
Chris Lattneraf669fb2008-10-12 05:03:36 +00001338 case DumpRawTokens: {
1339 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001340 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001341 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001342 RawLex.SetKeepWhitespaceMode(true);
1343
1344 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001345 RawLex.LexFromRawLexer(RawTok);
1346 while (RawTok.isNot(tok::eof)) {
1347 PP.DumpToken(RawTok, true);
1348 fprintf(stderr, "\n");
1349 RawLex.LexFromRawLexer(RawTok);
1350 }
1351 ClearSourceMgr = true;
1352 break;
1353 }
Chris Lattner4b009652007-07-25 00:24:17 +00001354 case DumpTokens: { // Token dump mode.
1355 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001356 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001357 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001358 do {
1359 PP.Lex(Tok);
1360 PP.DumpToken(Tok, true);
1361 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001362 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001363 ClearSourceMgr = true;
1364 break;
1365 }
1366 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
1367 Token Tok;
1368 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001369 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001370 do {
1371 PP.Lex(Tok);
Chris Lattner3b494152007-10-09 18:03:42 +00001372 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001373 ClearSourceMgr = true;
1374 break;
1375 }
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001376
1377 case GeneratePCH: {
1378 CacheTokens(PP, OutputFile);
1379 ClearSourceMgr = true;
1380 break;
1381 }
Chris Lattner4b009652007-07-25 00:24:17 +00001382
1383 case PrintPreprocessedInput: // -E mode.
Chris Lattnerefd02a32008-01-27 23:55:11 +00001384 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattner4b009652007-07-25 00:24:17 +00001385 ClearSourceMgr = true;
1386 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001387
Chris Lattner4b009652007-07-25 00:24:17 +00001388 case ParseNoop: // -parse-noop
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001389 ParseFile(PP, new MinimalAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001390 ClearSourceMgr = true;
1391 break;
1392
1393 case ParsePrintCallbacks:
Daniel Dunbar747a95e2008-10-31 08:56:51 +00001394 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattner4b009652007-07-25 00:24:17 +00001395 ClearSourceMgr = true;
1396 break;
Ted Kremenek0841c702007-09-25 18:37:20 +00001397
Ted Kremenek6856c632007-09-26 18:39:29 +00001398 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek50aab982008-08-08 02:46:37 +00001399 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001400 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001401
1402 case RewriteMacros:
Chris Lattner302b0622008-05-09 22:43:24 +00001403 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattner1665a9f2008-05-08 06:52:13 +00001404 ClearSourceMgr = true;
1405 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001406
1407 case RewriteTest:
1408 DoRewriteTest(PP, InFile, OutputFile);
1409 ClearSourceMgr = true;
1410 break;
Chris Lattner129758d2007-09-16 19:46:59 +00001411 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001412
1413 if (Consumer) {
1414 TranslationUnit *TU = 0;
1415 if (DisableFree) {
1416 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1417 PP.getSourceManager(),
1418 PP.getTargetInfo(),
1419 PP.getIdentifierTable(),
1420 PP.getSelectorTable(),
1421 /* FreeMemory = */ false);
1422 TU = new TranslationUnit(*Context);
1423 }
1424 ParseAST(PP, Consumer.get(), TU, Stats);
1425 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00001426
1427 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001428 if (CheckDiagnostics(PP))
1429 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00001430
Chris Lattner4b009652007-07-25 00:24:17 +00001431 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001432 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00001433 PP.PrintStats();
1434 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00001435 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00001436 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00001437 fprintf(stderr, "\n");
1438 }
1439
1440 // For a multi-file compilation, some things are ok with nuking the source
1441 // manager tables, other require stable fileid/macroid's across multiple
1442 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00001443 if (ClearSourceMgr)
1444 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00001445
1446 if (DisableFree)
1447 Consumer.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001448}
1449
Ted Kremenek80d53372007-12-12 23:41:08 +00001450static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1451 FileManager& FileMgr) {
1452
1453 if (VerifyDiagnostics) {
1454 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1455 exit (1);
1456 }
1457
1458 llvm::sys::Path Filename(InFile);
1459
1460 if (!Filename.isValid()) {
1461 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1462 exit (1);
1463 }
1464
Ted Kremenek863b01f2008-04-23 16:25:39 +00001465 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenek2bd42412007-12-13 18:11:11 +00001466
1467 if (!TU) {
1468 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1469 InFile.c_str());
1470 exit (1);
1471 }
1472
Ted Kremenekab749372007-12-19 19:27:38 +00001473 // Observe that we use the source file name stored in the deserialized
1474 // translation unit, rather than InFile.
Ted Kremenek0c7cd7a2007-12-20 19:47:16 +00001475 llvm::OwningPtr<ASTConsumer>
Ted Kremenek842126e2008-06-04 15:55:15 +00001476 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek7c65b6c2008-08-05 18:50:11 +00001477 0, 0));
Nico Weberd2a6ac92008-08-10 19:59:06 +00001478
Ted Kremenek80d53372007-12-12 23:41:08 +00001479 if (!Consumer) {
1480 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1481 exit (1);
1482 }
Nico Weberd2a6ac92008-08-10 19:59:06 +00001483
Ted Kremenek863b01f2008-04-23 16:25:39 +00001484 Consumer->Initialize(TU->getContext());
Nico Weberd2a6ac92008-08-10 19:59:06 +00001485
Chris Lattner8d72ee02008-02-06 01:42:25 +00001486 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek80d53372007-12-12 23:41:08 +00001487 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1488 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek80d53372007-12-12 23:41:08 +00001489}
1490
1491
Chris Lattner4b009652007-07-25 00:24:17 +00001492static llvm::cl::list<std::string>
1493InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1494
Ted Kremenek80d53372007-12-12 23:41:08 +00001495static bool isSerializedFile(const std::string& InFile) {
1496 if (InFile.size() < 4)
1497 return false;
1498
1499 const char* s = InFile.c_str()+InFile.size()-4;
1500
1501 return s[0] == '.' &&
1502 s[1] == 'a' &&
1503 s[2] == 's' &&
1504 s[3] == 't';
1505}
1506
Chris Lattner4b009652007-07-25 00:24:17 +00001507
1508int main(int argc, char **argv) {
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001509 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Chris Lattner4b009652007-07-25 00:24:17 +00001510 llvm::sys::PrintStackTraceOnErrorSignal();
1511
1512 // If no input was specified, read from stdin.
1513 if (InputFilenames.empty())
1514 InputFilenames.push_back("-");
Ted Kremenekb240e822007-12-11 23:28:38 +00001515
Chris Lattner4b009652007-07-25 00:24:17 +00001516 // Create a file manager object to provide access to and cache the filesystem.
1517 FileManager FileMgr;
1518
Ted Kremenekb240e822007-12-11 23:28:38 +00001519 // Create the diagnostic client for reporting errors or for
1520 // implementing -verify.
Nico Weberd2a6ac92008-08-10 19:59:06 +00001521 DiagnosticClient* TextDiagClient = 0;
Ted Kremenekfd75e312008-03-27 06:17:42 +00001522
Ted Kremenek5c341732008-08-07 17:49:57 +00001523 if (!VerifyDiagnostics) {
1524 // Print diagnostics to stderr by default.
Chris Lattner92a33532008-11-19 06:56:25 +00001525 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1526 !NoShowColumn,
Ted Kremenek5c341732008-08-07 17:49:57 +00001527 !NoCaretDiagnostics);
1528 } else {
1529 // When checking diagnostics, just buffer them up.
1530 TextDiagClient = new TextDiagnosticBuffer();
1531
1532 if (InputFilenames.size() != 1) {
1533 fprintf(stderr,
1534 "-verify only works on single input files for now.\n");
1535 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001536 }
1537 }
Ted Kremenek5c341732008-08-07 17:49:57 +00001538
Chris Lattner4b009652007-07-25 00:24:17 +00001539 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00001540 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1541 Diagnostic Diags(DiagClient.get());
Ted Kremenekb240e822007-12-11 23:28:38 +00001542 InitializeDiagnostics(Diags);
1543
Chris Lattner45a56e02007-12-05 23:24:17 +00001544 // -I- is a deprecated GCC feature, scan for it and reject it.
1545 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1546 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00001547 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00001548 I_dirs.erase(I_dirs.begin()+i);
1549 --i;
1550 }
1551 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001552
1553 // Get information about the target being compiled for.
1554 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00001555 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1556
Chris Lattner2c77d852008-03-14 06:12:05 +00001557 if (Target == 0) {
1558 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1559 Triple.c_str());
1560 fprintf(stderr, "Please use -triple or -arch.\n");
1561 exit(1);
1562 }
Chris Lattner45a56e02007-12-05 23:24:17 +00001563
Daniel Dunbar9c321102009-01-20 23:17:32 +00001564 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00001565 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00001566
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001567 llvm::OwningPtr<SourceManager> SourceMgr;
1568
Chris Lattner4b009652007-07-25 00:24:17 +00001569 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00001570 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00001571
Ted Kremenek5c341732008-08-07 17:49:57 +00001572 if (isSerializedFile(InFile)) {
1573 Diags.setClient(TextDiagClient);
Ted Kremenek80d53372007-12-12 23:41:08 +00001574 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenek5c341732008-08-07 17:49:57 +00001575 }
Ted Kremenek80d53372007-12-12 23:41:08 +00001576 else {
1577 /// Create a SourceManager object. This tracks and owns all the file
1578 /// buffers allocated to a translation unit.
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001579 if (!SourceMgr)
1580 SourceMgr.reset(new SourceManager());
1581 else
1582 SourceMgr->clearIDTables();
Ted Kremenekb240e822007-12-11 23:28:38 +00001583
Ted Kremenek80d53372007-12-12 23:41:08 +00001584 // Initialize language options, inferring file types from input filenames.
1585 LangOptions LangInfo;
1586 InitializeBaseLanguage();
1587 LangKind LK = GetLanguage(InFile);
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001588 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek2658c4a2008-04-29 04:37:03 +00001589 InitializeGCMode(LangInfo);
Chris Lattnerddae7102008-12-04 22:54:33 +00001590 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001591
Ted Kremenek80d53372007-12-12 23:41:08 +00001592 // Process the -I options and set them in the HeaderInfo.
1593 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek649465c2008-06-06 01:47:30 +00001594
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001595 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001596
Ted Kremenek80d53372007-12-12 23:41:08 +00001597 // Set up the preprocessor with these options.
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001598 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001599 *SourceMgr.get(), HeaderInfo);
Ted Kremenek80d53372007-12-12 23:41:08 +00001600
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001601 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1602
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001603 if (!PP)
Ted Kremenek2578dd02007-12-19 22:29:55 +00001604 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00001605
1606 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1607 // always reset to using TextDiagClient.
1608 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek2578dd02007-12-19 22:29:55 +00001609
Ted Kremenek5c341732008-08-07 17:49:57 +00001610 if (!HTMLDiag.empty()) {
1611 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1612 &PPFactory));
1613 Diags.setClient(TmpClient.get());
1614 }
1615 else
1616 Diags.setClient(TextDiagClient);
1617
1618 // Process the source file.
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001619 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1620
Ted Kremenek2a4224a2008-06-06 22:42:39 +00001621 HeaderInfo.ClearFileInfo();
Ted Kremenek80d53372007-12-12 23:41:08 +00001622 }
Chris Lattner4b009652007-07-25 00:24:17 +00001623 }
Chris Lattner2c77d852008-03-14 06:12:05 +00001624
Mike Stump91d01352009-01-28 02:43:35 +00001625 if (Verbose)
1626 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1627 " hosted on " LLVM_HOSTTRIPLE "\n");
1628
Ted Kremenekec6c5252008-08-07 18:13:12 +00001629 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Chris Lattner4b009652007-07-25 00:24:17 +00001630 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1631 (NumDiagnostics == 1 ? "" : "s"));
1632
1633 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00001634 FileMgr.PrintStats();
1635 fprintf(stderr, "\n");
1636 }
1637
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00001638 // If verifying diagnostics and we reached here, all is well.
1639 if (VerifyDiagnostics)
1640 return 0;
1641
Daniel Dunbarbb298c02008-10-28 00:38:08 +00001642 // Managed static deconstruction. Useful for making things like
1643 // -time-passes usable.
1644 llvm::llvm_shutdown();
1645
Daniel Dunbar70a66b12008-10-04 23:42:49 +00001646 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001647}