blob: 3cf654f458b9ccd4a18645bb82e7b533b2e663bc [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"
Zhongxing Xu81488392008-08-24 02:33:36 +000028#include "clang/Driver/HTMLDiagnostics.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"
Daniel Dunbare553a722008-10-02 01:21:33 +000050#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000051#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000053using namespace clang;
54
55//===----------------------------------------------------------------------===//
56// Global options.
57//===----------------------------------------------------------------------===//
58
Daniel Dunbard3db4012008-10-16 16:54:18 +000059static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000060
Reid Spencer5f016e22007-07-11 17:01:13 +000061static llvm::cl::opt<bool>
62Verbose("v", llvm::cl::desc("Enable verbose output"));
63static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000064Stats("print-stats",
65 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000066static llvm::cl::opt<bool>
67DisableFree("disable-free",
68 llvm::cl::desc("Disable freeing of memory on exit"),
69 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000070
71enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000072 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000073 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000074 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000075 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000076 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000077 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000078 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000079 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000080 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000081 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000082 ASTPrint, // Parse ASTs and print them.
83 ASTDump, // Parse ASTs and dump them.
84 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000085 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000086 ParsePrintCallbacks, // Parse and print each callback.
87 ParseSyntaxOnly, // Parse and perform semantic analysis.
88 ParseNoop, // Parse with noop callbacks.
89 RunPreprocessorOnly, // Just lex, no output.
90 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +000091 DumpTokens, // Dump out preprocessed tokens.
92 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +000093 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +000094 GeneratePCH, // Generate precompiled header.
95 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +000096};
97
98static llvm::cl::opt<ProgActions>
99ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
100 llvm::cl::init(ParseSyntaxOnly),
101 llvm::cl::values(
102 clEnumValN(RunPreprocessorOnly, "Eonly",
103 "Just run preprocessor, no output (for timings)"),
104 clEnumValN(PrintPreprocessedInput, "E",
105 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000106 clEnumValN(DumpRawTokens, "dump-raw-tokens",
107 "Lex file in raw mode and dump raw tokens"),
108 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 "Run preprocessor, dump internal rep of tokens"),
110 clEnumValN(ParseNoop, "parse-noop",
111 "Run parser with noop callbacks (for timings)"),
112 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
113 "Run parser and perform semantic analysis"),
114 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
115 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000116 clEnumValN(EmitHTML, "emit-html",
117 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000118 clEnumValN(ASTPrint, "ast-print",
119 "Build ASTs and then pretty-print them"),
120 clEnumValN(ASTDump, "ast-dump",
121 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000122 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000123 "Build ASTs and view them with GraphViz"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000124 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000125 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000126 clEnumValN(EmitAssembly, "S",
127 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000129 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000130 clEnumValN(EmitBC, "emit-llvm-bc",
131 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000132 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000133 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000134 clEnumValN(RewriteTest, "rewrite-test",
135 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000136 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000137 "Rewrite ObjC into C (code rewriter example)"),
138 clEnumValN(RewriteMacros, "rewrite-macros",
139 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000140 clEnumValN(RewriteBlocks, "rewrite-blocks",
141 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 clEnumValEnd));
143
Ted Kremenekccc76472007-12-19 19:47:59 +0000144
145static llvm::cl::opt<std::string>
146OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000147 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000148 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000149
150//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000151// Code Generator Options
152//===----------------------------------------------------------------------===//
153static llvm::cl::opt<bool>
154GenerateDebugInfo("g",
155 llvm::cl::desc("Generate source level debug information"));
156
157//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000158// Diagnostic Options
159//===----------------------------------------------------------------------===//
160
Ted Kremenek41193e42007-09-26 19:42:19 +0000161static llvm::cl::opt<bool>
162VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000163 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000164
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000165static llvm::cl::opt<std::string>
166HTMLDiag("html-diags",
167 llvm::cl::desc("Generate HTML to report diagnostics"),
168 llvm::cl::value_desc("HTML directory"));
169
Nico Weberfd54ebc2008-08-05 23:33:20 +0000170static llvm::cl::opt<bool>
171NoShowColumn("fno-show-column",
172 llvm::cl::desc("Do not include column number on diagnostics"));
173
174static llvm::cl::opt<bool>
175NoCaretDiagnostics("fno-caret-diagnostics",
176 llvm::cl::desc("Do not include source line and caret with"
177 " diagnostics"));
178
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000181// C++ Visualization.
182//===----------------------------------------------------------------------===//
183
184static llvm::cl::opt<std::string>
185InheritanceViewCls("cxx-inheritance-view",
186 llvm::cl::value_desc("class name"),
187 llvm::cl::desc("View C++ inhertance for a specified class"));
188
189//===----------------------------------------------------------------------===//
190// Analyzer Options.
Ted Kremenek55af98c2008-04-14 18:40:58 +0000191//===----------------------------------------------------------------------===//
192
193static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000194VisualizeEGDot("analyzer-viz-egraph-graphviz",
195 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000196
197static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000198VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
199 llvm::cl::desc("Display exploded graph using Ubigraph"));
200
201static llvm::cl::opt<bool>
202AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek55af98c2008-04-14 18:40:58 +0000203 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000204 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000205
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000206static llvm::cl::list<Analyses>
Ted Kremenek95c7b002008-10-24 01:04:59 +0000207AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000208llvm::cl::values(
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000209#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000210clEnumValN(NAME, CMDFLAG, DESC),
211#include "Analyses.def"
212clEnumValEnd));
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000213
Ted Kremenek95c7b002008-10-24 01:04:59 +0000214static llvm::cl::opt<AnalysisStores>
215AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
216 llvm::cl::init(BasicStoreModel),
217 llvm::cl::values(
218#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
219clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
220#include "Analyses.def"
221clEnumValEnd));
222
Ted Kremenek55af98c2008-04-14 18:40:58 +0000223//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000224// Language Options
225//===----------------------------------------------------------------------===//
226
227enum LangKind {
228 langkind_unspecified,
229 langkind_c,
230 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000231 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000232 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 langkind_cxx,
234 langkind_cxx_cpp,
235 langkind_objc,
236 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000237 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 langkind_objcxx,
239 langkind_objcxx_cpp
240};
241
242/* TODO: GCC also accepts:
243 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera778d7d2008-10-22 17:29:21 +0000244 assembler
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 ada, f77*, ratfor (!), f95, java, treelang
246 */
247static llvm::cl::opt<LangKind>
248BaseLang("x", llvm::cl::desc("Base language to compile"),
249 llvm::cl::init(langkind_unspecified),
250 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
251 clEnumValN(langkind_cxx, "c++", "C++"),
252 clEnumValN(langkind_objc, "objective-c", "Objective C"),
253 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
254 clEnumValN(langkind_c_cpp, "c-cpp-output",
255 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000256 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
257 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek85888962008-10-21 00:54:44 +0000259 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
261 "Preprocessed Objective C"),
262 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
263 "Preprocessed Objective C++"),
Ted Kremenek85888962008-10-21 00:54:44 +0000264 clEnumValN(langkind_c_pch,"c-header",
265 "Precompiled C header"),
266 clEnumValN(langkind_objc_pch, "objective-c-header",
267 "Precompiled Objective C header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 clEnumValEnd));
269
270static llvm::cl::opt<bool>
271LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
272 llvm::cl::Hidden);
273static llvm::cl::opt<bool>
274LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
275 llvm::cl::Hidden);
276
Ted Kremenek8904f152007-12-05 23:49:08 +0000277/// InitializeBaseLanguage - Handle the -x foo options.
278static void InitializeBaseLanguage() {
279 if (LangObjC)
280 BaseLang = langkind_objc;
281 else if (LangObjCXX)
282 BaseLang = langkind_objcxx;
283}
284
285static LangKind GetLanguage(const std::string &Filename) {
286 if (BaseLang != langkind_unspecified)
287 return BaseLang;
288
289 std::string::size_type DotPos = Filename.rfind('.');
290
291 if (DotPos == std::string::npos) {
292 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000293 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 }
295
Ted Kremenek8904f152007-12-05 23:49:08 +0000296 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
297 // C header: .h
298 // C++ header: .hh or .H;
299 // assembler no preprocessing: .s
300 // assembler: .S
301 if (Ext == "c")
302 return langkind_c;
Chris Lattner1b450b02008-10-28 20:33:42 +0000303 else if (Ext == "S")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000304 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000305 else if (Ext == "i")
306 return langkind_c_cpp;
307 else if (Ext == "ii")
308 return langkind_cxx_cpp;
309 else if (Ext == "m")
310 return langkind_objc;
311 else if (Ext == "mi")
312 return langkind_objc_cpp;
313 else if (Ext == "mm" || Ext == "M")
314 return langkind_objcxx;
315 else if (Ext == "mii")
316 return langkind_objcxx_cpp;
317 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
318 Ext == "c++" || Ext == "cp" || Ext == "cxx")
319 return langkind_cxx;
320 else
321 return langkind_c;
322}
323
324
Ted Kremenek85888962008-10-21 00:54:44 +0000325static void InitializeCOptions(LangOptions &Options) {
326 // Do nothing.
327}
328
329static void InitializeObjCOptions(LangOptions &Options) {
330 Options.ObjC1 = Options.ObjC2 = 1;
331}
332
333
334static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 // FIXME: implement -fpreprocessed mode.
336 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000337 bool PCH = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
Ted Kremenek8904f152007-12-05 23:49:08 +0000339 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 default: assert(0 && "Unknown language kind!");
Ted Kremenek85888962008-10-21 00:54:44 +0000341 case langkind_c_pch:
342 InitializeCOptions(Options);
343 PCH = true;
344 break;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000345 case langkind_asm_cpp:
346 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 case langkind_c_cpp:
348 NoPreprocess = true;
349 // FALLTHROUGH
350 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000351 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 break;
353 case langkind_cxx_cpp:
354 NoPreprocess = true;
355 // FALLTHROUGH
356 case langkind_cxx:
357 Options.CPlusPlus = 1;
358 break;
Ted Kremenek85888962008-10-21 00:54:44 +0000359 case langkind_objc_pch:
360 InitializeObjCOptions(Options);
361 PCH = true;
362 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 case langkind_objc_cpp:
364 NoPreprocess = true;
365 // FALLTHROUGH
366 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000367 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 break;
369 case langkind_objcxx_cpp:
370 NoPreprocess = true;
371 // FALLTHROUGH
372 case langkind_objcxx:
373 Options.ObjC1 = Options.ObjC2 = 1;
374 Options.CPlusPlus = 1;
375 break;
376 }
Ted Kremenek85888962008-10-21 00:54:44 +0000377
378 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000379}
380
381/// LangStds - Language standards we support.
382enum LangStds {
383 lang_unspecified,
384 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000385 lang_gnu_START,
386 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000387 lang_cxx98, lang_gnucxx98,
388 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000389};
390
391static llvm::cl::opt<LangStds>
392LangStd("std", llvm::cl::desc("Language standard to compile for"),
393 llvm::cl::init(lang_unspecified),
394 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
395 clEnumValN(lang_c89, "c90", "ISO C 1990"),
396 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
397 clEnumValN(lang_c94, "iso9899:199409",
398 "ISO C 1990 with amendment 1"),
399 clEnumValN(lang_c99, "c99", "ISO C 1999"),
400// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
401 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
402// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
403 clEnumValN(lang_gnu89, "gnu89",
404 "ISO C 1990 with GNU extensions (default for C)"),
405 clEnumValN(lang_gnu99, "gnu99",
406 "ISO C 1999 with GNU extensions"),
407 clEnumValN(lang_gnu99, "gnu9x",
408 "ISO C 1999 with GNU extensions"),
409 clEnumValN(lang_cxx98, "c++98",
410 "ISO C++ 1998 with amendments"),
411 clEnumValN(lang_gnucxx98, "gnu++98",
412 "ISO C++ 1998 with amendments and GNU "
413 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000414 clEnumValN(lang_cxx0x, "c++0x",
415 "Upcoming ISO C++ 200x with amendments"),
416 clEnumValN(lang_gnucxx0x, "gnu++0x",
417 "Upcoming ISO C++ 200x with amendments and GNU "
418 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 clEnumValEnd));
420
421static llvm::cl::opt<bool>
422NoOperatorNames("fno-operator-names",
423 llvm::cl::desc("Do not treat C++ operator name keywords as "
424 "synonyms for operators"));
425
Anders Carlssonee98ac52007-10-15 02:50:23 +0000426static llvm::cl::opt<bool>
427PascalStrings("fpascal-strings",
428 llvm::cl::desc("Recognize and construct Pascal-style "
429 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000430
431static llvm::cl::opt<bool>
432MSExtensions("fms-extensions",
433 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000434 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000435
436static llvm::cl::opt<bool>
437WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000438 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000439
440static llvm::cl::opt<bool>
441LaxVectorConversions("flax-vector-conversions",
442 llvm::cl::desc("Allow implicit conversions between vectors"
443 " with a different number of elements or "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000444 "different element types"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000445
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000446// FIXME: This (and all GCC -f options) really come in -f... and
447// -fno-... forms, and additionally support automagic behavior when
448// they are not defined. For example, -fexceptions defaults to on or
449// off depending on the language. We should support this behavior in
450// some form (perhaps just add a facility for distinguishing when an
451// has its default value from when it has been set to its default
452// value).
453static llvm::cl::opt<bool>
454Exceptions("fexceptions",
455 llvm::cl::desc("Enable support for exception handling."));
456
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000457static llvm::cl::opt<bool>
458GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000459 llvm::cl::desc("Generate output compatible with the standard GNU "
460 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000461
462static llvm::cl::opt<bool>
463NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000464 llvm::cl::desc("Generate output compatible with the NeXT "
465 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000466
Ted Kremenekea644d82008-09-03 21:22:16 +0000467
468
469static llvm::cl::opt<bool>
470Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
471
472static llvm::cl::opt<bool>
473Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
474
Reid Spencer5f016e22007-07-11 17:01:13 +0000475// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000476// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000477// -fpascal-strings
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000478static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
479 TargetInfo *Target) {
Ted Kremenekea644d82008-09-03 21:22:16 +0000480
481 if (Ansi) // "The -ansi option is equivalent to -std=c89."
482 LangStd = lang_c89;
483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 if (LangStd == lang_unspecified) {
485 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000486 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 default: assert(0 && "Unknown base language");
488 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000489 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000491 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 case langkind_objc:
493 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000494 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 LangStd = lang_gnu99;
496 break;
497 case langkind_cxx:
498 case langkind_cxx_cpp:
499 case langkind_objcxx:
500 case langkind_objcxx_cpp:
501 LangStd = lang_gnucxx98;
502 break;
503 }
504 }
505
506 switch (LangStd) {
507 default: assert(0 && "Unknown language standard!");
508
509 // Fall through from newer standards to older ones. This isn't really right.
510 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000511 case lang_gnucxx0x:
512 case lang_cxx0x:
513 Options.CPlusPlus0x = 1;
514 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 case lang_gnucxx98:
516 case lang_cxx98:
517 Options.CPlusPlus = 1;
518 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000519 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 // FALL THROUGH.
521 case lang_gnu99:
522 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 Options.C99 = 1;
524 Options.HexFloats = 1;
525 // FALL THROUGH.
526 case lang_gnu89:
527 Options.BCPLComment = 1; // Only for C99/C++.
528 // FALL THROUGH.
529 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000530 Options.Digraphs = 1; // C94, C99, C++.
531 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 case lang_c89:
533 break;
534 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000535
536 if (Options.CPlusPlus) {
537 Options.C99 = 0;
538 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
539 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000540
Chris Lattnerd658b562008-04-05 06:32:51 +0000541 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
542 Options.ImplicitInt = 1;
543 else
544 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000545
546 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
547 // is specified, or -std is set to a conforming mode.
548 Options.Trigraphs = LangStd < lang_gnu_START || Trigraphs ? 1 : 0;
549
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000551 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000552 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000553 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000554 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000555 Options.Exceptions = Exceptions;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000556
557 if (NeXTRuntime) {
558 Options.NeXTRuntime = 1;
559 } else if (GNURuntime) {
560 Options.NeXTRuntime = 0;
561 } else {
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000562 Options.NeXTRuntime = Target->useNeXTRuntimeAsDefault();
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000563 }
Daniel Dunbar0b0ee502008-10-10 00:20:52 +0000564
565 if (Options.CPlusPlus)
566 Options.Blocks = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000567}
568
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000569static llvm::cl::opt<bool>
570ObjCExclusiveGC("fobjc-gc-only",
571 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000572 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000573
574static llvm::cl::opt<bool>
575ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000576 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000577
578void InitializeGCMode(LangOptions &Options) {
579 if (ObjCExclusiveGC)
580 Options.setGCMode(LangOptions::GCOnly);
581 else if (ObjCEnableGC)
582 Options.setGCMode(LangOptions::HybridGC);
583}
584
585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586//===----------------------------------------------------------------------===//
587// Our DiagnosticClient implementation
588//===----------------------------------------------------------------------===//
589
590// FIXME: Werror should take a list of things, -Werror=foo,bar
591static llvm::cl::opt<bool>
592WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
593
594static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000595SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
596
597static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000598WarnOnExtensions("pedantic", llvm::cl::init(false),
599 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
600
601static llvm::cl::opt<bool>
602ErrorOnExtensions("pedantic-errors",
603 llvm::cl::desc("Issue an error on uses of GCC extensions"));
604
605static llvm::cl::opt<bool>
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000606SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar320a0542008-09-30 20:49:53 +0000607 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000608 llvm::cl::init(true));
609
610static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000611WarnUnusedMacros("Wunused_macros",
612 llvm::cl::desc("Warn for unused macros in the main translation unit"));
613
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000614static llvm::cl::opt<bool>
615WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000616 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000617
Ted Kremenek73da5902007-12-17 17:50:07 +0000618static llvm::cl::opt<bool>
619WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000620 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000621
Chris Lattner116a4b12008-01-23 17:19:46 +0000622static llvm::cl::opt<bool>
623WarnUndefMacros("Wundef",
624 llvm::cl::desc("Warn on use of undefined macros in #if's"));
625
Chris Lattner37d10842008-05-05 21:18:06 +0000626static llvm::cl::opt<bool>
Ted Kremenek358256d2008-05-30 16:42:02 +0000627WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
628 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattner116a4b12008-01-23 17:19:46 +0000629
Steve Narofffe6b0dc2008-10-21 10:37:50 +0000630static llvm::cl::opt<bool>
631WarnNoStrictSelectorMatch("Wno-strict-selector-match",
632 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
633 llvm::cl::init(true));
634
Reid Spencer5f016e22007-07-11 17:01:13 +0000635/// InitializeDiagnostics - Initialize the diagnostic object, based on the
636/// current command line option settings.
637static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000638 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 Diags.setWarningsAsErrors(WarningsAsErrors);
640 Diags.setWarnOnExtensions(WarnOnExtensions);
641 Diags.setErrorOnExtensions(ErrorOnExtensions);
642
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000643 // Suppress warnings in system headers unless requested not to.
644 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
645
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 // Silence the "macro is not used" warning unless requested.
647 if (!WarnUnusedMacros)
648 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000649
650 // Silence "floating point comparison" warnings unless requested.
651 if (!WarnFloatEqual)
652 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000653
654 // Silence "format string is not a string literal" warnings if requested
655 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000656 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
657 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000658 if (!WarnUndefMacros)
659 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000660
Chris Lattner37d10842008-05-05 21:18:06 +0000661 if (!WarnImplicitFunctionDeclaration)
662 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
663 diag::MAP_IGNORE);
664
Steve Naroffe7a37302008-02-11 22:40:08 +0000665 if (MSExtensions) // MS allows unnamed struct/union fields.
666 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner8aedf192008-05-04 23:52:02 +0000667
668 // If -pedantic-errors is set, turn extensions that warn by default into
669 // errors.
670 if (ErrorOnExtensions) {
671 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
672 diag::MAP_ERROR);
673 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
674 diag::MAP_ERROR);
675 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000676}
677
678//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000679// Analysis-specific options.
680//===----------------------------------------------------------------------===//
681
682static llvm::cl::opt<std::string>
683AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000684 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000685
Ted Kremenekffe0f432008-03-07 22:58:01 +0000686static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000687TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000688 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000689
Ted Kremenekcb330932008-02-18 21:21:23 +0000690//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000691// Target Triple Processing.
692//===----------------------------------------------------------------------===//
693
694static llvm::cl::opt<std::string>
695TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000696 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000697
Chris Lattner42e67372008-03-05 01:18:20 +0000698static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000699Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000700
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000701static llvm::cl::opt<std::string>
702MacOSVersionMin("mmacosx-version-min",
703 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
704
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000705// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
706// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
707static void HandleMacOSVersionMin(std::string &Triple) {
708 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
709 if (DarwinDashIdx == std::string::npos) {
710 fprintf(stderr,
711 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
712 exit(1);
713 }
714 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
715
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000716 // Remove the number.
717 Triple.resize(DarwinNumIdx);
718
719 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
720 bool MacOSVersionMinIsInvalid = false;
721 int VersionNum = 0;
722 if (MacOSVersionMin.size() < 4 ||
723 MacOSVersionMin.substr(0, 3) != "10." ||
724 !isdigit(MacOSVersionMin[3])) {
725 MacOSVersionMinIsInvalid = true;
726 } else {
727 const char *Start = MacOSVersionMin.c_str()+3;
728 char *End = 0;
729 VersionNum = (int)strtol(Start, &End, 10);
730
Chris Lattner079f2c462008-09-30 20:30:12 +0000731 // The version number must be in the range 0-9.
732 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
733
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000734 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
735 Triple += llvm::itostr(VersionNum+4);
736
Chris Lattner079f2c462008-09-30 20:30:12 +0000737 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
738 // Add the period piece (.7) to the end of the triple. This gives us
739 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000740 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000741 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
742 MacOSVersionMinIsInvalid = true;
743 }
744 }
745
746 if (MacOSVersionMinIsInvalid) {
747 fprintf(stderr,
748 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
749 MacOSVersionMin.c_str());
750 exit(1);
751 }
752}
753
754/// CreateTargetTriple - Process the various options that affect the target
755/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000756static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000757 // Initialize base triple. If a -triple option has been specified, use
758 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000759 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000760 if (Triple.empty()) {
761 Triple = LLVM_HOSTTRIPLE;
762
763 // On darwin, we want to update the version to match that of the
764 // host.
765 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
766 if (DarwinDashIdx != std::string::npos) {
767 Triple.resize(DarwinDashIdx + strlen("-darwin"));
768
769 Triple += llvm::sys::osVersion();
770 }
771 }
Ted Kremenekae360762007-12-03 22:06:55 +0000772
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000773 // If -arch foo was specified, remove the architecture from the triple we have
774 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000775 if (!Arch.empty()) {
776 // Decompose the base triple into "arch" and suffix.
777 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000778
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000779 if (FirstDashIdx == std::string::npos) {
780 fprintf(stderr,
781 "Malformed target triple: \"%s\" ('-' could not be found).\n",
782 Triple.c_str());
783 exit(1);
784 }
Ted Kremenekae360762007-12-03 22:06:55 +0000785
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000786 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
787 }
788
789 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
790 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000791 if (!MacOSVersionMin.empty())
792 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000793
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000794 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000795}
796
797//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000798// Preprocessor Initialization
799//===----------------------------------------------------------------------===//
800
801// FIXME: Preprocessor builtins to support.
802// -A... - Play with #assertions
803// -undef - Undefine all predefined macros
804
805static llvm::cl::list<std::string>
806D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
807 llvm::cl::desc("Predefine the specified macro"));
808static llvm::cl::list<std::string>
809U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
810 llvm::cl::desc("Undefine the specified macro"));
811
Chris Lattner64299f82008-01-10 01:53:41 +0000812static llvm::cl::list<std::string>
813ImplicitIncludes("include", llvm::cl::value_desc("file"),
814 llvm::cl::desc("Include file before parsing"));
815
816
Reid Spencer5f016e22007-07-11 17:01:13 +0000817// Append a #define line to Buf for Macro. Macro should be of the form XXX,
818// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
819// "#define XXX Y z W". To get a #define with no value, use "XXX=".
820static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
821 const char *Command = "#define ") {
822 Buf.insert(Buf.end(), Command, Command+strlen(Command));
823 if (const char *Equal = strchr(Macro, '=')) {
824 // Turn the = into ' '.
825 Buf.insert(Buf.end(), Macro, Equal);
826 Buf.push_back(' ');
827 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
828 } else {
829 // Push "macroname 1".
830 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
831 Buf.push_back(' ');
832 Buf.push_back('1');
833 }
834 Buf.push_back('\n');
835}
836
Chris Lattner64299f82008-01-10 01:53:41 +0000837/// AddImplicitInclude - Add an implicit #include of the specified file to the
838/// predefines buffer.
839static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
840 const char *Inc = "#include \"";
841 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
842 Buf.insert(Buf.end(), File.begin(), File.end());
843 Buf.push_back('"');
844 Buf.push_back('\n');
845}
846
Reid Spencer5f016e22007-07-11 17:01:13 +0000847
Chris Lattner53b0dab2007-10-09 22:10:18 +0000848/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000849/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000850///
Chris Lattner51574ea2008-04-19 23:25:44 +0000851static bool InitializePreprocessor(Preprocessor &PP,
852 bool InitializeSourceMgr,
853 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000854 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000855
Chris Lattner53b0dab2007-10-09 22:10:18 +0000856 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000857 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000858
859 if (InitializeSourceMgr) {
860 if (InFile != "-") {
861 const FileEntry *File = FileMgr.getFile(InFile);
862 if (File) SourceMgr.createMainFileID(File, SourceLocation());
863 if (SourceMgr.getMainFileID() == 0) {
864 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000865 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000866 }
867 } else {
868 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
869 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
870 if (SourceMgr.getMainFileID() == 0) {
871 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000872 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000873 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000874 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000876
Chris Lattneraa391972008-04-19 23:09:31 +0000877 std::vector<char> PredefineBuffer;
878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000880 unsigned d = 0, D = D_macros.size();
881 unsigned u = 0, U = U_macros.size();
882 while (d < D || u < U) {
883 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
884 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
885 else
886 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
887 }
888
Chris Lattner64299f82008-01-10 01:53:41 +0000889 // FIXME: Read any files specified by -imacros.
890
891 // Add implicit #includes from -include.
892 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
893 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000894
Chris Lattneraa391972008-04-19 23:09:31 +0000895 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000896 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000897 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000898
899 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000900 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000901}
902
903//===----------------------------------------------------------------------===//
904// Preprocessor include path information.
905//===----------------------------------------------------------------------===//
906
907// This tool exports a large number of command line options to control how the
908// preprocessor searches for header files. At root, however, the Preprocessor
909// object takes a very simple interface: a list of directories to search for
910//
911// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000912// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000913//
Chris Lattner64299f82008-01-10 01:53:41 +0000914// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000915
916static llvm::cl::opt<bool>
917nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
918
919// Various command line options. These four add directories to each chain.
920static llvm::cl::list<std::string>
921F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
922 llvm::cl::desc("Add directory to framework include search path"));
923static llvm::cl::list<std::string>
924I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
925 llvm::cl::desc("Add directory to include search path"));
926static llvm::cl::list<std::string>
927idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
928 llvm::cl::desc("Add directory to AFTER include search path"));
929static llvm::cl::list<std::string>
930iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
931 llvm::cl::desc("Add directory to QUOTE include search path"));
932static llvm::cl::list<std::string>
933isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
934 llvm::cl::desc("Add directory to SYSTEM include search path"));
935
936// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
937static llvm::cl::list<std::string>
938iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
939 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
940static llvm::cl::list<std::string>
941iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
942 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
943static llvm::cl::list<std::string>
944iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
945 llvm::cl::Prefix,
946 llvm::cl::desc("Set directory to include search path with prefix"));
947
Chris Lattner0c946412007-08-26 17:47:35 +0000948static llvm::cl::opt<std::string>
949isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
950 llvm::cl::desc("Set the system root directory (usually /)"));
951
Reid Spencer5f016e22007-07-11 17:01:13 +0000952// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000953
Reid Spencer5f016e22007-07-11 17:01:13 +0000954/// InitializeIncludePaths - Process the -I options and set them in the
955/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +0000956void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
957 FileManager &FM, const LangOptions &Lang) {
958 InitHeaderSearch Init(Headers, Verbose, isysroot);
959
Ted Kremenekf3721112008-05-31 00:27:00 +0000960 // Handle -I... and -F... options, walking the lists in parallel.
961 unsigned Iidx = 0, Fidx = 0;
962 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
963 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +0000964 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +0000965 ++Iidx;
966 } else {
Nico Weber0fca0222008-08-22 09:25:22 +0000967 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +0000968 ++Fidx;
969 }
970 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000971
Ted Kremenekf3721112008-05-31 00:27:00 +0000972 // Consume what's left from whatever list was longer.
973 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +0000974 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +0000975 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +0000976 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000977
978 // Handle -idirafter... options.
979 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +0000980 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
981 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000982
983 // Handle -iquote... options.
984 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +0000985 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000986
987 // Handle -isystem... options.
988 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +0000989 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000990
991 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
992 // parallel, processing the values in order of occurance to get the right
993 // prefixes.
994 {
995 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
996 unsigned iprefix_idx = 0;
997 unsigned iwithprefix_idx = 0;
998 unsigned iwithprefixbefore_idx = 0;
999 bool iprefix_done = iprefix_vals.empty();
1000 bool iwithprefix_done = iwithprefix_vals.empty();
1001 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1002 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1003 if (!iprefix_done &&
1004 (iwithprefix_done ||
1005 iprefix_vals.getPosition(iprefix_idx) <
1006 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1007 (iwithprefixbefore_done ||
1008 iprefix_vals.getPosition(iprefix_idx) <
1009 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1010 Prefix = iprefix_vals[iprefix_idx];
1011 ++iprefix_idx;
1012 iprefix_done = iprefix_idx == iprefix_vals.size();
1013 } else if (!iwithprefix_done &&
1014 (iwithprefixbefore_done ||
1015 iwithprefix_vals.getPosition(iwithprefix_idx) <
1016 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001017 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1018 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 ++iwithprefix_idx;
1020 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1021 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001022 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1023 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 ++iwithprefixbefore_idx;
1025 iwithprefixbefore_done =
1026 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1027 }
1028 }
1029 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001030
Nico Weber0fca0222008-08-22 09:25:22 +00001031 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001032
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001033 // Add the clang headers, which are relative to the clang driver.
1034 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001035 llvm::sys::Path::GetMainExecutable(Argv0,
1036 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001037 if (!MainExecutablePath.isEmpty()) {
1038 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1039 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1040 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber0fca0222008-08-22 09:25:22 +00001041 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1042 false, false, false);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001043 }
1044
Nico Weber0fca0222008-08-22 09:25:22 +00001045 if (!nostdinc)
1046 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001047
1048 // Now that we have collected all of the include paths, merge them all
1049 // together and tell the preprocessor about them.
1050
Nico Weber0fca0222008-08-22 09:25:22 +00001051 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001052}
1053
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001054//===----------------------------------------------------------------------===//
1055// Driver PreprocessorFactory - For lazily generating preprocessors ...
1056//===----------------------------------------------------------------------===//
1057
1058namespace {
1059class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001060 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001061 Diagnostic &Diags;
1062 const LangOptions &LangInfo;
1063 TargetInfo &Target;
1064 SourceManager &SourceMgr;
1065 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001066 bool InitializeSourceMgr;
1067
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001068public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001069 DriverPreprocessorFactory(const std::string &infile,
1070 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001071 TargetInfo &target, SourceManager &SM,
1072 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001073 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1074 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1075
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001076
1077 virtual ~DriverPreprocessorFactory() {}
1078
1079 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001080 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1081 SourceMgr, HeaderInfo);
1082
Chris Lattner51574ea2008-04-19 23:25:44 +00001083 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001084 delete PP;
1085 return NULL;
1086 }
1087
Daniel Dunbar750c3582008-10-24 22:12:41 +00001088 /// FIXME: PP can only handle one callback
1089 if (ProgAction != PrintPreprocessedInput) {
1090 const char* ErrStr;
1091 bool DFG = CreateDependencyFileGen(PP, OutputFile, InFile, ErrStr);
1092 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001093 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001094 return NULL;
1095 }
1096 }
1097
Ted Kremenek339b9c22008-04-17 22:31:54 +00001098 InitializeSourceMgr = false;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001099 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001100 }
1101};
1102}
Reid Spencer5f016e22007-07-11 17:01:13 +00001103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104//===----------------------------------------------------------------------===//
1105// Basic Parser driver
1106//===----------------------------------------------------------------------===//
1107
Chris Lattner51574ea2008-04-19 23:25:44 +00001108static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001110 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001111
1112 // Parsing the specified input file.
1113 P.ParseTranslationUnit();
1114 delete PA;
1115}
1116
1117//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001118// Code generation options
1119//===----------------------------------------------------------------------===//
1120
1121static llvm::cl::opt<bool>
1122OptSize("Os",
1123 llvm::cl::desc("Optimize for size"));
1124
1125// It might be nice to add bounds to the CommandLine library directly.
1126struct OptLevelParser : public llvm::cl::parser<unsigned> {
1127 bool parse(llvm::cl::Option &O, const char *ArgName,
1128 const std::string &Arg, unsigned &Val) {
1129 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1130 return true;
1131 // FIXME: Support -O4.
1132 if (Val > 3)
1133 return O.error(": '" + Arg + "' invalid optimization level!");
1134 return false;
1135 }
1136};
1137static llvm::cl::opt<unsigned, false, OptLevelParser>
1138OptLevel("O", llvm::cl::Prefix,
1139 llvm::cl::desc("Optimization level"),
1140 llvm::cl::init(0));
1141
1142static void InitializeCompileOptions(CompileOptions &Opts) {
1143 Opts.OptimizationLevel = OptLevel;
1144 Opts.OptimizeSize = OptSize;
1145 // FIXME: Wire other options.
1146}
1147
1148//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001149// Main driver
1150//===----------------------------------------------------------------------===//
1151
Ted Kremenekdb094a22007-12-05 18:27:04 +00001152/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1153/// action. These consumers can operate on both ASTs that are freshly
1154/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001155static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001156 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001157 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001158 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001159 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001160 switch (ProgAction) {
1161 default:
1162 return NULL;
1163
1164 case ASTPrint:
1165 return CreateASTPrinter();
1166
1167 case ASTDump:
1168 return CreateASTDumper();
1169
1170 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001171 return CreateASTViewer();
1172
1173 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001174 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001175
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001176 case InheritanceView:
1177 return CreateInheritanceViewer(InheritanceViewCls);
1178
Ted Kremenekdb094a22007-12-05 18:27:04 +00001179 case TestSerialization:
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001180 return CreateSerializationTest(Diag, FileMgr);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001181
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001182 case EmitAssembly:
Ted Kremenekdb094a22007-12-05 18:27:04 +00001183 case EmitLLVM:
Daniel Dunbar70f92432008-10-23 05:50:47 +00001184 case EmitBC: {
1185 BackendAction Act;
1186 if (ProgAction == EmitAssembly) {
1187 Act = Backend_EmitAssembly;
1188 } else if (ProgAction == EmitLLVM) {
1189 Act = Backend_EmitLL;
1190 } else {
1191 Act = Backend_EmitBC;
1192 }
1193 CompileOptions Opts;
1194 InitializeCompileOptions(Opts);
1195 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001196 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbar70f92432008-10-23 05:50:47 +00001197 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001198
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001199 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001200 // FIXME: Allow user to tailor where the file is written.
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001201 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001202
Steve Naroffb29b4272008-04-14 22:03:09 +00001203 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001204 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001205
1206 case RewriteBlocks:
1207 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001208
1209 case RunAnalysis:
1210 assert (!AnalysisList.empty());
1211 return CreateAnalysisConsumer(&AnalysisList[0],
1212 &AnalysisList[0]+AnalysisList.size(),
Ted Kremenek95c7b002008-10-24 01:04:59 +00001213 AnalysisStoreOpt,
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001214 Diag, PP, PPF, LangOpts,
1215 AnalyzeSpecificFunction,
Ted Kremenekf8ce6992008-08-27 22:31:43 +00001216 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1217 TrimGraph, AnalyzeAll);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001218 }
1219}
1220
Reid Spencer5f016e22007-07-11 17:01:13 +00001221/// ProcessInputFile - Process a single input file with the specified state.
1222///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001223static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001224 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001225 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001226 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001227
Ted Kremenek85888962008-10-21 00:54:44 +00001228 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001230 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1231 PP.getFileManager(), PP.getLangOptions(),
1232 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001233
1234 if (!Consumer) {
1235 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001236 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001237 return;
1238 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001239
Ted Kremenekdb094a22007-12-05 18:27:04 +00001240 break;
1241
Chris Lattnerc106c102008-10-12 05:03:36 +00001242 case DumpRawTokens: {
1243 SourceManager &SM = PP.getSourceManager();
1244 std::pair<const char*,const char*> File =
1245 SM.getBufferData(SM.getMainFileID());
1246 // Start lexing the specified input file.
1247 Lexer RawLex(SourceLocation::getFileLoc(SM.getMainFileID(), 0),
1248 PP.getLangOptions(), File.first, File.second);
1249 RawLex.SetKeepWhitespaceMode(true);
1250
1251 Token RawTok;
1252
1253 RawLex.LexFromRawLexer(RawTok);
1254 while (RawTok.isNot(tok::eof)) {
1255 PP.DumpToken(RawTok, true);
1256 fprintf(stderr, "\n");
1257 RawLex.LexFromRawLexer(RawTok);
1258 }
1259 ClearSourceMgr = true;
1260 break;
1261 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001263 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001264 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001265 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 do {
1267 PP.Lex(Tok);
1268 PP.DumpToken(Tok, true);
1269 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001270 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001271 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 break;
1273 }
1274 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001275 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001277 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 do {
1279 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001280 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001281 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 break;
1283 }
Ted Kremenek85888962008-10-21 00:54:44 +00001284
1285 case GeneratePCH: {
1286 CacheTokens(PP, OutputFile);
1287 ClearSourceMgr = true;
1288 break;
1289 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001290
1291 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001292 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001293 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001295
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001297 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001298 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 break;
1300
1301 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001302 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001303 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001305
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001306 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001307 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001308 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001309
1310 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001311 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001312 ClearSourceMgr = true;
1313 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001314
1315 case RewriteTest:
1316 DoRewriteTest(PP, InFile, OutputFile);
1317 ClearSourceMgr = true;
1318 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001319 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001320
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001321 if (Consumer)
Daniel Dunbard3db4012008-10-16 16:54:18 +00001322 ParseAST(PP, Consumer.get(), Stats, !DisableFree);
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001323
1324 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001325 if (CheckDiagnostics(PP))
1326 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001327
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001329 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 PP.PrintStats();
1331 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001332 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001333 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001334 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 fprintf(stderr, "\n");
1336 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001337
1338 // For a multi-file compilation, some things are ok with nuking the source
1339 // manager tables, other require stable fileid/macroid's across multiple
1340 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001341 if (ClearSourceMgr)
1342 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001343}
1344
Ted Kremenek20e97482007-12-12 23:41:08 +00001345static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1346 FileManager& FileMgr) {
1347
1348 if (VerifyDiagnostics) {
1349 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1350 exit (1);
1351 }
1352
1353 llvm::sys::Path Filename(InFile);
1354
1355 if (!Filename.isValid()) {
1356 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1357 exit (1);
1358 }
1359
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001360 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001361
1362 if (!TU) {
1363 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1364 InFile.c_str());
1365 exit (1);
1366 }
1367
Ted Kremenek63ea8632007-12-19 19:27:38 +00001368 // Observe that we use the source file name stored in the deserialized
1369 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001370 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001371 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001372 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001373
Ted Kremenek20e97482007-12-12 23:41:08 +00001374 if (!Consumer) {
1375 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1376 exit (1);
1377 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001378
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001379 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001380
Chris Lattnere66b65c2008-02-06 01:42:25 +00001381 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001382 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1383 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001384}
1385
1386
Reid Spencer5f016e22007-07-11 17:01:13 +00001387static llvm::cl::list<std::string>
1388InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1389
Ted Kremenek20e97482007-12-12 23:41:08 +00001390static bool isSerializedFile(const std::string& InFile) {
1391 if (InFile.size() < 4)
1392 return false;
1393
1394 const char* s = InFile.c_str()+InFile.size()-4;
1395
1396 return s[0] == '.' &&
1397 s[1] == 'a' &&
1398 s[2] == 's' &&
1399 s[3] == 't';
1400}
1401
Reid Spencer5f016e22007-07-11 17:01:13 +00001402
1403int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001404 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 llvm::sys::PrintStackTraceOnErrorSignal();
1406
1407 // If no input was specified, read from stdin.
1408 if (InputFilenames.empty())
1409 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001410
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 // Create a file manager object to provide access to and cache the filesystem.
1412 FileManager FileMgr;
1413
Ted Kremenek31e703b2007-12-11 23:28:38 +00001414 // Create the diagnostic client for reporting errors or for
1415 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001416 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001417
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001418 if (!VerifyDiagnostics) {
1419 // Print diagnostics to stderr by default.
1420 TextDiagClient = new TextDiagnosticPrinter(!NoShowColumn,
1421 !NoCaretDiagnostics);
1422 } else {
1423 // When checking diagnostics, just buffer them up.
1424 TextDiagClient = new TextDiagnosticBuffer();
1425
1426 if (InputFilenames.size() != 1) {
1427 fprintf(stderr,
1428 "-verify only works on single input files for now.\n");
1429 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 }
1431 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001432
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001434 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1435 Diagnostic Diags(DiagClient.get());
Ted Kremenek31e703b2007-12-11 23:28:38 +00001436 InitializeDiagnostics(Diags);
1437
Chris Lattner4f037832007-12-05 23:24:17 +00001438 // -I- is a deprecated GCC feature, scan for it and reject it.
1439 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1440 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001441 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001442 I_dirs.erase(I_dirs.begin()+i);
1443 --i;
1444 }
1445 }
Chris Lattner11215192008-03-14 06:12:05 +00001446
1447 // Get information about the target being compiled for.
1448 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001449 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1450
Chris Lattner11215192008-03-14 06:12:05 +00001451 if (Target == 0) {
1452 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1453 Triple.c_str());
1454 fprintf(stderr, "Please use -triple or -arch.\n");
1455 exit(1);
1456 }
Chris Lattner4f037832007-12-05 23:24:17 +00001457
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001458 // Are we invoking one or more source analyses?
1459 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1460 ProgAction = RunAnalysis;
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001461 else if (!InheritanceViewCls.empty()) // C++ visualization?
1462 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001463
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001464 llvm::OwningPtr<SourceManager> SourceMgr;
1465
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001467 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001468
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001469 if (isSerializedFile(InFile)) {
1470 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001471 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001472 }
Ted Kremenek20e97482007-12-12 23:41:08 +00001473 else {
1474 /// Create a SourceManager object. This tracks and owns all the file
1475 /// buffers allocated to a translation unit.
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001476 if (!SourceMgr)
1477 SourceMgr.reset(new SourceManager());
1478 else
1479 SourceMgr->clearIDTables();
Ted Kremenek31e703b2007-12-11 23:28:38 +00001480
Ted Kremenek20e97482007-12-12 23:41:08 +00001481 // Initialize language options, inferring file types from input filenames.
1482 LangOptions LangInfo;
1483 InitializeBaseLanguage();
1484 LangKind LK = GetLanguage(InFile);
Ted Kremenek85888962008-10-21 00:54:44 +00001485 bool PCH = InitializeLangOptions(LangInfo, LK);
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +00001486 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001487 InitializeGCMode(LangInfo);
Ted Kremenek85888962008-10-21 00:54:44 +00001488
Ted Kremenek20e97482007-12-12 23:41:08 +00001489 // Process the -I options and set them in the HeaderInfo.
1490 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekc68ecb52008-06-06 01:47:30 +00001491
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001492 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001493
Ted Kremenek20e97482007-12-12 23:41:08 +00001494 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001495 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001496 *SourceMgr.get(), HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001497
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001498 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1499
Ted Kremenek339b9c22008-04-17 22:31:54 +00001500 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001501 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001502
1503 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1504 // always reset to using TextDiagClient.
1505 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001506
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001507 if (!HTMLDiag.empty()) {
1508 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1509 &PPFactory));
1510 Diags.setClient(TmpClient.get());
1511 }
1512 else
1513 Diags.setClient(TextDiagClient);
1514
1515 // Process the source file.
Ted Kremenek85888962008-10-21 00:54:44 +00001516 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1517
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001518 HeaderInfo.ClearFileInfo();
Ted Kremenek20e97482007-12-12 23:41:08 +00001519
1520 if (Stats)
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001521 SourceMgr->PrintStats();
Ted Kremenek20e97482007-12-12 23:41:08 +00001522 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 }
Chris Lattner11215192008-03-14 06:12:05 +00001524
Ted Kremenek7a08e282008-08-07 18:13:12 +00001525 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1527 (NumDiagnostics == 1 ? "" : "s"));
1528
1529 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 FileMgr.PrintStats();
1531 fprintf(stderr, "\n");
1532 }
1533
Daniel Dunbar276373d2008-10-27 22:10:13 +00001534 // If verifying diagnostics and we reached here, all is well.
1535 if (VerifyDiagnostics)
1536 return 0;
1537
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001538 // Managed static deconstruction. Useful for making things like
1539 // -time-passes usable.
1540 llvm::llvm_shutdown();
1541
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001542 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001543}