blob: 8b665a34c4e4bdc8379d438a922791cb5b55b89a [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman809bc4b2009-05-19 03:57:28 +000025#include "AnalysisConsumer.h"
Eli Friedmanbc821a42009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor133d2552009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattner94269d72009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedman7e1d6372009-05-19 04:14:29 +000036#include "clang/Frontend/Utils.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000037#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000038#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000039#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000040#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000041#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000042#include "clang/AST/ASTContext.h"
43#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000044#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000045#include "clang/Parse/Parser.h"
46#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000047#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000048#include "clang/Basic/FileManager.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/TargetInfo.h"
Daniel Dunbarae81a792009-05-06 04:07:06 +000051#include "clang/Basic/Version.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000052#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000053#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000054#include "llvm/ADT/StringExtras.h"
Daniel Dunbar07181d72009-05-06 03:16:41 +000055#include "llvm/ADT/StringMap.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000056#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000059#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000060#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000061#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000062#include "llvm/Support/PrettyStackTrace.h"
Eli Friedmana9c310842009-05-18 22:20:00 +000063#include "llvm/Support/Streams.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000065#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000066#include "llvm/System/Path.h"
Douglas Gregor3dd11e82009-05-03 03:52:38 +000067#include "llvm/System/Process.h"
Eli Friedmana9c310842009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000070#include <cstdlib>
Douglas Gregor3dd11e82009-05-03 03:52:38 +000071#if HAVE_SYS_TYPES_H
Douglas Gregor965a13c2009-05-02 00:03:46 +000072# include <sys/types.h>
73#endif
Douglas Gregor24b48b02009-04-02 19:05:20 +000074
Chris Lattner4b009652007-07-25 00:24:17 +000075using namespace clang;
76
77//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000078// Source Location Parser
79//===----------------------------------------------------------------------===//
80
81/// \brief A source location that has been parsed on the command line.
82struct ParsedSourceLocation {
83 std::string FileName;
84 unsigned Line;
85 unsigned Column;
86
87 /// \brief Try to resolve the file name of a parsed source location.
88 ///
89 /// \returns true if there was an error, false otherwise.
90 bool ResolveLocation(FileManager &FileMgr, RequestedSourceLocation &Result);
91};
92
93bool
94ParsedSourceLocation::ResolveLocation(FileManager &FileMgr,
95 RequestedSourceLocation &Result) {
96 const FileEntry *File = FileMgr.getFile(FileName);
97 if (!File)
98 return true;
99
100 Result.File = File;
101 Result.Line = Line;
102 Result.Column = Column;
103 return false;
104}
105
106namespace llvm {
107 namespace cl {
108 /// \brief Command-line option parser that parses source locations.
109 ///
110 /// Source locations are of the form filename:line:column.
111 template<>
112 class parser<ParsedSourceLocation>
113 : public basic_parser<ParsedSourceLocation> {
114 public:
115 bool parse(Option &O, const char *ArgName,
116 const std::string &ArgValue,
117 ParsedSourceLocation &Val);
118 };
119
120 bool
121 parser<ParsedSourceLocation>::
122 parse(Option &O, const char *ArgName, const std::string &ArgValue,
123 ParsedSourceLocation &Val) {
124 using namespace clang;
125
126 const char *ExpectedFormat
127 = "source location must be of the form filename:line:column";
128 std::string::size_type SecondColon = ArgValue.rfind(':');
129 if (SecondColon == std::string::npos) {
130 std::fprintf(stderr, "%s\n", ExpectedFormat);
131 return true;
132 }
133 char *EndPtr;
134 long Column
135 = std::strtol(ArgValue.c_str() + SecondColon + 1, &EndPtr, 10);
136 if (EndPtr != ArgValue.c_str() + ArgValue.size()) {
137 std::fprintf(stderr, "%s\n", ExpectedFormat);
138 return true;
139 }
140
141 std::string::size_type FirstColon = ArgValue.rfind(':', SecondColon-1);
142 if (SecondColon == std::string::npos) {
143 std::fprintf(stderr, "%s\n", ExpectedFormat);
144 return true;
145 }
146 long Line = std::strtol(ArgValue.c_str() + FirstColon + 1, &EndPtr, 10);
147 if (EndPtr != ArgValue.c_str() + SecondColon) {
148 std::fprintf(stderr, "%s\n", ExpectedFormat);
149 return true;
150 }
151
152 Val.FileName = ArgValue.substr(0, FirstColon);
153 Val.Line = Line;
154 Val.Column = Column;
155 return false;
156 }
157 }
158}
159
160//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000161// Global options.
162//===----------------------------------------------------------------------===//
163
Chris Lattnerefe33382009-02-18 01:51:21 +0000164/// ClangFrontendTimer - The front-end activities should charge time to it with
165/// TimeRegion. The -ftime-report option controls whether this will do
166/// anything.
167llvm::Timer *ClangFrontendTimer = 0;
168
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000169static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000170
Chris Lattner4b009652007-07-25 00:24:17 +0000171static llvm::cl::opt<bool>
172Verbose("v", llvm::cl::desc("Enable verbose output"));
173static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000174Stats("print-stats",
175 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-10-16 16:54:18 +0000176static llvm::cl::opt<bool>
177DisableFree("disable-free",
178 llvm::cl::desc("Disable freeing of memory on exit"),
179 llvm::cl::init(false));
Daniel Dunbarbb56def2009-04-27 21:19:07 +0000180static llvm::cl::opt<bool>
181EmptyInputOnly("empty-input-only",
182 llvm::cl::desc("Force running on an empty input file"));
Chris Lattner4b009652007-07-25 00:24:17 +0000183
184enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000185 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000186 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000187 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000188 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000189 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000190 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000191 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000192 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000193 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000194 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000195 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000196 ASTPrint, // Parse ASTs and print them.
197 ASTDump, // Parse ASTs and dump them.
Douglas Gregord7915fd2009-04-26 02:02:08 +0000198 ASTDumpFull, // Parse ASTs and dump them, including the
199 // contents of a PCH file.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000200 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000201 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000202 ParsePrintCallbacks, // Parse and print each callback.
203 ParseSyntaxOnly, // Parse and perform semantic analysis.
204 ParseNoop, // Parse with noop callbacks.
205 RunPreprocessorOnly, // Just lex, no output.
206 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000207 DumpTokens, // Dump out preprocessed tokens.
208 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000209 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000210 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000211 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000212 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000213};
214
215static llvm::cl::opt<ProgActions>
216ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
217 llvm::cl::init(ParseSyntaxOnly),
218 llvm::cl::values(
219 clEnumValN(RunPreprocessorOnly, "Eonly",
220 "Just run preprocessor, no output (for timings)"),
221 clEnumValN(PrintPreprocessedInput, "E",
222 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000223 clEnumValN(DumpRawTokens, "dump-raw-tokens",
224 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000225 clEnumValN(RunAnalysis, "analyze",
226 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000227 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000228 "Run preprocessor, dump internal rep of tokens"),
229 clEnumValN(ParseNoop, "parse-noop",
230 "Run parser with noop callbacks (for timings)"),
231 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
232 "Run parser and perform semantic analysis"),
233 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
234 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000235 clEnumValN(EmitHTML, "emit-html",
236 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000237 clEnumValN(ASTPrint, "ast-print",
238 "Build ASTs and then pretty-print them"),
239 clEnumValN(ASTDump, "ast-dump",
240 "Build ASTs and then debug dump them"),
Douglas Gregord7915fd2009-04-26 02:02:08 +0000241 clEnumValN(ASTDumpFull, "ast-dump-full",
242 "Build ASTs and then debug dump them, including PCH"),
Chris Lattner664dd082007-10-11 00:37:43 +0000243 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000244 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000245 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000246 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000247 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000248 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000249 clEnumValN(GeneratePCH, "emit-pch",
250 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000251 clEnumValN(EmitAssembly, "S",
252 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000253 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000254 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000255 clEnumValN(EmitBC, "emit-llvm-bc",
256 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000257 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
258 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000259 clEnumValN(RewriteTest, "rewrite-test",
260 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000261 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000262 "Rewrite ObjC into C (code rewriter example)"),
263 clEnumValN(RewriteMacros, "rewrite-macros",
264 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000265 clEnumValN(RewriteBlocks, "rewrite-blocks",
266 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000267 clEnumValN(FixIt, "fixit",
268 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000269 clEnumValEnd));
270
Ted Kremenekd01eae62007-12-19 19:47:59 +0000271
272static llvm::cl::opt<std::string>
273OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000274 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000275 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000276
Ted Kremenek57f25b22008-12-02 19:57:31 +0000277
278//===----------------------------------------------------------------------===//
279// PTH.
280//===----------------------------------------------------------------------===//
281
282static llvm::cl::opt<std::string>
283TokenCache("token-cache", llvm::cl::value_desc("path"),
284 llvm::cl::desc("Use specified token cache file"));
285
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000286//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000287// Diagnostic Options
288//===----------------------------------------------------------------------===//
289
Ted Kremenek10389cf2007-09-26 19:42:19 +0000290static llvm::cl::opt<bool>
291VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000292 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000293
Ted Kremenekfd75e312008-03-27 06:17:42 +0000294static llvm::cl::opt<std::string>
295HTMLDiag("html-diags",
296 llvm::cl::desc("Generate HTML to report diagnostics"),
297 llvm::cl::value_desc("HTML directory"));
298
Nico Weber0e13eaa2008-08-05 23:33:20 +0000299static llvm::cl::opt<bool>
300NoShowColumn("fno-show-column",
301 llvm::cl::desc("Do not include column number on diagnostics"));
302
303static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000304NoShowLocation("fno-show-source-location",
305 llvm::cl::desc("Do not include source location information with"
306 " diagnostics"));
307
308static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000309NoCaretDiagnostics("fno-caret-diagnostics",
310 llvm::cl::desc("Do not include source line and caret with"
311 " diagnostics"));
312
Chris Lattner695a4f52009-03-13 01:08:23 +0000313static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000314NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
315 llvm::cl::desc("Do not include fixit information in"
316 " diagnostics"));
317
318static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000319PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
320 llvm::cl::desc("Print source range spans in numeric form"));
321
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000322static llvm::cl::opt<bool>
323PrintDiagnosticOption("fdiagnostics-show-option",
324 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000325
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000326static llvm::cl::opt<unsigned>
327MessageLength("fmessage-length",
328 llvm::cl::desc("Format message diagnostics so that they fit "
329 "within N columns or fewer, when possible."),
330 llvm::cl::value_desc("N"));
331
Chris Lattner4b009652007-07-25 00:24:17 +0000332//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000333// C++ Visualization.
334//===----------------------------------------------------------------------===//
335
336static llvm::cl::opt<std::string>
337InheritanceViewCls("cxx-inheritance-view",
338 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000339 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000340
341//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000342// Builtin Options
343//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000344
345static llvm::cl::opt<bool>
346TimeReport("ftime-report",
347 llvm::cl::desc("Print the amount of time each "
348 "phase of compilation takes"));
349
Douglas Gregor23d23262009-02-14 20:49:29 +0000350static llvm::cl::opt<bool>
351Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000352 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000353 "freestanding environment"));
354
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000355static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000356AllowBuiltins("fbuiltin", llvm::cl::init(true),
357 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000358
359
360static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000361MathErrno("fmath-errno", llvm::cl::init(true),
362 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000363
Douglas Gregor23d23262009-02-14 20:49:29 +0000364//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000365// Language Options
366//===----------------------------------------------------------------------===//
367
368enum LangKind {
369 langkind_unspecified,
370 langkind_c,
371 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000372 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000373 langkind_cxx,
374 langkind_cxx_cpp,
375 langkind_objc,
376 langkind_objc_cpp,
377 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000378 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000379};
380
Chris Lattner4b009652007-07-25 00:24:17 +0000381static llvm::cl::opt<LangKind>
382BaseLang("x", llvm::cl::desc("Base language to compile"),
383 llvm::cl::init(langkind_unspecified),
384 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
385 clEnumValN(langkind_cxx, "c++", "C++"),
386 clEnumValN(langkind_objc, "objective-c", "Objective C"),
387 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000388 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000389 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000390 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
391 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000392 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000393 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000394 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
395 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000396 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000397 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000398 clEnumValN(langkind_c, "c-header",
399 "C header"),
400 clEnumValN(langkind_objc, "objective-c-header",
401 "Objective-C header"),
402 clEnumValN(langkind_cxx, "c++-header",
403 "C++ header"),
404 clEnumValN(langkind_objcxx, "objective-c++-header",
405 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000406 clEnumValEnd));
407
408static llvm::cl::opt<bool>
409LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
410 llvm::cl::Hidden);
411static llvm::cl::opt<bool>
412LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
413 llvm::cl::Hidden);
414
Chris Lattnere1be6022009-04-14 23:22:57 +0000415static llvm::cl::opt<bool>
416ObjCExclusiveGC("fobjc-gc-only",
417 llvm::cl::desc("Use GC exclusively for Objective-C related "
418 "memory management"));
419
420static llvm::cl::opt<bool>
421ObjCEnableGC("fobjc-gc",
422 llvm::cl::desc("Enable Objective-C garbage collection"));
423
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000424static llvm::cl::opt<bool>
425ObjCEnableGCBitmapPrint("print-ivar-layout",
426 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
427
Chris Lattnere1be6022009-04-14 23:22:57 +0000428static llvm::cl::opt<LangOptions::VisibilityMode>
429SymbolVisibility("fvisibility",
430 llvm::cl::desc("Set the default symbol visibility:"),
431 llvm::cl::init(LangOptions::Default),
432 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
433 "Use default symbol visibility"),
434 clEnumValN(LangOptions::Hidden, "hidden",
435 "Use hidden symbol visibility"),
436 clEnumValN(LangOptions::Protected,"protected",
437 "Use protected symbol visibility"),
438 clEnumValEnd));
439
440static llvm::cl::opt<bool>
441OverflowChecking("ftrapv",
442 llvm::cl::desc("Trap on integer overflow"),
443 llvm::cl::init(false));
444
445
Ted Kremenek11ad8952007-12-05 23:49:08 +0000446/// InitializeBaseLanguage - Handle the -x foo options.
447static void InitializeBaseLanguage() {
448 if (LangObjC)
449 BaseLang = langkind_objc;
450 else if (LangObjCXX)
451 BaseLang = langkind_objcxx;
452}
453
454static LangKind GetLanguage(const std::string &Filename) {
455 if (BaseLang != langkind_unspecified)
456 return BaseLang;
457
458 std::string::size_type DotPos = Filename.rfind('.');
459
460 if (DotPos == std::string::npos) {
461 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000462 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000463 }
464
Ted Kremenek11ad8952007-12-05 23:49:08 +0000465 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
466 // C header: .h
467 // C++ header: .hh or .H;
468 // assembler no preprocessing: .s
469 // assembler: .S
470 if (Ext == "c")
471 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000472 else if (Ext == "S" ||
473 // If the compiler is run on a .s file, preprocess it as .S
474 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000475 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000476 else if (Ext == "i")
477 return langkind_c_cpp;
478 else if (Ext == "ii")
479 return langkind_cxx_cpp;
480 else if (Ext == "m")
481 return langkind_objc;
482 else if (Ext == "mi")
483 return langkind_objc_cpp;
484 else if (Ext == "mm" || Ext == "M")
485 return langkind_objcxx;
486 else if (Ext == "mii")
487 return langkind_objcxx_cpp;
488 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
489 Ext == "c++" || Ext == "cp" || Ext == "cxx")
490 return langkind_cxx;
491 else
492 return langkind_c;
493}
494
495
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000496static void InitializeCOptions(LangOptions &Options) {
497 // Do nothing.
498}
499
500static void InitializeObjCOptions(LangOptions &Options) {
501 Options.ObjC1 = Options.ObjC2 = 1;
502}
503
504
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000505static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000506 // FIXME: implement -fpreprocessed mode.
507 bool NoPreprocess = false;
508
Ted Kremenek11ad8952007-12-05 23:49:08 +0000509 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000510 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000511 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000512 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000513 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000514 case langkind_c_cpp:
515 NoPreprocess = true;
516 // FALLTHROUGH
517 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000518 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000519 break;
520 case langkind_cxx_cpp:
521 NoPreprocess = true;
522 // FALLTHROUGH
523 case langkind_cxx:
524 Options.CPlusPlus = 1;
525 break;
526 case langkind_objc_cpp:
527 NoPreprocess = true;
528 // FALLTHROUGH
529 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000530 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000531 break;
532 case langkind_objcxx_cpp:
533 NoPreprocess = true;
534 // FALLTHROUGH
535 case langkind_objcxx:
536 Options.ObjC1 = Options.ObjC2 = 1;
537 Options.CPlusPlus = 1;
538 break;
539 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000540
541 if (ObjCExclusiveGC)
542 Options.setGCMode(LangOptions::GCOnly);
543 else if (ObjCEnableGC)
544 Options.setGCMode(LangOptions::HybridGC);
545
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000546 if (ObjCEnableGCBitmapPrint)
547 Options.ObjCGCBitmapPrint = 1;
548
Chris Lattnere1be6022009-04-14 23:22:57 +0000549 Options.setVisibilityMode(SymbolVisibility);
550 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000551}
552
553/// LangStds - Language standards we support.
554enum LangStds {
555 lang_unspecified,
556 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000557 lang_gnu_START,
558 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000559 lang_cxx98, lang_gnucxx98,
560 lang_cxx0x, lang_gnucxx0x
561};
562
563static llvm::cl::opt<LangStds>
564LangStd("std", llvm::cl::desc("Language standard to compile for"),
565 llvm::cl::init(lang_unspecified),
566 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
567 clEnumValN(lang_c89, "c90", "ISO C 1990"),
568 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
569 clEnumValN(lang_c94, "iso9899:199409",
570 "ISO C 1990 with amendment 1"),
571 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000572 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000573 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000574 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000575 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000576 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000577 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000578 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000579 clEnumValN(lang_gnu99, "gnu9x",
580 "ISO C 1999 with GNU extensions"),
581 clEnumValN(lang_cxx98, "c++98",
582 "ISO C++ 1998 with amendments"),
583 clEnumValN(lang_gnucxx98, "gnu++98",
584 "ISO C++ 1998 with amendments and GNU "
585 "extensions (default for C++)"),
586 clEnumValN(lang_cxx0x, "c++0x",
587 "Upcoming ISO C++ 200x with amendments"),
588 clEnumValN(lang_gnucxx0x, "gnu++0x",
589 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000590 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000591 clEnumValEnd));
592
593static llvm::cl::opt<bool>
594NoOperatorNames("fno-operator-names",
595 llvm::cl::desc("Do not treat C++ operator name keywords as "
596 "synonyms for operators"));
597
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000598static llvm::cl::opt<bool>
599PascalStrings("fpascal-strings",
600 llvm::cl::desc("Recognize and construct Pascal-style "
601 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000602
603static llvm::cl::opt<bool>
604MSExtensions("fms-extensions",
605 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000606 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000607
608static llvm::cl::opt<bool>
609WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000610 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000611
612static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000613NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000614 llvm::cl::desc("Disallow implicit conversions between "
615 "vectors with a different number of "
616 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000617
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000618static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000619EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000620
621static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000622EnableHeinousExtensions("fheinous-gnu-extensions",
623 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
624 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
625
626static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000627ObjCNonFragileABI("fobjc-nonfragile-abi",
628 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000629
Daniel Dunbar5523e862009-05-04 05:16:21 +0000630
631static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000632EmitAllDecls("femit-all-decls",
633 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000634
Daniel Dunbar91692d92008-08-11 17:36:14 +0000635static llvm::cl::opt<bool>
636Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000637 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000638
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000639static llvm::cl::opt<bool>
640GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000641 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000642 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000643
644static llvm::cl::opt<bool>
645NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000646 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000647 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000648
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000649
650
651static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000652Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000653
Douglas Gregor375733c2009-03-10 00:06:19 +0000654static llvm::cl::opt<unsigned>
655TemplateDepth("ftemplate-depth", llvm::cl::init(99),
656 llvm::cl::desc("Maximum depth of recursive template "
657 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000658static llvm::cl::opt<bool>
659DollarsInIdents("fdollars-in-identifiers",
660 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000661
Anders Carlssondfd77642009-04-06 17:37:10 +0000662
663static llvm::cl::opt<bool>
664OptSize("Os", llvm::cl::desc("Optimize for size"));
665
666static llvm::cl::opt<bool>
667NoCommon("fno-common",
668 llvm::cl::desc("Compile common globals like normal definitions"),
669 llvm::cl::ValueDisallowed);
670
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000671static llvm::cl::opt<std::string>
672MainFileName("main-file-name",
673 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000674
Anders Carlssonf2310142009-05-13 19:49:53 +0000675// FIXME: Also add an "-fno-access-control" option.
676static llvm::cl::opt<bool>
677AccessControl("faccess-control",
678 llvm::cl::desc("Enable C++ access control"));
679
Anders Carlssondfd77642009-04-06 17:37:10 +0000680// It might be nice to add bounds to the CommandLine library directly.
681struct OptLevelParser : public llvm::cl::parser<unsigned> {
682 bool parse(llvm::cl::Option &O, const char *ArgName,
683 const std::string &Arg, unsigned &Val) {
684 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
685 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000686 if (Val > 3)
687 return O.error(": '" + Arg + "' invalid optimization level!");
688 return false;
689 }
690};
691static llvm::cl::opt<unsigned, false, OptLevelParser>
692OptLevel("O", llvm::cl::Prefix,
693 llvm::cl::desc("Optimization level"),
694 llvm::cl::init(0));
695
Daniel Dunbare079c712009-04-08 03:03:23 +0000696static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000697PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
698
699static llvm::cl::opt<bool>
700StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000701
Daniel Dunbar34542952008-08-23 08:43:39 +0000702static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000703 TargetInfo *Target,
704 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000705 // Allow the target to set the default the langauge options as it sees fit.
706 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000707
708 // Pass the map of target features to the target for validation and
709 // processing.
710 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000711
Chris Lattner4b009652007-07-25 00:24:17 +0000712 if (LangStd == lang_unspecified) {
713 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000714 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000715 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000716 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000717 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +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.
737 case lang_gnucxx0x:
738 case lang_cxx0x:
739 Options.CPlusPlus0x = 1;
740 // FALL THROUGH
741 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:
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner0297c762008-02-25 04:01:39 +0000755 Options.Digraphs = 1; // C94, C99, C++.
756 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000757 case lang_c89:
758 break;
759 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000760
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000761 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
762 Options.GNUMode = LangStd >= lang_gnu_START;
763
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000764 if (Options.CPlusPlus) {
765 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000766 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000767 }
Chris Lattner4b009652007-07-25 00:24:17 +0000768
Chris Lattner6ab935b2008-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 Kremenek88bec0f2008-09-03 21:22:16 +0000773
Daniel Dunbarfacf3512009-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 Lattner31e7f6f2009-03-20 15:44:26 +0000776 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000777 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000778 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000779
Chris Lattner58d5ba52008-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 Carlsson8ffcf732009-01-21 18:47:36 +0000783 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000784 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000785 Options.Blocks = 0;
786
Chris Lattner284784c2009-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 Lattner77c04832009-04-19 07:00:02 +0000792 Options.DollarIdents = DollarsInIdents;
793
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000794 if (PascalStrings.getPosition())
795 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000796 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000797 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000798 if (NoLaxVectorConversions.getPosition())
799 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000800 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000801 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000802 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000803
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000804 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000805 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000806 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000807 Options.Freestanding = Options.NoBuiltin = 1;
808
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000809 if (EnableHeinousExtensions)
810 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000811
Anders Carlssonf2310142009-05-13 19:49:53 +0000812 if (AccessControl)
813 Options.AccessControl = 1;
814
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000815 Options.MathErrno = MathErrno;
816
Douglas Gregor375733c2009-03-10 00:06:19 +0000817 Options.InstantiationDepth = TemplateDepth;
818
Chris Lattnerddae7102008-12-04 22:54:33 +0000819 // Override the default runtime if the user requested it.
820 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000821 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000822 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000823 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000824
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000825 if (ObjCNonFragileABI)
826 Options.ObjCNonFragileABI = 1;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000827
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000828 if (EmitAllDecls)
829 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000830
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000831 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
832 // support.
833 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000834
835 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000836 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000837 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000838
839 assert(PICLevel <= 2 && "Invalid value for -pic-level");
840 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000841
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000842 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000843 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000844 Options.NoInline = !OptSize && !OptLevel;
845
846 Options.Static = StaticDefine;
847
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000848 if (MainFileName.getPosition())
849 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000850}
851
852//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000853// Target Triple Processing.
854//===----------------------------------------------------------------------===//
855
856static llvm::cl::opt<std::string>
857TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000858 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000859
Chris Lattnerfc457002008-03-05 01:18:20 +0000860static llvm::cl::opt<std::string>
Sanjiv Gupta69683532008-05-08 08:28:14 +0000861Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000862
Chris Lattner2b168e02008-09-30 01:13:12 +0000863static llvm::cl::opt<std::string>
864MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000865 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000866
Chris Lattner01de9c82008-09-30 20:16:56 +0000867// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
868// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000869
870// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000871static void HandleMacOSVersionMin(std::string &Triple) {
872 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
873 if (DarwinDashIdx == std::string::npos) {
874 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000875 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000876 exit(1);
877 }
878 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
879
Chris Lattner01de9c82008-09-30 20:16:56 +0000880 // Remove the number.
881 Triple.resize(DarwinNumIdx);
882
883 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
884 bool MacOSVersionMinIsInvalid = false;
885 int VersionNum = 0;
886 if (MacOSVersionMin.size() < 4 ||
887 MacOSVersionMin.substr(0, 3) != "10." ||
888 !isdigit(MacOSVersionMin[3])) {
889 MacOSVersionMinIsInvalid = true;
890 } else {
891 const char *Start = MacOSVersionMin.c_str()+3;
892 char *End = 0;
893 VersionNum = (int)strtol(Start, &End, 10);
894
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000895 // The version number must be in the range 0-9.
896 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
897
Chris Lattner01de9c82008-09-30 20:16:56 +0000898 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
899 Triple += llvm::itostr(VersionNum+4);
900
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000901 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
902 // Add the period piece (.7) to the end of the triple. This gives us
903 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000904 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000905 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
906 MacOSVersionMinIsInvalid = true;
907 }
908 }
909
910 if (MacOSVersionMinIsInvalid) {
911 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000912 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000913 MacOSVersionMin.c_str());
914 exit(1);
915 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000916 else if (VersionNum <= 4 &&
917 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
918 fprintf(stderr,
919 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
920 MacOSVersionMin.c_str());
921 exit(1);
922 }
923
Chris Lattner01de9c82008-09-30 20:16:56 +0000924}
925
Daniel Dunbar93f64532009-04-10 19:52:24 +0000926static llvm::cl::opt<std::string>
927IPhoneOSVersionMin("miphoneos-version-min",
928 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
929
930// If -miphoneos-version-min=2.2 is specified, change the triple from being
931// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
932// 9 as the default major Darwin number, and encode the iPhone OS version
933// number in the minor version and revision.
934
935// FIXME: We should have the driver do this instead.
936static void HandleIPhoneOSVersionMin(std::string &Triple) {
937 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
938 if (DarwinDashIdx == std::string::npos) {
939 fprintf(stderr,
940 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
941 exit(1);
942 }
943 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
944
945 // Remove the number.
946 Triple.resize(DarwinNumIdx);
947
948 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
949 bool IPhoneOSVersionMinIsInvalid = false;
950 int VersionNum = 0;
951 if (IPhoneOSVersionMin.size() < 3 ||
952 !isdigit(IPhoneOSVersionMin[0])) {
953 IPhoneOSVersionMinIsInvalid = true;
954 } else {
955 const char *Start = IPhoneOSVersionMin.c_str();
956 char *End = 0;
957 VersionNum = (int)strtol(Start, &End, 10);
958
959 // The version number must be in the range 0-9.
960 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
961
962 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
963 Triple += "9." + llvm::itostr(VersionNum);
964
965 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
966 // Add the period piece (.2) to the end of the triple. This gives us
967 // something like ...-darwin9.2.2
968 Triple += End;
969 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
970 IPhoneOSVersionMinIsInvalid = true;
971 }
972 }
973
974 if (IPhoneOSVersionMinIsInvalid) {
975 fprintf(stderr,
976 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
977 IPhoneOSVersionMin.c_str());
978 exit(1);
979 }
980}
981
Chris Lattner01de9c82008-09-30 20:16:56 +0000982/// CreateTargetTriple - Process the various options that affect the target
983/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000984static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000985 // Initialize base triple. If a -triple option has been specified, use
986 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000987 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000988 if (Triple.empty())
989 Triple = llvm::sys::getHostTriple();
Ted Kremenek40499482007-12-03 22:06:55 +0000990
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000991 // If -arch foo was specified, remove the architecture from the triple we have
992 // so far and replace it with the specified one.
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000993
994 // FIXME: -arch should be removed, the driver should handle this.
Chris Lattner2b168e02008-09-30 01:13:12 +0000995 if (!Arch.empty()) {
996 // Decompose the base triple into "arch" and suffix.
997 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000998
Chris Lattner2b168e02008-09-30 01:13:12 +0000999 if (FirstDashIdx == std::string::npos) {
1000 fprintf(stderr,
1001 "Malformed target triple: \"%s\" ('-' could not be found).\n",
1002 Triple.c_str());
1003 exit(1);
1004 }
Chris Lattnerf6cde9f2009-03-24 16:18:41 +00001005
1006 // Canonicalize -arch ppc to add "powerpc" to the triple, not ppc.
1007 if (Arch == "ppc")
1008 Arch = "powerpc";
1009 else if (Arch == "ppc64")
1010 Arch = "powerpc64";
Ted Kremenek40499482007-12-03 22:06:55 +00001011
Chris Lattner2b168e02008-09-30 01:13:12 +00001012 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
1013 }
1014
1015 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1016 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001017 if (!MacOSVersionMin.empty())
1018 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001019 else if (!IPhoneOSVersionMin.empty())
1020 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001021
Chris Lattner2b168e02008-09-30 01:13:12 +00001022 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001023}
1024
1025//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001026// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001027//===----------------------------------------------------------------------===//
1028
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001029static bool InitializeSourceManager(Preprocessor &PP,
1030 const std::string &InFile) {
1031 // Figure out where to get and map in the main file.
1032 SourceManager &SourceMgr = PP.getSourceManager();
1033 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001034
1035 if (EmptyInputOnly) {
1036 const char *EmptyStr = "";
1037 llvm::MemoryBuffer *SB =
1038 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1039 SourceMgr.createMainFileIDForMemBuffer(SB);
1040 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001041 const FileEntry *File = FileMgr.getFile(InFile);
1042 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1043 if (SourceMgr.getMainFileID().isInvalid()) {
1044 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1045 << InFile.c_str();
1046 return true;
1047 }
1048 } else {
1049 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1050
1051 // If stdin was empty, SB is null. Cons up an empty memory
1052 // buffer now.
1053 if (!SB) {
1054 const char *EmptyStr = "";
1055 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1056 }
1057
1058 SourceMgr.createMainFileIDForMemBuffer(SB);
1059 if (SourceMgr.getMainFileID().isInvalid()) {
1060 PP.getDiagnostics().Report(FullSourceLoc(),
1061 diag::err_fe_error_reading_stdin);
1062 return true;
1063 }
1064 }
1065
1066 return false;
1067}
1068
Chris Lattner47b6a162008-04-19 23:09:31 +00001069
Chris Lattner94269d72009-04-21 05:40:52 +00001070//===----------------------------------------------------------------------===//
1071// Preprocessor Initialization
1072//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001073
Chris Lattner94269d72009-04-21 05:40:52 +00001074// FIXME: Preprocessor builtins to support.
1075// -A... - Play with #assertions
1076// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001077
Chris Lattner94269d72009-04-21 05:40:52 +00001078static llvm::cl::list<std::string>
1079D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1080 llvm::cl::desc("Predefine the specified macro"));
1081static llvm::cl::list<std::string>
1082U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1083 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001084
Chris Lattner94269d72009-04-21 05:40:52 +00001085static llvm::cl::list<std::string>
1086ImplicitIncludes("include", llvm::cl::value_desc("file"),
1087 llvm::cl::desc("Include file before parsing"));
1088static llvm::cl::list<std::string>
1089ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1090 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001091
Chris Lattner94269d72009-04-21 05:40:52 +00001092static llvm::cl::opt<std::string>
1093ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1094 llvm::cl::desc("Include precompiled header file"));
1095
1096static llvm::cl::opt<std::string>
1097ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1098 llvm::cl::desc("Include file before parsing"));
1099
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbarf1c39f02009-05-06 03:48:17 +00001109// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001110// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001111//
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerae3dcc02007-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
Chris Lattner4b009652007-07-25 00:24:17 +00001149// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001150
Chris Lattner4b009652007-07-25 00:24:17 +00001151/// InitializeIncludePaths - Process the -I options and set them in the
1152/// HeaderSearch object.
Nico Weber770e3882008-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 Kremenekb4d41e12008-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 Weber770e3882008-08-22 09:25:22 +00001161 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001162 ++Iidx;
1163 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001164 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001165 ++Fidx;
1166 }
1167 }
Chris Lattner4b009652007-07-25 00:24:17 +00001168
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001169 // Consume what's left from whatever list was longer.
1170 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001171 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001172 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001173 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001174
1175 // Handle -idirafter... options.
1176 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001177 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1178 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001179
1180 // Handle -iquote... options.
1181 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001182 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001183
1184 // Handle -isystem... options.
1185 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001186 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +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 Weber770e3882008-08-22 09:25:22 +00001214 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1215 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001216 ++iwithprefix_idx;
1217 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1218 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001219 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1220 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001221 ++iwithprefixbefore_idx;
1222 iwithprefixbefore_done =
1223 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1224 }
1225 }
1226 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001227
Nico Weber770e3882008-08-22 09:25:22 +00001228 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001229
Daniel Dunbar4e604292009-02-21 20:52:41 +00001230 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001231 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001232 llvm::sys::Path::GetMainExecutable(Argv0,
1233 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-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 Dunbar4e604292009-02-21 20:52:41 +00001237
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001238 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001239 MainExecutablePath.appendComponent("lib");
1240 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001241 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001242 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-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 Lattner3ee4a2f2008-03-03 03:16:03 +00001248 }
1249
Nico Weber770e3882008-08-22 09:25:22 +00001250 if (!nostdinc)
1251 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +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 Weber770e3882008-08-22 09:25:22 +00001256 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001257}
1258
Chris Lattner94269d72009-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 Gregoreccf0d12009-05-12 01:31:05 +00001276 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1277 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner94269d72009-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 Gregoreccf0d12009-05-12 01:31:05 +00001285 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1286 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1287 &ImplicitIncludePCH));
Chris Lattner94269d72009-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 Gregoreccf0d12009-05-12 01:31:05 +00001301 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner94269d72009-04-21 05:40:52 +00001302 InitOpts.addInclude(*Ptr, true);
Douglas Gregoreccf0d12009-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 Lattner94269d72009-04-21 05:40:52 +00001313 }
1314 }
1315 }
1316}
1317
Ted Kremenek01d3bf72008-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 Kremenek4e9899f2008-04-17 22:31:54 +00001329
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001330public:
Eli Friedmane934dca2009-05-18 07:39:39 +00001331 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001332 TargetInfo &target, SourceManager &SM,
1333 HeaderSearch &Headers)
Eli Friedmane934dca2009-05-18 07:39:39 +00001334 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001335 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001336
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001337
1338 virtual ~DriverPreprocessorFactory() {}
1339
1340 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001341 llvm::OwningPtr<PTHManager> PTHMgr;
1342
Ted Kremenek2ee90d52009-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 Kremenek6348cc62009-03-22 06:42:39 +00001346 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001347 }
1348
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001349 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001350 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1351 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001352 PTHMgr.reset(PTHManager::Create(x, &Diags,
1353 TokenCache.empty() ? Diagnostic::Error
1354 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001355 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001356
Ted Kremenek6348cc62009-03-22 06:42:39 +00001357 if (Diags.hasErrorOccurred())
1358 exit(1);
1359
Ted Kremenekd976c3d2009-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 Gregorab1cef72009-04-10 03:52:48 +00001372
Chris Lattner94269d72009-04-21 05:40:52 +00001373 PreprocessorInitOptions InitOpts;
1374 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmane934dca2009-05-18 07:39:39 +00001375 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001376 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001377
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001378 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001379 }
1380};
1381}
Chris Lattner4b009652007-07-25 00:24:17 +00001382
Chris Lattner4b009652007-07-25 00:24:17 +00001383//===----------------------------------------------------------------------===//
1384// Basic Parser driver
1385//===----------------------------------------------------------------------===//
1386
Chris Lattner9d818a22008-04-19 23:25:44 +00001387static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001388 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001389 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001390
1391 // Parsing the specified input file.
1392 P.ParseTranslationUnit();
1393 delete PA;
1394}
1395
1396//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001397// Code generation options
1398//===----------------------------------------------------------------------===//
1399
1400static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001401GenerateDebugInfo("g",
1402 llvm::cl::desc("Generate source level debug information"));
1403
Daniel Dunbar9101a632009-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 Dunbar07181d72009-05-06 03:16:41 +00001408static llvm::cl::list<std::string>
1409TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1410
1411/// ComputeTargetFeatures - Recompute the target feature list to only
1412/// be the list of things that are enabled, based on the target cpu
1413/// and feature list.
1414static void ComputeFeatureMap(TargetInfo *Target,
1415 llvm::StringMap<bool> &Features) {
1416 assert(Features.empty() && "invalid map");
1417
1418 // Initialize the feature map based on the target.
1419 Target->getDefaultFeatures(TargetCPU, Features);
1420
1421 // Apply the user specified deltas.
1422 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1423 ie = TargetFeatures.end(); it != ie; ++it) {
1424 const char *Name = it->c_str();
1425
1426 // FIXME: Don't handle errors like this.
1427 if (Name[0] != '-' && Name[0] != '+') {
1428 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1429 Name);
1430 exit(1);
1431 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001432 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1433 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1434 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001435 exit(1);
1436 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001437 }
1438}
1439
Chris Lattner8a9615c2009-03-16 18:41:18 +00001440static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001441 const LangOptions &LangOpts,
1442 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001443 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001444 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001445 if (OptSize) {
1446 // -Os implies -O2
1447 // FIXME: Diagnose conflicting options.
1448 Opts.OptimizationLevel = 2;
1449 } else {
1450 Opts.OptimizationLevel = OptLevel;
1451 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001452
1453 // FIXME: There are llvm-gcc options to control these selectively.
1454 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1455 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001456 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001457
1458#ifdef NDEBUG
1459 Opts.VerifyModule = 0;
1460#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001461
1462 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001463 Opts.Features.clear();
1464 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1465 ie = Features.end(); it != ie; ++it) {
1466 // FIXME: If we are completely confident that we have the right
1467 // set, we only need to pass the minuses.
1468 std::string Name(it->second ? "+" : "-");
1469 Name += it->first();
1470 Opts.Features.push_back(Name);
1471 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001472
Chris Lattnerf04a7562009-03-26 05:00:52 +00001473 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1474
Chris Lattnere8f70712009-02-18 01:23:44 +00001475 // Handle -ftime-report.
1476 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001477}
1478
1479//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001480// Fix-It Options
1481//===----------------------------------------------------------------------===//
1482static llvm::cl::list<ParsedSourceLocation>
1483FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1484 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1485
1486//===----------------------------------------------------------------------===//
Eli Friedman35ba7a62009-05-18 22:39:16 +00001487// ObjC Rewriter Options
1488//===----------------------------------------------------------------------===//
1489static llvm::cl::opt<bool>
1490SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1491 llvm::cl::desc("Silence ObjC rewriting warnings"));
1492
1493//===----------------------------------------------------------------------===//
Eli Friedman4d03d382009-05-19 01:17:04 +00001494// Warning Options
1495//===----------------------------------------------------------------------===//
1496
1497// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1498// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1499// -Wextra, so we don't need to worry about it.
1500static llvm::cl::list<std::string>
1501OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1502
1503static llvm::cl::opt<bool> OptPedantic("pedantic");
1504static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1505static llvm::cl::opt<bool> OptNoWarnings("w");
1506
1507//===----------------------------------------------------------------------===//
Eli Friedmane2554252009-05-19 03:06:47 +00001508// Preprocessing (-E mode) Options
1509//===----------------------------------------------------------------------===//
1510static llvm::cl::opt<bool>
1511DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1512static llvm::cl::opt<bool>
1513EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1514static llvm::cl::opt<bool>
1515EnableMacroCommentOutput("CC",
1516 llvm::cl::desc("Enable comment output in -E mode, "
1517 "even from macro expansions"));
1518static llvm::cl::opt<bool>
1519DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1520 " normal output"));
1521static llvm::cl::opt<bool>
1522DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1523 "addition to normal output"));
Eli Friedmane595fe92009-05-19 03:35:57 +00001524
1525//===----------------------------------------------------------------------===//
1526// Dependency file options
1527//===----------------------------------------------------------------------===//
1528static llvm::cl::opt<std::string>
1529DependencyFile("dependency-file",
1530 llvm::cl::desc("Filename (or -) to write dependency output to"));
1531
1532static llvm::cl::opt<bool>
1533DependenciesIncludeSystemHeaders("sys-header-deps",
1534 llvm::cl::desc("Include system headers in dependency output"));
1535
1536static llvm::cl::list<std::string>
1537DependencyTargets("MT",
1538 llvm::cl::desc("Specify target for dependency"));
1539
1540// FIXME: Implement feature
1541static llvm::cl::opt<bool>
1542PhonyDependencyTarget("MP",
1543 llvm::cl::desc("Create phony target for each dependency "
1544 "(other than main file)"));
1545
Eli Friedmane2554252009-05-19 03:06:47 +00001546//===----------------------------------------------------------------------===//
Eli Friedman78a57622009-05-19 10:18:02 +00001547// Analysis options
1548//===----------------------------------------------------------------------===//
1549
1550static llvm::cl::list<Analyses>
1551AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1552llvm::cl::values(
1553#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1554clEnumValN(NAME, CMDFLAG, DESC),
1555#include "Analyses.def"
1556clEnumValEnd));
1557
1558static llvm::cl::opt<AnalysisStores>
1559AnalysisStoreOpt("analyzer-store",
1560 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1561 llvm::cl::init(BasicStoreModel),
1562 llvm::cl::values(
1563#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1564clEnumValN(NAME##Model, CMDFLAG, DESC),
1565#include "Analyses.def"
1566clEnumValEnd));
1567
1568static llvm::cl::opt<AnalysisConstraints>
1569AnalysisConstraintsOpt("analyzer-constraints",
1570 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1571 llvm::cl::init(RangeConstraintsModel),
1572 llvm::cl::values(
1573#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1574clEnumValN(NAME##Model, CMDFLAG, DESC),
1575#include "Analyses.def"
1576clEnumValEnd));
1577
1578static llvm::cl::opt<AnalysisDiagClients>
1579AnalysisDiagOpt("analyzer-output",
1580 llvm::cl::desc("Source Code Analysis - Output Options"),
1581 llvm::cl::init(PD_HTML),
1582 llvm::cl::values(
1583#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1584clEnumValN(PD_##NAME, CMDFLAG, DESC),
1585#include "Analyses.def"
1586clEnumValEnd));
1587
1588static llvm::cl::opt<bool>
1589VisualizeEGDot("analyzer-viz-egraph-graphviz",
1590 llvm::cl::desc("Display exploded graph using GraphViz"));
1591
1592static llvm::cl::opt<bool>
1593VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1594 llvm::cl::desc("Display exploded graph using Ubigraph"));
1595
1596static llvm::cl::opt<bool>
1597AnalyzeAll("analyzer-opt-analyze-headers",
1598 llvm::cl::desc("Force the static analyzer to analyze "
1599 "functions defined in header files"));
1600
1601static llvm::cl::opt<bool>
1602AnalyzerDisplayProgress("analyzer-display-progress",
1603 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1604
1605static llvm::cl::opt<bool>
1606PurgeDead("analyzer-purge-dead",
1607 llvm::cl::init(true),
1608 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1609 " processing a statement."));
1610
1611static llvm::cl::opt<bool>
1612EagerlyAssume("analyzer-eagerly-assume",
1613 llvm::cl::init(false),
1614 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1615 "symbolic constraints."));
1616
1617static llvm::cl::opt<std::string>
1618AnalyzeSpecificFunction("analyze-function",
1619 llvm::cl::desc("Run analysis on specific function"));
1620
1621static llvm::cl::opt<bool>
1622TrimGraph("trim-egraph",
1623 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1624
1625static AnalyzerOptions ReadAnalyzerOptions() {
1626 AnalyzerOptions Opts;
1627 Opts.AnalysisList = AnalysisList;
1628 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1629 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1630 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1631 Opts.VisualizeEGDot = VisualizeEGDot;
1632 Opts.VisualizeEGUbi = VisualizeEGUbi;
1633 Opts.AnalyzeAll = AnalyzeAll;
1634 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1635 Opts.PurgeDead = PurgeDead;
1636 Opts.EagerlyAssume = EagerlyAssume;
1637 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1638 Opts.TrimGraph = TrimGraph;
1639 return Opts;
1640}
1641
1642//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001643// -dump-build-information Stuff
1644//===----------------------------------------------------------------------===//
1645
1646static llvm::cl::opt<std::string>
1647DumpBuildInformation("dump-build-information",
1648 llvm::cl::value_desc("filename"),
1649 llvm::cl::desc("output a dump of some build information to a file"));
1650
1651static llvm::raw_ostream *BuildLogFile = 0;
1652
1653/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1654/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1655namespace {
1656class LoggingDiagnosticClient : public DiagnosticClient {
1657 llvm::OwningPtr<DiagnosticClient> Chain1;
1658 llvm::OwningPtr<DiagnosticClient> Chain2;
1659public:
1660
1661 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1662 // Output diags both where requested...
1663 Chain1.reset(Normal);
1664 // .. and to our log file.
1665 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1666 !NoShowColumn,
1667 !NoCaretDiagnostics,
1668 !NoShowLocation,
1669 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001670 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001671 !NoDiagnosticsFixIt,
1672 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001673 }
1674
1675 virtual void setLangOptions(const LangOptions *LO) {
1676 Chain1->setLangOptions(LO);
1677 Chain2->setLangOptions(LO);
1678 }
1679
1680 virtual bool IncludeInDiagnosticCounts() const {
1681 return Chain1->IncludeInDiagnosticCounts();
1682 }
1683
1684 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1685 const DiagnosticInfo &Info) {
1686 Chain1->HandleDiagnostic(DiagLevel, Info);
1687 Chain2->HandleDiagnostic(DiagLevel, Info);
1688 }
1689};
1690} // end anonymous namespace.
1691
1692static void SetUpBuildDumpLog(unsigned argc, char **argv,
1693 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1694
1695 std::string ErrorInfo;
1696 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1697 ErrorInfo);
1698
1699 if (!ErrorInfo.empty()) {
1700 llvm::errs() << "error opening -dump-build-information file '"
1701 << DumpBuildInformation << "', option ignored!\n";
1702 delete BuildLogFile;
1703 BuildLogFile = 0;
1704 DumpBuildInformation = "";
1705 return;
1706 }
1707
1708 (*BuildLogFile) << "clang-cc command line arguments: ";
1709 for (unsigned i = 0; i != argc; ++i)
1710 (*BuildLogFile) << argv[i] << ' ';
1711 (*BuildLogFile) << '\n';
1712
1713 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1714 // the diagnostic producers and the normal receiver.
1715 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1716}
1717
1718
1719
1720//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001721// Main driver
1722//===----------------------------------------------------------------------===//
1723
Eli Friedmana9c310842009-05-18 22:20:00 +00001724static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1725 const char* Extension,
1726 bool Binary,
1727 llvm::sys::Path& OutPath) {
1728 llvm::raw_ostream* Ret;
1729 bool UseStdout = false;
1730 std::string OutFile;
1731 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1732 UseStdout = true;
1733 } else if (!OutputFile.empty()) {
1734 OutFile = OutputFile;
1735 } else if (Extension) {
1736 llvm::sys::Path Path(InFile);
1737 Path.eraseSuffix();
1738 Path.appendSuffix(Extension);
1739 OutFile = Path.toString();
1740 } else {
1741 UseStdout = true;
Chris Lattner7f902922009-02-18 01:20:05 +00001742 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001743
Eli Friedmana9c310842009-05-18 22:20:00 +00001744 if (UseStdout) {
1745 Ret = new llvm::raw_stdout_ostream();
1746 if (Binary)
1747 llvm::sys::Program::ChangeStdoutToBinary();
1748 } else {
1749 std::string Error;
1750 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1751 if (!Error.empty()) {
1752 // FIXME: Don't fail this way.
1753 llvm::cerr << "ERROR: " << Error << "\n";
1754 ::exit(1);
1755 }
1756 OutPath = OutFile;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001757 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001758
1759 return Ret;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001760}
1761
Chris Lattner4b009652007-07-25 00:24:17 +00001762/// ProcessInputFile - Process a single input file with the specified state.
1763///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001764static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001765 const std::string &InFile, ProgActions PA,
1766 const llvm::StringMap<bool> &Features) {
Eli Friedmana9c310842009-05-18 22:20:00 +00001767 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek50aab982008-08-08 02:46:37 +00001768 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001769 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001770 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001771 bool CompleteTranslationUnit = true;
Eli Friedmana9c310842009-05-18 22:20:00 +00001772 llvm::sys::Path OutPath;
Douglas Gregor133d2552009-04-02 01:08:08 +00001773
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001774 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001775 default:
Eli Friedmana9c310842009-05-18 22:20:00 +00001776 fprintf(stderr, "Unexpected program action!\n");
1777 HadErrors = true;
1778 return;
1779
1780 case ASTPrint:
1781 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1782 Consumer.reset(CreateASTPrinter(OS.get()));
1783 break;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001784
Eli Friedmana9c310842009-05-18 22:20:00 +00001785 case ASTDump:
1786 Consumer.reset(CreateASTDumper(false));
1787 break;
1788
1789 case ASTDumpFull:
1790 Consumer.reset(CreateASTDumper(true));
1791 break;
1792
1793 case ASTView:
1794 Consumer.reset(CreateASTViewer());
1795 break;
1796
1797 case PrintDeclContext:
1798 Consumer.reset(CreateDeclContextPrinter());
1799 break;
1800
1801 case EmitHTML:
1802 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1803 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1804 break;
1805
1806 case InheritanceView:
1807 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1808 break;
1809
1810 case EmitAssembly:
1811 case EmitLLVM:
1812 case EmitBC:
1813 case EmitLLVMOnly: {
1814 BackendAction Act;
1815 if (ProgAction == EmitAssembly) {
1816 Act = Backend_EmitAssembly;
1817 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1818 } else if (ProgAction == EmitLLVM) {
1819 Act = Backend_EmitLL;
1820 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1821 } else if (ProgAction == EmitLLVMOnly) {
1822 Act = Backend_EmitNothing;
1823 } else {
1824 Act = Backend_EmitBC;
1825 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001826 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001827
Eli Friedmana9c310842009-05-18 22:20:00 +00001828 CompileOptions Opts;
1829 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1830 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1831 PP.getLangOptions(), Opts, InFile,
1832 OS.get()));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001833 break;
Eli Friedmana9c310842009-05-18 22:20:00 +00001834 }
1835
1836 case GeneratePCH:
1837 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1838 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1839 CompleteTranslationUnit = false;
1840 break;
1841
1842 case RewriteObjC:
1843 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedman848763f2009-05-18 22:29:17 +00001844 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedman35ba7a62009-05-18 22:39:16 +00001845 PP.getLangOptions(),
1846 SilenceRewriteMacroWarning));
Eli Friedmana9c310842009-05-18 22:20:00 +00001847 break;
1848
1849 case RewriteBlocks:
1850 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1851 PP.getLangOptions()));
1852 break;
1853
Eli Friedman78a57622009-05-19 10:18:02 +00001854 case RunAnalysis: {
Eli Friedmana9c310842009-05-18 22:20:00 +00001855 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedman78a57622009-05-19 10:18:02 +00001856 PP.getLangOptions(), OutputFile,
1857 ReadAnalyzerOptions()));
Eli Friedmana9c310842009-05-18 22:20:00 +00001858 break;
Eli Friedman78a57622009-05-19 10:18:02 +00001859 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001860
Chris Lattneraf669fb2008-10-12 05:03:36 +00001861 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001862 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001863 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001864 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001865 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001866 RawLex.SetKeepWhitespaceMode(true);
1867
1868 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001869 RawLex.LexFromRawLexer(RawTok);
1870 while (RawTok.isNot(tok::eof)) {
1871 PP.DumpToken(RawTok, true);
1872 fprintf(stderr, "\n");
1873 RawLex.LexFromRawLexer(RawTok);
1874 }
1875 ClearSourceMgr = true;
1876 break;
1877 }
Chris Lattner4b009652007-07-25 00:24:17 +00001878 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001879 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001880 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001881 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001882 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001883 do {
1884 PP.Lex(Tok);
1885 PP.DumpToken(Tok, true);
1886 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001887 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001888 ClearSourceMgr = true;
1889 break;
1890 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001891 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001892 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001893
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001894 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001895 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001896 if (OutputFile.empty() || OutputFile == "-") {
1897 // FIXME: Don't fail this way.
1898 // FIXME: Verify that we can actually seek in the given file.
1899 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1900 ::exit(1);
1901 }
1902 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1903 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001904 ClearSourceMgr = true;
1905 break;
1906 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001907
Chris Lattner772a7c12009-04-27 22:02:30 +00001908 case PrintPreprocessedInput:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001909 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Chris Lattner4b009652007-07-25 00:24:17 +00001910 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001911
Chris Lattner270d29a2009-04-27 21:45:14 +00001912 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001913 break;
1914
Chris Lattnerefe33382009-02-18 01:51:21 +00001915 case ParsePrintCallbacks: {
1916 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001917 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1918 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattner4b009652007-07-25 00:24:17 +00001919 ClearSourceMgr = true;
1920 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001921 }
1922
1923 case ParseSyntaxOnly: { // -fsyntax-only
1924 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001925 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001926 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001927 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001928
1929 case RewriteMacros:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001930 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1931 RewriteMacrosInInput(PP, OS.get());
Chris Lattner1665a9f2008-05-08 06:52:13 +00001932 ClearSourceMgr = true;
1933 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001934
Eli Friedman4ae15b92009-05-19 01:02:07 +00001935 case RewriteTest:
1936 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1937 DoRewriteTest(PP, OS.get());
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001938 ClearSourceMgr = true;
1939 break;
Douglas Gregor133d2552009-04-02 01:08:08 +00001940
1941 case FixIt:
1942 llvm::TimeRegion Timer(ClangFrontendTimer);
1943 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001944 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001945 PP.getSourceManager(),
1946 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001947 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001948 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001949
Chris Lattner38a4f182009-04-27 21:25:27 +00001950 if (FixItAtLocations.size() > 0) {
1951 // Even without the "-fixit" flag, with may have some specific
1952 // locations where the user has requested fixes. Process those
1953 // locations now.
1954 if (!FixItRewrite)
1955 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1956 PP.getSourceManager(),
1957 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001958
Chris Lattner38a4f182009-04-27 21:25:27 +00001959 bool AddedFixitLocation = false;
1960 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1961 Idx != Last; ++Idx) {
1962 RequestedSourceLocation Requested;
1963 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1964 Requested)) {
1965 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1966 FixItAtLocations[Idx].FileName.c_str());
1967 } else {
1968 FixItRewrite->addFixItLocation(Requested);
1969 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001970 }
1971 }
1972
Chris Lattner38a4f182009-04-27 21:25:27 +00001973 if (!AddedFixitLocation) {
1974 // All of the fix-it locations were bad. Don't fix anything.
1975 delete FixItRewrite;
1976 FixItRewrite = 0;
1977 }
1978 }
1979
1980 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001981 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001982 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1983 PP.getSourceManager(),
1984 PP.getTargetInfo(),
1985 PP.getIdentifierTable(),
1986 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001987 /* FreeMemory = */ !DisableFree,
1988 /* size_reserve = */0,
1989 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00001990 llvm::OwningPtr<PCHReader> Reader;
1991 llvm::OwningPtr<ExternalASTSource> Source;
1992
Chris Lattner270d29a2009-04-27 21:45:14 +00001993 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001994 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1995
Chris Lattner270d29a2009-04-27 21:45:14 +00001996 // The user has asked us to include a precompiled header. Load
1997 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001998 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1999 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00002000 // Set the predefines buffer as suggested by the PCH
2001 // reader. Typically, the predefines buffer will be empty.
2002 PP.setPredefines(Reader->getSuggestedPredefines());
2003
Chris Lattner270d29a2009-04-27 21:45:14 +00002004 // Attach the PCH reader to the AST context as an external AST
2005 // source, so that declarations will be deserialized from the
2006 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00002007 if (ContextOwner) {
2008 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002009 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00002010 }
Chris Lattner270d29a2009-04-27 21:45:14 +00002011 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002012 }
2013
Chris Lattner270d29a2009-04-27 21:45:14 +00002014 case PCHReader::Failure:
2015 // Unrecoverable failure: don't even try to process the input
2016 // file.
2017 return;
2018
2019 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002020 // No suitable PCH file could be found. Return an error.
2021 return;
2022
2023#if 0
2024 // FIXME: We can recover from failed attempts to load PCH
2025 // files. This code will do so, if we ever want to enable it.
2026
Chris Lattner270d29a2009-04-27 21:45:14 +00002027 // We delayed the initialization of builtins in the hope of
2028 // loading the PCH file. Since the PCH file could not be
2029 // loaded, initialize builtins now.
2030 if (ContextOwner)
2031 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002032#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00002033 }
2034
2035 // Finish preprocessor initialization. We do this now (rather
2036 // than earlier) because this initialization creates new source
2037 // location entries in the source manager, which must come after
2038 // the source location entries for the PCH file.
2039 if (InitializeSourceManager(PP, InFile))
2040 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00002041 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002042
Chris Lattner270d29a2009-04-27 21:45:14 +00002043
2044 // If we have an ASTConsumer, run the parser with it.
2045 if (Consumer)
2046 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2047 CompleteTranslationUnit);
2048
2049 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2050 llvm::TimeRegion Timer(ClangFrontendTimer);
2051 Token Tok;
2052 // Start parsing the specified input file.
2053 PP.EnterMainSourceFile();
2054 do {
2055 PP.Lex(Tok);
2056 } while (Tok.isNot(tok::eof));
2057 ClearSourceMgr = true;
2058 } else if (PA == ParseNoop) { // -parse-noop
2059 llvm::TimeRegion Timer(ClangFrontendTimer);
2060 ParseFile(PP, new MinimalAction(PP));
2061 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00002062 } else if (PA == PrintPreprocessedInput){ // -E mode.
2063 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmane2554252009-05-19 03:06:47 +00002064 if (DumpMacros)
2065 DoPrintMacros(PP, OS.get());
2066 else
2067 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2068 EnableMacroCommentOutput,
2069 DisableLineMarkers, DumpDefines);
Chris Lattner772a7c12009-04-27 22:02:30 +00002070 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00002071 }
2072
Chris Lattner38a4f182009-04-27 21:25:27 +00002073 if (FixItRewrite)
2074 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2075
2076 // If in -disable-free mode, don't deallocate ASTContext.
2077 if (DisableFree)
2078 ContextOwner.take();
2079 else
2080 ContextOwner.reset(); // Delete ASTContext
Eli Friedmana9c310842009-05-18 22:20:00 +00002081
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002082 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002083 if (CheckDiagnostics(PP))
2084 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002085
Chris Lattner4b009652007-07-25 00:24:17 +00002086 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002087 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002088 PP.PrintStats();
2089 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002090 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002091 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002092 fprintf(stderr, "\n");
2093 }
2094
2095 // For a multi-file compilation, some things are ok with nuking the source
2096 // manager tables, other require stable fileid/macroid's across multiple
2097 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002098 if (ClearSourceMgr)
2099 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002100
2101 if (DisableFree)
2102 Consumer.take();
Eli Friedmana9c310842009-05-18 22:20:00 +00002103 else
2104 Consumer.reset();
2105
2106 // Always delete the output stream because we don't want to leak file
2107 // handles. Also, we don't want to try to erase an open file.
2108 OS.reset();
2109
2110 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2111 !OutPath.isEmpty()) {
2112 // If we had errors, try to erase the output file.
2113 OutPath.eraseFromDisk();
2114 }
Chris Lattner4b009652007-07-25 00:24:17 +00002115}
2116
2117static llvm::cl::list<std::string>
2118InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2119
Chris Lattner4b009652007-07-25 00:24:17 +00002120int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002121 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002122 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002123 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002124 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00002125
Chris Lattnerefe33382009-02-18 01:51:21 +00002126 if (TimeReport)
2127 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2128
Chris Lattner4b009652007-07-25 00:24:17 +00002129 // If no input was specified, read from stdin.
2130 if (InputFilenames.empty())
2131 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00002132
Ted Kremenekb240e822007-12-11 23:28:38 +00002133 // Create the diagnostic client for reporting errors or for
2134 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002135 llvm::OwningPtr<DiagnosticClient> DiagClient;
2136 if (VerifyDiagnostics) {
2137 // When checking diagnostics, just buffer them up.
2138 DiagClient.reset(new TextDiagnosticBuffer());
2139 if (InputFilenames.size() != 1) {
2140 fprintf(stderr, "-verify only works on single input files for now.\n");
2141 return 1;
2142 }
2143 if (!HTMLDiag.empty()) {
2144 fprintf(stderr, "-verify and -html-diags don't work together\n");
2145 return 1;
2146 }
2147 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002148 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00002149
2150 // If -fmessage-length=N was not specified, determine whether this
2151 // is a terminal and, if so, implicitly define -fmessage-length
2152 // appropriately.
2153 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00002154 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00002155
Chris Lattner5f7937d2009-04-17 20:40:01 +00002156 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002157 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002158 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002159 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002160 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00002161 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00002162 !NoDiagnosticsFixIt,
2163 MessageLength));
Ted Kremenek5c341732008-08-07 17:49:57 +00002164 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002165 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002166 }
Chris Lattner94859302009-04-17 21:05:01 +00002167
2168 if (!DumpBuildInformation.empty()) {
2169 if (!HTMLDiag.empty()) {
2170 fprintf(stderr,
2171 "-dump-build-information and -html-diags don't work together\n");
2172 return 1;
2173 }
2174
2175 SetUpBuildDumpLog(argc, argv, DiagClient);
2176 }
2177
Ted Kremenek5c341732008-08-07 17:49:57 +00002178
Chris Lattner4b009652007-07-25 00:24:17 +00002179 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002180 Diagnostic Diags(DiagClient.get());
Eli Friedman4d03d382009-05-19 01:17:04 +00002181 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2182 OptNoWarnings))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002183 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002184
Chris Lattner45a56e02007-12-05 23:24:17 +00002185 // -I- is a deprecated GCC feature, scan for it and reject it.
2186 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2187 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002188 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002189 I_dirs.erase(I_dirs.begin()+i);
2190 --i;
2191 }
2192 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002193
2194 // Get information about the target being compiled for.
2195 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002196 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2197
Chris Lattner2c77d852008-03-14 06:12:05 +00002198 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002199 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2200 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002201 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002202 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002203
Daniel Dunbar9c321102009-01-20 23:17:32 +00002204 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002205 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002206
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002207 llvm::OwningPtr<SourceManager> SourceMgr;
2208
Chris Lattnere1be6022009-04-14 23:22:57 +00002209 // Create a file manager object to provide access to and cache the filesystem.
2210 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002211
Daniel Dunbar07181d72009-05-06 03:16:41 +00002212 // Compute the feature set, unfortunately this effects the language!
2213 llvm::StringMap<bool> Features;
2214 ComputeFeatureMap(Target.get(), Features);
2215
Chris Lattner4b009652007-07-25 00:24:17 +00002216 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002217 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002218
Chris Lattner2b989562009-03-04 21:40:56 +00002219 /// Create a SourceManager object. This tracks and owns all the file
2220 /// buffers allocated to a translation unit.
2221 if (!SourceMgr)
2222 SourceMgr.reset(new SourceManager());
2223 else
2224 SourceMgr->clearIDTables();
2225
2226 // Initialize language options, inferring file types from input filenames.
2227 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002228 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002229
Chris Lattner2b989562009-03-04 21:40:56 +00002230 InitializeBaseLanguage();
2231 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002232 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002233 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002234
2235 // Process the -I options and set them in the HeaderInfo.
2236 HeaderSearch HeaderInfo(FileMgr);
2237
Chris Lattnere1be6022009-04-14 23:22:57 +00002238
Chris Lattner2b989562009-03-04 21:40:56 +00002239 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2240
2241 // Set up the preprocessor with these options.
Eli Friedmane934dca2009-05-18 07:39:39 +00002242 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattner2b989562009-03-04 21:40:56 +00002243 *SourceMgr.get(), HeaderInfo);
2244
2245 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2246
2247 if (!PP)
2248 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002249
Eli Friedmane595fe92009-05-19 03:35:57 +00002250 // Handle generating dependencies, if requested
2251 if (!DependencyFile.empty()) {
2252 llvm::raw_ostream *DependencyOS;
2253 if (DependencyTargets.empty()) {
2254 // FIXME: Use a proper diagnostic
2255 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2256 HadErrors = true;
2257 continue;
2258 }
2259 std::string ErrStr;
2260 DependencyOS =
2261 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2262 if (!ErrStr.empty()) {
2263 // FIXME: Use a proper diagnostic
2264 llvm::cerr << "unable to open dependency file: " + ErrStr;
2265 HadErrors = true;
2266 continue;
2267 }
2268
2269 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2270 DependenciesIncludeSystemHeaders,
2271 PhonyDependencyTarget);
2272 }
2273
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002274 if (ImplicitIncludePCH.empty() &&
2275 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002276 continue;
2277
Chris Lattner5f7937d2009-04-17 20:40:01 +00002278 if (!HTMLDiag.empty())
2279 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002280
2281 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002282 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002283
Chris Lattner2961dc52009-04-17 20:16:08 +00002284 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002285 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002286 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002287
Mike Stump91d01352009-01-28 02:43:35 +00002288 if (Verbose)
2289 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2290 " hosted on " LLVM_HOSTTRIPLE "\n");
2291
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002292 if (!NoCaretDiagnostics)
2293 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2294 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2295 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002296
2297 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002298 FileMgr.PrintStats();
2299 fprintf(stderr, "\n");
2300 }
Chris Lattner94859302009-04-17 21:05:01 +00002301
2302 delete ClangFrontendTimer;
2303 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002304
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002305 // If verifying diagnostics and we reached here, all is well.
2306 if (VerifyDiagnostics)
2307 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002308
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002309 // Managed static deconstruction. Useful for making things like
2310 // -time-passes usable.
2311 llvm::llvm_shutdown();
2312
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002313 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002314}