blob: ee6d9267c5f72bf61177d81ab05a513f7b1b073a [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//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman0ec78fa2009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000036#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000037#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000038#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000039#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000040#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000041#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000042#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000043#include "clang/AST/ASTContext.h"
44#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000045#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000046#include "clang/Parse/Parser.h"
47#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000048#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "clang/Basic/FileManager.h"
50#include "clang/Basic/SourceManager.h"
51#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000052#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000053#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000055#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000057#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000061#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000062#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000063#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000064#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000065#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000066#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000067#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000068#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000069#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000070#include "llvm/System/Process.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000071#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000072#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000073#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000074#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000075#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000076# include <sys/types.h>
77#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000078
Reid Spencer5f016e22007-07-11 17:01:13 +000079using namespace clang;
80
81//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000082// Source Location Parser
83//===----------------------------------------------------------------------===//
84
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000085static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
86 FileManager &FileMgr,
87 RequestedSourceLocation &Result) {
88 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000089 if (!File)
90 return true;
91
92 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000093 Result.Line = ParsedLoc.Line;
94 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000095 return false;
96}
97
Douglas Gregor26df2f02009-04-02 19:05:20 +000098//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000099// Global options.
100//===----------------------------------------------------------------------===//
101
Chris Lattner47099742009-02-18 01:51:21 +0000102/// ClangFrontendTimer - The front-end activities should charge time to it with
103/// TimeRegion. The -ftime-report option controls whether this will do
104/// anything.
105llvm::Timer *ClangFrontendTimer = 0;
106
Daniel Dunbard3db4012008-10-16 16:54:18 +0000107static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109static llvm::cl::opt<bool>
110Verbose("v", llvm::cl::desc("Enable verbose output"));
111static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000112Stats("print-stats",
113 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000114static llvm::cl::opt<bool>
115DisableFree("disable-free",
116 llvm::cl::desc("Disable freeing of memory on exit"),
117 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000118static llvm::cl::opt<bool>
119EmptyInputOnly("empty-input-only",
120 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000121
122enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000124 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000125 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000126 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000127 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000128 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000129 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000131 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000132 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000133 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000135 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 ASTDump, // Parse ASTs and dump them.
137 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000138 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 ParsePrintCallbacks, // Parse and print each callback.
140 ParseSyntaxOnly, // Parse and perform semantic analysis.
141 ParseNoop, // Parse with noop callbacks.
142 RunPreprocessorOnly, // Just lex, no output.
143 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000144 DumpTokens, // Dump out preprocessed tokens.
145 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000146 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000147 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000148 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000149 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000150};
151
152static llvm::cl::opt<ProgActions>
153ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
154 llvm::cl::init(ParseSyntaxOnly),
155 llvm::cl::values(
156 clEnumValN(RunPreprocessorOnly, "Eonly",
157 "Just run preprocessor, no output (for timings)"),
158 clEnumValN(PrintPreprocessedInput, "E",
159 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000160 clEnumValN(DumpRawTokens, "dump-raw-tokens",
161 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000162 clEnumValN(RunAnalysis, "analyze",
163 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000164 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 "Run preprocessor, dump internal rep of tokens"),
166 clEnumValN(ParseNoop, "parse-noop",
167 "Run parser with noop callbacks (for timings)"),
168 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
169 "Run parser and perform semantic analysis"),
170 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
171 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000172 clEnumValN(EmitHTML, "emit-html",
173 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000174 clEnumValN(ASTPrint, "ast-print",
175 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000176 clEnumValN(ASTPrintXML, "ast-print-xml",
177 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000178 clEnumValN(ASTDump, "ast-dump",
179 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000180 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000181 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000182 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000183 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000184 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000185 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000186 clEnumValN(GeneratePCH, "emit-pch",
187 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000188 clEnumValN(EmitAssembly, "S",
189 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000191 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000192 clEnumValN(EmitBC, "emit-llvm-bc",
193 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000194 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
195 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000196 clEnumValN(RewriteTest, "rewrite-test",
197 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000198 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000199 "Rewrite ObjC into C (code rewriter example)"),
200 clEnumValN(RewriteMacros, "rewrite-macros",
201 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000202 clEnumValN(RewriteBlocks, "rewrite-blocks",
203 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000204 clEnumValN(FixIt, "fixit",
205 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 clEnumValEnd));
207
Ted Kremenekccc76472007-12-19 19:47:59 +0000208
209static llvm::cl::opt<std::string>
210OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000211 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000212 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000213
Ted Kremenekc2e72992008-12-02 19:57:31 +0000214
215//===----------------------------------------------------------------------===//
216// PTH.
217//===----------------------------------------------------------------------===//
218
219static llvm::cl::opt<std::string>
220TokenCache("token-cache", llvm::cl::value_desc("path"),
221 llvm::cl::desc("Use specified token cache file"));
222
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000223//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000224// Diagnostic Options
225//===----------------------------------------------------------------------===//
226
Ted Kremenek41193e42007-09-26 19:42:19 +0000227static llvm::cl::opt<bool>
228VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000229 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000230
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000231static llvm::cl::opt<std::string>
232HTMLDiag("html-diags",
233 llvm::cl::desc("Generate HTML to report diagnostics"),
234 llvm::cl::value_desc("HTML directory"));
235
Nico Weberfd54ebc2008-08-05 23:33:20 +0000236static llvm::cl::opt<bool>
237NoShowColumn("fno-show-column",
238 llvm::cl::desc("Do not include column number on diagnostics"));
239
240static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000241NoShowLocation("fno-show-source-location",
242 llvm::cl::desc("Do not include source location information with"
243 " diagnostics"));
244
245static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000246NoCaretDiagnostics("fno-caret-diagnostics",
247 llvm::cl::desc("Do not include source line and caret with"
248 " diagnostics"));
249
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000250static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000251NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
252 llvm::cl::desc("Do not include fixit information in"
253 " diagnostics"));
254
255static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000256PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
257 llvm::cl::desc("Print source range spans in numeric form"));
258
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000259static llvm::cl::opt<bool>
260PrintDiagnosticOption("fdiagnostics-show-option",
261 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000262
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000263static llvm::cl::opt<unsigned>
264MessageLength("fmessage-length",
265 llvm::cl::desc("Format message diagnostics so that they fit "
266 "within N columns or fewer, when possible."),
267 llvm::cl::value_desc("N"));
268
Torok Edwin603fca72009-06-04 07:18:23 +0000269static llvm::cl::opt<bool>
Torok Edwina46c71a2009-06-04 07:27:53 +0000270NoColorDiagnostic("fno-color-diagnostics",
Torok Edwin603fca72009-06-04 07:18:23 +0000271 llvm::cl::desc("Don't use colors when showing diagnostics "
272 "(automatically turned off if output is not a "
273 "terminal)."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000274//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000275// C++ Visualization.
276//===----------------------------------------------------------------------===//
277
278static llvm::cl::opt<std::string>
279InheritanceViewCls("cxx-inheritance-view",
280 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000281 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000282
283//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000284// Builtin Options
285//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000286
287static llvm::cl::opt<bool>
288TimeReport("ftime-report",
289 llvm::cl::desc("Print the amount of time each "
290 "phase of compilation takes"));
291
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000292static llvm::cl::opt<bool>
293Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000294 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000295 "freestanding environment"));
296
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000297static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000298AllowBuiltins("fbuiltin", llvm::cl::init(true),
299 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000300
301
302static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000303MathErrno("fmath-errno", llvm::cl::init(true),
304 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000305
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000306//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000307// Language Options
308//===----------------------------------------------------------------------===//
309
310enum LangKind {
311 langkind_unspecified,
312 langkind_c,
313 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000314 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 langkind_cxx,
316 langkind_cxx_cpp,
317 langkind_objc,
318 langkind_objc_cpp,
319 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000320 langkind_objcxx_cpp,
321 langkind_ocl
Reid Spencer5f016e22007-07-11 17:01:13 +0000322};
323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324static llvm::cl::opt<LangKind>
325BaseLang("x", llvm::cl::desc("Base language to compile"),
326 llvm::cl::init(langkind_unspecified),
327 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000328 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 clEnumValN(langkind_cxx, "c++", "C++"),
330 clEnumValN(langkind_objc, "objective-c", "Objective C"),
331 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000332 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000334 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
335 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000337 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
339 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000340 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000342 clEnumValN(langkind_c, "c-header",
343 "C header"),
344 clEnumValN(langkind_objc, "objective-c-header",
345 "Objective-C header"),
346 clEnumValN(langkind_cxx, "c++-header",
347 "C++ header"),
348 clEnumValN(langkind_objcxx, "objective-c++-header",
349 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 clEnumValEnd));
351
352static llvm::cl::opt<bool>
353LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
354 llvm::cl::Hidden);
355static llvm::cl::opt<bool>
356LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
357 llvm::cl::Hidden);
358
Chris Lattner2c78b872009-04-14 23:22:57 +0000359static llvm::cl::opt<bool>
360ObjCExclusiveGC("fobjc-gc-only",
361 llvm::cl::desc("Use GC exclusively for Objective-C related "
362 "memory management"));
363
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000364static llvm::cl::opt<std::string>
365ObjCConstantStringClass("fconstant-string-class",
366 llvm::cl::value_desc("class name"),
367 llvm::cl::desc("Specify the class to use for constant "
368 "Objective-C string objects."));
369
Chris Lattner2c78b872009-04-14 23:22:57 +0000370static llvm::cl::opt<bool>
371ObjCEnableGC("fobjc-gc",
372 llvm::cl::desc("Enable Objective-C garbage collection"));
373
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000374static llvm::cl::opt<bool>
375ObjCEnableGCBitmapPrint("print-ivar-layout",
376 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
377
Chris Lattner2c78b872009-04-14 23:22:57 +0000378static llvm::cl::opt<LangOptions::VisibilityMode>
379SymbolVisibility("fvisibility",
380 llvm::cl::desc("Set the default symbol visibility:"),
381 llvm::cl::init(LangOptions::Default),
382 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
383 "Use default symbol visibility"),
384 clEnumValN(LangOptions::Hidden, "hidden",
385 "Use hidden symbol visibility"),
386 clEnumValN(LangOptions::Protected,"protected",
387 "Use protected symbol visibility"),
388 clEnumValEnd));
389
390static llvm::cl::opt<bool>
391OverflowChecking("ftrapv",
392 llvm::cl::desc("Trap on integer overflow"),
393 llvm::cl::init(false));
394
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000395static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000396AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
397 llvm::cl::init(false));
398
399static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000400PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
401 llvm::cl::init(false));
402
403static llvm::cl::opt<bool>
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000404ObjCSenderDispatch("fobjc-sender-dependent-dispatch",
405 llvm::cl::desc("Enable sender-dependent dispatch for"
406 "Objective-C messages"), llvm::cl::init(false));
Chris Lattner2c78b872009-04-14 23:22:57 +0000407
Ted Kremenek8904f152007-12-05 23:49:08 +0000408/// InitializeBaseLanguage - Handle the -x foo options.
409static void InitializeBaseLanguage() {
410 if (LangObjC)
411 BaseLang = langkind_objc;
412 else if (LangObjCXX)
413 BaseLang = langkind_objcxx;
414}
415
416static LangKind GetLanguage(const std::string &Filename) {
417 if (BaseLang != langkind_unspecified)
418 return BaseLang;
419
420 std::string::size_type DotPos = Filename.rfind('.');
421
422 if (DotPos == std::string::npos) {
423 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000424 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 }
426
Ted Kremenek8904f152007-12-05 23:49:08 +0000427 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
428 // C header: .h
429 // C++ header: .hh or .H;
430 // assembler no preprocessing: .s
431 // assembler: .S
432 if (Ext == "c")
433 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000434 else if (Ext == "S" ||
435 // If the compiler is run on a .s file, preprocess it as .S
436 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000437 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000438 else if (Ext == "i")
439 return langkind_c_cpp;
440 else if (Ext == "ii")
441 return langkind_cxx_cpp;
442 else if (Ext == "m")
443 return langkind_objc;
444 else if (Ext == "mi")
445 return langkind_objc_cpp;
446 else if (Ext == "mm" || Ext == "M")
447 return langkind_objcxx;
448 else if (Ext == "mii")
449 return langkind_objcxx_cpp;
450 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
451 Ext == "c++" || Ext == "cp" || Ext == "cxx")
452 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000453 else if (Ext == "cl")
454 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000455 else
456 return langkind_c;
457}
458
459
Ted Kremenek85888962008-10-21 00:54:44 +0000460static void InitializeCOptions(LangOptions &Options) {
461 // Do nothing.
462}
463
464static void InitializeObjCOptions(LangOptions &Options) {
465 Options.ObjC1 = Options.ObjC2 = 1;
466}
467
468
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000469static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 // FIXME: implement -fpreprocessed mode.
471 bool NoPreprocess = false;
472
Ted Kremenek8904f152007-12-05 23:49:08 +0000473 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000475 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000476 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000477 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 case langkind_c_cpp:
479 NoPreprocess = true;
480 // FALLTHROUGH
481 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000482 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 break;
484 case langkind_cxx_cpp:
485 NoPreprocess = true;
486 // FALLTHROUGH
487 case langkind_cxx:
488 Options.CPlusPlus = 1;
489 break;
490 case langkind_objc_cpp:
491 NoPreprocess = true;
492 // FALLTHROUGH
493 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000494 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 break;
496 case langkind_objcxx_cpp:
497 NoPreprocess = true;
498 // FALLTHROUGH
499 case langkind_objcxx:
500 Options.ObjC1 = Options.ObjC2 = 1;
501 Options.CPlusPlus = 1;
502 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000503 case langkind_ocl:
504 Options.OpenCL = 1;
505 Options.AltiVec = 1;
506 Options.CXXOperatorNames = 1;
507 Options.LaxVectorConversions = 1;
508 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000510
511 if (ObjCExclusiveGC)
512 Options.setGCMode(LangOptions::GCOnly);
513 else if (ObjCEnableGC)
514 Options.setGCMode(LangOptions::HybridGC);
515
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000516 if (ObjCEnableGCBitmapPrint)
517 Options.ObjCGCBitmapPrint = 1;
518
Nate Begeman2ef13e52009-08-10 23:49:36 +0000519 if (AltiVec)
520 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000521
522 if (PThread)
523 Options.POSIXThreads = 1;
Nate Begeman2ef13e52009-08-10 23:49:36 +0000524
Chris Lattner2c78b872009-04-14 23:22:57 +0000525 Options.setVisibilityMode(SymbolVisibility);
526 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000527}
528
529/// LangStds - Language standards we support.
530enum LangStds {
531 lang_unspecified,
532 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000533 lang_gnu_START,
534 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000535 lang_cxx98, lang_gnucxx98,
536 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000537};
538
539static llvm::cl::opt<LangStds>
540LangStd("std", llvm::cl::desc("Language standard to compile for"),
541 llvm::cl::init(lang_unspecified),
542 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
543 clEnumValN(lang_c89, "c90", "ISO C 1990"),
544 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
545 clEnumValN(lang_c94, "iso9899:199409",
546 "ISO C 1990 with amendment 1"),
547 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000548 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000550 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000552 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000554 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 clEnumValN(lang_gnu99, "gnu9x",
556 "ISO C 1999 with GNU extensions"),
557 clEnumValN(lang_cxx98, "c++98",
558 "ISO C++ 1998 with amendments"),
559 clEnumValN(lang_gnucxx98, "gnu++98",
560 "ISO C++ 1998 with amendments and GNU "
561 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000562 clEnumValN(lang_cxx0x, "c++0x",
563 "Upcoming ISO C++ 200x with amendments"),
564 clEnumValN(lang_gnucxx0x, "gnu++0x",
565 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000566 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 clEnumValEnd));
568
569static llvm::cl::opt<bool>
570NoOperatorNames("fno-operator-names",
571 llvm::cl::desc("Do not treat C++ operator name keywords as "
572 "synonyms for operators"));
573
Anders Carlssonee98ac52007-10-15 02:50:23 +0000574static llvm::cl::opt<bool>
575PascalStrings("fpascal-strings",
576 llvm::cl::desc("Recognize and construct Pascal-style "
577 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000578
579static llvm::cl::opt<bool>
580MSExtensions("fms-extensions",
581 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000582 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000583
584static llvm::cl::opt<bool>
585WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000586 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000587
588static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000589NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000590 llvm::cl::desc("Disallow implicit conversions between "
591 "vectors with a different number of "
592 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000593
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000594static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000595EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000596
597static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000598EnableHeinousExtensions("fheinous-gnu-extensions",
599 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
600 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
601
602static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000603ObjCNonFragileABI("fobjc-nonfragile-abi",
604 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000605
Daniel Dunbard6884a02009-05-04 05:16:21 +0000606
607static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000608EmitAllDecls("femit-all-decls",
609 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000610
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000611static llvm::cl::opt<bool>
612Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000613 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000614
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000615static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000616Rtti("frtti", llvm::cl::init(true),
617 llvm::cl::desc("Enable generation of rtti information"));
618
619static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000620GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000621 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000622 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000623
624static llvm::cl::opt<bool>
625NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000626 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000627 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000628
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000629static llvm::cl::opt<bool>
630CharIsSigned("fsigned-char",
631 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000632
633
634static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000635Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000636
Douglas Gregor26dce442009-03-10 00:06:19 +0000637static llvm::cl::opt<unsigned>
638TemplateDepth("ftemplate-depth", llvm::cl::init(99),
639 llvm::cl::desc("Maximum depth of recursive template "
640 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000641static llvm::cl::opt<bool>
642DollarsInIdents("fdollars-in-identifiers",
643 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000644
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000645
646static llvm::cl::opt<bool>
647OptSize("Os", llvm::cl::desc("Optimize for size"));
648
649static llvm::cl::opt<bool>
Daniel Dunbar877db382009-06-02 22:07:45 +0000650DisableLLVMOptimizations("disable-llvm-optzns",
651 llvm::cl::desc("Don't run LLVM optimization passes"));
652
653static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000654NoCommon("fno-common",
655 llvm::cl::desc("Compile common globals like normal definitions"),
656 llvm::cl::ValueDisallowed);
657
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000658static llvm::cl::opt<std::string>
659MainFileName("main-file-name",
660 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000661
Anders Carlssona33d9b42009-05-13 19:49:53 +0000662// FIXME: Also add an "-fno-access-control" option.
663static llvm::cl::opt<bool>
664AccessControl("faccess-control",
665 llvm::cl::desc("Enable C++ access control"));
666
Anders Carlsson92f58222009-08-22 22:30:33 +0000667static llvm::cl::opt<bool>
668NoElideConstructors("fno-elide-constructors",
669 llvm::cl::desc("Disable C++ copy constructor elision"));
670
671
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000672// It might be nice to add bounds to the CommandLine library directly.
673struct OptLevelParser : public llvm::cl::parser<unsigned> {
674 bool parse(llvm::cl::Option &O, const char *ArgName,
675 const std::string &Arg, unsigned &Val) {
676 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
677 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000678 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000679 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000680 return false;
681 }
682};
683static llvm::cl::opt<unsigned, false, OptLevelParser>
684OptLevel("O", llvm::cl::Prefix,
685 llvm::cl::desc("Optimization level"),
686 llvm::cl::init(0));
687
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000688static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000689PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
690
691static llvm::cl::opt<bool>
692StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000693
Bill Wendling45483f72009-06-28 07:36:13 +0000694static llvm::cl::opt<int>
695StackProtector("stack-protector",
696 llvm::cl::desc("Enable stack protectors"),
697 llvm::cl::init(-1));
698
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000699static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000700 TargetInfo *Target,
701 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000702 // Allow the target to set the default the langauge options as it sees fit.
703 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000704
705 // Pass the map of target features to the target for validation and
706 // processing.
707 Target->HandleTargetFeatures(Features);
Chris Lattner16167a62009-03-02 22:11:07 +0000708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 if (LangStd == lang_unspecified) {
710 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000711 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000712 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000713 case langkind_ocl:
714 LangStd = lang_c99;
715 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000717 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 case langkind_c_cpp:
719 case langkind_objc:
720 case langkind_objc_cpp:
721 LangStd = lang_gnu99;
722 break;
723 case langkind_cxx:
724 case langkind_cxx_cpp:
725 case langkind_objcxx:
726 case langkind_objcxx_cpp:
727 LangStd = lang_gnucxx98;
728 break;
729 }
730 }
731
732 switch (LangStd) {
733 default: assert(0 && "Unknown language standard!");
734
735 // Fall through from newer standards to older ones. This isn't really right.
736 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000737 case lang_gnucxx0x:
738 case lang_cxx0x:
739 Options.CPlusPlus0x = 1;
740 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 case lang_gnucxx98:
742 case lang_cxx98:
743 Options.CPlusPlus = 1;
744 Options.CXXOperatorNames = !NoOperatorNames;
745 // FALL THROUGH.
746 case lang_gnu99:
747 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 Options.C99 = 1;
749 Options.HexFloats = 1;
750 // FALL THROUGH.
751 case lang_gnu89:
752 Options.BCPLComment = 1; // Only for C99/C++.
753 // FALL THROUGH.
754 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000755 Options.Digraphs = 1; // C94, C99, C++.
756 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 case lang_c89:
758 break;
759 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000760
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000761 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
762 Options.GNUMode = LangStd >= lang_gnu_START;
763
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000764 if (Options.CPlusPlus) {
765 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000766 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000767 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000768
Chris Lattnerd658b562008-04-05 06:32:51 +0000769 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
770 Options.ImplicitInt = 1;
771 else
772 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000773
Daniel Dunbard573d262009-04-07 22:13:21 +0000774 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
775 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000776 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000777 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000778 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000779
Chris Lattner802db9b2008-12-05 00:10:44 +0000780 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
781 // even if they are normally on for the target. In GNU modes (e.g.
782 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000783 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000784 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000785 Options.Blocks = 0;
786
Chris Lattner01638a62009-04-19 07:06:52 +0000787 // Default to not accepting '$' in identifiers when preprocessing assembler,
788 // but do accept when preprocessing C. FIXME: these defaults are right for
789 // darwin, are they right everywhere?
790 Options.DollarIdents = LK != langkind_asm_cpp;
791 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000792 Options.DollarIdents = DollarsInIdents;
793
Chris Lattnerae0ee032008-12-04 23:20:07 +0000794 if (PascalStrings.getPosition())
795 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000796 if (MSExtensions.getPosition())
797 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000798 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000799 if (NoLaxVectorConversions.getPosition())
800 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000801 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000802 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000803 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000804 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000805 if (CharIsSigned.getPosition())
806 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000807
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000808 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000809 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000810 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000811 Options.Freestanding = Options.NoBuiltin = 1;
812
Chris Lattner810f6d52009-03-13 17:38:01 +0000813 if (EnableHeinousExtensions)
814 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000815
Anders Carlssona33d9b42009-05-13 19:49:53 +0000816 if (AccessControl)
817 Options.AccessControl = 1;
818
Anders Carlsson92f58222009-08-22 22:30:33 +0000819 Options.ElideConstructors = !NoElideConstructors;
820
Chris Lattnere4f21422009-06-30 01:26:17 +0000821 // OpenCL and C++ both have bool, true, false keywords.
822 Options.Bool = Options.OpenCL | Options.CPlusPlus;
823
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000824 Options.MathErrno = MathErrno;
825
Douglas Gregor26dce442009-03-10 00:06:19 +0000826 Options.InstantiationDepth = TemplateDepth;
827
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000828 // Override the default runtime if the user requested it.
829 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000830 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000831 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000832 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000833
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000834 if (!ObjCConstantStringClass.empty())
835 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
836
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000837 if (ObjCNonFragileABI)
838 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000839
840 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbard6884a02009-05-04 05:16:21 +0000841
Daniel Dunbard604c402009-02-04 21:19:06 +0000842 if (EmitAllDecls)
843 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000844
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000845 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
846 // support.
847 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000848
849 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000850 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000851 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000852
853 assert(PICLevel <= 2 && "Invalid value for -pic-level");
854 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000855
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000856 Options.GNUInline = !Options.C99;
Chris Lattner5aeb9e72009-05-06 04:38:30 +0000857 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000858 Options.NoInline = !OptSize && !OptLevel;
859
860 Options.Static = StaticDefine;
861
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000862 switch (StackProtector) {
863 default:
864 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
865 case -1: break;
866 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
867 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
868 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
869 }
Bill Wendling45483f72009-06-28 07:36:13 +0000870
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000871 if (MainFileName.getPosition())
872 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000873}
874
875//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000876// Target Triple Processing.
877//===----------------------------------------------------------------------===//
878
879static llvm::cl::opt<std::string>
880TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000881 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000882
Chris Lattner42e67372008-03-05 01:18:20 +0000883static llvm::cl::opt<std::string>
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000884MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000885 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000886
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000887// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
888// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000889
890// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000891static void HandleMacOSVersionMin(std::string &Triple) {
892 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
893 if (DarwinDashIdx == std::string::npos) {
894 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000895 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000896 exit(1);
897 }
898 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
899
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000900 // Remove the number.
901 Triple.resize(DarwinNumIdx);
902
903 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
904 bool MacOSVersionMinIsInvalid = false;
905 int VersionNum = 0;
906 if (MacOSVersionMin.size() < 4 ||
907 MacOSVersionMin.substr(0, 3) != "10." ||
908 !isdigit(MacOSVersionMin[3])) {
909 MacOSVersionMinIsInvalid = true;
910 } else {
911 const char *Start = MacOSVersionMin.c_str()+3;
912 char *End = 0;
913 VersionNum = (int)strtol(Start, &End, 10);
914
Chris Lattner079f2c462008-09-30 20:30:12 +0000915 // The version number must be in the range 0-9.
916 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
917
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000918 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
919 Triple += llvm::itostr(VersionNum+4);
920
Chris Lattner079f2c462008-09-30 20:30:12 +0000921 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
922 // Add the period piece (.7) to the end of the triple. This gives us
923 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000924 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000925 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
926 MacOSVersionMinIsInvalid = true;
927 }
928 }
929
930 if (MacOSVersionMinIsInvalid) {
931 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000932 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000933 MacOSVersionMin.c_str());
934 exit(1);
935 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000936 else if (VersionNum <= 4 &&
937 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
938 fprintf(stderr,
939 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
940 MacOSVersionMin.c_str());
941 exit(1);
942 }
943
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000944}
945
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000946static llvm::cl::opt<std::string>
947IPhoneOSVersionMin("miphoneos-version-min",
948 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
949
950// If -miphoneos-version-min=2.2 is specified, change the triple from being
951// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
952// 9 as the default major Darwin number, and encode the iPhone OS version
953// number in the minor version and revision.
954
955// FIXME: We should have the driver do this instead.
956static void HandleIPhoneOSVersionMin(std::string &Triple) {
957 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
958 if (DarwinDashIdx == std::string::npos) {
959 fprintf(stderr,
960 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
961 exit(1);
962 }
963 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
964
965 // Remove the number.
966 Triple.resize(DarwinNumIdx);
967
968 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
969 bool IPhoneOSVersionMinIsInvalid = false;
970 int VersionNum = 0;
971 if (IPhoneOSVersionMin.size() < 3 ||
972 !isdigit(IPhoneOSVersionMin[0])) {
973 IPhoneOSVersionMinIsInvalid = true;
974 } else {
975 const char *Start = IPhoneOSVersionMin.c_str();
976 char *End = 0;
977 VersionNum = (int)strtol(Start, &End, 10);
978
979 // The version number must be in the range 0-9.
980 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
981
982 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
983 Triple += "9." + llvm::itostr(VersionNum);
984
985 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
986 // Add the period piece (.2) to the end of the triple. This gives us
987 // something like ...-darwin9.2.2
988 Triple += End;
989 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
990 IPhoneOSVersionMinIsInvalid = true;
991 }
992 }
993
994 if (IPhoneOSVersionMinIsInvalid) {
995 fprintf(stderr,
996 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
997 IPhoneOSVersionMin.c_str());
998 exit(1);
999 }
1000}
1001
Chris Lattnerba0f25f2008-09-30 20:16:56 +00001002/// CreateTargetTriple - Process the various options that affect the target
1003/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +00001004static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +00001005 // Initialize base triple. If a -triple option has been specified, use
1006 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +00001007 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +00001008 if (Triple.empty())
1009 Triple = llvm::sys::getHostTriple();
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001010
1011 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1012 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +00001013 if (!MacOSVersionMin.empty())
1014 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +00001015 else if (!IPhoneOSVersionMin.empty())
1016 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +00001017
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001018 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +00001019}
1020
1021//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +00001022// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001023//===----------------------------------------------------------------------===//
1024
Douglas Gregore1d918e2009-04-10 23:10:45 +00001025static bool InitializeSourceManager(Preprocessor &PP,
1026 const std::string &InFile) {
1027 // Figure out where to get and map in the main file.
1028 SourceManager &SourceMgr = PP.getSourceManager();
1029 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001030
1031 if (EmptyInputOnly) {
1032 const char *EmptyStr = "";
1033 llvm::MemoryBuffer *SB =
1034 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1035 SourceMgr.createMainFileIDForMemBuffer(SB);
1036 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001037 const FileEntry *File = FileMgr.getFile(InFile);
1038 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1039 if (SourceMgr.getMainFileID().isInvalid()) {
1040 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1041 << InFile.c_str();
1042 return true;
1043 }
1044 } else {
1045 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1046
1047 // If stdin was empty, SB is null. Cons up an empty memory
1048 // buffer now.
1049 if (!SB) {
1050 const char *EmptyStr = "";
1051 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1052 }
1053
1054 SourceMgr.createMainFileIDForMemBuffer(SB);
1055 if (SourceMgr.getMainFileID().isInvalid()) {
1056 PP.getDiagnostics().Report(FullSourceLoc(),
1057 diag::err_fe_error_reading_stdin);
1058 return true;
1059 }
1060 }
1061
1062 return false;
1063}
1064
Chris Lattneraa391972008-04-19 23:09:31 +00001065
Chris Lattnere116ccf2009-04-21 05:40:52 +00001066//===----------------------------------------------------------------------===//
1067// Preprocessor Initialization
1068//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001069
Chris Lattnere116ccf2009-04-21 05:40:52 +00001070// FIXME: Preprocessor builtins to support.
1071// -A... - Play with #assertions
1072// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001073
Chris Lattnere116ccf2009-04-21 05:40:52 +00001074static llvm::cl::list<std::string>
1075D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1076 llvm::cl::desc("Predefine the specified macro"));
1077static llvm::cl::list<std::string>
1078U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1079 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001080
Chris Lattnere116ccf2009-04-21 05:40:52 +00001081static llvm::cl::list<std::string>
1082ImplicitIncludes("include", llvm::cl::value_desc("file"),
1083 llvm::cl::desc("Include file before parsing"));
1084static llvm::cl::list<std::string>
1085ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1086 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001087
Chris Lattnere116ccf2009-04-21 05:40:52 +00001088static llvm::cl::opt<std::string>
1089ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1090 llvm::cl::desc("Include precompiled header file"));
1091
1092static llvm::cl::opt<std::string>
1093ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1094 llvm::cl::desc("Include file before parsing"));
1095
Douglas Gregore650c8c2009-07-07 00:12:59 +00001096static llvm::cl::opt<bool>
1097RelocatablePCH("relocatable-pch",
1098 llvm::cl::desc("Whether to build a relocatable precompiled "
1099 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +00001100
1101//===----------------------------------------------------------------------===//
1102// Preprocessor include path information.
1103//===----------------------------------------------------------------------===//
1104
1105// This tool exports a large number of command line options to control how the
1106// preprocessor searches for header files. At root, however, the Preprocessor
1107// object takes a very simple interface: a list of directories to search for
1108//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001109// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001110// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001111//
Reid Spencer5f016e22007-07-11 17:01:13 +00001112
1113static llvm::cl::opt<bool>
1114nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1115
1116// Various command line options. These four add directories to each chain.
1117static llvm::cl::list<std::string>
1118F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1119 llvm::cl::desc("Add directory to framework include search path"));
1120static llvm::cl::list<std::string>
1121I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1122 llvm::cl::desc("Add directory to include search path"));
1123static llvm::cl::list<std::string>
1124idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1125 llvm::cl::desc("Add directory to AFTER include search path"));
1126static llvm::cl::list<std::string>
1127iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1128 llvm::cl::desc("Add directory to QUOTE include search path"));
1129static llvm::cl::list<std::string>
1130isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1131 llvm::cl::desc("Add directory to SYSTEM include search path"));
1132
1133// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1134static llvm::cl::list<std::string>
1135iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1136 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1137static llvm::cl::list<std::string>
1138iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1139 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1140static llvm::cl::list<std::string>
1141iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1142 llvm::cl::Prefix,
1143 llvm::cl::desc("Set directory to include search path with prefix"));
1144
Chris Lattner0c946412007-08-26 17:47:35 +00001145static llvm::cl::opt<std::string>
1146isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1147 llvm::cl::desc("Set the system root directory (usually /)"));
1148
Reid Spencer5f016e22007-07-11 17:01:13 +00001149// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151/// InitializeIncludePaths - Process the -I options and set them in the
1152/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001153void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1154 FileManager &FM, const LangOptions &Lang) {
1155 InitHeaderSearch Init(Headers, Verbose, isysroot);
1156
Ted Kremenekf3721112008-05-31 00:27:00 +00001157 // Handle -I... and -F... options, walking the lists in parallel.
1158 unsigned Iidx = 0, Fidx = 0;
1159 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1160 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001161 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001162 ++Iidx;
1163 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001164 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001165 ++Fidx;
1166 }
1167 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001168
Ted Kremenekf3721112008-05-31 00:27:00 +00001169 // Consume what's left from whatever list was longer.
1170 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001171 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001172 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001173 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001174
1175 // Handle -idirafter... options.
1176 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001177 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1178 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001179
1180 // Handle -iquote... options.
1181 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001182 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001183
1184 // Handle -isystem... options.
1185 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001186 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001187
1188 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1189 // parallel, processing the values in order of occurance to get the right
1190 // prefixes.
1191 {
1192 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1193 unsigned iprefix_idx = 0;
1194 unsigned iwithprefix_idx = 0;
1195 unsigned iwithprefixbefore_idx = 0;
1196 bool iprefix_done = iprefix_vals.empty();
1197 bool iwithprefix_done = iwithprefix_vals.empty();
1198 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1199 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1200 if (!iprefix_done &&
1201 (iwithprefix_done ||
1202 iprefix_vals.getPosition(iprefix_idx) <
1203 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1204 (iwithprefixbefore_done ||
1205 iprefix_vals.getPosition(iprefix_idx) <
1206 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1207 Prefix = iprefix_vals[iprefix_idx];
1208 ++iprefix_idx;
1209 iprefix_done = iprefix_idx == iprefix_vals.size();
1210 } else if (!iwithprefix_done &&
1211 (iwithprefixbefore_done ||
1212 iwithprefix_vals.getPosition(iwithprefix_idx) <
1213 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001214 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1215 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 ++iwithprefix_idx;
1217 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1218 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001219 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1220 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 ++iwithprefixbefore_idx;
1222 iwithprefixbefore_done =
1223 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1224 }
1225 }
1226 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001227
Nico Weber0fca0222008-08-22 09:25:22 +00001228 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001229
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001230 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001231 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001232 llvm::sys::Path::GetMainExecutable(Argv0,
1233 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001234 if (!MainExecutablePath.isEmpty()) {
1235 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1236 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001237
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001238 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001239 MainExecutablePath.appendComponent("lib");
1240 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001241 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001242 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001243
1244 // We pass true to ignore sysroot so that we *always* look for clang headers
1245 // relative to our executable, never relative to -isysroot.
1246 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1247 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001248 }
1249
Nico Weber0fca0222008-08-22 09:25:22 +00001250 if (!nostdinc)
1251 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001252
1253 // Now that we have collected all of the include paths, merge them all
1254 // together and tell the preprocessor about them.
1255
Nico Weber0fca0222008-08-22 09:25:22 +00001256 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001257}
1258
Chris Lattnere116ccf2009-04-21 05:40:52 +00001259void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1260{
1261 // Add macros from the command line.
1262 unsigned d = 0, D = D_macros.size();
1263 unsigned u = 0, U = U_macros.size();
1264 while (d < D || u < U) {
1265 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1266 InitOpts.addMacroDef(D_macros[d++]);
1267 else
1268 InitOpts.addMacroUndef(U_macros[u++]);
1269 }
1270
1271 // If -imacros are specified, include them now. These are processed before
1272 // any -include directives.
1273 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1274 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1275
Douglas Gregorb64c1932009-05-12 01:31:05 +00001276 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1277 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001278 // We want to add these paths to the predefines buffer in order, make a
1279 // temporary vector to sort by their occurrence.
1280 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1281
1282 if (!ImplicitIncludePTH.empty())
1283 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1284 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001285 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1286 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1287 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001288 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1289 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1290 &ImplicitIncludes[i]));
1291 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1292
1293
1294 // Now that they are ordered by position, add to the predefines buffer.
1295 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1296 std::string *Ptr = OrderedPaths[i].second;
1297 if (!ImplicitIncludes.empty() &&
1298 Ptr >= &ImplicitIncludes[0] &&
1299 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1300 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001301 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001302 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001303 } else {
1304 // We end up here when we're producing preprocessed output and
1305 // we loaded a PCH file. In this case, just include the header
1306 // file that was used to build the precompiled header.
1307 assert(Ptr == &ImplicitIncludePCH);
1308 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1309 if (!OriginalFile.empty()) {
1310 InitOpts.addInclude(OriginalFile, false);
1311 ImplicitIncludePCH.clear();
1312 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001313 }
1314 }
1315 }
1316}
1317
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001318//===----------------------------------------------------------------------===//
1319// Driver PreprocessorFactory - For lazily generating preprocessors ...
1320//===----------------------------------------------------------------------===//
1321
1322namespace {
1323class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1324 Diagnostic &Diags;
1325 const LangOptions &LangInfo;
1326 TargetInfo &Target;
1327 SourceManager &SourceMgr;
1328 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001329
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001330public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001331 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001332 TargetInfo &target, SourceManager &SM,
1333 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001334 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001335 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001336
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001337
1338 virtual ~DriverPreprocessorFactory() {}
1339
1340 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001341 llvm::OwningPtr<PTHManager> PTHMgr;
1342
Ted Kremenek748d5d62009-03-20 00:26:38 +00001343 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1344 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1345 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001346 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001347 }
1348
Ted Kremenek72b1b152009-01-15 18:47:46 +00001349 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001350 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1351 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001352 PTHMgr.reset(PTHManager::Create(x, &Diags,
1353 TokenCache.empty() ? Diagnostic::Error
1354 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001355 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001356
Ted Kremenek22f0d092009-03-22 06:42:39 +00001357 if (Diags.hasErrorOccurred())
1358 exit(1);
1359
Ted Kremenek72b1b152009-01-15 18:47:46 +00001360 // Create the Preprocessor.
1361 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1362 SourceMgr, HeaderInfo,
1363 PTHMgr.get()));
1364
1365 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1366 // That argument is used as the IdentifierInfoLookup argument to
1367 // IdentifierTable's ctor.
1368 if (PTHMgr) {
1369 PTHMgr->setPreprocessor(PP.get());
1370 PP->setPTHManager(PTHMgr.take());
1371 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001372
Chris Lattnere116ccf2009-04-21 05:40:52 +00001373 PreprocessorInitOptions InitOpts;
1374 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001375 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001376 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001377
Douglas Gregore1d918e2009-04-10 23:10:45 +00001378 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001379 }
1380};
1381}
Reid Spencer5f016e22007-07-11 17:01:13 +00001382
Reid Spencer5f016e22007-07-11 17:01:13 +00001383//===----------------------------------------------------------------------===//
1384// Basic Parser driver
1385//===----------------------------------------------------------------------===//
1386
Chris Lattner51574ea2008-04-19 23:25:44 +00001387static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001389 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001390
1391 // Parsing the specified input file.
1392 P.ParseTranslationUnit();
1393 delete PA;
1394}
1395
1396//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001397// Code generation options
1398//===----------------------------------------------------------------------===//
1399
1400static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001401GenerateDebugInfo("g",
1402 llvm::cl::desc("Generate source level debug information"));
1403
Daniel Dunbara034ba82009-02-17 19:47:34 +00001404static llvm::cl::opt<std::string>
1405TargetCPU("mcpu",
1406 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1407
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001408static llvm::cl::list<std::string>
1409TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1410
Devang Patel24095da2009-06-04 23:32:02 +00001411
1412static llvm::cl::opt<bool>
1413DisableRedZone("disable-red-zone",
1414 llvm::cl::desc("Do not emit code that uses the red zone."),
1415 llvm::cl::init(false));
1416
Devang Patelacebb392009-06-05 22:05:48 +00001417static llvm::cl::opt<bool>
1418NoImplicitFloat("no-implicit-float",
1419 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1420 llvm::cl::init(false));
1421
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001422/// ComputeTargetFeatures - Recompute the target feature list to only
1423/// be the list of things that are enabled, based on the target cpu
1424/// and feature list.
1425static void ComputeFeatureMap(TargetInfo *Target,
1426 llvm::StringMap<bool> &Features) {
1427 assert(Features.empty() && "invalid map");
1428
1429 // Initialize the feature map based on the target.
1430 Target->getDefaultFeatures(TargetCPU, Features);
1431
1432 // Apply the user specified deltas.
1433 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1434 ie = TargetFeatures.end(); it != ie; ++it) {
1435 const char *Name = it->c_str();
1436
1437 // FIXME: Don't handle errors like this.
1438 if (Name[0] != '-' && Name[0] != '+') {
1439 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1440 Name);
1441 exit(1);
1442 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001443 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1444 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1445 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001446 exit(1);
1447 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001448 }
1449}
1450
Chris Lattner7afae712009-03-16 18:41:18 +00001451static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001452 const LangOptions &LangOpts,
1453 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001454 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001455 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001456
1457 if (DisableLLVMOptimizations) {
1458 Opts.OptimizationLevel = 0;
1459 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001460 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001461 if (OptSize) {
1462 // -Os implies -O2
1463 Opts.OptimizationLevel = 2;
1464 } else {
1465 Opts.OptimizationLevel = OptLevel;
1466 }
1467
1468 // We must always run at least the always inlining pass.
1469 if (Opts.OptimizationLevel > 1)
1470 Opts.Inlining = CompileOptions::NormalInlining;
1471 else
1472 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001473 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001474
1475 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001476 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001477 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001478
1479#ifdef NDEBUG
1480 Opts.VerifyModule = 0;
1481#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001482
1483 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001484 Opts.Features.clear();
1485 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1486 ie = Features.end(); it != ie; ++it) {
1487 // FIXME: If we are completely confident that we have the right
1488 // set, we only need to pass the minuses.
1489 std::string Name(it->second ? "+" : "-");
1490 Name += it->first();
1491 Opts.Features.push_back(Name);
1492 }
Chris Lattner44502662009-02-18 01:23:44 +00001493
Chris Lattnerbd360642009-03-26 05:00:52 +00001494 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1495
Chris Lattner44502662009-02-18 01:23:44 +00001496 // Handle -ftime-report.
1497 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001498
1499 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001500 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001501}
1502
1503//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001504// Fix-It Options
1505//===----------------------------------------------------------------------===//
1506static llvm::cl::list<ParsedSourceLocation>
1507FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1508 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1509
1510//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001511// ObjC Rewriter Options
1512//===----------------------------------------------------------------------===//
1513static llvm::cl::opt<bool>
1514SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1515 llvm::cl::desc("Silence ObjC rewriting warnings"));
1516
1517//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001518// Warning Options
1519//===----------------------------------------------------------------------===//
1520
1521// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1522// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1523// -Wextra, so we don't need to worry about it.
1524static llvm::cl::list<std::string>
1525OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1526
1527static llvm::cl::opt<bool> OptPedantic("pedantic");
1528static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1529static llvm::cl::opt<bool> OptNoWarnings("w");
1530
1531//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001532// Preprocessing (-E mode) Options
1533//===----------------------------------------------------------------------===//
1534static llvm::cl::opt<bool>
1535DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1536static llvm::cl::opt<bool>
1537EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1538static llvm::cl::opt<bool>
1539EnableMacroCommentOutput("CC",
1540 llvm::cl::desc("Enable comment output in -E mode, "
1541 "even from macro expansions"));
1542static llvm::cl::opt<bool>
1543DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1544 " normal output"));
1545static llvm::cl::opt<bool>
1546DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1547 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001548
1549//===----------------------------------------------------------------------===//
1550// Dependency file options
1551//===----------------------------------------------------------------------===//
1552static llvm::cl::opt<std::string>
1553DependencyFile("dependency-file",
1554 llvm::cl::desc("Filename (or -) to write dependency output to"));
1555
1556static llvm::cl::opt<bool>
1557DependenciesIncludeSystemHeaders("sys-header-deps",
1558 llvm::cl::desc("Include system headers in dependency output"));
1559
1560static llvm::cl::list<std::string>
1561DependencyTargets("MT",
1562 llvm::cl::desc("Specify target for dependency"));
1563
1564// FIXME: Implement feature
1565static llvm::cl::opt<bool>
1566PhonyDependencyTarget("MP",
1567 llvm::cl::desc("Create phony target for each dependency "
1568 "(other than main file)"));
1569
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001570//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001571// Analysis options
1572//===----------------------------------------------------------------------===//
1573
1574static llvm::cl::list<Analyses>
1575AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1576llvm::cl::values(
1577#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1578clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001579#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001580clEnumValEnd));
1581
1582static llvm::cl::opt<AnalysisStores>
1583AnalysisStoreOpt("analyzer-store",
1584 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1585 llvm::cl::init(BasicStoreModel),
1586 llvm::cl::values(
1587#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1588clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001589#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001590clEnumValEnd));
1591
1592static llvm::cl::opt<AnalysisConstraints>
1593AnalysisConstraintsOpt("analyzer-constraints",
1594 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1595 llvm::cl::init(RangeConstraintsModel),
1596 llvm::cl::values(
1597#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1598clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001599#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001600clEnumValEnd));
1601
1602static llvm::cl::opt<AnalysisDiagClients>
1603AnalysisDiagOpt("analyzer-output",
1604 llvm::cl::desc("Source Code Analysis - Output Options"),
1605 llvm::cl::init(PD_HTML),
1606 llvm::cl::values(
1607#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1608clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001609#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001610clEnumValEnd));
1611
1612static llvm::cl::opt<bool>
1613VisualizeEGDot("analyzer-viz-egraph-graphviz",
1614 llvm::cl::desc("Display exploded graph using GraphViz"));
1615
1616static llvm::cl::opt<bool>
1617VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1618 llvm::cl::desc("Display exploded graph using Ubigraph"));
1619
1620static llvm::cl::opt<bool>
1621AnalyzeAll("analyzer-opt-analyze-headers",
1622 llvm::cl::desc("Force the static analyzer to analyze "
1623 "functions defined in header files"));
1624
1625static llvm::cl::opt<bool>
1626AnalyzerDisplayProgress("analyzer-display-progress",
1627 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1628
1629static llvm::cl::opt<bool>
1630PurgeDead("analyzer-purge-dead",
1631 llvm::cl::init(true),
1632 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1633 " processing a statement."));
1634
1635static llvm::cl::opt<bool>
1636EagerlyAssume("analyzer-eagerly-assume",
1637 llvm::cl::init(false),
1638 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1639 "symbolic constraints."));
1640
1641static llvm::cl::opt<std::string>
1642AnalyzeSpecificFunction("analyze-function",
1643 llvm::cl::desc("Run analysis on specific function"));
1644
1645static llvm::cl::opt<bool>
1646TrimGraph("trim-egraph",
1647 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1648
1649static AnalyzerOptions ReadAnalyzerOptions() {
1650 AnalyzerOptions Opts;
1651 Opts.AnalysisList = AnalysisList;
1652 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1653 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1654 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1655 Opts.VisualizeEGDot = VisualizeEGDot;
1656 Opts.VisualizeEGUbi = VisualizeEGUbi;
1657 Opts.AnalyzeAll = AnalyzeAll;
1658 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1659 Opts.PurgeDead = PurgeDead;
1660 Opts.EagerlyAssume = EagerlyAssume;
1661 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1662 Opts.TrimGraph = TrimGraph;
1663 return Opts;
1664}
1665
1666//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001667// -dump-build-information Stuff
1668//===----------------------------------------------------------------------===//
1669
1670static llvm::cl::opt<std::string>
1671DumpBuildInformation("dump-build-information",
1672 llvm::cl::value_desc("filename"),
1673 llvm::cl::desc("output a dump of some build information to a file"));
1674
1675static llvm::raw_ostream *BuildLogFile = 0;
1676
1677/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1678/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1679namespace {
1680class LoggingDiagnosticClient : public DiagnosticClient {
1681 llvm::OwningPtr<DiagnosticClient> Chain1;
1682 llvm::OwningPtr<DiagnosticClient> Chain2;
1683public:
1684
1685 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1686 // Output diags both where requested...
1687 Chain1.reset(Normal);
1688 // .. and to our log file.
1689 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1690 !NoShowColumn,
1691 !NoCaretDiagnostics,
1692 !NoShowLocation,
1693 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001694 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001695 !NoDiagnosticsFixIt,
Nate Begeman4e3629e2009-06-25 22:43:10 +00001696 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001697 }
1698
1699 virtual void setLangOptions(const LangOptions *LO) {
1700 Chain1->setLangOptions(LO);
1701 Chain2->setLangOptions(LO);
1702 }
1703
1704 virtual bool IncludeInDiagnosticCounts() const {
1705 return Chain1->IncludeInDiagnosticCounts();
1706 }
1707
1708 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1709 const DiagnosticInfo &Info) {
1710 Chain1->HandleDiagnostic(DiagLevel, Info);
1711 Chain2->HandleDiagnostic(DiagLevel, Info);
1712 }
1713};
1714} // end anonymous namespace.
1715
1716static void SetUpBuildDumpLog(unsigned argc, char **argv,
1717 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1718
1719 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001720 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001721 ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +00001722
1723 if (!ErrorInfo.empty()) {
1724 llvm::errs() << "error opening -dump-build-information file '"
1725 << DumpBuildInformation << "', option ignored!\n";
1726 delete BuildLogFile;
1727 BuildLogFile = 0;
1728 DumpBuildInformation = "";
1729 return;
1730 }
1731
1732 (*BuildLogFile) << "clang-cc command line arguments: ";
1733 for (unsigned i = 0; i != argc; ++i)
1734 (*BuildLogFile) << argv[i] << ' ';
1735 (*BuildLogFile) << '\n';
1736
1737 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1738 // the diagnostic producers and the normal receiver.
1739 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1740}
1741
1742
1743
1744//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001745// Main driver
1746//===----------------------------------------------------------------------===//
1747
Chris Lattner92bcc272009-08-23 02:59:41 +00001748static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1749 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001750 bool Binary,
1751 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001752 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001753 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001754 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001755 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001756 else if (InFile == "-") {
1757 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001758 } else if (Extension) {
1759 llvm::sys::Path Path(InFile);
1760 Path.eraseSuffix();
1761 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001762 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001763 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001764 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001765 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001766
Chris Lattner92bcc272009-08-23 02:59:41 +00001767 std::string Error;
1768 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001769 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001770 if (!Error.empty()) {
1771 // FIXME: Don't fail this way.
1772 llvm::errs() << "ERROR: " << Error << "\n";
1773 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001774 }
Chris Lattner92bcc272009-08-23 02:59:41 +00001775
1776 if (OutFile != "-")
1777 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001778
1779 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001780}
1781
Reid Spencer5f016e22007-07-11 17:01:13 +00001782/// ProcessInputFile - Process a single input file with the specified state.
1783///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001784static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001785 const std::string &InFile, ProgActions PA,
Owen Anderson42253cc2009-07-01 17:00:06 +00001786 const llvm::StringMap<bool> &Features,
Owen Anderson8f1ca782009-07-01 23:14:14 +00001787 llvm::LLVMContext& Context) {
Eli Friedman66d6f042009-05-18 22:20:00 +00001788 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001789 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001790 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001791 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001792 bool CompleteTranslationUnit = true;
Eli Friedman66d6f042009-05-18 22:20:00 +00001793 llvm::sys::Path OutPath;
Douglas Gregor558cb562009-04-02 01:08:08 +00001794
Ted Kremenek85888962008-10-21 00:54:44 +00001795 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 default:
Eli Friedman66d6f042009-05-18 22:20:00 +00001797 fprintf(stderr, "Unexpected program action!\n");
1798 HadErrors = true;
1799 return;
1800
1801 case ASTPrint:
1802 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1803 Consumer.reset(CreateASTPrinter(OS.get()));
1804 break;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001805
Douglas Gregoree75c052009-05-21 20:55:50 +00001806 case ASTPrintXML:
1807 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1808 Consumer.reset(CreateASTPrinterXML(OS.get()));
1809 break;
1810
Eli Friedman66d6f042009-05-18 22:20:00 +00001811 case ASTDump:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001812 Consumer.reset(CreateASTDumper());
Eli Friedman66d6f042009-05-18 22:20:00 +00001813 break;
1814
Eli Friedman66d6f042009-05-18 22:20:00 +00001815 case ASTView:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001816 Consumer.reset(CreateASTViewer());
Eli Friedman66d6f042009-05-18 22:20:00 +00001817 break;
1818
1819 case PrintDeclContext:
1820 Consumer.reset(CreateDeclContextPrinter());
1821 break;
1822
1823 case EmitHTML:
1824 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1825 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1826 break;
1827
1828 case InheritanceView:
1829 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1830 break;
1831
1832 case EmitAssembly:
1833 case EmitLLVM:
1834 case EmitBC:
1835 case EmitLLVMOnly: {
1836 BackendAction Act;
1837 if (ProgAction == EmitAssembly) {
1838 Act = Backend_EmitAssembly;
1839 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1840 } else if (ProgAction == EmitLLVM) {
1841 Act = Backend_EmitLL;
1842 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1843 } else if (ProgAction == EmitLLVMOnly) {
1844 Act = Backend_EmitNothing;
1845 } else {
1846 Act = Backend_EmitBC;
1847 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001848 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001849
Eli Friedman66d6f042009-05-18 22:20:00 +00001850 CompileOptions Opts;
1851 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1852 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1853 PP.getLangOptions(), Opts, InFile,
Owen Anderson42253cc2009-07-01 17:00:06 +00001854 OS.get(), Context));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001855 break;
Eli Friedman66d6f042009-05-18 22:20:00 +00001856 }
1857
1858 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001859 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1860 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1861 RelocatablePCH.setValue(false);
1862 }
1863
Eli Friedman66d6f042009-05-18 22:20:00 +00001864 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001865 if (RelocatablePCH.getValue())
1866 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1867 else
1868 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001869 CompleteTranslationUnit = false;
1870 break;
1871
1872 case RewriteObjC:
1873 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedmanbce831b2009-05-18 22:29:17 +00001874 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001875 PP.getLangOptions(),
1876 SilenceRewriteMacroWarning));
Eli Friedman66d6f042009-05-18 22:20:00 +00001877 break;
1878
1879 case RewriteBlocks:
1880 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1881 PP.getLangOptions()));
1882 break;
1883
Eli Friedmane71b85f2009-05-19 10:18:02 +00001884 case RunAnalysis: {
Eli Friedman66d6f042009-05-18 22:20:00 +00001885 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedmane71b85f2009-05-19 10:18:02 +00001886 PP.getLangOptions(), OutputFile,
1887 ReadAnalyzerOptions()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001888 break;
Eli Friedmane71b85f2009-05-19 10:18:02 +00001889 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001890
Chris Lattnerc106c102008-10-12 05:03:36 +00001891 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001892 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001893 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001894 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001895 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001896 RawLex.SetKeepWhitespaceMode(true);
1897
1898 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001899 RawLex.LexFromRawLexer(RawTok);
1900 while (RawTok.isNot(tok::eof)) {
1901 PP.DumpToken(RawTok, true);
1902 fprintf(stderr, "\n");
1903 RawLex.LexFromRawLexer(RawTok);
1904 }
1905 ClearSourceMgr = true;
1906 break;
1907 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001909 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001910 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001911 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001912 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 do {
1914 PP.Lex(Tok);
1915 PP.DumpToken(Tok, true);
1916 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001917 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001918 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 break;
1920 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001921 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 break;
Ted Kremenek85888962008-10-21 00:54:44 +00001923
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001924 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001925 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001926 if (OutputFile.empty() || OutputFile == "-") {
1927 // FIXME: Don't fail this way.
1928 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001929 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001930 ::exit(1);
1931 }
1932 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1933 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001934 ClearSourceMgr = true;
1935 break;
1936 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001937
Chris Lattnercc7dea82009-04-27 22:02:30 +00001938 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001939 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001941
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001942 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 break;
1944
Chris Lattner47099742009-02-18 01:51:21 +00001945 case ParsePrintCallbacks: {
1946 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001947 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1948 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001949 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 break;
Chris Lattner47099742009-02-18 01:51:21 +00001951 }
1952
1953 case ParseSyntaxOnly: { // -fsyntax-only
1954 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001955 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001956 break;
Chris Lattner47099742009-02-18 01:51:21 +00001957 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001958
1959 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001960 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1961 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001962 ClearSourceMgr = true;
1963 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001964
Eli Friedmanf54fce82009-05-19 01:02:07 +00001965 case RewriteTest:
1966 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1967 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001968 ClearSourceMgr = true;
1969 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001970
1971 case FixIt:
1972 llvm::TimeRegion Timer(ClangFrontendTimer);
1973 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001974 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001975 PP.getSourceManager(),
1976 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001977 break;
Chris Lattner47099742009-02-18 01:51:21 +00001978 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001979
Chris Lattner1aee61a2009-04-27 21:25:27 +00001980 if (FixItAtLocations.size() > 0) {
1981 // Even without the "-fixit" flag, with may have some specific
1982 // locations where the user has requested fixes. Process those
1983 // locations now.
1984 if (!FixItRewrite)
1985 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1986 PP.getSourceManager(),
1987 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001988
Chris Lattner1aee61a2009-04-27 21:25:27 +00001989 bool AddedFixitLocation = false;
1990 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1991 Idx != Last; ++Idx) {
1992 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001993 if (ResolveParsedLocation(FixItAtLocations[Idx],
1994 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001995 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1996 FixItAtLocations[Idx].FileName.c_str());
1997 } else {
1998 FixItRewrite->addFixItLocation(Requested);
1999 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00002000 }
2001 }
2002
Chris Lattner1aee61a2009-04-27 21:25:27 +00002003 if (!AddedFixitLocation) {
2004 // All of the fix-it locations were bad. Don't fix anything.
2005 delete FixItRewrite;
2006 FixItRewrite = 0;
2007 }
2008 }
2009
2010 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002011 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00002012 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
2013 PP.getSourceManager(),
2014 PP.getTargetInfo(),
2015 PP.getIdentifierTable(),
2016 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002017 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00002018 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002019 /* size_reserve = */0));
2020
Chris Lattnercc7dea82009-04-27 22:02:30 +00002021 llvm::OwningPtr<PCHReader> Reader;
2022 llvm::OwningPtr<ExternalASTSource> Source;
2023
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002024 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00002025 // If the user specified -isysroot, it will be used for relocatable PCH
2026 // files.
2027 const char *isysrootPCH = 0;
2028 if (isysroot.getNumOccurrences() != 0)
2029 isysrootPCH = isysroot.c_str();
2030
2031 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Chris Lattnercc7dea82009-04-27 22:02:30 +00002032
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002033 // The user has asked us to include a precompiled header. Load
2034 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002035 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2036 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00002037 // Set the predefines buffer as suggested by the PCH
2038 // reader. Typically, the predefines buffer will be empty.
2039 PP.setPredefines(Reader->getSuggestedPredefines());
2040
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002041 // Attach the PCH reader to the AST context as an external AST
2042 // source, so that declarations will be deserialized from the
2043 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00002044 if (ContextOwner) {
2045 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00002046 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002047 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002048 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002049 }
2050
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002051 case PCHReader::Failure:
2052 // Unrecoverable failure: don't even try to process the input
2053 // file.
2054 return;
2055
2056 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002057 // No suitable PCH file could be found. Return an error.
2058 return;
2059
2060#if 0
2061 // FIXME: We can recover from failed attempts to load PCH
2062 // files. This code will do so, if we ever want to enable it.
2063
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002064 // We delayed the initialization of builtins in the hope of
2065 // loading the PCH file. Since the PCH file could not be
2066 // loaded, initialize builtins now.
2067 if (ContextOwner)
2068 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002069#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002070 }
2071
2072 // Finish preprocessor initialization. We do this now (rather
2073 // than earlier) because this initialization creates new source
2074 // location entries in the source manager, which must come after
2075 // the source location entries for the PCH file.
2076 if (InitializeSourceManager(PP, InFile))
2077 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002078 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002079
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002080
2081 // If we have an ASTConsumer, run the parser with it.
2082 if (Consumer)
2083 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2084 CompleteTranslationUnit);
2085
2086 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2087 llvm::TimeRegion Timer(ClangFrontendTimer);
2088 Token Tok;
2089 // Start parsing the specified input file.
2090 PP.EnterMainSourceFile();
2091 do {
2092 PP.Lex(Tok);
2093 } while (Tok.isNot(tok::eof));
2094 ClearSourceMgr = true;
2095 } else if (PA == ParseNoop) { // -parse-noop
2096 llvm::TimeRegion Timer(ClangFrontendTimer);
2097 ParseFile(PP, new MinimalAction(PP));
2098 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002099 } else if (PA == PrintPreprocessedInput){ // -E mode.
2100 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002101 if (DumpMacros)
2102 DoPrintMacros(PP, OS.get());
2103 else
2104 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2105 EnableMacroCommentOutput,
2106 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002107 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002108 }
2109
Chris Lattner1aee61a2009-04-27 21:25:27 +00002110 if (FixItRewrite)
2111 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002112
2113 // Disable the consumer prior to the context, the consumer may perform actions
2114 // in its destructor which require the context.
2115 if (DisableFree)
2116 Consumer.take();
2117 else
2118 Consumer.reset();
Chris Lattner1aee61a2009-04-27 21:25:27 +00002119
2120 // If in -disable-free mode, don't deallocate ASTContext.
2121 if (DisableFree)
2122 ContextOwner.take();
2123 else
2124 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002125
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002126 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002127 if (CheckDiagnostics(PP))
2128 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002131 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 PP.PrintStats();
2133 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002134 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002135 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 fprintf(stderr, "\n");
2137 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002138
2139 // For a multi-file compilation, some things are ok with nuking the source
2140 // manager tables, other require stable fileid/macroid's across multiple
2141 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002142 if (ClearSourceMgr)
2143 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002144
Eli Friedman66d6f042009-05-18 22:20:00 +00002145 // Always delete the output stream because we don't want to leak file
2146 // handles. Also, we don't want to try to erase an open file.
2147 OS.reset();
2148
2149 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2150 !OutPath.isEmpty()) {
2151 // If we had errors, try to erase the output file.
2152 OutPath.eraseFromDisk();
2153 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002154}
2155
2156static llvm::cl::list<std::string>
2157InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2158
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002159static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2160 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2161
2162 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2163
2164 // We cannot recover from llvm errors.
2165 exit(1);
2166}
2167
Reid Spencer5f016e22007-07-11 17:01:13 +00002168int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002169 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002170 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002171 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002172
Daniel Dunbar4d861512009-09-03 04:54:12 +00002173 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002174 llvm::InitializeAllTargets();
2175 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002176
2177 llvm::cl::ParseCommandLineOptions(argc, argv,
2178 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner2fe11942009-06-17 17:25:50 +00002179
Chris Lattner47099742009-02-18 01:51:21 +00002180 if (TimeReport)
2181 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2182
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002183 if (Verbose)
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002184 llvm::errs() << "clang-cc version 1.0 based upon " << PACKAGE_STRING
2185 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002186
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 // If no input was specified, read from stdin.
2188 if (InputFilenames.empty())
2189 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002190
Ted Kremenek31e703b2007-12-11 23:28:38 +00002191 // Create the diagnostic client for reporting errors or for
2192 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002193 llvm::OwningPtr<DiagnosticClient> DiagClient;
2194 if (VerifyDiagnostics) {
2195 // When checking diagnostics, just buffer them up.
2196 DiagClient.reset(new TextDiagnosticBuffer());
2197 if (InputFilenames.size() != 1) {
2198 fprintf(stderr, "-verify only works on single input files for now.\n");
2199 return 1;
2200 }
2201 if (!HTMLDiag.empty()) {
2202 fprintf(stderr, "-verify and -html-diags don't work together\n");
2203 return 1;
2204 }
2205 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002206 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002207
2208 // If -fmessage-length=N was not specified, determine whether this
2209 // is a terminal and, if so, implicitly define -fmessage-length
2210 // appropriately.
2211 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002212 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002213
Torok Edwin603fca72009-06-04 07:18:23 +00002214 if (!NoColorDiagnostic) {
2215 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2216 }
2217
Chris Lattner409d4e72009-04-17 20:40:01 +00002218 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002219 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002220 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002221 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002222 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002223 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002224 !NoDiagnosticsFixIt,
Torok Edwin603fca72009-06-04 07:18:23 +00002225 MessageLength,
2226 !NoColorDiagnostic));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002227 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002228 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002230
2231 if (!DumpBuildInformation.empty()) {
2232 if (!HTMLDiag.empty()) {
2233 fprintf(stderr,
2234 "-dump-build-information and -html-diags don't work together\n");
2235 return 1;
2236 }
2237
2238 SetUpBuildDumpLog(argc, argv, DiagClient);
2239 }
2240
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002241
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002243 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002244 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2245 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002246 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002247
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002248 // Set an error handler, so that any LLVM backend diagnostics go through our
2249 // error handler.
2250 llvm::llvm_install_error_handler(LLVMErrorHandler,
2251 static_cast<void*>(&Diags));
2252
Chris Lattner4f037832007-12-05 23:24:17 +00002253 // -I- is a deprecated GCC feature, scan for it and reject it.
2254 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2255 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00002256 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002257 I_dirs.erase(I_dirs.begin()+i);
2258 --i;
2259 }
2260 }
Chris Lattner11215192008-03-14 06:12:05 +00002261
2262 // Get information about the target being compiled for.
2263 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00002264 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2265
Chris Lattner11215192008-03-14 06:12:05 +00002266 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00002267 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2268 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002269 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002270 }
Chris Lattner4f037832007-12-05 23:24:17 +00002271
Daniel Dunbard4270232009-01-20 23:17:32 +00002272 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002273 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002274
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002275 llvm::OwningPtr<SourceManager> SourceMgr;
2276
Chris Lattner2c78b872009-04-14 23:22:57 +00002277 // Create a file manager object to provide access to and cache the filesystem.
2278 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002279
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002280 // Compute the feature set, unfortunately this effects the language!
2281 llvm::StringMap<bool> Features;
2282 ComputeFeatureMap(Target.get(), Features);
2283
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002285 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00002286
Chris Lattnerf63aea32009-03-04 21:40:56 +00002287 /// Create a SourceManager object. This tracks and owns all the file
2288 /// buffers allocated to a translation unit.
2289 if (!SourceMgr)
2290 SourceMgr.reset(new SourceManager());
2291 else
2292 SourceMgr->clearIDTables();
2293
2294 // Initialize language options, inferring file types from input filenames.
2295 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002296 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00002297
Chris Lattnerf63aea32009-03-04 21:40:56 +00002298 InitializeBaseLanguage();
2299 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002300 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002301 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002302
2303 // Process the -I options and set them in the HeaderInfo.
2304 HeaderSearch HeaderInfo(FileMgr);
2305
Chris Lattner2c78b872009-04-14 23:22:57 +00002306
Chris Lattnerf63aea32009-03-04 21:40:56 +00002307 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2308
2309 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002310 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002311 *SourceMgr.get(), HeaderInfo);
2312
2313 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2314
2315 if (!PP)
2316 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002317
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002318 // Handle generating dependencies, if requested
2319 if (!DependencyFile.empty()) {
2320 llvm::raw_ostream *DependencyOS;
2321 if (DependencyTargets.empty()) {
2322 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002323 llvm::errs() << "-dependency-file requires at least one -MT option\n";
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002324 HadErrors = true;
2325 continue;
2326 }
2327 std::string ErrStr;
2328 DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002329 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002330 if (!ErrStr.empty()) {
2331 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002332 llvm::errs() << "unable to open dependency file: " + ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002333 HadErrors = true;
2334 continue;
2335 }
2336
2337 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2338 DependenciesIncludeSystemHeaders,
2339 PhonyDependencyTarget);
2340 }
2341
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002342 if (ImplicitIncludePCH.empty()) {
2343 if (InitializeSourceManager(*PP.get(), InFile))
2344 continue;
2345
2346 // Initialize builtin info.
2347 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002348 PP->getLangOptions().NoBuiltin);
2349 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002350
Chris Lattner409d4e72009-04-17 20:40:01 +00002351 if (!HTMLDiag.empty())
2352 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002353
2354 // Process the source file.
Owen Andersonc93f4982009-07-01 21:23:16 +00002355 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features, Context);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002356
Chris Lattner40469652009-04-17 20:16:08 +00002357 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002358 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 }
Chris Lattner11215192008-03-14 06:12:05 +00002360
Mike Stumpfc0fed32009-04-28 01:19:10 +00002361 if (!NoCaretDiagnostics)
2362 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2363 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2364 (NumDiagnostics == 1 ? "" : "s"));
Reid Spencer5f016e22007-07-11 17:01:13 +00002365
2366 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 FileMgr.PrintStats();
2368 fprintf(stderr, "\n");
2369 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002370
2371 delete ClangFrontendTimer;
2372 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00002373
Daniel Dunbar276373d2008-10-27 22:10:13 +00002374 // If verifying diagnostics and we reached here, all is well.
2375 if (VerifyDiagnostics)
2376 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00002377
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002378 // Managed static deconstruction. Useful for making things like
2379 // -time-passes usable.
2380 llvm::llvm_shutdown();
2381
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002382 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002383}