blob: 52f34783c1f2ce96995248e4225ec140f3b9c204 [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 Lattner88eccaf2009-01-29 06:55:46 +000037#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000038#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerba0f25f2008-09-30 20:16:56 +000044#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000045#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000046#include "llvm/ADT/StringExtras.h"
47#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000048#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000049#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000050#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000051#include "llvm/Support/PluginLoader.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000052#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000053#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000055using namespace clang;
56
57//===----------------------------------------------------------------------===//
58// Global options.
59//===----------------------------------------------------------------------===//
60
Daniel Dunbard3db4012008-10-16 16:54:18 +000061static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000062
Reid Spencer5f016e22007-07-11 17:01:13 +000063static llvm::cl::opt<bool>
64Verbose("v", llvm::cl::desc("Enable verbose output"));
65static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000066Stats("print-stats",
67 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-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));
Reid Spencer5f016e22007-07-11 17:01:13 +000072
73enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000074 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000075 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000076 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000077 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000078 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000079 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000080 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000081 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000082 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000083 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-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 Xu2d75d6f2009-01-13 01:29:24 +000087 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000088 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +000094 DumpTokens, // Dump out preprocessed tokens.
95 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +000096 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +000097 GeneratePCH, // Generate precompiled header.
98 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerc106c102008-10-12 05:03:36 +0000109 clEnumValN(DumpRawTokens, "dump-raw-tokens",
110 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000111 clEnumValN(RunAnalysis, "analyze",
112 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000113 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek6a340832008-03-18 21:19:49 +0000121 clEnumValN(EmitHTML, "emit-html",
122 "Output input source as HTML"),
Chris Lattner3b427b32007-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 Lattnerea254db2007-10-11 00:37:43 +0000127 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000128 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000129 clEnumValN(PrintDeclContext, "print-decl-contexts",
130 "Print DeclContexts and their Decls."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000131 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000132 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000133 clEnumValN(EmitAssembly, "S",
134 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000136 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000137 clEnumValN(EmitBC, "emit-llvm-bc",
138 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000139 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000140 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000141 clEnumValN(RewriteTest, "rewrite-test",
142 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000143 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-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 Naroff13188952008-09-18 14:10:13 +0000147 clEnumValN(RewriteBlocks, "rewrite-blocks",
148 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 clEnumValEnd));
150
Ted Kremenekccc76472007-12-19 19:47:59 +0000151
152static llvm::cl::opt<std::string>
153OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000154 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000155 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000156
157//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-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 Kremenekc2e72992008-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 Guptae8b9f5b2008-05-08 08:54:20 +0000173//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000174// Diagnostic Options
175//===----------------------------------------------------------------------===//
176
Ted Kremenek41193e42007-09-26 19:42:19 +0000177static llvm::cl::opt<bool>
178VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000179 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000180
Ted Kremenek88f5cde2008-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 Weberfd54ebc2008-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>
Chris Lattner65f5e642009-01-30 19:01:41 +0000191NoShowLocation("fno-show-source-location",
192 llvm::cl::desc("Do not include source location information with"
193 " diagnostics"));
194
195static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000196NoCaretDiagnostics("fno-caret-diagnostics",
197 llvm::cl::desc("Do not include source line and caret with"
198 " diagnostics"));
199
200
Reid Spencer5f016e22007-07-11 17:01:13 +0000201//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000202// C++ Visualization.
203//===----------------------------------------------------------------------===//
204
205static llvm::cl::opt<std::string>
206InheritanceViewCls("cxx-inheritance-view",
207 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000208 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000209
210//===----------------------------------------------------------------------===//
211// Analyzer Options.
Ted Kremenek55af98c2008-04-14 18:40:58 +0000212//===----------------------------------------------------------------------===//
213
214static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000215VisualizeEGDot("analyzer-viz-egraph-graphviz",
216 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000217
218static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000219VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
220 llvm::cl::desc("Display exploded graph using Ubigraph"));
221
222static llvm::cl::opt<bool>
223AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek55af98c2008-04-14 18:40:58 +0000224 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000225 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000226
Ted Kremenek491918e2009-01-23 20:52:26 +0000227static llvm::cl::opt<bool>
228AnalyzerDisplayProgress("analyzer-display-progress",
229 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
230
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000231static llvm::cl::list<Analyses>
Ted Kremenek95c7b002008-10-24 01:04:59 +0000232AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000233llvm::cl::values(
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000234#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000235clEnumValN(NAME, CMDFLAG, DESC),
236#include "Analyses.def"
237clEnumValEnd));
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000238
Ted Kremenek95c7b002008-10-24 01:04:59 +0000239static llvm::cl::opt<AnalysisStores>
240AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
241 llvm::cl::init(BasicStoreModel),
242 llvm::cl::values(
243#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
244clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
245#include "Analyses.def"
246clEnumValEnd));
247
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000248static llvm::cl::opt<AnalysisDiagClients>
249AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
250 llvm::cl::init(PD_HTML),
251 llvm::cl::values(
Ted Kremenekc472d792009-01-23 20:06:20 +0000252#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000253clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
254#include "Analyses.def"
255clEnumValEnd));
256
Ted Kremenek55af98c2008-04-14 18:40:58 +0000257//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000258// Language Options
259//===----------------------------------------------------------------------===//
260
261enum LangKind {
262 langkind_unspecified,
263 langkind_c,
264 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000265 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000266 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 langkind_cxx,
268 langkind_cxx_cpp,
269 langkind_objc,
270 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000271 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000273 langkind_objcxx_cpp,
274 langkind_objcxx_pch
Reid Spencer5f016e22007-07-11 17:01:13 +0000275};
276
277/* TODO: GCC also accepts:
278 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera778d7d2008-10-22 17:29:21 +0000279 assembler
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 ada, f77*, ratfor (!), f95, java, treelang
281 */
282static llvm::cl::opt<LangKind>
283BaseLang("x", llvm::cl::desc("Base language to compile"),
284 llvm::cl::init(langkind_unspecified),
285 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
286 clEnumValN(langkind_cxx, "c++", "C++"),
287 clEnumValN(langkind_objc, "objective-c", "Objective C"),
288 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000289 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000291 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
292 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek85888962008-10-21 00:54:44 +0000294 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
296 "Preprocessed Objective C"),
297 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
298 "Preprocessed Objective C++"),
Ted Kremenek85888962008-10-21 00:54:44 +0000299 clEnumValN(langkind_c_pch,"c-header",
300 "Precompiled C header"),
301 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000302 "Precompiled Objective-C header"),
303 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
304 "Precompiled Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 clEnumValEnd));
306
307static llvm::cl::opt<bool>
308LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
309 llvm::cl::Hidden);
310static llvm::cl::opt<bool>
311LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
312 llvm::cl::Hidden);
313
Ted Kremenek8904f152007-12-05 23:49:08 +0000314/// InitializeBaseLanguage - Handle the -x foo options.
315static void InitializeBaseLanguage() {
316 if (LangObjC)
317 BaseLang = langkind_objc;
318 else if (LangObjCXX)
319 BaseLang = langkind_objcxx;
320}
321
322static LangKind GetLanguage(const std::string &Filename) {
323 if (BaseLang != langkind_unspecified)
324 return BaseLang;
325
326 std::string::size_type DotPos = Filename.rfind('.');
327
328 if (DotPos == std::string::npos) {
329 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000330 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 }
332
Ted Kremenek8904f152007-12-05 23:49:08 +0000333 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
334 // C header: .h
335 // C++ header: .hh or .H;
336 // assembler no preprocessing: .s
337 // assembler: .S
338 if (Ext == "c")
339 return langkind_c;
Chris Lattner1b450b02008-10-28 20:33:42 +0000340 else if (Ext == "S")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000341 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000342 else if (Ext == "i")
343 return langkind_c_cpp;
344 else if (Ext == "ii")
345 return langkind_cxx_cpp;
346 else if (Ext == "m")
347 return langkind_objc;
348 else if (Ext == "mi")
349 return langkind_objc_cpp;
350 else if (Ext == "mm" || Ext == "M")
351 return langkind_objcxx;
352 else if (Ext == "mii")
353 return langkind_objcxx_cpp;
354 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
355 Ext == "c++" || Ext == "cp" || Ext == "cxx")
356 return langkind_cxx;
357 else
358 return langkind_c;
359}
360
361
Ted Kremenek85888962008-10-21 00:54:44 +0000362static void InitializeCOptions(LangOptions &Options) {
363 // Do nothing.
364}
365
366static void InitializeObjCOptions(LangOptions &Options) {
367 Options.ObjC1 = Options.ObjC2 = 1;
368}
369
370
371static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 // FIXME: implement -fpreprocessed mode.
373 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000374 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000375
376 // Test for 'PCH'.
377 switch (LK) {
378 default:
379 break;
380 case langkind_c_pch:
381 LK = langkind_c;
382 PCH = true;
383 break;
384 case langkind_objc_pch:
385 LK = langkind_objc;
386 PCH = true;
387 break;
388 case langkind_objcxx_pch:
389 LK = langkind_objcxx;
390 PCH = true;
391 break;
392 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000393
Ted Kremenek8904f152007-12-05 23:49:08 +0000394 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000396 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000397 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000398 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 case langkind_c_cpp:
400 NoPreprocess = true;
401 // FALLTHROUGH
402 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000403 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 break;
405 case langkind_cxx_cpp:
406 NoPreprocess = true;
407 // FALLTHROUGH
408 case langkind_cxx:
409 Options.CPlusPlus = 1;
410 break;
411 case langkind_objc_cpp:
412 NoPreprocess = true;
413 // FALLTHROUGH
414 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000415 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 break;
417 case langkind_objcxx_cpp:
418 NoPreprocess = true;
419 // FALLTHROUGH
420 case langkind_objcxx:
421 Options.ObjC1 = Options.ObjC2 = 1;
422 Options.CPlusPlus = 1;
423 break;
424 }
Ted Kremenek85888962008-10-21 00:54:44 +0000425
426 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000427}
428
429/// LangStds - Language standards we support.
430enum LangStds {
431 lang_unspecified,
432 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000433 lang_gnu_START,
434 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000435 lang_cxx98, lang_gnucxx98,
436 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000437};
438
439static llvm::cl::opt<LangStds>
440LangStd("std", llvm::cl::desc("Language standard to compile for"),
441 llvm::cl::init(lang_unspecified),
442 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
443 clEnumValN(lang_c89, "c90", "ISO C 1990"),
444 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
445 clEnumValN(lang_c94, "iso9899:199409",
446 "ISO C 1990 with amendment 1"),
447 clEnumValN(lang_c99, "c99", "ISO C 1999"),
448// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
449 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
450// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
451 clEnumValN(lang_gnu89, "gnu89",
452 "ISO C 1990 with GNU extensions (default for C)"),
453 clEnumValN(lang_gnu99, "gnu99",
454 "ISO C 1999 with GNU extensions"),
455 clEnumValN(lang_gnu99, "gnu9x",
456 "ISO C 1999 with GNU extensions"),
457 clEnumValN(lang_cxx98, "c++98",
458 "ISO C++ 1998 with amendments"),
459 clEnumValN(lang_gnucxx98, "gnu++98",
460 "ISO C++ 1998 with amendments and GNU "
461 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000462 clEnumValN(lang_cxx0x, "c++0x",
463 "Upcoming ISO C++ 200x with amendments"),
464 clEnumValN(lang_gnucxx0x, "gnu++0x",
465 "Upcoming ISO C++ 200x with amendments and GNU "
466 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 clEnumValEnd));
468
469static llvm::cl::opt<bool>
470NoOperatorNames("fno-operator-names",
471 llvm::cl::desc("Do not treat C++ operator name keywords as "
472 "synonyms for operators"));
473
Anders Carlssonee98ac52007-10-15 02:50:23 +0000474static llvm::cl::opt<bool>
475PascalStrings("fpascal-strings",
476 llvm::cl::desc("Recognize and construct Pascal-style "
477 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000478
479static llvm::cl::opt<bool>
480MSExtensions("fms-extensions",
481 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000482 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000483
484static llvm::cl::opt<bool>
485WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000486 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000487
488static llvm::cl::opt<bool>
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000489NoLaxVectorConversions("fnolax-vector-conversions",
490 llvm::cl::desc("Disallow implicit conversions between "
491 "vectors with a different number of "
492 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000493static llvm::cl::opt<bool>
Mike Stumpb55cc632009-01-30 08:22:07 +0000494EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"), llvm::cl::ValueDisallowed);
495
496static llvm::cl::inverse_opt
497DisableBlocks("fno-blocks", llvm::cl::opposite_of(EnableBlocks), llvm::cl::ValueDisallowed);
Chris Lattnerae0ee032008-12-04 23:20:07 +0000498
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000499static llvm::cl::opt<bool>
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000500ObjCNonFragileABI("fobjc-nonfragile-abi", llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000501
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000502
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000503// FIXME: This (and all GCC -f options) really come in -f... and
504// -fno-... forms, and additionally support automagic behavior when
505// they are not defined. For example, -fexceptions defaults to on or
506// off depending on the language. We should support this behavior in
507// some form (perhaps just add a facility for distinguishing when an
508// has its default value from when it has been set to its default
509// value).
510static llvm::cl::opt<bool>
511Exceptions("fexceptions",
512 llvm::cl::desc("Enable support for exception handling."));
513
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000514static llvm::cl::opt<bool>
515GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000516 llvm::cl::desc("Generate output compatible with the standard GNU "
517 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000518
519static llvm::cl::opt<bool>
520NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000521 llvm::cl::desc("Generate output compatible with the NeXT "
522 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000523
Ted Kremenekea644d82008-09-03 21:22:16 +0000524
525
526static llvm::cl::opt<bool>
527Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
528
529static llvm::cl::opt<bool>
530Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
531
Reid Spencer5f016e22007-07-11 17:01:13 +0000532// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000533// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000534static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
535 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000536 // Allow the target to set the default the langauge options as it sees fit.
537 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000538
539 if (Ansi) // "The -ansi option is equivalent to -std=c89."
540 LangStd = lang_c89;
541
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 if (LangStd == lang_unspecified) {
543 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000544 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 default: assert(0 && "Unknown base language");
546 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000547 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000549 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 case langkind_objc:
551 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000552 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 LangStd = lang_gnu99;
554 break;
555 case langkind_cxx:
556 case langkind_cxx_cpp:
557 case langkind_objcxx:
558 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000559 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 LangStd = lang_gnucxx98;
561 break;
562 }
563 }
564
565 switch (LangStd) {
566 default: assert(0 && "Unknown language standard!");
567
568 // Fall through from newer standards to older ones. This isn't really right.
569 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000570 case lang_gnucxx0x:
571 case lang_cxx0x:
572 Options.CPlusPlus0x = 1;
573 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 case lang_gnucxx98:
575 case lang_cxx98:
576 Options.CPlusPlus = 1;
577 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000578 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 // FALL THROUGH.
580 case lang_gnu99:
581 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 Options.C99 = 1;
583 Options.HexFloats = 1;
584 // FALL THROUGH.
585 case lang_gnu89:
586 Options.BCPLComment = 1; // Only for C99/C++.
587 // FALL THROUGH.
588 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000589 Options.Digraphs = 1; // C94, C99, C++.
590 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 case lang_c89:
592 break;
593 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000594
595 if (Options.CPlusPlus) {
596 Options.C99 = 0;
597 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
598 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000599
Chris Lattnerd658b562008-04-05 06:32:51 +0000600 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
601 Options.ImplicitInt = 1;
602 else
603 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000604
605 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
606 // is specified, or -std is set to a conforming mode.
Chris Lattner802db9b2008-12-05 00:10:44 +0000607 Options.Trigraphs = LangStd < lang_gnu_START;
608 if (Trigraphs.getPosition())
609 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenekea644d82008-09-03 21:22:16 +0000610
Chris Lattner802db9b2008-12-05 00:10:44 +0000611 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
612 // even if they are normally on for the target. In GNU modes (e.g.
613 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000614 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
615 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner802db9b2008-12-05 00:10:44 +0000616 Options.Blocks = 0;
617
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000619 if (PascalStrings.getPosition())
620 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000621 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000622 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000623 if (NoLaxVectorConversions.getPosition())
624 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000625 Options.Exceptions = Exceptions;
Mike Stumpb55cc632009-01-30 08:22:07 +0000626 if (EnableBlocks.getPosition() || DisableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000627 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000628
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000629 // Override the default runtime if the user requested it.
630 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000631 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000632 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000633 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000634
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000635 if (ObjCNonFragileABI)
636 Options.ObjCNonFragileABI = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000637}
638
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000639static llvm::cl::opt<bool>
640ObjCExclusiveGC("fobjc-gc-only",
641 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000642 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000643
644static llvm::cl::opt<bool>
645ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000646 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000647
648void InitializeGCMode(LangOptions &Options) {
649 if (ObjCExclusiveGC)
650 Options.setGCMode(LangOptions::GCOnly);
651 else if (ObjCEnableGC)
652 Options.setGCMode(LangOptions::HybridGC);
653}
654
655
Reid Spencer5f016e22007-07-11 17:01:13 +0000656//===----------------------------------------------------------------------===//
657// Our DiagnosticClient implementation
658//===----------------------------------------------------------------------===//
659
660// FIXME: Werror should take a list of things, -Werror=foo,bar
661static llvm::cl::opt<bool>
662WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
663
664static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000665SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
666
667static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000668WarnOnExtensions("pedantic", llvm::cl::init(false),
669 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
670
671static llvm::cl::opt<bool>
672ErrorOnExtensions("pedantic-errors",
673 llvm::cl::desc("Issue an error on uses of GCC extensions"));
674
675static llvm::cl::opt<bool>
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000676SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar320a0542008-09-30 20:49:53 +0000677 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000678 llvm::cl::init(true));
679
680static llvm::cl::opt<bool>
Daniel Dunbard77b2512009-01-14 18:56:36 +0000681WarnUnusedMacros("Wunused-macros",
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 llvm::cl::desc("Warn for unused macros in the main translation unit"));
683
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000684static llvm::cl::opt<bool>
685WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000686 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000687
Ted Kremenek73da5902007-12-17 17:50:07 +0000688static llvm::cl::opt<bool>
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000689WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
690 llvm::cl::desc("Warn about readonly properties with writable attributes"));
691
692static llvm::cl::opt<bool>
Ted Kremenek73da5902007-12-17 17:50:07 +0000693WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000694 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000695
Chris Lattner116a4b12008-01-23 17:19:46 +0000696static llvm::cl::opt<bool>
697WarnUndefMacros("Wundef",
698 llvm::cl::desc("Warn on use of undefined macros in #if's"));
699
Chris Lattner37d10842008-05-05 21:18:06 +0000700static llvm::cl::opt<bool>
Ted Kremenek358256d2008-05-30 16:42:02 +0000701WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
702 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattner116a4b12008-01-23 17:19:46 +0000703
Steve Narofffe6b0dc2008-10-21 10:37:50 +0000704static llvm::cl::opt<bool>
705WarnNoStrictSelectorMatch("Wno-strict-selector-match",
706 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
707 llvm::cl::init(true));
708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709/// InitializeDiagnostics - Initialize the diagnostic object, based on the
710/// current command line option settings.
711static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000712 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 Diags.setWarningsAsErrors(WarningsAsErrors);
714 Diags.setWarnOnExtensions(WarnOnExtensions);
715 Diags.setErrorOnExtensions(ErrorOnExtensions);
716
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000717 // Suppress warnings in system headers unless requested not to.
718 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
719
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 // Silence the "macro is not used" warning unless requested.
721 if (!WarnUnusedMacros)
722 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000723
724 // Silence "floating point comparison" warnings unless requested.
725 if (!WarnFloatEqual)
726 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000727
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000728 if (!WarnPropertyReadonlyAttrs)
729 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
730 diag::MAP_IGNORE);
731
Ted Kremenek73da5902007-12-17 17:50:07 +0000732 // Silence "format string is not a string literal" warnings if requested
733 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000734 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
735 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000736 if (!WarnUndefMacros)
737 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000738
Chris Lattner88eccaf2009-01-29 06:55:46 +0000739 if (WarnImplicitFunctionDeclaration)
740 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
741 diag::MAP_WARNING);
742 else
Chris Lattner37d10842008-05-05 21:18:06 +0000743 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
744 diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000745}
746
747//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000748// Analysis-specific options.
749//===----------------------------------------------------------------------===//
750
751static llvm::cl::opt<std::string>
752AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000753 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000754
Ted Kremenekffe0f432008-03-07 22:58:01 +0000755static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000756TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000757 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000758
Ted Kremenekcb330932008-02-18 21:21:23 +0000759//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000760// Target Triple Processing.
761//===----------------------------------------------------------------------===//
762
763static llvm::cl::opt<std::string>
764TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000765 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000766
Chris Lattner42e67372008-03-05 01:18:20 +0000767static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000768Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000769
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000770static llvm::cl::opt<std::string>
771MacOSVersionMin("mmacosx-version-min",
772 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
773
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000774// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
775// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
776static void HandleMacOSVersionMin(std::string &Triple) {
777 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
778 if (DarwinDashIdx == std::string::npos) {
779 fprintf(stderr,
780 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
781 exit(1);
782 }
783 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
784
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000785 // Remove the number.
786 Triple.resize(DarwinNumIdx);
787
788 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
789 bool MacOSVersionMinIsInvalid = false;
790 int VersionNum = 0;
791 if (MacOSVersionMin.size() < 4 ||
792 MacOSVersionMin.substr(0, 3) != "10." ||
793 !isdigit(MacOSVersionMin[3])) {
794 MacOSVersionMinIsInvalid = true;
795 } else {
796 const char *Start = MacOSVersionMin.c_str()+3;
797 char *End = 0;
798 VersionNum = (int)strtol(Start, &End, 10);
799
Chris Lattner079f2c462008-09-30 20:30:12 +0000800 // The version number must be in the range 0-9.
801 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
802
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000803 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
804 Triple += llvm::itostr(VersionNum+4);
805
Chris Lattner079f2c462008-09-30 20:30:12 +0000806 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
807 // Add the period piece (.7) to the end of the triple. This gives us
808 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000809 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000810 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
811 MacOSVersionMinIsInvalid = true;
812 }
813 }
814
815 if (MacOSVersionMinIsInvalid) {
816 fprintf(stderr,
817 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
818 MacOSVersionMin.c_str());
819 exit(1);
820 }
821}
822
823/// CreateTargetTriple - Process the various options that affect the target
824/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000825static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000826 // Initialize base triple. If a -triple option has been specified, use
827 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000828 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000829 if (Triple.empty()) {
830 Triple = LLVM_HOSTTRIPLE;
831
Daniel Dunbara6291902008-12-12 18:34:35 +0000832 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
833 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
834 Triple[2] == '8' && Triple[3] == '6')
835 Triple[1] = '3';
836
Daniel Dunbare553a722008-10-02 01:21:33 +0000837 // On darwin, we want to update the version to match that of the
838 // host.
839 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
840 if (DarwinDashIdx != std::string::npos) {
841 Triple.resize(DarwinDashIdx + strlen("-darwin"));
842
Daniel Dunbara6291902008-12-12 18:34:35 +0000843 // Only add the major part of the os version.
Chris Lattnera05ff452009-01-22 20:57:52 +0000844 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbara6291902008-12-12 18:34:35 +0000845 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000846 }
847 }
Ted Kremenekae360762007-12-03 22:06:55 +0000848
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000849 // If -arch foo was specified, remove the architecture from the triple we have
850 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000851 if (!Arch.empty()) {
852 // Decompose the base triple into "arch" and suffix.
853 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000854
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000855 if (FirstDashIdx == std::string::npos) {
856 fprintf(stderr,
857 "Malformed target triple: \"%s\" ('-' could not be found).\n",
858 Triple.c_str());
859 exit(1);
860 }
Ted Kremenekae360762007-12-03 22:06:55 +0000861
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000862 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
863 }
864
865 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
866 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000867 if (!MacOSVersionMin.empty())
868 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000869
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000870 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000871}
872
873//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000874// Preprocessor Initialization
875//===----------------------------------------------------------------------===//
876
877// FIXME: Preprocessor builtins to support.
878// -A... - Play with #assertions
879// -undef - Undefine all predefined macros
880
881static llvm::cl::list<std::string>
882D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
883 llvm::cl::desc("Predefine the specified macro"));
884static llvm::cl::list<std::string>
885U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
886 llvm::cl::desc("Undefine the specified macro"));
887
Chris Lattner64299f82008-01-10 01:53:41 +0000888static llvm::cl::list<std::string>
889ImplicitIncludes("include", llvm::cl::value_desc("file"),
890 llvm::cl::desc("Include file before parsing"));
891
892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893// Append a #define line to Buf for Macro. Macro should be of the form XXX,
894// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
895// "#define XXX Y z W". To get a #define with no value, use "XXX=".
896static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
897 const char *Command = "#define ") {
898 Buf.insert(Buf.end(), Command, Command+strlen(Command));
899 if (const char *Equal = strchr(Macro, '=')) {
900 // Turn the = into ' '.
901 Buf.insert(Buf.end(), Macro, Equal);
902 Buf.push_back(' ');
903 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
904 } else {
905 // Push "macroname 1".
906 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
907 Buf.push_back(' ');
908 Buf.push_back('1');
909 }
910 Buf.push_back('\n');
911}
912
Chris Lattner64299f82008-01-10 01:53:41 +0000913/// AddImplicitInclude - Add an implicit #include of the specified file to the
914/// predefines buffer.
915static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
916 const char *Inc = "#include \"";
917 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
918 Buf.insert(Buf.end(), File.begin(), File.end());
919 Buf.push_back('"');
920 Buf.push_back('\n');
921}
922
Reid Spencer5f016e22007-07-11 17:01:13 +0000923
Chris Lattner53b0dab2007-10-09 22:10:18 +0000924/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000925/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000926///
Chris Lattner51574ea2008-04-19 23:25:44 +0000927static bool InitializePreprocessor(Preprocessor &PP,
928 bool InitializeSourceMgr,
929 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000930 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000931
Chris Lattner53b0dab2007-10-09 22:10:18 +0000932 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000933 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000934
935 if (InitializeSourceMgr) {
936 if (InFile != "-") {
937 const FileEntry *File = FileMgr.getFile(InFile);
938 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000939 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000940 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000941 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000942 }
943 } else {
944 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
945 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000946 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000947 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000948 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000949 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000950 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000952
Chris Lattneraa391972008-04-19 23:09:31 +0000953 std::vector<char> PredefineBuffer;
954
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000956 unsigned d = 0, D = D_macros.size();
957 unsigned u = 0, U = U_macros.size();
958 while (d < D || u < U) {
959 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
960 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
961 else
962 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
963 }
964
Chris Lattner64299f82008-01-10 01:53:41 +0000965 // FIXME: Read any files specified by -imacros.
966
967 // Add implicit #includes from -include.
968 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
969 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000970
Chris Lattneraa391972008-04-19 23:09:31 +0000971 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000972 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000973 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000974
975 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000976 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000977}
978
979//===----------------------------------------------------------------------===//
980// Preprocessor include path information.
981//===----------------------------------------------------------------------===//
982
983// This tool exports a large number of command line options to control how the
984// preprocessor searches for header files. At root, however, the Preprocessor
985// object takes a very simple interface: a list of directories to search for
986//
987// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000988// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000989//
Chris Lattner64299f82008-01-10 01:53:41 +0000990// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000991
992static llvm::cl::opt<bool>
993nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
994
995// Various command line options. These four add directories to each chain.
996static llvm::cl::list<std::string>
997F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
998 llvm::cl::desc("Add directory to framework include search path"));
999static llvm::cl::list<std::string>
1000I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1001 llvm::cl::desc("Add directory to include search path"));
1002static llvm::cl::list<std::string>
1003idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1004 llvm::cl::desc("Add directory to AFTER include search path"));
1005static llvm::cl::list<std::string>
1006iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1007 llvm::cl::desc("Add directory to QUOTE include search path"));
1008static llvm::cl::list<std::string>
1009isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1010 llvm::cl::desc("Add directory to SYSTEM include search path"));
1011
1012// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1013static llvm::cl::list<std::string>
1014iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1015 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1016static llvm::cl::list<std::string>
1017iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1018 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1019static llvm::cl::list<std::string>
1020iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1021 llvm::cl::Prefix,
1022 llvm::cl::desc("Set directory to include search path with prefix"));
1023
Chris Lattner0c946412007-08-26 17:47:35 +00001024static llvm::cl::opt<std::string>
1025isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1026 llvm::cl::desc("Set the system root directory (usually /)"));
1027
Reid Spencer5f016e22007-07-11 17:01:13 +00001028// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030/// InitializeIncludePaths - Process the -I options and set them in the
1031/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001032void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1033 FileManager &FM, const LangOptions &Lang) {
1034 InitHeaderSearch Init(Headers, Verbose, isysroot);
1035
Ted Kremenekf3721112008-05-31 00:27:00 +00001036 // Handle -I... and -F... options, walking the lists in parallel.
1037 unsigned Iidx = 0, Fidx = 0;
1038 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1039 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001040 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001041 ++Iidx;
1042 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001043 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001044 ++Fidx;
1045 }
1046 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001047
Ted Kremenekf3721112008-05-31 00:27:00 +00001048 // Consume what's left from whatever list was longer.
1049 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001050 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001051 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001052 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001053
1054 // Handle -idirafter... options.
1055 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001056 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1057 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001058
1059 // Handle -iquote... options.
1060 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001061 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001062
1063 // Handle -isystem... options.
1064 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001065 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001066
1067 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1068 // parallel, processing the values in order of occurance to get the right
1069 // prefixes.
1070 {
1071 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1072 unsigned iprefix_idx = 0;
1073 unsigned iwithprefix_idx = 0;
1074 unsigned iwithprefixbefore_idx = 0;
1075 bool iprefix_done = iprefix_vals.empty();
1076 bool iwithprefix_done = iwithprefix_vals.empty();
1077 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1078 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1079 if (!iprefix_done &&
1080 (iwithprefix_done ||
1081 iprefix_vals.getPosition(iprefix_idx) <
1082 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1083 (iwithprefixbefore_done ||
1084 iprefix_vals.getPosition(iprefix_idx) <
1085 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1086 Prefix = iprefix_vals[iprefix_idx];
1087 ++iprefix_idx;
1088 iprefix_done = iprefix_idx == iprefix_vals.size();
1089 } else if (!iwithprefix_done &&
1090 (iwithprefixbefore_done ||
1091 iwithprefix_vals.getPosition(iwithprefix_idx) <
1092 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001093 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1094 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 ++iwithprefix_idx;
1096 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1097 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001098 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1099 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 ++iwithprefixbefore_idx;
1101 iwithprefixbefore_done =
1102 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1103 }
1104 }
1105 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001106
Nico Weber0fca0222008-08-22 09:25:22 +00001107 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001108
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001109 // Add the clang headers, which are relative to the clang driver.
1110 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001111 llvm::sys::Path::GetMainExecutable(Argv0,
1112 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001113 if (!MainExecutablePath.isEmpty()) {
1114 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1115 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1116 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber0fca0222008-08-22 09:25:22 +00001117 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1118 false, false, false);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001119 }
1120
Nico Weber0fca0222008-08-22 09:25:22 +00001121 if (!nostdinc)
1122 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001123
1124 // Now that we have collected all of the include paths, merge them all
1125 // together and tell the preprocessor about them.
1126
Nico Weber0fca0222008-08-22 09:25:22 +00001127 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001128}
1129
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001130//===----------------------------------------------------------------------===//
1131// Driver PreprocessorFactory - For lazily generating preprocessors ...
1132//===----------------------------------------------------------------------===//
1133
1134namespace {
1135class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001136 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001137 Diagnostic &Diags;
1138 const LangOptions &LangInfo;
1139 TargetInfo &Target;
1140 SourceManager &SourceMgr;
1141 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001142 bool InitializeSourceMgr;
1143
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001144public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001145 DriverPreprocessorFactory(const std::string &infile,
1146 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001147 TargetInfo &target, SourceManager &SM,
1148 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001149 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1150 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1151
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001152
1153 virtual ~DriverPreprocessorFactory() {}
1154
1155 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001156 llvm::OwningPtr<PTHManager> PTHMgr;
1157
1158 // Use PTH?
1159 if (!TokenCache.empty())
Ted Kremenek8a6aec62009-01-28 20:49:33 +00001160 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenek72b1b152009-01-15 18:47:46 +00001161
1162 // Create the Preprocessor.
1163 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1164 SourceMgr, HeaderInfo,
1165 PTHMgr.get()));
1166
1167 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1168 // That argument is used as the IdentifierInfoLookup argument to
1169 // IdentifierTable's ctor.
1170 if (PTHMgr) {
1171 PTHMgr->setPreprocessor(PP.get());
1172 PP->setPTHManager(PTHMgr.take());
1173 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001174
Chris Lattner51574ea2008-04-19 23:25:44 +00001175 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001176 return NULL;
1177 }
1178
Daniel Dunbar750c3582008-10-24 22:12:41 +00001179 /// FIXME: PP can only handle one callback
1180 if (ProgAction != PrintPreprocessedInput) {
1181 const char* ErrStr;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001182 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001183 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001184 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001185 return NULL;
1186 }
1187 }
1188
Ted Kremenek339b9c22008-04-17 22:31:54 +00001189 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001190 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001191 }
1192};
1193}
Reid Spencer5f016e22007-07-11 17:01:13 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195//===----------------------------------------------------------------------===//
1196// Basic Parser driver
1197//===----------------------------------------------------------------------===//
1198
Chris Lattner51574ea2008-04-19 23:25:44 +00001199static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001201 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001202
1203 // Parsing the specified input file.
1204 P.ParseTranslationUnit();
1205 delete PA;
1206}
1207
1208//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001209// Code generation options
1210//===----------------------------------------------------------------------===//
1211
1212static llvm::cl::opt<bool>
1213OptSize("Os",
1214 llvm::cl::desc("Optimize for size"));
1215
1216// It might be nice to add bounds to the CommandLine library directly.
1217struct OptLevelParser : public llvm::cl::parser<unsigned> {
1218 bool parse(llvm::cl::Option &O, const char *ArgName,
1219 const std::string &Arg, unsigned &Val) {
1220 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1221 return true;
1222 // FIXME: Support -O4.
1223 if (Val > 3)
1224 return O.error(": '" + Arg + "' invalid optimization level!");
1225 return false;
1226 }
1227};
1228static llvm::cl::opt<unsigned, false, OptLevelParser>
1229OptLevel("O", llvm::cl::Prefix,
1230 llvm::cl::desc("Optimization level"),
1231 llvm::cl::init(0));
1232
1233static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001234 Opts.OptimizeSize = OptSize;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001235 if (OptSize) {
1236 // -Os implies -O2
1237 // FIXME: Diagnose conflicting options.
1238 Opts.OptimizationLevel = 2;
1239 } else {
1240 Opts.OptimizationLevel = OptLevel;
1241 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001242
1243 // FIXME: There are llvm-gcc options to control these selectively.
1244 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1245 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1246 Opts.SimplifyLibCalls = 1;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001247
1248#ifdef NDEBUG
1249 Opts.VerifyModule = 0;
1250#endif
Daniel Dunbar70f92432008-10-23 05:50:47 +00001251}
1252
1253//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001254// Main driver
1255//===----------------------------------------------------------------------===//
1256
Ted Kremenekdb094a22007-12-05 18:27:04 +00001257/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1258/// action. These consumers can operate on both ASTs that are freshly
1259/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001260static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001261 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001262 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001263 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001264 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001265 switch (ProgAction) {
1266 default:
1267 return NULL;
1268
1269 case ASTPrint:
1270 return CreateASTPrinter();
1271
1272 case ASTDump:
1273 return CreateASTDumper();
1274
1275 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001276 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001277
1278 case PrintDeclContext:
1279 return CreateDeclContextPrinter();
Ted Kremenek6a340832008-03-18 21:19:49 +00001280
1281 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001282 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001283
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001284 case InheritanceView:
1285 return CreateInheritanceViewer(InheritanceViewCls);
1286
Ted Kremenekdb094a22007-12-05 18:27:04 +00001287 case TestSerialization:
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001288 return CreateSerializationTest(Diag, FileMgr);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001289
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001290 case EmitAssembly:
Ted Kremenekdb094a22007-12-05 18:27:04 +00001291 case EmitLLVM:
Daniel Dunbar70f92432008-10-23 05:50:47 +00001292 case EmitBC: {
1293 BackendAction Act;
1294 if (ProgAction == EmitAssembly) {
1295 Act = Backend_EmitAssembly;
1296 } else if (ProgAction == EmitLLVM) {
1297 Act = Backend_EmitLL;
1298 } else {
1299 Act = Backend_EmitBC;
1300 }
1301 CompileOptions Opts;
1302 InitializeCompileOptions(Opts);
1303 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001304 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbar70f92432008-10-23 05:50:47 +00001305 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001306
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001307 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001308 // FIXME: Allow user to tailor where the file is written.
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001309 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001310
Steve Naroffb29b4272008-04-14 22:03:09 +00001311 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001312 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001313
1314 case RewriteBlocks:
1315 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001316
1317 case RunAnalysis:
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001318 return CreateAnalysisConsumer(&AnalysisList[0],
1319 &AnalysisList[0]+AnalysisList.size(),
Ted Kremenek4fc82c82008-11-03 23:18:07 +00001320 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001321 Diag, PP, PPF, LangOpts,
1322 AnalyzeSpecificFunction,
Ted Kremenekf8ce6992008-08-27 22:31:43 +00001323 OutputFile, VisualizeEGDot, VisualizeEGUbi,
Ted Kremenek491918e2009-01-23 20:52:26 +00001324 TrimGraph, AnalyzeAll,
1325 AnalyzerDisplayProgress);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001326 }
1327}
1328
Reid Spencer5f016e22007-07-11 17:01:13 +00001329/// ProcessInputFile - Process a single input file with the specified state.
1330///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001331static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001332 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001333 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001334 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001335
Ted Kremenek85888962008-10-21 00:54:44 +00001336 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001338 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1339 PP.getFileManager(), PP.getLangOptions(),
1340 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001341
1342 if (!Consumer) {
1343 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001344 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001345 return;
1346 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001347
Ted Kremenekdb094a22007-12-05 18:27:04 +00001348 break;
1349
Chris Lattnerc106c102008-10-12 05:03:36 +00001350 case DumpRawTokens: {
1351 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001352 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001353 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001354 RawLex.SetKeepWhitespaceMode(true);
1355
1356 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001357 RawLex.LexFromRawLexer(RawTok);
1358 while (RawTok.isNot(tok::eof)) {
1359 PP.DumpToken(RawTok, true);
1360 fprintf(stderr, "\n");
1361 RawLex.LexFromRawLexer(RawTok);
1362 }
1363 ClearSourceMgr = true;
1364 break;
1365 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001367 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001368 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001369 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 do {
1371 PP.Lex(Tok);
1372 PP.DumpToken(Tok, true);
1373 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001374 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001375 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 break;
1377 }
1378 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001379 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001381 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 do {
1383 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001384 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001385 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 break;
1387 }
Ted Kremenek85888962008-10-21 00:54:44 +00001388
1389 case GeneratePCH: {
1390 CacheTokens(PP, OutputFile);
1391 ClearSourceMgr = true;
1392 break;
1393 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001394
1395 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001396 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001397 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 case ParseNoop: // -parse-noop
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001401 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001402 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 break;
1404
1405 case ParsePrintCallbacks:
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001406 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001407 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001409
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001410 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001411 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001412 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001413
1414 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001415 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001416 ClearSourceMgr = true;
1417 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001418
1419 case RewriteTest:
1420 DoRewriteTest(PP, InFile, OutputFile);
1421 ClearSourceMgr = true;
1422 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001423 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001424
1425 if (Consumer) {
1426 TranslationUnit *TU = 0;
1427 if (DisableFree) {
1428 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1429 PP.getSourceManager(),
1430 PP.getTargetInfo(),
1431 PP.getIdentifierTable(),
1432 PP.getSelectorTable(),
1433 /* FreeMemory = */ false);
1434 TU = new TranslationUnit(*Context);
1435 }
1436 ParseAST(PP, Consumer.get(), TU, Stats);
1437 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001438
1439 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001440 if (CheckDiagnostics(PP))
1441 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001442
Reid Spencer5f016e22007-07-11 17:01:13 +00001443 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001444 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 PP.PrintStats();
1446 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001447 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001448 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 fprintf(stderr, "\n");
1450 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001451
1452 // For a multi-file compilation, some things are ok with nuking the source
1453 // manager tables, other require stable fileid/macroid's across multiple
1454 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001455 if (ClearSourceMgr)
1456 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001457
1458 if (DisableFree)
1459 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001460}
1461
Ted Kremenek20e97482007-12-12 23:41:08 +00001462static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1463 FileManager& FileMgr) {
1464
1465 if (VerifyDiagnostics) {
1466 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1467 exit (1);
1468 }
1469
1470 llvm::sys::Path Filename(InFile);
1471
1472 if (!Filename.isValid()) {
1473 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1474 exit (1);
1475 }
1476
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001477 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001478
1479 if (!TU) {
1480 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1481 InFile.c_str());
1482 exit (1);
1483 }
1484
Ted Kremenek63ea8632007-12-19 19:27:38 +00001485 // Observe that we use the source file name stored in the deserialized
1486 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001487 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001488 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001489 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001490
Ted Kremenek20e97482007-12-12 23:41:08 +00001491 if (!Consumer) {
1492 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1493 exit (1);
1494 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001495
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001496 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001497
Chris Lattnere66b65c2008-02-06 01:42:25 +00001498 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001499 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1500 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001501}
1502
1503
Reid Spencer5f016e22007-07-11 17:01:13 +00001504static llvm::cl::list<std::string>
1505InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1506
Ted Kremenek20e97482007-12-12 23:41:08 +00001507static bool isSerializedFile(const std::string& InFile) {
1508 if (InFile.size() < 4)
1509 return false;
1510
1511 const char* s = InFile.c_str()+InFile.size()-4;
1512
1513 return s[0] == '.' &&
1514 s[1] == 'a' &&
1515 s[2] == 's' &&
1516 s[3] == 't';
1517}
1518
Reid Spencer5f016e22007-07-11 17:01:13 +00001519
1520int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001521 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 llvm::sys::PrintStackTraceOnErrorSignal();
1523
1524 // If no input was specified, read from stdin.
1525 if (InputFilenames.empty())
1526 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001527
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // Create a file manager object to provide access to and cache the filesystem.
1529 FileManager FileMgr;
1530
Ted Kremenek31e703b2007-12-11 23:28:38 +00001531 // Create the diagnostic client for reporting errors or for
1532 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001533 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001534
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001535 if (!VerifyDiagnostics) {
1536 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001537 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1538 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00001539 !NoCaretDiagnostics,
1540 !NoShowLocation);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001541 } else {
1542 // When checking diagnostics, just buffer them up.
1543 TextDiagClient = new TextDiagnosticBuffer();
1544
1545 if (InputFilenames.size() != 1) {
1546 fprintf(stderr,
1547 "-verify only works on single input files for now.\n");
1548 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 }
1550 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001553 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1554 Diagnostic Diags(DiagClient.get());
Ted Kremenek31e703b2007-12-11 23:28:38 +00001555 InitializeDiagnostics(Diags);
1556
Chris Lattner4f037832007-12-05 23:24:17 +00001557 // -I- is a deprecated GCC feature, scan for it and reject it.
1558 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1559 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001560 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001561 I_dirs.erase(I_dirs.begin()+i);
1562 --i;
1563 }
1564 }
Chris Lattner11215192008-03-14 06:12:05 +00001565
1566 // Get information about the target being compiled for.
1567 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001568 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1569
Chris Lattner11215192008-03-14 06:12:05 +00001570 if (Target == 0) {
1571 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1572 Triple.c_str());
1573 fprintf(stderr, "Please use -triple or -arch.\n");
1574 exit(1);
1575 }
Chris Lattner4f037832007-12-05 23:24:17 +00001576
Daniel Dunbard4270232009-01-20 23:17:32 +00001577 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001578 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001579
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001580 llvm::OwningPtr<SourceManager> SourceMgr;
1581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001583 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001584
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001585 if (isSerializedFile(InFile)) {
1586 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001587 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001588 }
Ted Kremenek20e97482007-12-12 23:41:08 +00001589 else {
1590 /// Create a SourceManager object. This tracks and owns all the file
1591 /// buffers allocated to a translation unit.
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001592 if (!SourceMgr)
1593 SourceMgr.reset(new SourceManager());
1594 else
1595 SourceMgr->clearIDTables();
Ted Kremenek31e703b2007-12-11 23:28:38 +00001596
Ted Kremenek20e97482007-12-12 23:41:08 +00001597 // Initialize language options, inferring file types from input filenames.
1598 LangOptions LangInfo;
1599 InitializeBaseLanguage();
1600 LangKind LK = GetLanguage(InFile);
Ted Kremenek85888962008-10-21 00:54:44 +00001601 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001602 InitializeGCMode(LangInfo);
Chris Lattner8fc4dfb2008-12-04 22:54:33 +00001603 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek85888962008-10-21 00:54:44 +00001604
Ted Kremenek20e97482007-12-12 23:41:08 +00001605 // Process the -I options and set them in the HeaderInfo.
1606 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekc68ecb52008-06-06 01:47:30 +00001607
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001608 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001609
Ted Kremenek20e97482007-12-12 23:41:08 +00001610 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001611 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001612 *SourceMgr.get(), HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001613
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001614 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1615
Ted Kremenek339b9c22008-04-17 22:31:54 +00001616 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001617 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001618
1619 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1620 // always reset to using TextDiagClient.
1621 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001622
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001623 if (!HTMLDiag.empty()) {
1624 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1625 &PPFactory));
1626 Diags.setClient(TmpClient.get());
1627 }
1628 else
1629 Diags.setClient(TextDiagClient);
1630
1631 // Process the source file.
Ted Kremenek85888962008-10-21 00:54:44 +00001632 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1633
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001634 HeaderInfo.ClearFileInfo();
Ted Kremenek20e97482007-12-12 23:41:08 +00001635 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 }
Chris Lattner11215192008-03-14 06:12:05 +00001637
Mike Stump007f2a92009-01-28 02:43:35 +00001638 if (Verbose)
1639 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1640 " hosted on " LLVM_HOSTTRIPLE "\n");
1641
Ted Kremenek7a08e282008-08-07 18:13:12 +00001642 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1644 (NumDiagnostics == 1 ? "" : "s"));
1645
1646 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 FileMgr.PrintStats();
1648 fprintf(stderr, "\n");
1649 }
1650
Daniel Dunbar276373d2008-10-27 22:10:13 +00001651 // If verifying diagnostics and we reached here, all is well.
1652 if (VerifyDiagnostics)
1653 return 0;
1654
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001655 // Managed static deconstruction. Useful for making things like
1656 // -time-passes usable.
1657 llvm::llvm_shutdown();
1658
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001659 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001660}