blob: 900e0a03905bb000cb6425dafe486eb36de4503d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000027#include "clang/Driver/CompileOptions.h"
Ted Kremenekad99dbf2008-11-03 22:31:48 +000028#include "clang/Driver/PathDiagnosticClients.h"
Nico Weber0fca0222008-08-22 09:25:22 +000029#include "clang/Driver/InitHeaderSearch.h"
Nico Weberfd54ebc2008-08-05 23:33:20 +000030#include "clang/Driver/TextDiagnosticBuffer.h"
31#include "clang/Driver/TextDiagnosticPrinter.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000037#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerba0f25f2008-09-30 20:16:56 +000043#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000044#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000048#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000050#include "llvm/Support/PluginLoader.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000051#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000052#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000053#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Global options.
58//===----------------------------------------------------------------------===//
59
Daniel Dunbard3db4012008-10-16 16:54:18 +000060static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000061
Reid Spencer5f016e22007-07-11 17:01:13 +000062static llvm::cl::opt<bool>
63Verbose("v", llvm::cl::desc("Enable verbose output"));
64static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000065Stats("print-stats",
66 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-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));
Reid Spencer5f016e22007-07-11 17:01:13 +000071
72enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000073 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000074 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000075 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000076 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000077 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000078 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000079 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000080 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000081 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000082 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-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 Xu2d75d6f2009-01-13 01:29:24 +000086 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000087 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +000093 DumpTokens, // Dump out preprocessed tokens.
94 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +000095 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +000096 GeneratePCH, // Generate precompiled header.
97 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000108 clEnumValN(DumpRawTokens, "dump-raw-tokens",
109 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000110 clEnumValN(RunAnalysis, "analyze",
111 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000112 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 "Run preprocessor, dump internal rep of tokens"),
114 clEnumValN(ParseNoop, "parse-noop",
115 "Run parser with noop callbacks (for timings)"),
116 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
117 "Run parser and perform semantic analysis"),
118 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
119 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000120 clEnumValN(EmitHTML, "emit-html",
121 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000122 clEnumValN(ASTPrint, "ast-print",
123 "Build ASTs and then pretty-print them"),
124 clEnumValN(ASTDump, "ast-dump",
125 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000126 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000127 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000128 clEnumValN(PrintDeclContext, "print-decl-contexts",
129 "Print DeclContexts and their Decls."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000130 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000131 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000132 clEnumValN(EmitAssembly, "S",
133 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000135 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000136 clEnumValN(EmitBC, "emit-llvm-bc",
137 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000138 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000139 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000140 clEnumValN(RewriteTest, "rewrite-test",
141 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000142 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000143 "Rewrite ObjC into C (code rewriter example)"),
144 clEnumValN(RewriteMacros, "rewrite-macros",
145 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000146 clEnumValN(RewriteBlocks, "rewrite-blocks",
147 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 clEnumValEnd));
149
Ted Kremenekccc76472007-12-19 19:47:59 +0000150
151static llvm::cl::opt<std::string>
152OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000153 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000154 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000155
156//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000157// Code Generator Options
158//===----------------------------------------------------------------------===//
159static llvm::cl::opt<bool>
160GenerateDebugInfo("g",
161 llvm::cl::desc("Generate source level debug information"));
162
Ted Kremenekc2e72992008-12-02 19:57:31 +0000163
164//===----------------------------------------------------------------------===//
165// PTH.
166//===----------------------------------------------------------------------===//
167
168static llvm::cl::opt<std::string>
169TokenCache("token-cache", llvm::cl::value_desc("path"),
170 llvm::cl::desc("Use specified token cache file"));
171
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000172//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000173// Diagnostic Options
174//===----------------------------------------------------------------------===//
175
Ted Kremenek41193e42007-09-26 19:42:19 +0000176static llvm::cl::opt<bool>
177VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000178 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000179
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000180static llvm::cl::opt<std::string>
181HTMLDiag("html-diags",
182 llvm::cl::desc("Generate HTML to report diagnostics"),
183 llvm::cl::value_desc("HTML directory"));
184
Nico Weberfd54ebc2008-08-05 23:33:20 +0000185static llvm::cl::opt<bool>
186NoShowColumn("fno-show-column",
187 llvm::cl::desc("Do not include column number on diagnostics"));
188
189static llvm::cl::opt<bool>
190NoCaretDiagnostics("fno-caret-diagnostics",
191 llvm::cl::desc("Do not include source line and caret with"
192 " diagnostics"));
193
194
Reid Spencer5f016e22007-07-11 17:01:13 +0000195//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000196// C++ Visualization.
197//===----------------------------------------------------------------------===//
198
199static llvm::cl::opt<std::string>
200InheritanceViewCls("cxx-inheritance-view",
201 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000202 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000203
204//===----------------------------------------------------------------------===//
205// Analyzer Options.
Ted Kremenek55af98c2008-04-14 18:40:58 +0000206//===----------------------------------------------------------------------===//
207
208static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000209VisualizeEGDot("analyzer-viz-egraph-graphviz",
210 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000211
212static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000213VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
214 llvm::cl::desc("Display exploded graph using Ubigraph"));
215
216static llvm::cl::opt<bool>
217AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek55af98c2008-04-14 18:40:58 +0000218 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000219 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000220
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000221static llvm::cl::list<Analyses>
Ted Kremenek95c7b002008-10-24 01:04:59 +0000222AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000223llvm::cl::values(
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000224#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000225clEnumValN(NAME, CMDFLAG, DESC),
226#include "Analyses.def"
227clEnumValEnd));
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000228
Ted Kremenek95c7b002008-10-24 01:04:59 +0000229static llvm::cl::opt<AnalysisStores>
230AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
231 llvm::cl::init(BasicStoreModel),
232 llvm::cl::values(
233#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
234clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
235#include "Analyses.def"
236clEnumValEnd));
237
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000238static llvm::cl::opt<AnalysisDiagClients>
239AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
240 llvm::cl::init(PD_HTML),
241 llvm::cl::values(
242#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)\
243clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
244#include "Analyses.def"
245clEnumValEnd));
246
Ted Kremenek55af98c2008-04-14 18:40:58 +0000247//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000248// Language Options
249//===----------------------------------------------------------------------===//
250
251enum LangKind {
252 langkind_unspecified,
253 langkind_c,
254 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000255 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000256 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 langkind_cxx,
258 langkind_cxx_cpp,
259 langkind_objc,
260 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000261 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000262 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000263 langkind_objcxx_cpp,
264 langkind_objcxx_pch
Reid Spencer5f016e22007-07-11 17:01:13 +0000265};
266
267/* TODO: GCC also accepts:
268 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera778d7d2008-10-22 17:29:21 +0000269 assembler
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 ada, f77*, ratfor (!), f95, java, treelang
271 */
272static llvm::cl::opt<LangKind>
273BaseLang("x", llvm::cl::desc("Base language to compile"),
274 llvm::cl::init(langkind_unspecified),
275 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
276 clEnumValN(langkind_cxx, "c++", "C++"),
277 clEnumValN(langkind_objc, "objective-c", "Objective C"),
278 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
279 clEnumValN(langkind_c_cpp, "c-cpp-output",
280 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000281 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
282 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek85888962008-10-21 00:54:44 +0000284 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
286 "Preprocessed Objective C"),
287 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
288 "Preprocessed Objective C++"),
Ted Kremenek85888962008-10-21 00:54:44 +0000289 clEnumValN(langkind_c_pch,"c-header",
290 "Precompiled C header"),
291 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000292 "Precompiled Objective-C header"),
293 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
294 "Precompiled Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 clEnumValEnd));
296
297static llvm::cl::opt<bool>
298LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
299 llvm::cl::Hidden);
300static llvm::cl::opt<bool>
301LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
302 llvm::cl::Hidden);
303
Ted Kremenek8904f152007-12-05 23:49:08 +0000304/// InitializeBaseLanguage - Handle the -x foo options.
305static void InitializeBaseLanguage() {
306 if (LangObjC)
307 BaseLang = langkind_objc;
308 else if (LangObjCXX)
309 BaseLang = langkind_objcxx;
310}
311
312static LangKind GetLanguage(const std::string &Filename) {
313 if (BaseLang != langkind_unspecified)
314 return BaseLang;
315
316 std::string::size_type DotPos = Filename.rfind('.');
317
318 if (DotPos == std::string::npos) {
319 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000320 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 }
322
Ted Kremenek8904f152007-12-05 23:49:08 +0000323 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
324 // C header: .h
325 // C++ header: .hh or .H;
326 // assembler no preprocessing: .s
327 // assembler: .S
328 if (Ext == "c")
329 return langkind_c;
Chris Lattner1b450b02008-10-28 20:33:42 +0000330 else if (Ext == "S")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000331 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000332 else if (Ext == "i")
333 return langkind_c_cpp;
334 else if (Ext == "ii")
335 return langkind_cxx_cpp;
336 else if (Ext == "m")
337 return langkind_objc;
338 else if (Ext == "mi")
339 return langkind_objc_cpp;
340 else if (Ext == "mm" || Ext == "M")
341 return langkind_objcxx;
342 else if (Ext == "mii")
343 return langkind_objcxx_cpp;
344 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
345 Ext == "c++" || Ext == "cp" || Ext == "cxx")
346 return langkind_cxx;
347 else
348 return langkind_c;
349}
350
351
Ted Kremenek85888962008-10-21 00:54:44 +0000352static void InitializeCOptions(LangOptions &Options) {
353 // Do nothing.
354}
355
356static void InitializeObjCOptions(LangOptions &Options) {
357 Options.ObjC1 = Options.ObjC2 = 1;
358}
359
360
361static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // FIXME: implement -fpreprocessed mode.
363 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000364 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000365
366 // Test for 'PCH'.
367 switch (LK) {
368 default:
369 break;
370 case langkind_c_pch:
371 LK = langkind_c;
372 PCH = true;
373 break;
374 case langkind_objc_pch:
375 LK = langkind_objc;
376 PCH = true;
377 break;
378 case langkind_objcxx_pch:
379 LK = langkind_objcxx;
380 PCH = true;
381 break;
382 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
Ted Kremenek8904f152007-12-05 23:49:08 +0000384 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000386 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000387 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000388 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 case langkind_c_cpp:
390 NoPreprocess = true;
391 // FALLTHROUGH
392 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000393 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 break;
395 case langkind_cxx_cpp:
396 NoPreprocess = true;
397 // FALLTHROUGH
398 case langkind_cxx:
399 Options.CPlusPlus = 1;
400 break;
401 case langkind_objc_cpp:
402 NoPreprocess = true;
403 // FALLTHROUGH
404 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000405 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 break;
407 case langkind_objcxx_cpp:
408 NoPreprocess = true;
409 // FALLTHROUGH
410 case langkind_objcxx:
411 Options.ObjC1 = Options.ObjC2 = 1;
412 Options.CPlusPlus = 1;
413 break;
414 }
Ted Kremenek85888962008-10-21 00:54:44 +0000415
416 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000417}
418
419/// LangStds - Language standards we support.
420enum LangStds {
421 lang_unspecified,
422 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000423 lang_gnu_START,
424 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000425 lang_cxx98, lang_gnucxx98,
426 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000427};
428
429static llvm::cl::opt<LangStds>
430LangStd("std", llvm::cl::desc("Language standard to compile for"),
431 llvm::cl::init(lang_unspecified),
432 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
433 clEnumValN(lang_c89, "c90", "ISO C 1990"),
434 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
435 clEnumValN(lang_c94, "iso9899:199409",
436 "ISO C 1990 with amendment 1"),
437 clEnumValN(lang_c99, "c99", "ISO C 1999"),
438// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
439 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
440// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
441 clEnumValN(lang_gnu89, "gnu89",
442 "ISO C 1990 with GNU extensions (default for C)"),
443 clEnumValN(lang_gnu99, "gnu99",
444 "ISO C 1999 with GNU extensions"),
445 clEnumValN(lang_gnu99, "gnu9x",
446 "ISO C 1999 with GNU extensions"),
447 clEnumValN(lang_cxx98, "c++98",
448 "ISO C++ 1998 with amendments"),
449 clEnumValN(lang_gnucxx98, "gnu++98",
450 "ISO C++ 1998 with amendments and GNU "
451 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000452 clEnumValN(lang_cxx0x, "c++0x",
453 "Upcoming ISO C++ 200x with amendments"),
454 clEnumValN(lang_gnucxx0x, "gnu++0x",
455 "Upcoming ISO C++ 200x with amendments and GNU "
456 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 clEnumValEnd));
458
459static llvm::cl::opt<bool>
460NoOperatorNames("fno-operator-names",
461 llvm::cl::desc("Do not treat C++ operator name keywords as "
462 "synonyms for operators"));
463
Anders Carlssonee98ac52007-10-15 02:50:23 +0000464static llvm::cl::opt<bool>
465PascalStrings("fpascal-strings",
466 llvm::cl::desc("Recognize and construct Pascal-style "
467 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000468
469static llvm::cl::opt<bool>
470MSExtensions("fms-extensions",
471 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000472 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000473
474static llvm::cl::opt<bool>
475WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000476 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000477
478static llvm::cl::opt<bool>
479LaxVectorConversions("flax-vector-conversions",
480 llvm::cl::desc("Allow implicit conversions between vectors"
481 " with a different number of elements or "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000482 "different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000483static llvm::cl::opt<bool>
484EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
485
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000486static llvm::cl::opt<bool>
487ObjCModernABI("fobjc-modern-abi", llvm::cl::desc("enable objective-c's modern abi"));
488
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000489
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000490// FIXME: This (and all GCC -f options) really come in -f... and
491// -fno-... forms, and additionally support automagic behavior when
492// they are not defined. For example, -fexceptions defaults to on or
493// off depending on the language. We should support this behavior in
494// some form (perhaps just add a facility for distinguishing when an
495// has its default value from when it has been set to its default
496// value).
497static llvm::cl::opt<bool>
498Exceptions("fexceptions",
499 llvm::cl::desc("Enable support for exception handling."));
500
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000501static llvm::cl::opt<bool>
502GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000503 llvm::cl::desc("Generate output compatible with the standard GNU "
504 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000505
506static llvm::cl::opt<bool>
507NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000508 llvm::cl::desc("Generate output compatible with the NeXT "
509 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000510
Ted Kremenekea644d82008-09-03 21:22:16 +0000511
512
513static llvm::cl::opt<bool>
514Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
515
516static llvm::cl::opt<bool>
517Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
518
Reid Spencer5f016e22007-07-11 17:01:13 +0000519// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000520// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000521static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
522 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000523 // Allow the target to set the default the langauge options as it sees fit.
524 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000525
526 if (Ansi) // "The -ansi option is equivalent to -std=c89."
527 LangStd = lang_c89;
528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 if (LangStd == lang_unspecified) {
530 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000531 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 default: assert(0 && "Unknown base language");
533 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000534 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000536 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 case langkind_objc:
538 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000539 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000540 LangStd = lang_gnu99;
541 break;
542 case langkind_cxx:
543 case langkind_cxx_cpp:
544 case langkind_objcxx:
545 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000546 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 LangStd = lang_gnucxx98;
548 break;
549 }
550 }
551
552 switch (LangStd) {
553 default: assert(0 && "Unknown language standard!");
554
555 // Fall through from newer standards to older ones. This isn't really right.
556 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000557 case lang_gnucxx0x:
558 case lang_cxx0x:
559 Options.CPlusPlus0x = 1;
560 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 case lang_gnucxx98:
562 case lang_cxx98:
563 Options.CPlusPlus = 1;
564 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000565 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 // FALL THROUGH.
567 case lang_gnu99:
568 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 Options.C99 = 1;
570 Options.HexFloats = 1;
571 // FALL THROUGH.
572 case lang_gnu89:
573 Options.BCPLComment = 1; // Only for C99/C++.
574 // FALL THROUGH.
575 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000576 Options.Digraphs = 1; // C94, C99, C++.
577 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 case lang_c89:
579 break;
580 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000581
582 if (Options.CPlusPlus) {
583 Options.C99 = 0;
584 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
585 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000586
Chris Lattnerd658b562008-04-05 06:32:51 +0000587 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
588 Options.ImplicitInt = 1;
589 else
590 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000591
592 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
593 // is specified, or -std is set to a conforming mode.
Chris Lattner802db9b2008-12-05 00:10:44 +0000594 Options.Trigraphs = LangStd < lang_gnu_START;
595 if (Trigraphs.getPosition())
596 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenekea644d82008-09-03 21:22:16 +0000597
Chris Lattner802db9b2008-12-05 00:10:44 +0000598 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
599 // even if they are normally on for the target. In GNU modes (e.g.
600 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000601 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
602 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner802db9b2008-12-05 00:10:44 +0000603 Options.Blocks = 0;
604
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000606 if (PascalStrings.getPosition())
607 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000608 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000609 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000610 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000611 Options.Exceptions = Exceptions;
Chris Lattnerae0ee032008-12-04 23:20:07 +0000612 if (EnableBlocks.getPosition())
613 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000614
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000615 // Override the default runtime if the user requested it.
616 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000617 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000618 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000619 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000620
621 if (ObjCModernABI)
622 Options.ObjCModernABI = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000623}
624
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000625static llvm::cl::opt<bool>
626ObjCExclusiveGC("fobjc-gc-only",
627 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000628 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000629
630static llvm::cl::opt<bool>
631ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000632 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000633
634void InitializeGCMode(LangOptions &Options) {
635 if (ObjCExclusiveGC)
636 Options.setGCMode(LangOptions::GCOnly);
637 else if (ObjCEnableGC)
638 Options.setGCMode(LangOptions::HybridGC);
639}
640
641
Reid Spencer5f016e22007-07-11 17:01:13 +0000642//===----------------------------------------------------------------------===//
643// Our DiagnosticClient implementation
644//===----------------------------------------------------------------------===//
645
646// FIXME: Werror should take a list of things, -Werror=foo,bar
647static llvm::cl::opt<bool>
648WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
649
650static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000651SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
652
653static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000654WarnOnExtensions("pedantic", llvm::cl::init(false),
655 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
656
657static llvm::cl::opt<bool>
658ErrorOnExtensions("pedantic-errors",
659 llvm::cl::desc("Issue an error on uses of GCC extensions"));
660
661static llvm::cl::opt<bool>
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000662SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar320a0542008-09-30 20:49:53 +0000663 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000664 llvm::cl::init(true));
665
666static llvm::cl::opt<bool>
Daniel Dunbard77b2512009-01-14 18:56:36 +0000667WarnUnusedMacros("Wunused-macros",
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 llvm::cl::desc("Warn for unused macros in the main translation unit"));
669
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000670static llvm::cl::opt<bool>
671WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000672 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000673
Ted Kremenek73da5902007-12-17 17:50:07 +0000674static llvm::cl::opt<bool>
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000675WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
676 llvm::cl::desc("Warn about readonly properties with writable attributes"));
677
678static llvm::cl::opt<bool>
Ted Kremenek73da5902007-12-17 17:50:07 +0000679WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000680 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000681
Chris Lattner116a4b12008-01-23 17:19:46 +0000682static llvm::cl::opt<bool>
683WarnUndefMacros("Wundef",
684 llvm::cl::desc("Warn on use of undefined macros in #if's"));
685
Chris Lattner37d10842008-05-05 21:18:06 +0000686static llvm::cl::opt<bool>
Ted Kremenek358256d2008-05-30 16:42:02 +0000687WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
688 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattner116a4b12008-01-23 17:19:46 +0000689
Steve Narofffe6b0dc2008-10-21 10:37:50 +0000690static llvm::cl::opt<bool>
691WarnNoStrictSelectorMatch("Wno-strict-selector-match",
692 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
693 llvm::cl::init(true));
694
Reid Spencer5f016e22007-07-11 17:01:13 +0000695/// InitializeDiagnostics - Initialize the diagnostic object, based on the
696/// current command line option settings.
697static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000698 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 Diags.setWarningsAsErrors(WarningsAsErrors);
700 Diags.setWarnOnExtensions(WarnOnExtensions);
701 Diags.setErrorOnExtensions(ErrorOnExtensions);
702
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000703 // Suppress warnings in system headers unless requested not to.
704 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
705
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 // Silence the "macro is not used" warning unless requested.
707 if (!WarnUnusedMacros)
708 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000709
710 // Silence "floating point comparison" warnings unless requested.
711 if (!WarnFloatEqual)
712 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000713
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000714 if (!WarnPropertyReadonlyAttrs)
715 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
716 diag::MAP_IGNORE);
717
Ted Kremenek73da5902007-12-17 17:50:07 +0000718 // Silence "format string is not a string literal" warnings if requested
719 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000720 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
721 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000722 if (!WarnUndefMacros)
723 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000724
Chris Lattner37d10842008-05-05 21:18:06 +0000725 if (!WarnImplicitFunctionDeclaration)
726 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
727 diag::MAP_IGNORE);
728
Chris Lattner8aedf192008-05-04 23:52:02 +0000729 // If -pedantic-errors is set, turn extensions that warn by default into
730 // errors.
731 if (ErrorOnExtensions) {
732 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
733 diag::MAP_ERROR);
734 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
735 diag::MAP_ERROR);
736 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000737}
738
739//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000740// Analysis-specific options.
741//===----------------------------------------------------------------------===//
742
743static llvm::cl::opt<std::string>
744AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000745 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000746
Ted Kremenekffe0f432008-03-07 22:58:01 +0000747static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000748TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000749 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000750
Ted Kremenekcb330932008-02-18 21:21:23 +0000751//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000752// Target Triple Processing.
753//===----------------------------------------------------------------------===//
754
755static llvm::cl::opt<std::string>
756TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000757 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000758
Chris Lattner42e67372008-03-05 01:18:20 +0000759static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000760Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000761
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000762static llvm::cl::opt<std::string>
763MacOSVersionMin("mmacosx-version-min",
764 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
765
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000766// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
767// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
768static void HandleMacOSVersionMin(std::string &Triple) {
769 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
770 if (DarwinDashIdx == std::string::npos) {
771 fprintf(stderr,
772 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
773 exit(1);
774 }
775 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
776
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000777 // Remove the number.
778 Triple.resize(DarwinNumIdx);
779
780 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
781 bool MacOSVersionMinIsInvalid = false;
782 int VersionNum = 0;
783 if (MacOSVersionMin.size() < 4 ||
784 MacOSVersionMin.substr(0, 3) != "10." ||
785 !isdigit(MacOSVersionMin[3])) {
786 MacOSVersionMinIsInvalid = true;
787 } else {
788 const char *Start = MacOSVersionMin.c_str()+3;
789 char *End = 0;
790 VersionNum = (int)strtol(Start, &End, 10);
791
Chris Lattner079f2c462008-09-30 20:30:12 +0000792 // The version number must be in the range 0-9.
793 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
794
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000795 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
796 Triple += llvm::itostr(VersionNum+4);
797
Chris Lattner079f2c462008-09-30 20:30:12 +0000798 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
799 // Add the period piece (.7) to the end of the triple. This gives us
800 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000801 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000802 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
803 MacOSVersionMinIsInvalid = true;
804 }
805 }
806
807 if (MacOSVersionMinIsInvalid) {
808 fprintf(stderr,
809 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
810 MacOSVersionMin.c_str());
811 exit(1);
812 }
813}
814
815/// CreateTargetTriple - Process the various options that affect the target
816/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000817static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000818 // Initialize base triple. If a -triple option has been specified, use
819 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000820 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000821 if (Triple.empty()) {
822 Triple = LLVM_HOSTTRIPLE;
823
Daniel Dunbara6291902008-12-12 18:34:35 +0000824 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
825 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
826 Triple[2] == '8' && Triple[3] == '6')
827 Triple[1] = '3';
828
Daniel Dunbare553a722008-10-02 01:21:33 +0000829 // On darwin, we want to update the version to match that of the
830 // host.
831 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
832 if (DarwinDashIdx != std::string::npos) {
833 Triple.resize(DarwinDashIdx + strlen("-darwin"));
834
Daniel Dunbara6291902008-12-12 18:34:35 +0000835 // Only add the major part of the os version.
836 std::string Version = llvm::sys::osVersion();
837 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000838 }
839 }
Ted Kremenekae360762007-12-03 22:06:55 +0000840
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000841 // If -arch foo was specified, remove the architecture from the triple we have
842 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000843 if (!Arch.empty()) {
844 // Decompose the base triple into "arch" and suffix.
845 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000846
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000847 if (FirstDashIdx == std::string::npos) {
848 fprintf(stderr,
849 "Malformed target triple: \"%s\" ('-' could not be found).\n",
850 Triple.c_str());
851 exit(1);
852 }
Ted Kremenekae360762007-12-03 22:06:55 +0000853
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000854 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
855 }
856
857 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
858 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000859 if (!MacOSVersionMin.empty())
860 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000861
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000862 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000863}
864
865//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000866// Preprocessor Initialization
867//===----------------------------------------------------------------------===//
868
869// FIXME: Preprocessor builtins to support.
870// -A... - Play with #assertions
871// -undef - Undefine all predefined macros
872
873static llvm::cl::list<std::string>
874D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
875 llvm::cl::desc("Predefine the specified macro"));
876static llvm::cl::list<std::string>
877U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
878 llvm::cl::desc("Undefine the specified macro"));
879
Chris Lattner64299f82008-01-10 01:53:41 +0000880static llvm::cl::list<std::string>
881ImplicitIncludes("include", llvm::cl::value_desc("file"),
882 llvm::cl::desc("Include file before parsing"));
883
884
Reid Spencer5f016e22007-07-11 17:01:13 +0000885// Append a #define line to Buf for Macro. Macro should be of the form XXX,
886// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
887// "#define XXX Y z W". To get a #define with no value, use "XXX=".
888static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
889 const char *Command = "#define ") {
890 Buf.insert(Buf.end(), Command, Command+strlen(Command));
891 if (const char *Equal = strchr(Macro, '=')) {
892 // Turn the = into ' '.
893 Buf.insert(Buf.end(), Macro, Equal);
894 Buf.push_back(' ');
895 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
896 } else {
897 // Push "macroname 1".
898 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
899 Buf.push_back(' ');
900 Buf.push_back('1');
901 }
902 Buf.push_back('\n');
903}
904
Chris Lattner64299f82008-01-10 01:53:41 +0000905/// AddImplicitInclude - Add an implicit #include of the specified file to the
906/// predefines buffer.
907static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
908 const char *Inc = "#include \"";
909 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
910 Buf.insert(Buf.end(), File.begin(), File.end());
911 Buf.push_back('"');
912 Buf.push_back('\n');
913}
914
Reid Spencer5f016e22007-07-11 17:01:13 +0000915
Chris Lattner53b0dab2007-10-09 22:10:18 +0000916/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000917/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000918///
Chris Lattner51574ea2008-04-19 23:25:44 +0000919static bool InitializePreprocessor(Preprocessor &PP,
920 bool InitializeSourceMgr,
921 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000922 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000923
Chris Lattner53b0dab2007-10-09 22:10:18 +0000924 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000925 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000926
927 if (InitializeSourceMgr) {
928 if (InFile != "-") {
929 const FileEntry *File = FileMgr.getFile(InFile);
930 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000931 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000932 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000933 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000934 }
935 } else {
936 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
937 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000938 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000939 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000940 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000941 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000942 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000944
Chris Lattneraa391972008-04-19 23:09:31 +0000945 std::vector<char> PredefineBuffer;
946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000948 unsigned d = 0, D = D_macros.size();
949 unsigned u = 0, U = U_macros.size();
950 while (d < D || u < U) {
951 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
952 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
953 else
954 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
955 }
956
Chris Lattner64299f82008-01-10 01:53:41 +0000957 // FIXME: Read any files specified by -imacros.
958
959 // Add implicit #includes from -include.
960 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
961 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000962
Chris Lattneraa391972008-04-19 23:09:31 +0000963 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000964 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000965 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000966
967 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000968 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000969}
970
971//===----------------------------------------------------------------------===//
972// Preprocessor include path information.
973//===----------------------------------------------------------------------===//
974
975// This tool exports a large number of command line options to control how the
976// preprocessor searches for header files. At root, however, the Preprocessor
977// object takes a very simple interface: a list of directories to search for
978//
979// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000980// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000981//
Chris Lattner64299f82008-01-10 01:53:41 +0000982// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000983
984static llvm::cl::opt<bool>
985nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
986
987// Various command line options. These four add directories to each chain.
988static llvm::cl::list<std::string>
989F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
990 llvm::cl::desc("Add directory to framework include search path"));
991static llvm::cl::list<std::string>
992I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
993 llvm::cl::desc("Add directory to include search path"));
994static llvm::cl::list<std::string>
995idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
996 llvm::cl::desc("Add directory to AFTER include search path"));
997static llvm::cl::list<std::string>
998iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
999 llvm::cl::desc("Add directory to QUOTE include search path"));
1000static llvm::cl::list<std::string>
1001isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1002 llvm::cl::desc("Add directory to SYSTEM include search path"));
1003
1004// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1005static llvm::cl::list<std::string>
1006iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1007 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1008static llvm::cl::list<std::string>
1009iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1010 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1011static llvm::cl::list<std::string>
1012iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1013 llvm::cl::Prefix,
1014 llvm::cl::desc("Set directory to include search path with prefix"));
1015
Chris Lattner0c946412007-08-26 17:47:35 +00001016static llvm::cl::opt<std::string>
1017isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1018 llvm::cl::desc("Set the system root directory (usually /)"));
1019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001021
Reid Spencer5f016e22007-07-11 17:01:13 +00001022/// InitializeIncludePaths - Process the -I options and set them in the
1023/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001024void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1025 FileManager &FM, const LangOptions &Lang) {
1026 InitHeaderSearch Init(Headers, Verbose, isysroot);
1027
Ted Kremenekf3721112008-05-31 00:27:00 +00001028 // Handle -I... and -F... options, walking the lists in parallel.
1029 unsigned Iidx = 0, Fidx = 0;
1030 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1031 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001032 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001033 ++Iidx;
1034 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001035 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001036 ++Fidx;
1037 }
1038 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001039
Ted Kremenekf3721112008-05-31 00:27:00 +00001040 // Consume what's left from whatever list was longer.
1041 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001042 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001043 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001044 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001045
1046 // Handle -idirafter... options.
1047 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001048 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1049 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001050
1051 // Handle -iquote... options.
1052 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001053 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001054
1055 // Handle -isystem... options.
1056 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001057 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001058
1059 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1060 // parallel, processing the values in order of occurance to get the right
1061 // prefixes.
1062 {
1063 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1064 unsigned iprefix_idx = 0;
1065 unsigned iwithprefix_idx = 0;
1066 unsigned iwithprefixbefore_idx = 0;
1067 bool iprefix_done = iprefix_vals.empty();
1068 bool iwithprefix_done = iwithprefix_vals.empty();
1069 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1070 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1071 if (!iprefix_done &&
1072 (iwithprefix_done ||
1073 iprefix_vals.getPosition(iprefix_idx) <
1074 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1075 (iwithprefixbefore_done ||
1076 iprefix_vals.getPosition(iprefix_idx) <
1077 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1078 Prefix = iprefix_vals[iprefix_idx];
1079 ++iprefix_idx;
1080 iprefix_done = iprefix_idx == iprefix_vals.size();
1081 } else if (!iwithprefix_done &&
1082 (iwithprefixbefore_done ||
1083 iwithprefix_vals.getPosition(iwithprefix_idx) <
1084 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001085 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1086 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 ++iwithprefix_idx;
1088 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1089 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001090 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1091 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 ++iwithprefixbefore_idx;
1093 iwithprefixbefore_done =
1094 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1095 }
1096 }
1097 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001098
Nico Weber0fca0222008-08-22 09:25:22 +00001099 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001100
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001101 // Add the clang headers, which are relative to the clang driver.
1102 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001103 llvm::sys::Path::GetMainExecutable(Argv0,
1104 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001105 if (!MainExecutablePath.isEmpty()) {
1106 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1107 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1108 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber0fca0222008-08-22 09:25:22 +00001109 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1110 false, false, false);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001111 }
1112
Nico Weber0fca0222008-08-22 09:25:22 +00001113 if (!nostdinc)
1114 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001115
1116 // Now that we have collected all of the include paths, merge them all
1117 // together and tell the preprocessor about them.
1118
Nico Weber0fca0222008-08-22 09:25:22 +00001119 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001120}
1121
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001122//===----------------------------------------------------------------------===//
1123// Driver PreprocessorFactory - For lazily generating preprocessors ...
1124//===----------------------------------------------------------------------===//
1125
1126namespace {
1127class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001128 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001129 Diagnostic &Diags;
1130 const LangOptions &LangInfo;
1131 TargetInfo &Target;
1132 SourceManager &SourceMgr;
1133 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001134 bool InitializeSourceMgr;
1135
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001136public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001137 DriverPreprocessorFactory(const std::string &infile,
1138 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001139 TargetInfo &target, SourceManager &SM,
1140 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001141 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1142 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1143
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001144
1145 virtual ~DriverPreprocessorFactory() {}
1146
1147 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001148 llvm::OwningPtr<PTHManager> PTHMgr;
1149
1150 // Use PTH?
1151 if (!TokenCache.empty())
1152 PTHMgr.reset(PTHManager::Create(TokenCache));
1153
1154 // Create the Preprocessor.
1155 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1156 SourceMgr, HeaderInfo,
1157 PTHMgr.get()));
1158
1159 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1160 // That argument is used as the IdentifierInfoLookup argument to
1161 // IdentifierTable's ctor.
1162 if (PTHMgr) {
1163 PTHMgr->setPreprocessor(PP.get());
1164 PP->setPTHManager(PTHMgr.take());
1165 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001166
Chris Lattner51574ea2008-04-19 23:25:44 +00001167 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001168 return NULL;
1169 }
1170
Daniel Dunbar750c3582008-10-24 22:12:41 +00001171 /// FIXME: PP can only handle one callback
1172 if (ProgAction != PrintPreprocessedInput) {
1173 const char* ErrStr;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001174 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001175 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001176 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001177 return NULL;
1178 }
1179 }
1180
Ted Kremenek339b9c22008-04-17 22:31:54 +00001181 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001182 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001183 }
1184};
1185}
Reid Spencer5f016e22007-07-11 17:01:13 +00001186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187//===----------------------------------------------------------------------===//
1188// Basic Parser driver
1189//===----------------------------------------------------------------------===//
1190
Chris Lattner51574ea2008-04-19 23:25:44 +00001191static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001193 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001194
1195 // Parsing the specified input file.
1196 P.ParseTranslationUnit();
1197 delete PA;
1198}
1199
1200//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001201// Code generation options
1202//===----------------------------------------------------------------------===//
1203
1204static llvm::cl::opt<bool>
1205OptSize("Os",
1206 llvm::cl::desc("Optimize for size"));
1207
1208// It might be nice to add bounds to the CommandLine library directly.
1209struct OptLevelParser : public llvm::cl::parser<unsigned> {
1210 bool parse(llvm::cl::Option &O, const char *ArgName,
1211 const std::string &Arg, unsigned &Val) {
1212 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1213 return true;
1214 // FIXME: Support -O4.
1215 if (Val > 3)
1216 return O.error(": '" + Arg + "' invalid optimization level!");
1217 return false;
1218 }
1219};
1220static llvm::cl::opt<unsigned, false, OptLevelParser>
1221OptLevel("O", llvm::cl::Prefix,
1222 llvm::cl::desc("Optimization level"),
1223 llvm::cl::init(0));
1224
1225static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001226 Opts.OptimizeSize = OptSize;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001227 if (OptSize) {
1228 // -Os implies -O2
1229 // FIXME: Diagnose conflicting options.
1230 Opts.OptimizationLevel = 2;
1231 } else {
1232 Opts.OptimizationLevel = OptLevel;
1233 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001234
1235 // FIXME: There are llvm-gcc options to control these selectively.
1236 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1237 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1238 Opts.SimplifyLibCalls = 1;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001239
1240#ifdef NDEBUG
1241 Opts.VerifyModule = 0;
1242#endif
Daniel Dunbar70f92432008-10-23 05:50:47 +00001243}
1244
1245//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001246// Main driver
1247//===----------------------------------------------------------------------===//
1248
Ted Kremenekdb094a22007-12-05 18:27:04 +00001249/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1250/// action. These consumers can operate on both ASTs that are freshly
1251/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001252static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001253 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001254 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001255 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001256 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001257 switch (ProgAction) {
1258 default:
1259 return NULL;
1260
1261 case ASTPrint:
1262 return CreateASTPrinter();
1263
1264 case ASTDump:
1265 return CreateASTDumper();
1266
1267 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001268 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001269
1270 case PrintDeclContext:
1271 return CreateDeclContextPrinter();
Ted Kremenek6a340832008-03-18 21:19:49 +00001272
1273 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001274 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001275
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001276 case InheritanceView:
1277 return CreateInheritanceViewer(InheritanceViewCls);
1278
Ted Kremenekdb094a22007-12-05 18:27:04 +00001279 case TestSerialization:
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001280 return CreateSerializationTest(Diag, FileMgr);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001281
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001282 case EmitAssembly:
Ted Kremenekdb094a22007-12-05 18:27:04 +00001283 case EmitLLVM:
Daniel Dunbar70f92432008-10-23 05:50:47 +00001284 case EmitBC: {
1285 BackendAction Act;
1286 if (ProgAction == EmitAssembly) {
1287 Act = Backend_EmitAssembly;
1288 } else if (ProgAction == EmitLLVM) {
1289 Act = Backend_EmitLL;
1290 } else {
1291 Act = Backend_EmitBC;
1292 }
1293 CompileOptions Opts;
1294 InitializeCompileOptions(Opts);
1295 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001296 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbar70f92432008-10-23 05:50:47 +00001297 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001298
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001299 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001300 // FIXME: Allow user to tailor where the file is written.
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001301 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001302
Steve Naroffb29b4272008-04-14 22:03:09 +00001303 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001304 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001305
1306 case RewriteBlocks:
1307 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001308
1309 case RunAnalysis:
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001310 return CreateAnalysisConsumer(&AnalysisList[0],
1311 &AnalysisList[0]+AnalysisList.size(),
Ted Kremenek4fc82c82008-11-03 23:18:07 +00001312 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001313 Diag, PP, PPF, LangOpts,
1314 AnalyzeSpecificFunction,
Ted Kremenekf8ce6992008-08-27 22:31:43 +00001315 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1316 TrimGraph, AnalyzeAll);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001317 }
1318}
1319
Reid Spencer5f016e22007-07-11 17:01:13 +00001320/// ProcessInputFile - Process a single input file with the specified state.
1321///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001322static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001323 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001324 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001325 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001326
Ted Kremenek85888962008-10-21 00:54:44 +00001327 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001329 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1330 PP.getFileManager(), PP.getLangOptions(),
1331 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001332
1333 if (!Consumer) {
1334 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001335 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001336 return;
1337 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001338
Ted Kremenekdb094a22007-12-05 18:27:04 +00001339 break;
1340
Chris Lattnerc106c102008-10-12 05:03:36 +00001341 case DumpRawTokens: {
1342 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001343 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001344 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001345 RawLex.SetKeepWhitespaceMode(true);
1346
1347 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001348 RawLex.LexFromRawLexer(RawTok);
1349 while (RawTok.isNot(tok::eof)) {
1350 PP.DumpToken(RawTok, true);
1351 fprintf(stderr, "\n");
1352 RawLex.LexFromRawLexer(RawTok);
1353 }
1354 ClearSourceMgr = true;
1355 break;
1356 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001358 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001359 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001360 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 do {
1362 PP.Lex(Tok);
1363 PP.DumpToken(Tok, true);
1364 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001365 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001366 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 break;
1368 }
1369 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001370 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001372 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 do {
1374 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001375 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001376 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 break;
1378 }
Ted Kremenek85888962008-10-21 00:54:44 +00001379
1380 case GeneratePCH: {
1381 CacheTokens(PP, OutputFile);
1382 ClearSourceMgr = true;
1383 break;
1384 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001385
1386 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001387 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001388 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001390
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 case ParseNoop: // -parse-noop
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001392 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001393 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 break;
1395
1396 case ParsePrintCallbacks:
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001397 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001398 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001400
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001401 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001402 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001403 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001404
1405 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001406 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001407 ClearSourceMgr = true;
1408 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001409
1410 case RewriteTest:
1411 DoRewriteTest(PP, InFile, OutputFile);
1412 ClearSourceMgr = true;
1413 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001414 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001415
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001416 if (Consumer)
Daniel Dunbard3db4012008-10-16 16:54:18 +00001417 ParseAST(PP, Consumer.get(), Stats, !DisableFree);
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001418
1419 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001420 if (CheckDiagnostics(PP))
1421 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001422
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001424 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 PP.PrintStats();
1426 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001427 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001428 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 fprintf(stderr, "\n");
1430 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001431
1432 // For a multi-file compilation, some things are ok with nuking the source
1433 // manager tables, other require stable fileid/macroid's across multiple
1434 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001435 if (ClearSourceMgr)
1436 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001437
1438 if (DisableFree)
1439 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001440}
1441
Ted Kremenek20e97482007-12-12 23:41:08 +00001442static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1443 FileManager& FileMgr) {
1444
1445 if (VerifyDiagnostics) {
1446 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1447 exit (1);
1448 }
1449
1450 llvm::sys::Path Filename(InFile);
1451
1452 if (!Filename.isValid()) {
1453 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1454 exit (1);
1455 }
1456
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001457 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001458
1459 if (!TU) {
1460 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1461 InFile.c_str());
1462 exit (1);
1463 }
1464
Ted Kremenek63ea8632007-12-19 19:27:38 +00001465 // Observe that we use the source file name stored in the deserialized
1466 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001467 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001468 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001469 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001470
Ted Kremenek20e97482007-12-12 23:41:08 +00001471 if (!Consumer) {
1472 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1473 exit (1);
1474 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001475
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001476 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001477
Chris Lattnere66b65c2008-02-06 01:42:25 +00001478 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001479 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1480 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001481}
1482
1483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484static llvm::cl::list<std::string>
1485InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1486
Ted Kremenek20e97482007-12-12 23:41:08 +00001487static bool isSerializedFile(const std::string& InFile) {
1488 if (InFile.size() < 4)
1489 return false;
1490
1491 const char* s = InFile.c_str()+InFile.size()-4;
1492
1493 return s[0] == '.' &&
1494 s[1] == 'a' &&
1495 s[2] == 's' &&
1496 s[3] == 't';
1497}
1498
Reid Spencer5f016e22007-07-11 17:01:13 +00001499
1500int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001501 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 llvm::sys::PrintStackTraceOnErrorSignal();
1503
1504 // If no input was specified, read from stdin.
1505 if (InputFilenames.empty())
1506 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001507
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 // Create a file manager object to provide access to and cache the filesystem.
1509 FileManager FileMgr;
1510
Ted Kremenek31e703b2007-12-11 23:28:38 +00001511 // Create the diagnostic client for reporting errors or for
1512 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001513 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001514
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001515 if (!VerifyDiagnostics) {
1516 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001517 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1518 !NoShowColumn,
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001519 !NoCaretDiagnostics);
1520 } else {
1521 // When checking diagnostics, just buffer them up.
1522 TextDiagClient = new TextDiagnosticBuffer();
1523
1524 if (InputFilenames.size() != 1) {
1525 fprintf(stderr,
1526 "-verify only works on single input files for now.\n");
1527 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 }
1529 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001530
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001532 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1533 Diagnostic Diags(DiagClient.get());
Ted Kremenek31e703b2007-12-11 23:28:38 +00001534 InitializeDiagnostics(Diags);
1535
Chris Lattner4f037832007-12-05 23:24:17 +00001536 // -I- is a deprecated GCC feature, scan for it and reject it.
1537 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1538 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001539 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001540 I_dirs.erase(I_dirs.begin()+i);
1541 --i;
1542 }
1543 }
Chris Lattner11215192008-03-14 06:12:05 +00001544
1545 // Get information about the target being compiled for.
1546 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001547 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1548
Chris Lattner11215192008-03-14 06:12:05 +00001549 if (Target == 0) {
1550 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1551 Triple.c_str());
1552 fprintf(stderr, "Please use -triple or -arch.\n");
1553 exit(1);
1554 }
Chris Lattner4f037832007-12-05 23:24:17 +00001555
Daniel Dunbard4270232009-01-20 23:17:32 +00001556 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001557 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001558
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001559 llvm::OwningPtr<SourceManager> SourceMgr;
1560
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001562 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001563
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001564 if (isSerializedFile(InFile)) {
1565 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001566 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001567 }
Ted Kremenek20e97482007-12-12 23:41:08 +00001568 else {
1569 /// Create a SourceManager object. This tracks and owns all the file
1570 /// buffers allocated to a translation unit.
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001571 if (!SourceMgr)
1572 SourceMgr.reset(new SourceManager());
1573 else
1574 SourceMgr->clearIDTables();
Ted Kremenek31e703b2007-12-11 23:28:38 +00001575
Ted Kremenek20e97482007-12-12 23:41:08 +00001576 // Initialize language options, inferring file types from input filenames.
1577 LangOptions LangInfo;
1578 InitializeBaseLanguage();
1579 LangKind LK = GetLanguage(InFile);
Ted Kremenek85888962008-10-21 00:54:44 +00001580 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001581 InitializeGCMode(LangInfo);
Chris Lattner8fc4dfb2008-12-04 22:54:33 +00001582 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek85888962008-10-21 00:54:44 +00001583
Ted Kremenek20e97482007-12-12 23:41:08 +00001584 // Process the -I options and set them in the HeaderInfo.
1585 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekc68ecb52008-06-06 01:47:30 +00001586
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001587 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001588
Ted Kremenek20e97482007-12-12 23:41:08 +00001589 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001590 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001591 *SourceMgr.get(), HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001592
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001593 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1594
Ted Kremenek339b9c22008-04-17 22:31:54 +00001595 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001596 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001597
1598 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1599 // always reset to using TextDiagClient.
1600 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001601
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001602 if (!HTMLDiag.empty()) {
1603 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1604 &PPFactory));
1605 Diags.setClient(TmpClient.get());
1606 }
1607 else
1608 Diags.setClient(TextDiagClient);
1609
1610 // Process the source file.
Ted Kremenek85888962008-10-21 00:54:44 +00001611 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1612
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001613 HeaderInfo.ClearFileInfo();
Ted Kremenek20e97482007-12-12 23:41:08 +00001614 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 }
Chris Lattner11215192008-03-14 06:12:05 +00001616
Ted Kremenek7a08e282008-08-07 18:13:12 +00001617 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1619 (NumDiagnostics == 1 ? "" : "s"));
1620
1621 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 FileMgr.PrintStats();
1623 fprintf(stderr, "\n");
1624 }
1625
Daniel Dunbar276373d2008-10-27 22:10:13 +00001626 // If verifying diagnostics and we reached here, all is well.
1627 if (VerifyDiagnostics)
1628 return 0;
1629
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001630 // Managed static deconstruction. Useful for making things like
1631 // -time-passes usable.
1632 llvm::llvm_shutdown();
1633
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001634 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001635}