blob: a0ccafa9afceacd88d610414d9bb52b461c578e6 [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 Friedman7efefa52009-05-19 21:10:40 +000025#include "clang/Frontend/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.
Douglas Gregor8987c032009-05-21 20:55:50 +0000197 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000198 ASTDump, // Parse ASTs and dump them.
199 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000200 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000201 ParsePrintCallbacks, // Parse and print each callback.
202 ParseSyntaxOnly, // Parse and perform semantic analysis.
203 ParseNoop, // Parse with noop callbacks.
204 RunPreprocessorOnly, // Just lex, no output.
205 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000206 DumpTokens, // Dump out preprocessed tokens.
207 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000208 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000209 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000210 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000211 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000212};
213
214static llvm::cl::opt<ProgActions>
215ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
216 llvm::cl::init(ParseSyntaxOnly),
217 llvm::cl::values(
218 clEnumValN(RunPreprocessorOnly, "Eonly",
219 "Just run preprocessor, no output (for timings)"),
220 clEnumValN(PrintPreprocessedInput, "E",
221 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000222 clEnumValN(DumpRawTokens, "dump-raw-tokens",
223 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000224 clEnumValN(RunAnalysis, "analyze",
225 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000226 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000227 "Run preprocessor, dump internal rep of tokens"),
228 clEnumValN(ParseNoop, "parse-noop",
229 "Run parser with noop callbacks (for timings)"),
230 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
231 "Run parser and perform semantic analysis"),
232 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
233 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000234 clEnumValN(EmitHTML, "emit-html",
235 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000236 clEnumValN(ASTPrint, "ast-print",
237 "Build ASTs and then pretty-print them"),
Douglas Gregor8987c032009-05-21 20:55:50 +0000238 clEnumValN(ASTPrintXML, "ast-print-xml",
239 "Build ASTs and then print them in XML format"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000240 clEnumValN(ASTDump, "ast-dump",
241 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000242 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000243 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000244 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000245 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000246 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000247 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000248 clEnumValN(GeneratePCH, "emit-pch",
249 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000250 clEnumValN(EmitAssembly, "S",
251 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000252 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000253 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000254 clEnumValN(EmitBC, "emit-llvm-bc",
255 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000256 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
257 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000258 clEnumValN(RewriteTest, "rewrite-test",
259 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000260 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000261 "Rewrite ObjC into C (code rewriter example)"),
262 clEnumValN(RewriteMacros, "rewrite-macros",
263 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000264 clEnumValN(RewriteBlocks, "rewrite-blocks",
265 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000266 clEnumValN(FixIt, "fixit",
267 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000268 clEnumValEnd));
269
Ted Kremenekd01eae62007-12-19 19:47:59 +0000270
271static llvm::cl::opt<std::string>
272OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000273 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000274 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000275
Ted Kremenek57f25b22008-12-02 19:57:31 +0000276
277//===----------------------------------------------------------------------===//
278// PTH.
279//===----------------------------------------------------------------------===//
280
281static llvm::cl::opt<std::string>
282TokenCache("token-cache", llvm::cl::value_desc("path"),
283 llvm::cl::desc("Use specified token cache file"));
284
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000285//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000286// Diagnostic Options
287//===----------------------------------------------------------------------===//
288
Ted Kremenek10389cf2007-09-26 19:42:19 +0000289static llvm::cl::opt<bool>
290VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000291 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000292
Ted Kremenekfd75e312008-03-27 06:17:42 +0000293static llvm::cl::opt<std::string>
294HTMLDiag("html-diags",
295 llvm::cl::desc("Generate HTML to report diagnostics"),
296 llvm::cl::value_desc("HTML directory"));
297
Nico Weber0e13eaa2008-08-05 23:33:20 +0000298static llvm::cl::opt<bool>
299NoShowColumn("fno-show-column",
300 llvm::cl::desc("Do not include column number on diagnostics"));
301
302static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000303NoShowLocation("fno-show-source-location",
304 llvm::cl::desc("Do not include source location information with"
305 " diagnostics"));
306
307static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000308NoCaretDiagnostics("fno-caret-diagnostics",
309 llvm::cl::desc("Do not include source line and caret with"
310 " diagnostics"));
311
Chris Lattner695a4f52009-03-13 01:08:23 +0000312static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000313NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
314 llvm::cl::desc("Do not include fixit information in"
315 " diagnostics"));
316
317static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000318PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
319 llvm::cl::desc("Print source range spans in numeric form"));
320
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000321static llvm::cl::opt<bool>
322PrintDiagnosticOption("fdiagnostics-show-option",
323 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000324
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000325static llvm::cl::opt<unsigned>
326MessageLength("fmessage-length",
327 llvm::cl::desc("Format message diagnostics so that they fit "
328 "within N columns or fewer, when possible."),
329 llvm::cl::value_desc("N"));
330
Chris Lattner4b009652007-07-25 00:24:17 +0000331//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000332// C++ Visualization.
333//===----------------------------------------------------------------------===//
334
335static llvm::cl::opt<std::string>
336InheritanceViewCls("cxx-inheritance-view",
337 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000338 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000339
340//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000341// Builtin Options
342//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000343
344static llvm::cl::opt<bool>
345TimeReport("ftime-report",
346 llvm::cl::desc("Print the amount of time each "
347 "phase of compilation takes"));
348
Douglas Gregor23d23262009-02-14 20:49:29 +0000349static llvm::cl::opt<bool>
350Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000351 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000352 "freestanding environment"));
353
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000354static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000355AllowBuiltins("fbuiltin", llvm::cl::init(true),
356 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000357
358
359static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000360MathErrno("fmath-errno", llvm::cl::init(true),
361 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000362
Douglas Gregor23d23262009-02-14 20:49:29 +0000363//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000364// Language Options
365//===----------------------------------------------------------------------===//
366
367enum LangKind {
368 langkind_unspecified,
369 langkind_c,
370 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000371 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000372 langkind_cxx,
373 langkind_cxx_cpp,
374 langkind_objc,
375 langkind_objc_cpp,
376 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000377 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000378};
379
Chris Lattner4b009652007-07-25 00:24:17 +0000380static llvm::cl::opt<LangKind>
381BaseLang("x", llvm::cl::desc("Base language to compile"),
382 llvm::cl::init(langkind_unspecified),
383 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
384 clEnumValN(langkind_cxx, "c++", "C++"),
385 clEnumValN(langkind_objc, "objective-c", "Objective C"),
386 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000387 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000388 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000389 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
390 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000391 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000392 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000393 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
394 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000395 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000396 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000397 clEnumValN(langkind_c, "c-header",
398 "C header"),
399 clEnumValN(langkind_objc, "objective-c-header",
400 "Objective-C header"),
401 clEnumValN(langkind_cxx, "c++-header",
402 "C++ header"),
403 clEnumValN(langkind_objcxx, "objective-c++-header",
404 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000405 clEnumValEnd));
406
407static llvm::cl::opt<bool>
408LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
409 llvm::cl::Hidden);
410static llvm::cl::opt<bool>
411LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
412 llvm::cl::Hidden);
413
Chris Lattnere1be6022009-04-14 23:22:57 +0000414static llvm::cl::opt<bool>
415ObjCExclusiveGC("fobjc-gc-only",
416 llvm::cl::desc("Use GC exclusively for Objective-C related "
417 "memory management"));
418
419static llvm::cl::opt<bool>
420ObjCEnableGC("fobjc-gc",
421 llvm::cl::desc("Enable Objective-C garbage collection"));
422
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000423static llvm::cl::opt<bool>
424ObjCEnableGCBitmapPrint("print-ivar-layout",
425 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
426
Chris Lattnere1be6022009-04-14 23:22:57 +0000427static llvm::cl::opt<LangOptions::VisibilityMode>
428SymbolVisibility("fvisibility",
429 llvm::cl::desc("Set the default symbol visibility:"),
430 llvm::cl::init(LangOptions::Default),
431 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
432 "Use default symbol visibility"),
433 clEnumValN(LangOptions::Hidden, "hidden",
434 "Use hidden symbol visibility"),
435 clEnumValN(LangOptions::Protected,"protected",
436 "Use protected symbol visibility"),
437 clEnumValEnd));
438
439static llvm::cl::opt<bool>
440OverflowChecking("ftrapv",
441 llvm::cl::desc("Trap on integer overflow"),
442 llvm::cl::init(false));
443
Fariborz Jahanianfefd5e82009-05-22 20:17:16 +0000444static llvm::cl::opt<bool>
445ObjCSenderDispatch("fobjc-sender-dependent-dispatch",
446 llvm::cl::desc("Enable sender-dependent dispatch for"
447 "Objective-C messages"), llvm::cl::init(false));
Chris Lattnere1be6022009-04-14 23:22:57 +0000448
Ted Kremenek11ad8952007-12-05 23:49:08 +0000449/// InitializeBaseLanguage - Handle the -x foo options.
450static void InitializeBaseLanguage() {
451 if (LangObjC)
452 BaseLang = langkind_objc;
453 else if (LangObjCXX)
454 BaseLang = langkind_objcxx;
455}
456
457static LangKind GetLanguage(const std::string &Filename) {
458 if (BaseLang != langkind_unspecified)
459 return BaseLang;
460
461 std::string::size_type DotPos = Filename.rfind('.');
462
463 if (DotPos == std::string::npos) {
464 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000465 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000466 }
467
Ted Kremenek11ad8952007-12-05 23:49:08 +0000468 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
469 // C header: .h
470 // C++ header: .hh or .H;
471 // assembler no preprocessing: .s
472 // assembler: .S
473 if (Ext == "c")
474 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000475 else if (Ext == "S" ||
476 // If the compiler is run on a .s file, preprocess it as .S
477 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000478 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000479 else if (Ext == "i")
480 return langkind_c_cpp;
481 else if (Ext == "ii")
482 return langkind_cxx_cpp;
483 else if (Ext == "m")
484 return langkind_objc;
485 else if (Ext == "mi")
486 return langkind_objc_cpp;
487 else if (Ext == "mm" || Ext == "M")
488 return langkind_objcxx;
489 else if (Ext == "mii")
490 return langkind_objcxx_cpp;
491 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
492 Ext == "c++" || Ext == "cp" || Ext == "cxx")
493 return langkind_cxx;
494 else
495 return langkind_c;
496}
497
498
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000499static void InitializeCOptions(LangOptions &Options) {
500 // Do nothing.
501}
502
503static void InitializeObjCOptions(LangOptions &Options) {
504 Options.ObjC1 = Options.ObjC2 = 1;
505}
506
507
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000508static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000509 // FIXME: implement -fpreprocessed mode.
510 bool NoPreprocess = false;
511
Ted Kremenek11ad8952007-12-05 23:49:08 +0000512 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000513 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000514 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000515 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000516 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000517 case langkind_c_cpp:
518 NoPreprocess = true;
519 // FALLTHROUGH
520 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000521 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000522 break;
523 case langkind_cxx_cpp:
524 NoPreprocess = true;
525 // FALLTHROUGH
526 case langkind_cxx:
527 Options.CPlusPlus = 1;
528 break;
529 case langkind_objc_cpp:
530 NoPreprocess = true;
531 // FALLTHROUGH
532 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000533 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000534 break;
535 case langkind_objcxx_cpp:
536 NoPreprocess = true;
537 // FALLTHROUGH
538 case langkind_objcxx:
539 Options.ObjC1 = Options.ObjC2 = 1;
540 Options.CPlusPlus = 1;
541 break;
542 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000543
544 if (ObjCExclusiveGC)
545 Options.setGCMode(LangOptions::GCOnly);
546 else if (ObjCEnableGC)
547 Options.setGCMode(LangOptions::HybridGC);
548
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000549 if (ObjCEnableGCBitmapPrint)
550 Options.ObjCGCBitmapPrint = 1;
551
Chris Lattnere1be6022009-04-14 23:22:57 +0000552 Options.setVisibilityMode(SymbolVisibility);
553 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
556/// LangStds - Language standards we support.
557enum LangStds {
558 lang_unspecified,
559 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000560 lang_gnu_START,
561 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000562 lang_cxx98, lang_gnucxx98,
563 lang_cxx0x, lang_gnucxx0x
564};
565
566static llvm::cl::opt<LangStds>
567LangStd("std", llvm::cl::desc("Language standard to compile for"),
568 llvm::cl::init(lang_unspecified),
569 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
570 clEnumValN(lang_c89, "c90", "ISO C 1990"),
571 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
572 clEnumValN(lang_c94, "iso9899:199409",
573 "ISO C 1990 with amendment 1"),
574 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000575 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000576 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000577 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000578 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000579 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000580 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000581 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000582 clEnumValN(lang_gnu99, "gnu9x",
583 "ISO C 1999 with GNU extensions"),
584 clEnumValN(lang_cxx98, "c++98",
585 "ISO C++ 1998 with amendments"),
586 clEnumValN(lang_gnucxx98, "gnu++98",
587 "ISO C++ 1998 with amendments and GNU "
588 "extensions (default for C++)"),
589 clEnumValN(lang_cxx0x, "c++0x",
590 "Upcoming ISO C++ 200x with amendments"),
591 clEnumValN(lang_gnucxx0x, "gnu++0x",
592 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000593 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000594 clEnumValEnd));
595
596static llvm::cl::opt<bool>
597NoOperatorNames("fno-operator-names",
598 llvm::cl::desc("Do not treat C++ operator name keywords as "
599 "synonyms for operators"));
600
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000601static llvm::cl::opt<bool>
602PascalStrings("fpascal-strings",
603 llvm::cl::desc("Recognize and construct Pascal-style "
604 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000605
606static llvm::cl::opt<bool>
607MSExtensions("fms-extensions",
608 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000609 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000610
611static llvm::cl::opt<bool>
612WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000613 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000614
615static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000616NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000617 llvm::cl::desc("Disallow implicit conversions between "
618 "vectors with a different number of "
619 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000620
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000621static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000622EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000623
624static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000625EnableHeinousExtensions("fheinous-gnu-extensions",
626 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
627 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
628
629static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000630ObjCNonFragileABI("fobjc-nonfragile-abi",
631 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000632
Daniel Dunbar5523e862009-05-04 05:16:21 +0000633
634static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000635EmitAllDecls("femit-all-decls",
636 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000637
Daniel Dunbar91692d92008-08-11 17:36:14 +0000638static llvm::cl::opt<bool>
639Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000640 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000641
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000642static llvm::cl::opt<bool>
643GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000644 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000645 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000646
647static llvm::cl::opt<bool>
648NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000649 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000650 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000651
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000652
653
654static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000655Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000656
Douglas Gregor375733c2009-03-10 00:06:19 +0000657static llvm::cl::opt<unsigned>
658TemplateDepth("ftemplate-depth", llvm::cl::init(99),
659 llvm::cl::desc("Maximum depth of recursive template "
660 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000661static llvm::cl::opt<bool>
662DollarsInIdents("fdollars-in-identifiers",
663 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000664
Anders Carlssondfd77642009-04-06 17:37:10 +0000665
666static llvm::cl::opt<bool>
667OptSize("Os", llvm::cl::desc("Optimize for size"));
668
669static llvm::cl::opt<bool>
670NoCommon("fno-common",
671 llvm::cl::desc("Compile common globals like normal definitions"),
672 llvm::cl::ValueDisallowed);
673
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000674static llvm::cl::opt<std::string>
675MainFileName("main-file-name",
676 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000677
Anders Carlssonf2310142009-05-13 19:49:53 +0000678// FIXME: Also add an "-fno-access-control" option.
679static llvm::cl::opt<bool>
680AccessControl("faccess-control",
681 llvm::cl::desc("Enable C++ access control"));
682
Anders Carlssondfd77642009-04-06 17:37:10 +0000683// It might be nice to add bounds to the CommandLine library directly.
684struct OptLevelParser : public llvm::cl::parser<unsigned> {
685 bool parse(llvm::cl::Option &O, const char *ArgName,
686 const std::string &Arg, unsigned &Val) {
687 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
688 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000689 if (Val > 3)
690 return O.error(": '" + Arg + "' invalid optimization level!");
691 return false;
692 }
693};
694static llvm::cl::opt<unsigned, false, OptLevelParser>
695OptLevel("O", llvm::cl::Prefix,
696 llvm::cl::desc("Optimization level"),
697 llvm::cl::init(0));
698
Daniel Dunbare079c712009-04-08 03:03:23 +0000699static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000700PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
701
702static llvm::cl::opt<bool>
703StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000704
Daniel Dunbar34542952008-08-23 08:43:39 +0000705static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000706 TargetInfo *Target,
707 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000708 // Allow the target to set the default the langauge options as it sees fit.
709 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000710
711 // Pass the map of target features to the target for validation and
712 // processing.
713 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000714
Chris Lattner4b009652007-07-25 00:24:17 +0000715 if (LangStd == lang_unspecified) {
716 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000717 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000718 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000719 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000720 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000721 case langkind_c_cpp:
722 case langkind_objc:
723 case langkind_objc_cpp:
724 LangStd = lang_gnu99;
725 break;
726 case langkind_cxx:
727 case langkind_cxx_cpp:
728 case langkind_objcxx:
729 case langkind_objcxx_cpp:
730 LangStd = lang_gnucxx98;
731 break;
732 }
733 }
734
735 switch (LangStd) {
736 default: assert(0 && "Unknown language standard!");
737
738 // Fall through from newer standards to older ones. This isn't really right.
739 // FIXME: Enable specifically the right features based on the language stds.
740 case lang_gnucxx0x:
741 case lang_cxx0x:
742 Options.CPlusPlus0x = 1;
743 // FALL THROUGH
744 case lang_gnucxx98:
745 case lang_cxx98:
746 Options.CPlusPlus = 1;
747 Options.CXXOperatorNames = !NoOperatorNames;
748 // FALL THROUGH.
749 case lang_gnu99:
750 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000751 Options.C99 = 1;
752 Options.HexFloats = 1;
753 // FALL THROUGH.
754 case lang_gnu89:
755 Options.BCPLComment = 1; // Only for C99/C++.
756 // FALL THROUGH.
757 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000758 Options.Digraphs = 1; // C94, C99, C++.
759 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000760 case lang_c89:
761 break;
762 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000763
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000764 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
765 Options.GNUMode = LangStd >= lang_gnu_START;
766
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000767 if (Options.CPlusPlus) {
768 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000769 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000770 }
Chris Lattner4b009652007-07-25 00:24:17 +0000771
Chris Lattner6ab935b2008-04-05 06:32:51 +0000772 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
773 Options.ImplicitInt = 1;
774 else
775 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000776
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000777 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
778 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000779 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000780 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000781 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000782
Chris Lattner58d5ba52008-12-05 00:10:44 +0000783 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
784 // even if they are normally on for the target. In GNU modes (e.g.
785 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000786 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000787 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000788 Options.Blocks = 0;
789
Chris Lattner284784c2009-04-19 07:06:52 +0000790 // Default to not accepting '$' in identifiers when preprocessing assembler,
791 // but do accept when preprocessing C. FIXME: these defaults are right for
792 // darwin, are they right everywhere?
793 Options.DollarIdents = LK != langkind_asm_cpp;
794 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000795 Options.DollarIdents = DollarsInIdents;
796
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000797 if (PascalStrings.getPosition())
798 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000799 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000800 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000801 if (NoLaxVectorConversions.getPosition())
802 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000803 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000804 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000805 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000806
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000807 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000808 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000809 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000810 Options.Freestanding = Options.NoBuiltin = 1;
811
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000812 if (EnableHeinousExtensions)
813 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000814
Anders Carlssonf2310142009-05-13 19:49:53 +0000815 if (AccessControl)
816 Options.AccessControl = 1;
817
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000818 Options.MathErrno = MathErrno;
819
Douglas Gregor375733c2009-03-10 00:06:19 +0000820 Options.InstantiationDepth = TemplateDepth;
821
Chris Lattnerddae7102008-12-04 22:54:33 +0000822 // Override the default runtime if the user requested it.
823 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000824 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000825 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000826 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000827
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000828 if (ObjCNonFragileABI)
829 Options.ObjCNonFragileABI = 1;
Fariborz Jahanianfefd5e82009-05-22 20:17:16 +0000830
831 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000832
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000833 if (EmitAllDecls)
834 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000835
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000836 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
837 // support.
838 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000839
840 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000841 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000842 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000843
844 assert(PICLevel <= 2 && "Invalid value for -pic-level");
845 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000846
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000847 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000848 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000849 Options.NoInline = !OptSize && !OptLevel;
850
851 Options.Static = StaticDefine;
852
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000853 if (MainFileName.getPosition())
854 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000855}
856
857//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000858// Target Triple Processing.
859//===----------------------------------------------------------------------===//
860
861static llvm::cl::opt<std::string>
862TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000863 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000864
Chris Lattnerfc457002008-03-05 01:18:20 +0000865static llvm::cl::opt<std::string>
Chris Lattner2b168e02008-09-30 01:13:12 +0000866MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000867 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000868
Chris Lattner01de9c82008-09-30 20:16:56 +0000869// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
870// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000871
872// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000873static void HandleMacOSVersionMin(std::string &Triple) {
874 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
875 if (DarwinDashIdx == std::string::npos) {
876 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000877 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000878 exit(1);
879 }
880 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
881
Chris Lattner01de9c82008-09-30 20:16:56 +0000882 // Remove the number.
883 Triple.resize(DarwinNumIdx);
884
885 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
886 bool MacOSVersionMinIsInvalid = false;
887 int VersionNum = 0;
888 if (MacOSVersionMin.size() < 4 ||
889 MacOSVersionMin.substr(0, 3) != "10." ||
890 !isdigit(MacOSVersionMin[3])) {
891 MacOSVersionMinIsInvalid = true;
892 } else {
893 const char *Start = MacOSVersionMin.c_str()+3;
894 char *End = 0;
895 VersionNum = (int)strtol(Start, &End, 10);
896
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000897 // The version number must be in the range 0-9.
898 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
899
Chris Lattner01de9c82008-09-30 20:16:56 +0000900 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
901 Triple += llvm::itostr(VersionNum+4);
902
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000903 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
904 // Add the period piece (.7) to the end of the triple. This gives us
905 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000906 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000907 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
908 MacOSVersionMinIsInvalid = true;
909 }
910 }
911
912 if (MacOSVersionMinIsInvalid) {
913 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000914 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000915 MacOSVersionMin.c_str());
916 exit(1);
917 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000918 else if (VersionNum <= 4 &&
919 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
920 fprintf(stderr,
921 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
922 MacOSVersionMin.c_str());
923 exit(1);
924 }
925
Chris Lattner01de9c82008-09-30 20:16:56 +0000926}
927
Daniel Dunbar93f64532009-04-10 19:52:24 +0000928static llvm::cl::opt<std::string>
929IPhoneOSVersionMin("miphoneos-version-min",
930 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
931
932// If -miphoneos-version-min=2.2 is specified, change the triple from being
933// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
934// 9 as the default major Darwin number, and encode the iPhone OS version
935// number in the minor version and revision.
936
937// FIXME: We should have the driver do this instead.
938static void HandleIPhoneOSVersionMin(std::string &Triple) {
939 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
940 if (DarwinDashIdx == std::string::npos) {
941 fprintf(stderr,
942 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
943 exit(1);
944 }
945 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
946
947 // Remove the number.
948 Triple.resize(DarwinNumIdx);
949
950 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
951 bool IPhoneOSVersionMinIsInvalid = false;
952 int VersionNum = 0;
953 if (IPhoneOSVersionMin.size() < 3 ||
954 !isdigit(IPhoneOSVersionMin[0])) {
955 IPhoneOSVersionMinIsInvalid = true;
956 } else {
957 const char *Start = IPhoneOSVersionMin.c_str();
958 char *End = 0;
959 VersionNum = (int)strtol(Start, &End, 10);
960
961 // The version number must be in the range 0-9.
962 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
963
964 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
965 Triple += "9." + llvm::itostr(VersionNum);
966
967 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
968 // Add the period piece (.2) to the end of the triple. This gives us
969 // something like ...-darwin9.2.2
970 Triple += End;
971 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
972 IPhoneOSVersionMinIsInvalid = true;
973 }
974 }
975
976 if (IPhoneOSVersionMinIsInvalid) {
977 fprintf(stderr,
978 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
979 IPhoneOSVersionMin.c_str());
980 exit(1);
981 }
982}
983
Chris Lattner01de9c82008-09-30 20:16:56 +0000984/// CreateTargetTriple - Process the various options that affect the target
985/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000986static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000987 // Initialize base triple. If a -triple option has been specified, use
988 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000989 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000990 if (Triple.empty())
991 Triple = llvm::sys::getHostTriple();
Chris Lattner2b168e02008-09-30 01:13:12 +0000992
993 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
994 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000995 if (!MacOSVersionMin.empty())
996 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +0000997 else if (!IPhoneOSVersionMin.empty())
998 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +0000999
Chris Lattner2b168e02008-09-30 01:13:12 +00001000 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001001}
1002
1003//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001004// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001005//===----------------------------------------------------------------------===//
1006
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001007static bool InitializeSourceManager(Preprocessor &PP,
1008 const std::string &InFile) {
1009 // Figure out where to get and map in the main file.
1010 SourceManager &SourceMgr = PP.getSourceManager();
1011 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001012
1013 if (EmptyInputOnly) {
1014 const char *EmptyStr = "";
1015 llvm::MemoryBuffer *SB =
1016 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1017 SourceMgr.createMainFileIDForMemBuffer(SB);
1018 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001019 const FileEntry *File = FileMgr.getFile(InFile);
1020 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1021 if (SourceMgr.getMainFileID().isInvalid()) {
1022 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1023 << InFile.c_str();
1024 return true;
1025 }
1026 } else {
1027 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1028
1029 // If stdin was empty, SB is null. Cons up an empty memory
1030 // buffer now.
1031 if (!SB) {
1032 const char *EmptyStr = "";
1033 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1034 }
1035
1036 SourceMgr.createMainFileIDForMemBuffer(SB);
1037 if (SourceMgr.getMainFileID().isInvalid()) {
1038 PP.getDiagnostics().Report(FullSourceLoc(),
1039 diag::err_fe_error_reading_stdin);
1040 return true;
1041 }
1042 }
1043
1044 return false;
1045}
1046
Chris Lattner47b6a162008-04-19 23:09:31 +00001047
Chris Lattner94269d72009-04-21 05:40:52 +00001048//===----------------------------------------------------------------------===//
1049// Preprocessor Initialization
1050//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001051
Chris Lattner94269d72009-04-21 05:40:52 +00001052// FIXME: Preprocessor builtins to support.
1053// -A... - Play with #assertions
1054// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001055
Chris Lattner94269d72009-04-21 05:40:52 +00001056static llvm::cl::list<std::string>
1057D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1058 llvm::cl::desc("Predefine the specified macro"));
1059static llvm::cl::list<std::string>
1060U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1061 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001062
Chris Lattner94269d72009-04-21 05:40:52 +00001063static llvm::cl::list<std::string>
1064ImplicitIncludes("include", llvm::cl::value_desc("file"),
1065 llvm::cl::desc("Include file before parsing"));
1066static llvm::cl::list<std::string>
1067ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1068 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001069
Chris Lattner94269d72009-04-21 05:40:52 +00001070static llvm::cl::opt<std::string>
1071ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1072 llvm::cl::desc("Include precompiled header file"));
1073
1074static llvm::cl::opt<std::string>
1075ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1076 llvm::cl::desc("Include file before parsing"));
1077
Chris Lattner4b009652007-07-25 00:24:17 +00001078
1079//===----------------------------------------------------------------------===//
1080// Preprocessor include path information.
1081//===----------------------------------------------------------------------===//
1082
1083// This tool exports a large number of command line options to control how the
1084// preprocessor searches for header files. At root, however, the Preprocessor
1085// object takes a very simple interface: a list of directories to search for
1086//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001087// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001088// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001089//
Chris Lattner4b009652007-07-25 00:24:17 +00001090
1091static llvm::cl::opt<bool>
1092nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1093
1094// Various command line options. These four add directories to each chain.
1095static llvm::cl::list<std::string>
1096F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1097 llvm::cl::desc("Add directory to framework include search path"));
1098static llvm::cl::list<std::string>
1099I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1100 llvm::cl::desc("Add directory to include search path"));
1101static llvm::cl::list<std::string>
1102idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1103 llvm::cl::desc("Add directory to AFTER include search path"));
1104static llvm::cl::list<std::string>
1105iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1106 llvm::cl::desc("Add directory to QUOTE include search path"));
1107static llvm::cl::list<std::string>
1108isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1109 llvm::cl::desc("Add directory to SYSTEM include search path"));
1110
1111// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1112static llvm::cl::list<std::string>
1113iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1114 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1115static llvm::cl::list<std::string>
1116iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1117 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1118static llvm::cl::list<std::string>
1119iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1120 llvm::cl::Prefix,
1121 llvm::cl::desc("Set directory to include search path with prefix"));
1122
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001123static llvm::cl::opt<std::string>
1124isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1125 llvm::cl::desc("Set the system root directory (usually /)"));
1126
Chris Lattner4b009652007-07-25 00:24:17 +00001127// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001128
Chris Lattner4b009652007-07-25 00:24:17 +00001129/// InitializeIncludePaths - Process the -I options and set them in the
1130/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001131void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1132 FileManager &FM, const LangOptions &Lang) {
1133 InitHeaderSearch Init(Headers, Verbose, isysroot);
1134
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001135 // Handle -I... and -F... options, walking the lists in parallel.
1136 unsigned Iidx = 0, Fidx = 0;
1137 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1138 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001139 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001140 ++Iidx;
1141 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001142 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001143 ++Fidx;
1144 }
1145 }
Chris Lattner4b009652007-07-25 00:24:17 +00001146
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001147 // Consume what's left from whatever list was longer.
1148 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001149 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001150 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001151 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001152
1153 // Handle -idirafter... options.
1154 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001155 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1156 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001157
1158 // Handle -iquote... options.
1159 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001160 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001161
1162 // Handle -isystem... options.
1163 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001164 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001165
1166 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1167 // parallel, processing the values in order of occurance to get the right
1168 // prefixes.
1169 {
1170 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1171 unsigned iprefix_idx = 0;
1172 unsigned iwithprefix_idx = 0;
1173 unsigned iwithprefixbefore_idx = 0;
1174 bool iprefix_done = iprefix_vals.empty();
1175 bool iwithprefix_done = iwithprefix_vals.empty();
1176 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1177 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1178 if (!iprefix_done &&
1179 (iwithprefix_done ||
1180 iprefix_vals.getPosition(iprefix_idx) <
1181 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1182 (iwithprefixbefore_done ||
1183 iprefix_vals.getPosition(iprefix_idx) <
1184 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1185 Prefix = iprefix_vals[iprefix_idx];
1186 ++iprefix_idx;
1187 iprefix_done = iprefix_idx == iprefix_vals.size();
1188 } else if (!iwithprefix_done &&
1189 (iwithprefixbefore_done ||
1190 iwithprefix_vals.getPosition(iwithprefix_idx) <
1191 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001192 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1193 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001194 ++iwithprefix_idx;
1195 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1196 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001197 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1198 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001199 ++iwithprefixbefore_idx;
1200 iwithprefixbefore_done =
1201 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1202 }
1203 }
1204 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001205
Nico Weber770e3882008-08-22 09:25:22 +00001206 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001207
Daniel Dunbar4e604292009-02-21 20:52:41 +00001208 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001209 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001210 llvm::sys::Path::GetMainExecutable(Argv0,
1211 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001212 if (!MainExecutablePath.isEmpty()) {
1213 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1214 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001215
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001216 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001217 MainExecutablePath.appendComponent("lib");
1218 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001219 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001220 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001221
1222 // We pass true to ignore sysroot so that we *always* look for clang headers
1223 // relative to our executable, never relative to -isysroot.
1224 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1225 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001226 }
1227
Nico Weber770e3882008-08-22 09:25:22 +00001228 if (!nostdinc)
1229 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001230
1231 // Now that we have collected all of the include paths, merge them all
1232 // together and tell the preprocessor about them.
1233
Nico Weber770e3882008-08-22 09:25:22 +00001234 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001235}
1236
Chris Lattner94269d72009-04-21 05:40:52 +00001237void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1238{
1239 // Add macros from the command line.
1240 unsigned d = 0, D = D_macros.size();
1241 unsigned u = 0, U = U_macros.size();
1242 while (d < D || u < U) {
1243 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1244 InitOpts.addMacroDef(D_macros[d++]);
1245 else
1246 InitOpts.addMacroUndef(U_macros[u++]);
1247 }
1248
1249 // If -imacros are specified, include them now. These are processed before
1250 // any -include directives.
1251 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1252 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1253
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001254 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1255 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner94269d72009-04-21 05:40:52 +00001256 // We want to add these paths to the predefines buffer in order, make a
1257 // temporary vector to sort by their occurrence.
1258 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1259
1260 if (!ImplicitIncludePTH.empty())
1261 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1262 &ImplicitIncludePTH));
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001263 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1264 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1265 &ImplicitIncludePCH));
Chris Lattner94269d72009-04-21 05:40:52 +00001266 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1267 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1268 &ImplicitIncludes[i]));
1269 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1270
1271
1272 // Now that they are ordered by position, add to the predefines buffer.
1273 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1274 std::string *Ptr = OrderedPaths[i].second;
1275 if (!ImplicitIncludes.empty() &&
1276 Ptr >= &ImplicitIncludes[0] &&
1277 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1278 InitOpts.addInclude(*Ptr, false);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001279 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner94269d72009-04-21 05:40:52 +00001280 InitOpts.addInclude(*Ptr, true);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001281 } else {
1282 // We end up here when we're producing preprocessed output and
1283 // we loaded a PCH file. In this case, just include the header
1284 // file that was used to build the precompiled header.
1285 assert(Ptr == &ImplicitIncludePCH);
1286 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1287 if (!OriginalFile.empty()) {
1288 InitOpts.addInclude(OriginalFile, false);
1289 ImplicitIncludePCH.clear();
1290 }
Chris Lattner94269d72009-04-21 05:40:52 +00001291 }
1292 }
1293 }
1294}
1295
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001296//===----------------------------------------------------------------------===//
1297// Driver PreprocessorFactory - For lazily generating preprocessors ...
1298//===----------------------------------------------------------------------===//
1299
1300namespace {
1301class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1302 Diagnostic &Diags;
1303 const LangOptions &LangInfo;
1304 TargetInfo &Target;
1305 SourceManager &SourceMgr;
1306 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001307
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001308public:
Eli Friedmane934dca2009-05-18 07:39:39 +00001309 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001310 TargetInfo &target, SourceManager &SM,
1311 HeaderSearch &Headers)
Eli Friedmane934dca2009-05-18 07:39:39 +00001312 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001313 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001314
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001315
1316 virtual ~DriverPreprocessorFactory() {}
1317
1318 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001319 llvm::OwningPtr<PTHManager> PTHMgr;
1320
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001321 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1322 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1323 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001324 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001325 }
1326
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001327 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001328 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1329 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001330 PTHMgr.reset(PTHManager::Create(x, &Diags,
1331 TokenCache.empty() ? Diagnostic::Error
1332 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001333 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001334
Ted Kremenek6348cc62009-03-22 06:42:39 +00001335 if (Diags.hasErrorOccurred())
1336 exit(1);
1337
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001338 // Create the Preprocessor.
1339 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1340 SourceMgr, HeaderInfo,
1341 PTHMgr.get()));
1342
1343 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1344 // That argument is used as the IdentifierInfoLookup argument to
1345 // IdentifierTable's ctor.
1346 if (PTHMgr) {
1347 PTHMgr->setPreprocessor(PP.get());
1348 PP->setPTHManager(PTHMgr.take());
1349 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001350
Chris Lattner94269d72009-04-21 05:40:52 +00001351 PreprocessorInitOptions InitOpts;
1352 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmane934dca2009-05-18 07:39:39 +00001353 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001354 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001355
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001356 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001357 }
1358};
1359}
Chris Lattner4b009652007-07-25 00:24:17 +00001360
Chris Lattner4b009652007-07-25 00:24:17 +00001361//===----------------------------------------------------------------------===//
1362// Basic Parser driver
1363//===----------------------------------------------------------------------===//
1364
Chris Lattner9d818a22008-04-19 23:25:44 +00001365static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001366 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001367 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001368
1369 // Parsing the specified input file.
1370 P.ParseTranslationUnit();
1371 delete PA;
1372}
1373
1374//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001375// Code generation options
1376//===----------------------------------------------------------------------===//
1377
1378static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001379GenerateDebugInfo("g",
1380 llvm::cl::desc("Generate source level debug information"));
1381
Daniel Dunbar9101a632009-02-17 19:47:34 +00001382static llvm::cl::opt<std::string>
1383TargetCPU("mcpu",
1384 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1385
Daniel Dunbar07181d72009-05-06 03:16:41 +00001386static llvm::cl::list<std::string>
1387TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1388
1389/// ComputeTargetFeatures - Recompute the target feature list to only
1390/// be the list of things that are enabled, based on the target cpu
1391/// and feature list.
1392static void ComputeFeatureMap(TargetInfo *Target,
1393 llvm::StringMap<bool> &Features) {
1394 assert(Features.empty() && "invalid map");
1395
1396 // Initialize the feature map based on the target.
1397 Target->getDefaultFeatures(TargetCPU, Features);
1398
1399 // Apply the user specified deltas.
1400 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1401 ie = TargetFeatures.end(); it != ie; ++it) {
1402 const char *Name = it->c_str();
1403
1404 // FIXME: Don't handle errors like this.
1405 if (Name[0] != '-' && Name[0] != '+') {
1406 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1407 Name);
1408 exit(1);
1409 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001410 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1411 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1412 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001413 exit(1);
1414 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001415 }
1416}
1417
Chris Lattner8a9615c2009-03-16 18:41:18 +00001418static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001419 const LangOptions &LangOpts,
1420 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001421 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001422 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001423 if (OptSize) {
1424 // -Os implies -O2
1425 // FIXME: Diagnose conflicting options.
1426 Opts.OptimizationLevel = 2;
1427 } else {
1428 Opts.OptimizationLevel = OptLevel;
1429 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001430
1431 // FIXME: There are llvm-gcc options to control these selectively.
1432 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1433 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001434 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001435
1436#ifdef NDEBUG
1437 Opts.VerifyModule = 0;
1438#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001439
1440 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001441 Opts.Features.clear();
1442 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1443 ie = Features.end(); it != ie; ++it) {
1444 // FIXME: If we are completely confident that we have the right
1445 // set, we only need to pass the minuses.
1446 std::string Name(it->second ? "+" : "-");
1447 Name += it->first();
1448 Opts.Features.push_back(Name);
1449 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001450
Chris Lattnerf04a7562009-03-26 05:00:52 +00001451 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1452
Chris Lattnere8f70712009-02-18 01:23:44 +00001453 // Handle -ftime-report.
1454 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001455}
1456
1457//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001458// Fix-It Options
1459//===----------------------------------------------------------------------===//
1460static llvm::cl::list<ParsedSourceLocation>
1461FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1462 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1463
1464//===----------------------------------------------------------------------===//
Eli Friedman35ba7a62009-05-18 22:39:16 +00001465// ObjC Rewriter Options
1466//===----------------------------------------------------------------------===//
1467static llvm::cl::opt<bool>
1468SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1469 llvm::cl::desc("Silence ObjC rewriting warnings"));
1470
1471//===----------------------------------------------------------------------===//
Eli Friedman4d03d382009-05-19 01:17:04 +00001472// Warning Options
1473//===----------------------------------------------------------------------===//
1474
1475// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1476// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1477// -Wextra, so we don't need to worry about it.
1478static llvm::cl::list<std::string>
1479OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1480
1481static llvm::cl::opt<bool> OptPedantic("pedantic");
1482static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1483static llvm::cl::opt<bool> OptNoWarnings("w");
1484
1485//===----------------------------------------------------------------------===//
Eli Friedmane2554252009-05-19 03:06:47 +00001486// Preprocessing (-E mode) Options
1487//===----------------------------------------------------------------------===//
1488static llvm::cl::opt<bool>
1489DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1490static llvm::cl::opt<bool>
1491EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1492static llvm::cl::opt<bool>
1493EnableMacroCommentOutput("CC",
1494 llvm::cl::desc("Enable comment output in -E mode, "
1495 "even from macro expansions"));
1496static llvm::cl::opt<bool>
1497DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1498 " normal output"));
1499static llvm::cl::opt<bool>
1500DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1501 "addition to normal output"));
Eli Friedmane595fe92009-05-19 03:35:57 +00001502
1503//===----------------------------------------------------------------------===//
1504// Dependency file options
1505//===----------------------------------------------------------------------===//
1506static llvm::cl::opt<std::string>
1507DependencyFile("dependency-file",
1508 llvm::cl::desc("Filename (or -) to write dependency output to"));
1509
1510static llvm::cl::opt<bool>
1511DependenciesIncludeSystemHeaders("sys-header-deps",
1512 llvm::cl::desc("Include system headers in dependency output"));
1513
1514static llvm::cl::list<std::string>
1515DependencyTargets("MT",
1516 llvm::cl::desc("Specify target for dependency"));
1517
1518// FIXME: Implement feature
1519static llvm::cl::opt<bool>
1520PhonyDependencyTarget("MP",
1521 llvm::cl::desc("Create phony target for each dependency "
1522 "(other than main file)"));
1523
Eli Friedmane2554252009-05-19 03:06:47 +00001524//===----------------------------------------------------------------------===//
Eli Friedman78a57622009-05-19 10:18:02 +00001525// Analysis options
1526//===----------------------------------------------------------------------===//
1527
1528static llvm::cl::list<Analyses>
1529AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1530llvm::cl::values(
1531#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1532clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001533#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001534clEnumValEnd));
1535
1536static llvm::cl::opt<AnalysisStores>
1537AnalysisStoreOpt("analyzer-store",
1538 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1539 llvm::cl::init(BasicStoreModel),
1540 llvm::cl::values(
1541#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1542clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001543#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001544clEnumValEnd));
1545
1546static llvm::cl::opt<AnalysisConstraints>
1547AnalysisConstraintsOpt("analyzer-constraints",
1548 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1549 llvm::cl::init(RangeConstraintsModel),
1550 llvm::cl::values(
1551#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1552clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001553#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001554clEnumValEnd));
1555
1556static llvm::cl::opt<AnalysisDiagClients>
1557AnalysisDiagOpt("analyzer-output",
1558 llvm::cl::desc("Source Code Analysis - Output Options"),
1559 llvm::cl::init(PD_HTML),
1560 llvm::cl::values(
1561#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1562clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001563#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001564clEnumValEnd));
1565
1566static llvm::cl::opt<bool>
1567VisualizeEGDot("analyzer-viz-egraph-graphviz",
1568 llvm::cl::desc("Display exploded graph using GraphViz"));
1569
1570static llvm::cl::opt<bool>
1571VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1572 llvm::cl::desc("Display exploded graph using Ubigraph"));
1573
1574static llvm::cl::opt<bool>
1575AnalyzeAll("analyzer-opt-analyze-headers",
1576 llvm::cl::desc("Force the static analyzer to analyze "
1577 "functions defined in header files"));
1578
1579static llvm::cl::opt<bool>
1580AnalyzerDisplayProgress("analyzer-display-progress",
1581 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1582
1583static llvm::cl::opt<bool>
1584PurgeDead("analyzer-purge-dead",
1585 llvm::cl::init(true),
1586 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1587 " processing a statement."));
1588
1589static llvm::cl::opt<bool>
1590EagerlyAssume("analyzer-eagerly-assume",
1591 llvm::cl::init(false),
1592 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1593 "symbolic constraints."));
1594
1595static llvm::cl::opt<std::string>
1596AnalyzeSpecificFunction("analyze-function",
1597 llvm::cl::desc("Run analysis on specific function"));
1598
1599static llvm::cl::opt<bool>
1600TrimGraph("trim-egraph",
1601 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1602
1603static AnalyzerOptions ReadAnalyzerOptions() {
1604 AnalyzerOptions Opts;
1605 Opts.AnalysisList = AnalysisList;
1606 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1607 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1608 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1609 Opts.VisualizeEGDot = VisualizeEGDot;
1610 Opts.VisualizeEGUbi = VisualizeEGUbi;
1611 Opts.AnalyzeAll = AnalyzeAll;
1612 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1613 Opts.PurgeDead = PurgeDead;
1614 Opts.EagerlyAssume = EagerlyAssume;
1615 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1616 Opts.TrimGraph = TrimGraph;
1617 return Opts;
1618}
1619
1620//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001621// -dump-build-information Stuff
1622//===----------------------------------------------------------------------===//
1623
1624static llvm::cl::opt<std::string>
1625DumpBuildInformation("dump-build-information",
1626 llvm::cl::value_desc("filename"),
1627 llvm::cl::desc("output a dump of some build information to a file"));
1628
1629static llvm::raw_ostream *BuildLogFile = 0;
1630
1631/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1632/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1633namespace {
1634class LoggingDiagnosticClient : public DiagnosticClient {
1635 llvm::OwningPtr<DiagnosticClient> Chain1;
1636 llvm::OwningPtr<DiagnosticClient> Chain2;
1637public:
1638
1639 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1640 // Output diags both where requested...
1641 Chain1.reset(Normal);
1642 // .. and to our log file.
1643 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1644 !NoShowColumn,
1645 !NoCaretDiagnostics,
1646 !NoShowLocation,
1647 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001648 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001649 !NoDiagnosticsFixIt,
1650 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001651 }
1652
1653 virtual void setLangOptions(const LangOptions *LO) {
1654 Chain1->setLangOptions(LO);
1655 Chain2->setLangOptions(LO);
1656 }
1657
1658 virtual bool IncludeInDiagnosticCounts() const {
1659 return Chain1->IncludeInDiagnosticCounts();
1660 }
1661
1662 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1663 const DiagnosticInfo &Info) {
1664 Chain1->HandleDiagnostic(DiagLevel, Info);
1665 Chain2->HandleDiagnostic(DiagLevel, Info);
1666 }
1667};
1668} // end anonymous namespace.
1669
1670static void SetUpBuildDumpLog(unsigned argc, char **argv,
1671 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1672
1673 std::string ErrorInfo;
1674 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1675 ErrorInfo);
1676
1677 if (!ErrorInfo.empty()) {
1678 llvm::errs() << "error opening -dump-build-information file '"
1679 << DumpBuildInformation << "', option ignored!\n";
1680 delete BuildLogFile;
1681 BuildLogFile = 0;
1682 DumpBuildInformation = "";
1683 return;
1684 }
1685
1686 (*BuildLogFile) << "clang-cc command line arguments: ";
1687 for (unsigned i = 0; i != argc; ++i)
1688 (*BuildLogFile) << argv[i] << ' ';
1689 (*BuildLogFile) << '\n';
1690
1691 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1692 // the diagnostic producers and the normal receiver.
1693 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1694}
1695
1696
1697
1698//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001699// Main driver
1700//===----------------------------------------------------------------------===//
1701
Eli Friedmana9c310842009-05-18 22:20:00 +00001702static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1703 const char* Extension,
1704 bool Binary,
1705 llvm::sys::Path& OutPath) {
1706 llvm::raw_ostream* Ret;
1707 bool UseStdout = false;
1708 std::string OutFile;
1709 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1710 UseStdout = true;
1711 } else if (!OutputFile.empty()) {
1712 OutFile = OutputFile;
1713 } else if (Extension) {
1714 llvm::sys::Path Path(InFile);
1715 Path.eraseSuffix();
1716 Path.appendSuffix(Extension);
1717 OutFile = Path.toString();
1718 } else {
1719 UseStdout = true;
Chris Lattner7f902922009-02-18 01:20:05 +00001720 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001721
Eli Friedmana9c310842009-05-18 22:20:00 +00001722 if (UseStdout) {
1723 Ret = new llvm::raw_stdout_ostream();
1724 if (Binary)
1725 llvm::sys::Program::ChangeStdoutToBinary();
1726 } else {
1727 std::string Error;
1728 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1729 if (!Error.empty()) {
1730 // FIXME: Don't fail this way.
1731 llvm::cerr << "ERROR: " << Error << "\n";
1732 ::exit(1);
1733 }
1734 OutPath = OutFile;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001735 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001736
1737 return Ret;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001738}
1739
Chris Lattner4b009652007-07-25 00:24:17 +00001740/// ProcessInputFile - Process a single input file with the specified state.
1741///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001742static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001743 const std::string &InFile, ProgActions PA,
1744 const llvm::StringMap<bool> &Features) {
Eli Friedmana9c310842009-05-18 22:20:00 +00001745 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek50aab982008-08-08 02:46:37 +00001746 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001747 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001748 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001749 bool CompleteTranslationUnit = true;
Eli Friedmana9c310842009-05-18 22:20:00 +00001750 llvm::sys::Path OutPath;
Douglas Gregor133d2552009-04-02 01:08:08 +00001751
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001752 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001753 default:
Eli Friedmana9c310842009-05-18 22:20:00 +00001754 fprintf(stderr, "Unexpected program action!\n");
1755 HadErrors = true;
1756 return;
1757
1758 case ASTPrint:
1759 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1760 Consumer.reset(CreateASTPrinter(OS.get()));
1761 break;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001762
Douglas Gregor8987c032009-05-21 20:55:50 +00001763 case ASTPrintXML:
1764 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1765 Consumer.reset(CreateASTPrinterXML(OS.get()));
1766 break;
1767
Eli Friedmana9c310842009-05-18 22:20:00 +00001768 case ASTDump:
Douglas Gregor996677c2009-05-30 00:08:05 +00001769 Consumer.reset(CreateASTDumper());
Eli Friedmana9c310842009-05-18 22:20:00 +00001770 break;
1771
Eli Friedmana9c310842009-05-18 22:20:00 +00001772 case ASTView:
Douglas Gregor996677c2009-05-30 00:08:05 +00001773 Consumer.reset(CreateASTViewer());
Eli Friedmana9c310842009-05-18 22:20:00 +00001774 break;
1775
1776 case PrintDeclContext:
1777 Consumer.reset(CreateDeclContextPrinter());
1778 break;
1779
1780 case EmitHTML:
1781 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1782 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1783 break;
1784
1785 case InheritanceView:
1786 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1787 break;
1788
1789 case EmitAssembly:
1790 case EmitLLVM:
1791 case EmitBC:
1792 case EmitLLVMOnly: {
1793 BackendAction Act;
1794 if (ProgAction == EmitAssembly) {
1795 Act = Backend_EmitAssembly;
1796 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1797 } else if (ProgAction == EmitLLVM) {
1798 Act = Backend_EmitLL;
1799 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1800 } else if (ProgAction == EmitLLVMOnly) {
1801 Act = Backend_EmitNothing;
1802 } else {
1803 Act = Backend_EmitBC;
1804 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001805 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001806
Eli Friedmana9c310842009-05-18 22:20:00 +00001807 CompileOptions Opts;
1808 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1809 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1810 PP.getLangOptions(), Opts, InFile,
1811 OS.get()));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001812 break;
Eli Friedmana9c310842009-05-18 22:20:00 +00001813 }
1814
1815 case GeneratePCH:
1816 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1817 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1818 CompleteTranslationUnit = false;
1819 break;
1820
1821 case RewriteObjC:
1822 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedman848763f2009-05-18 22:29:17 +00001823 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedman35ba7a62009-05-18 22:39:16 +00001824 PP.getLangOptions(),
1825 SilenceRewriteMacroWarning));
Eli Friedmana9c310842009-05-18 22:20:00 +00001826 break;
1827
1828 case RewriteBlocks:
1829 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1830 PP.getLangOptions()));
1831 break;
1832
Eli Friedman78a57622009-05-19 10:18:02 +00001833 case RunAnalysis: {
Eli Friedmana9c310842009-05-18 22:20:00 +00001834 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedman78a57622009-05-19 10:18:02 +00001835 PP.getLangOptions(), OutputFile,
1836 ReadAnalyzerOptions()));
Eli Friedmana9c310842009-05-18 22:20:00 +00001837 break;
Eli Friedman78a57622009-05-19 10:18:02 +00001838 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001839
Chris Lattneraf669fb2008-10-12 05:03:36 +00001840 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001841 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001842 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001843 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001844 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001845 RawLex.SetKeepWhitespaceMode(true);
1846
1847 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001848 RawLex.LexFromRawLexer(RawTok);
1849 while (RawTok.isNot(tok::eof)) {
1850 PP.DumpToken(RawTok, true);
1851 fprintf(stderr, "\n");
1852 RawLex.LexFromRawLexer(RawTok);
1853 }
1854 ClearSourceMgr = true;
1855 break;
1856 }
Chris Lattner4b009652007-07-25 00:24:17 +00001857 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001858 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001859 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001860 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001861 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001862 do {
1863 PP.Lex(Tok);
1864 PP.DumpToken(Tok, true);
1865 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001866 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001867 ClearSourceMgr = true;
1868 break;
1869 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001870 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001871 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001872
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001873 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001874 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001875 if (OutputFile.empty() || OutputFile == "-") {
1876 // FIXME: Don't fail this way.
1877 // FIXME: Verify that we can actually seek in the given file.
1878 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1879 ::exit(1);
1880 }
1881 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1882 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001883 ClearSourceMgr = true;
1884 break;
1885 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001886
Chris Lattner772a7c12009-04-27 22:02:30 +00001887 case PrintPreprocessedInput:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001888 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Chris Lattner4b009652007-07-25 00:24:17 +00001889 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001890
Chris Lattner270d29a2009-04-27 21:45:14 +00001891 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001892 break;
1893
Chris Lattnerefe33382009-02-18 01:51:21 +00001894 case ParsePrintCallbacks: {
1895 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001896 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1897 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattner4b009652007-07-25 00:24:17 +00001898 ClearSourceMgr = true;
1899 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001900 }
1901
1902 case ParseSyntaxOnly: { // -fsyntax-only
1903 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001904 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001905 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001906 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001907
1908 case RewriteMacros:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001909 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1910 RewriteMacrosInInput(PP, OS.get());
Chris Lattner1665a9f2008-05-08 06:52:13 +00001911 ClearSourceMgr = true;
1912 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001913
Eli Friedman4ae15b92009-05-19 01:02:07 +00001914 case RewriteTest:
1915 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1916 DoRewriteTest(PP, OS.get());
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001917 ClearSourceMgr = true;
1918 break;
Douglas Gregor133d2552009-04-02 01:08:08 +00001919
1920 case FixIt:
1921 llvm::TimeRegion Timer(ClangFrontendTimer);
1922 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001923 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001924 PP.getSourceManager(),
1925 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001926 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001927 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001928
Chris Lattner38a4f182009-04-27 21:25:27 +00001929 if (FixItAtLocations.size() > 0) {
1930 // Even without the "-fixit" flag, with may have some specific
1931 // locations where the user has requested fixes. Process those
1932 // locations now.
1933 if (!FixItRewrite)
1934 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1935 PP.getSourceManager(),
1936 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001937
Chris Lattner38a4f182009-04-27 21:25:27 +00001938 bool AddedFixitLocation = false;
1939 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1940 Idx != Last; ++Idx) {
1941 RequestedSourceLocation Requested;
1942 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1943 Requested)) {
1944 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1945 FixItAtLocations[Idx].FileName.c_str());
1946 } else {
1947 FixItRewrite->addFixItLocation(Requested);
1948 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001949 }
1950 }
1951
Chris Lattner38a4f182009-04-27 21:25:27 +00001952 if (!AddedFixitLocation) {
1953 // All of the fix-it locations were bad. Don't fix anything.
1954 delete FixItRewrite;
1955 FixItRewrite = 0;
1956 }
1957 }
1958
1959 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001960 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001961 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1962 PP.getSourceManager(),
1963 PP.getTargetInfo(),
1964 PP.getIdentifierTable(),
1965 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001966 /* FreeMemory = */ !DisableFree,
1967 /* size_reserve = */0,
1968 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00001969 llvm::OwningPtr<PCHReader> Reader;
1970 llvm::OwningPtr<ExternalASTSource> Source;
1971
Chris Lattner270d29a2009-04-27 21:45:14 +00001972 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001973 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1974
Chris Lattner270d29a2009-04-27 21:45:14 +00001975 // The user has asked us to include a precompiled header. Load
1976 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001977 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1978 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00001979 // Set the predefines buffer as suggested by the PCH
1980 // reader. Typically, the predefines buffer will be empty.
1981 PP.setPredefines(Reader->getSuggestedPredefines());
1982
Chris Lattner270d29a2009-04-27 21:45:14 +00001983 // Attach the PCH reader to the AST context as an external AST
1984 // source, so that declarations will be deserialized from the
1985 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00001986 if (ContextOwner) {
1987 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001988 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00001989 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001990 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001991 }
1992
Chris Lattner270d29a2009-04-27 21:45:14 +00001993 case PCHReader::Failure:
1994 // Unrecoverable failure: don't even try to process the input
1995 // file.
1996 return;
1997
1998 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001999 // No suitable PCH file could be found. Return an error.
2000 return;
2001
2002#if 0
2003 // FIXME: We can recover from failed attempts to load PCH
2004 // files. This code will do so, if we ever want to enable it.
2005
Chris Lattner270d29a2009-04-27 21:45:14 +00002006 // We delayed the initialization of builtins in the hope of
2007 // loading the PCH file. Since the PCH file could not be
2008 // loaded, initialize builtins now.
2009 if (ContextOwner)
2010 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002011#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00002012 }
2013
2014 // Finish preprocessor initialization. We do this now (rather
2015 // than earlier) because this initialization creates new source
2016 // location entries in the source manager, which must come after
2017 // the source location entries for the PCH file.
2018 if (InitializeSourceManager(PP, InFile))
2019 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00002020 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002021
Chris Lattner270d29a2009-04-27 21:45:14 +00002022
2023 // If we have an ASTConsumer, run the parser with it.
2024 if (Consumer)
2025 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2026 CompleteTranslationUnit);
2027
2028 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2029 llvm::TimeRegion Timer(ClangFrontendTimer);
2030 Token Tok;
2031 // Start parsing the specified input file.
2032 PP.EnterMainSourceFile();
2033 do {
2034 PP.Lex(Tok);
2035 } while (Tok.isNot(tok::eof));
2036 ClearSourceMgr = true;
2037 } else if (PA == ParseNoop) { // -parse-noop
2038 llvm::TimeRegion Timer(ClangFrontendTimer);
2039 ParseFile(PP, new MinimalAction(PP));
2040 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00002041 } else if (PA == PrintPreprocessedInput){ // -E mode.
2042 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmane2554252009-05-19 03:06:47 +00002043 if (DumpMacros)
2044 DoPrintMacros(PP, OS.get());
2045 else
2046 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2047 EnableMacroCommentOutput,
2048 DisableLineMarkers, DumpDefines);
Chris Lattner772a7c12009-04-27 22:02:30 +00002049 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00002050 }
2051
Chris Lattner38a4f182009-04-27 21:25:27 +00002052 if (FixItRewrite)
2053 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2054
2055 // If in -disable-free mode, don't deallocate ASTContext.
2056 if (DisableFree)
2057 ContextOwner.take();
2058 else
2059 ContextOwner.reset(); // Delete ASTContext
Eli Friedmana9c310842009-05-18 22:20:00 +00002060
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002061 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002062 if (CheckDiagnostics(PP))
2063 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002064
Chris Lattner4b009652007-07-25 00:24:17 +00002065 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002066 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002067 PP.PrintStats();
2068 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002069 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002070 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002071 fprintf(stderr, "\n");
2072 }
2073
2074 // For a multi-file compilation, some things are ok with nuking the source
2075 // manager tables, other require stable fileid/macroid's across multiple
2076 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002077 if (ClearSourceMgr)
2078 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002079
2080 if (DisableFree)
2081 Consumer.take();
Eli Friedmana9c310842009-05-18 22:20:00 +00002082 else
2083 Consumer.reset();
2084
2085 // Always delete the output stream because we don't want to leak file
2086 // handles. Also, we don't want to try to erase an open file.
2087 OS.reset();
2088
2089 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2090 !OutPath.isEmpty()) {
2091 // If we had errors, try to erase the output file.
2092 OutPath.eraseFromDisk();
2093 }
Chris Lattner4b009652007-07-25 00:24:17 +00002094}
2095
2096static llvm::cl::list<std::string>
2097InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2098
Chris Lattner4b009652007-07-25 00:24:17 +00002099int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002100 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002101 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002102 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002103 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002104
Chris Lattnerefe33382009-02-18 01:51:21 +00002105 if (TimeReport)
2106 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2107
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002108 if (Verbose)
2109 fprintf(stderr, "clang-cc version 1.0 based upon " PACKAGE_STRING
2110 " hosted on " LLVM_HOSTTRIPLE "\n");
2111
Chris Lattner4b009652007-07-25 00:24:17 +00002112 // If no input was specified, read from stdin.
2113 if (InputFilenames.empty())
2114 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00002115
Ted Kremenekb240e822007-12-11 23:28:38 +00002116 // Create the diagnostic client for reporting errors or for
2117 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002118 llvm::OwningPtr<DiagnosticClient> DiagClient;
2119 if (VerifyDiagnostics) {
2120 // When checking diagnostics, just buffer them up.
2121 DiagClient.reset(new TextDiagnosticBuffer());
2122 if (InputFilenames.size() != 1) {
2123 fprintf(stderr, "-verify only works on single input files for now.\n");
2124 return 1;
2125 }
2126 if (!HTMLDiag.empty()) {
2127 fprintf(stderr, "-verify and -html-diags don't work together\n");
2128 return 1;
2129 }
2130 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002131 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00002132
2133 // If -fmessage-length=N was not specified, determine whether this
2134 // is a terminal and, if so, implicitly define -fmessage-length
2135 // appropriately.
2136 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00002137 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00002138
Chris Lattner5f7937d2009-04-17 20:40:01 +00002139 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002140 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002141 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002142 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002143 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00002144 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00002145 !NoDiagnosticsFixIt,
2146 MessageLength));
Ted Kremenek5c341732008-08-07 17:49:57 +00002147 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002148 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002149 }
Chris Lattner94859302009-04-17 21:05:01 +00002150
2151 if (!DumpBuildInformation.empty()) {
2152 if (!HTMLDiag.empty()) {
2153 fprintf(stderr,
2154 "-dump-build-information and -html-diags don't work together\n");
2155 return 1;
2156 }
2157
2158 SetUpBuildDumpLog(argc, argv, DiagClient);
2159 }
2160
Ted Kremenek5c341732008-08-07 17:49:57 +00002161
Chris Lattner4b009652007-07-25 00:24:17 +00002162 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002163 Diagnostic Diags(DiagClient.get());
Eli Friedman4d03d382009-05-19 01:17:04 +00002164 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2165 OptNoWarnings))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002166 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002167
Chris Lattner45a56e02007-12-05 23:24:17 +00002168 // -I- is a deprecated GCC feature, scan for it and reject it.
2169 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2170 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002171 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002172 I_dirs.erase(I_dirs.begin()+i);
2173 --i;
2174 }
2175 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002176
2177 // Get information about the target being compiled for.
2178 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002179 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2180
Chris Lattner2c77d852008-03-14 06:12:05 +00002181 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002182 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2183 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002184 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002185 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002186
Daniel Dunbar9c321102009-01-20 23:17:32 +00002187 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002188 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002189
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002190 llvm::OwningPtr<SourceManager> SourceMgr;
2191
Chris Lattnere1be6022009-04-14 23:22:57 +00002192 // Create a file manager object to provide access to and cache the filesystem.
2193 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002194
Daniel Dunbar07181d72009-05-06 03:16:41 +00002195 // Compute the feature set, unfortunately this effects the language!
2196 llvm::StringMap<bool> Features;
2197 ComputeFeatureMap(Target.get(), Features);
2198
Chris Lattner4b009652007-07-25 00:24:17 +00002199 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002200 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002201
Chris Lattner2b989562009-03-04 21:40:56 +00002202 /// Create a SourceManager object. This tracks and owns all the file
2203 /// buffers allocated to a translation unit.
2204 if (!SourceMgr)
2205 SourceMgr.reset(new SourceManager());
2206 else
2207 SourceMgr->clearIDTables();
2208
2209 // Initialize language options, inferring file types from input filenames.
2210 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002211 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002212
Chris Lattner2b989562009-03-04 21:40:56 +00002213 InitializeBaseLanguage();
2214 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002215 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002216 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002217
2218 // Process the -I options and set them in the HeaderInfo.
2219 HeaderSearch HeaderInfo(FileMgr);
2220
Chris Lattnere1be6022009-04-14 23:22:57 +00002221
Chris Lattner2b989562009-03-04 21:40:56 +00002222 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2223
2224 // Set up the preprocessor with these options.
Eli Friedmane934dca2009-05-18 07:39:39 +00002225 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattner2b989562009-03-04 21:40:56 +00002226 *SourceMgr.get(), HeaderInfo);
2227
2228 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2229
2230 if (!PP)
2231 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002232
Eli Friedmane595fe92009-05-19 03:35:57 +00002233 // Handle generating dependencies, if requested
2234 if (!DependencyFile.empty()) {
2235 llvm::raw_ostream *DependencyOS;
2236 if (DependencyTargets.empty()) {
2237 // FIXME: Use a proper diagnostic
2238 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2239 HadErrors = true;
2240 continue;
2241 }
2242 std::string ErrStr;
2243 DependencyOS =
2244 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2245 if (!ErrStr.empty()) {
2246 // FIXME: Use a proper diagnostic
2247 llvm::cerr << "unable to open dependency file: " + ErrStr;
2248 HadErrors = true;
2249 continue;
2250 }
2251
2252 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2253 DependenciesIncludeSystemHeaders,
2254 PhonyDependencyTarget);
2255 }
2256
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002257 if (ImplicitIncludePCH.empty() &&
2258 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002259 continue;
2260
Chris Lattner5f7937d2009-04-17 20:40:01 +00002261 if (!HTMLDiag.empty())
2262 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002263
2264 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002265 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002266
Chris Lattner2961dc52009-04-17 20:16:08 +00002267 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002268 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002269 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002270
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002271 if (!NoCaretDiagnostics)
2272 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2273 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2274 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002275
2276 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002277 FileMgr.PrintStats();
2278 fprintf(stderr, "\n");
2279 }
Chris Lattner94859302009-04-17 21:05:01 +00002280
2281 delete ClangFrontendTimer;
2282 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002283
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002284 // If verifying diagnostics and we reached here, all is well.
2285 if (VerifyDiagnostics)
2286 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002287
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002288 // Managed static deconstruction. Useful for making things like
2289 // -time-passes usable.
2290 llvm::llvm_shutdown();
2291
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002292 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002293}