blob: c58340c3eee7ed38407709e71fbd9cf8d5b0bc51 [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
Edwin Törökeff37122009-06-04 07:18:23 +0000331static llvm::cl::opt<bool>
Edwin Törökcca1e502009-06-04 07:27:53 +0000332NoColorDiagnostic("fno-color-diagnostics",
Edwin Törökeff37122009-06-04 07:18:23 +0000333 llvm::cl::desc("Don't use colors when showing diagnostics "
334 "(automatically turned off if output is not a "
335 "terminal)."));
Chris Lattner4b009652007-07-25 00:24:17 +0000336//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000337// C++ Visualization.
338//===----------------------------------------------------------------------===//
339
340static llvm::cl::opt<std::string>
341InheritanceViewCls("cxx-inheritance-view",
342 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000343 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000344
345//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000346// Builtin Options
347//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000348
349static llvm::cl::opt<bool>
350TimeReport("ftime-report",
351 llvm::cl::desc("Print the amount of time each "
352 "phase of compilation takes"));
353
Douglas Gregor23d23262009-02-14 20:49:29 +0000354static llvm::cl::opt<bool>
355Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000356 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000357 "freestanding environment"));
358
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000359static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000360AllowBuiltins("fbuiltin", llvm::cl::init(true),
361 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000362
363
364static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000365MathErrno("fmath-errno", llvm::cl::init(true),
366 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000367
Douglas Gregor23d23262009-02-14 20:49:29 +0000368//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000369// Language Options
370//===----------------------------------------------------------------------===//
371
372enum LangKind {
373 langkind_unspecified,
374 langkind_c,
375 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000376 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000377 langkind_cxx,
378 langkind_cxx_cpp,
379 langkind_objc,
380 langkind_objc_cpp,
381 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000382 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000383};
384
Chris Lattner4b009652007-07-25 00:24:17 +0000385static llvm::cl::opt<LangKind>
386BaseLang("x", llvm::cl::desc("Base language to compile"),
387 llvm::cl::init(langkind_unspecified),
388 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
389 clEnumValN(langkind_cxx, "c++", "C++"),
390 clEnumValN(langkind_objc, "objective-c", "Objective C"),
391 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000392 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000393 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000394 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
395 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000396 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000397 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000398 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
399 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000400 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000401 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000402 clEnumValN(langkind_c, "c-header",
403 "C header"),
404 clEnumValN(langkind_objc, "objective-c-header",
405 "Objective-C header"),
406 clEnumValN(langkind_cxx, "c++-header",
407 "C++ header"),
408 clEnumValN(langkind_objcxx, "objective-c++-header",
409 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000410 clEnumValEnd));
411
412static llvm::cl::opt<bool>
413LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
414 llvm::cl::Hidden);
415static llvm::cl::opt<bool>
416LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
417 llvm::cl::Hidden);
418
Chris Lattnere1be6022009-04-14 23:22:57 +0000419static llvm::cl::opt<bool>
420ObjCExclusiveGC("fobjc-gc-only",
421 llvm::cl::desc("Use GC exclusively for Objective-C related "
422 "memory management"));
423
424static llvm::cl::opt<bool>
425ObjCEnableGC("fobjc-gc",
426 llvm::cl::desc("Enable Objective-C garbage collection"));
427
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000428static llvm::cl::opt<bool>
429ObjCEnableGCBitmapPrint("print-ivar-layout",
430 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
431
Chris Lattnere1be6022009-04-14 23:22:57 +0000432static llvm::cl::opt<LangOptions::VisibilityMode>
433SymbolVisibility("fvisibility",
434 llvm::cl::desc("Set the default symbol visibility:"),
435 llvm::cl::init(LangOptions::Default),
436 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
437 "Use default symbol visibility"),
438 clEnumValN(LangOptions::Hidden, "hidden",
439 "Use hidden symbol visibility"),
440 clEnumValN(LangOptions::Protected,"protected",
441 "Use protected symbol visibility"),
442 clEnumValEnd));
443
444static llvm::cl::opt<bool>
445OverflowChecking("ftrapv",
446 llvm::cl::desc("Trap on integer overflow"),
447 llvm::cl::init(false));
448
Fariborz Jahanianfefd5e82009-05-22 20:17:16 +0000449static llvm::cl::opt<bool>
450ObjCSenderDispatch("fobjc-sender-dependent-dispatch",
451 llvm::cl::desc("Enable sender-dependent dispatch for"
452 "Objective-C messages"), llvm::cl::init(false));
Chris Lattnere1be6022009-04-14 23:22:57 +0000453
Ted Kremenek11ad8952007-12-05 23:49:08 +0000454/// InitializeBaseLanguage - Handle the -x foo options.
455static void InitializeBaseLanguage() {
456 if (LangObjC)
457 BaseLang = langkind_objc;
458 else if (LangObjCXX)
459 BaseLang = langkind_objcxx;
460}
461
462static LangKind GetLanguage(const std::string &Filename) {
463 if (BaseLang != langkind_unspecified)
464 return BaseLang;
465
466 std::string::size_type DotPos = Filename.rfind('.');
467
468 if (DotPos == std::string::npos) {
469 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000470 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000471 }
472
Ted Kremenek11ad8952007-12-05 23:49:08 +0000473 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
474 // C header: .h
475 // C++ header: .hh or .H;
476 // assembler no preprocessing: .s
477 // assembler: .S
478 if (Ext == "c")
479 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000480 else if (Ext == "S" ||
481 // If the compiler is run on a .s file, preprocess it as .S
482 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000483 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000484 else if (Ext == "i")
485 return langkind_c_cpp;
486 else if (Ext == "ii")
487 return langkind_cxx_cpp;
488 else if (Ext == "m")
489 return langkind_objc;
490 else if (Ext == "mi")
491 return langkind_objc_cpp;
492 else if (Ext == "mm" || Ext == "M")
493 return langkind_objcxx;
494 else if (Ext == "mii")
495 return langkind_objcxx_cpp;
496 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
497 Ext == "c++" || Ext == "cp" || Ext == "cxx")
498 return langkind_cxx;
499 else
500 return langkind_c;
501}
502
503
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000504static void InitializeCOptions(LangOptions &Options) {
505 // Do nothing.
506}
507
508static void InitializeObjCOptions(LangOptions &Options) {
509 Options.ObjC1 = Options.ObjC2 = 1;
510}
511
512
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000513static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000514 // FIXME: implement -fpreprocessed mode.
515 bool NoPreprocess = false;
516
Ted Kremenek11ad8952007-12-05 23:49:08 +0000517 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000518 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000519 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000520 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000521 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000522 case langkind_c_cpp:
523 NoPreprocess = true;
524 // FALLTHROUGH
525 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000526 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000527 break;
528 case langkind_cxx_cpp:
529 NoPreprocess = true;
530 // FALLTHROUGH
531 case langkind_cxx:
532 Options.CPlusPlus = 1;
533 break;
534 case langkind_objc_cpp:
535 NoPreprocess = true;
536 // FALLTHROUGH
537 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000538 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000539 break;
540 case langkind_objcxx_cpp:
541 NoPreprocess = true;
542 // FALLTHROUGH
543 case langkind_objcxx:
544 Options.ObjC1 = Options.ObjC2 = 1;
545 Options.CPlusPlus = 1;
546 break;
547 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000548
549 if (ObjCExclusiveGC)
550 Options.setGCMode(LangOptions::GCOnly);
551 else if (ObjCEnableGC)
552 Options.setGCMode(LangOptions::HybridGC);
553
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000554 if (ObjCEnableGCBitmapPrint)
555 Options.ObjCGCBitmapPrint = 1;
556
Chris Lattnere1be6022009-04-14 23:22:57 +0000557 Options.setVisibilityMode(SymbolVisibility);
558 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000559}
560
561/// LangStds - Language standards we support.
562enum LangStds {
563 lang_unspecified,
564 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000565 lang_gnu_START,
566 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000567 lang_cxx98, lang_gnucxx98,
568 lang_cxx0x, lang_gnucxx0x
569};
570
571static llvm::cl::opt<LangStds>
572LangStd("std", llvm::cl::desc("Language standard to compile for"),
573 llvm::cl::init(lang_unspecified),
574 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
575 clEnumValN(lang_c89, "c90", "ISO C 1990"),
576 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
577 clEnumValN(lang_c94, "iso9899:199409",
578 "ISO C 1990 with amendment 1"),
579 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000580 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000581 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000582 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000583 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000584 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000585 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000586 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000587 clEnumValN(lang_gnu99, "gnu9x",
588 "ISO C 1999 with GNU extensions"),
589 clEnumValN(lang_cxx98, "c++98",
590 "ISO C++ 1998 with amendments"),
591 clEnumValN(lang_gnucxx98, "gnu++98",
592 "ISO C++ 1998 with amendments and GNU "
593 "extensions (default for C++)"),
594 clEnumValN(lang_cxx0x, "c++0x",
595 "Upcoming ISO C++ 200x with amendments"),
596 clEnumValN(lang_gnucxx0x, "gnu++0x",
597 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000598 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000599 clEnumValEnd));
600
601static llvm::cl::opt<bool>
602NoOperatorNames("fno-operator-names",
603 llvm::cl::desc("Do not treat C++ operator name keywords as "
604 "synonyms for operators"));
605
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000606static llvm::cl::opt<bool>
607PascalStrings("fpascal-strings",
608 llvm::cl::desc("Recognize and construct Pascal-style "
609 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000610
611static llvm::cl::opt<bool>
612MSExtensions("fms-extensions",
613 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000614 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000615
616static llvm::cl::opt<bool>
617WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000618 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000619
620static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000621NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000622 llvm::cl::desc("Disallow implicit conversions between "
623 "vectors with a different number of "
624 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000625
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000626static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000627EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000628
629static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000630EnableHeinousExtensions("fheinous-gnu-extensions",
631 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
632 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
633
634static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000635ObjCNonFragileABI("fobjc-nonfragile-abi",
636 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000637
Daniel Dunbar5523e862009-05-04 05:16:21 +0000638
639static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000640EmitAllDecls("femit-all-decls",
641 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000642
Daniel Dunbar91692d92008-08-11 17:36:14 +0000643static llvm::cl::opt<bool>
644Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000645 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000646
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000647static llvm::cl::opt<bool>
648GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000649 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000650 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000651
652static llvm::cl::opt<bool>
653NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000654 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000655 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000656
Eli Friedman449eb692009-06-05 07:12:17 +0000657static llvm::cl::opt<bool>
658CharIsSigned("fsigned-char",
659 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000660
661
662static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000663Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000664
Douglas Gregor375733c2009-03-10 00:06:19 +0000665static llvm::cl::opt<unsigned>
666TemplateDepth("ftemplate-depth", llvm::cl::init(99),
667 llvm::cl::desc("Maximum depth of recursive template "
668 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000669static llvm::cl::opt<bool>
670DollarsInIdents("fdollars-in-identifiers",
671 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000672
Anders Carlssondfd77642009-04-06 17:37:10 +0000673
674static llvm::cl::opt<bool>
675OptSize("Os", llvm::cl::desc("Optimize for size"));
676
677static llvm::cl::opt<bool>
Daniel Dunbard27b66b2009-06-02 22:07:45 +0000678DisableLLVMOptimizations("disable-llvm-optzns",
679 llvm::cl::desc("Don't run LLVM optimization passes"));
680
681static llvm::cl::opt<bool>
Anders Carlssondfd77642009-04-06 17:37:10 +0000682NoCommon("fno-common",
683 llvm::cl::desc("Compile common globals like normal definitions"),
684 llvm::cl::ValueDisallowed);
685
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000686static llvm::cl::opt<std::string>
687MainFileName("main-file-name",
688 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000689
Anders Carlssonf2310142009-05-13 19:49:53 +0000690// FIXME: Also add an "-fno-access-control" option.
691static llvm::cl::opt<bool>
692AccessControl("faccess-control",
693 llvm::cl::desc("Enable C++ access control"));
694
Anders Carlssondfd77642009-04-06 17:37:10 +0000695// It might be nice to add bounds to the CommandLine library directly.
696struct OptLevelParser : public llvm::cl::parser<unsigned> {
697 bool parse(llvm::cl::Option &O, const char *ArgName,
698 const std::string &Arg, unsigned &Val) {
699 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
700 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000701 if (Val > 3)
702 return O.error(": '" + Arg + "' invalid optimization level!");
703 return false;
704 }
705};
706static llvm::cl::opt<unsigned, false, OptLevelParser>
707OptLevel("O", llvm::cl::Prefix,
708 llvm::cl::desc("Optimization level"),
709 llvm::cl::init(0));
710
Daniel Dunbare079c712009-04-08 03:03:23 +0000711static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000712PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
713
714static llvm::cl::opt<bool>
715StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000716
Daniel Dunbar34542952008-08-23 08:43:39 +0000717static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000718 TargetInfo *Target,
719 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000720 // Allow the target to set the default the langauge options as it sees fit.
721 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000722
723 // Pass the map of target features to the target for validation and
724 // processing.
725 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000726
Chris Lattner4b009652007-07-25 00:24:17 +0000727 if (LangStd == lang_unspecified) {
728 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000729 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000730 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000731 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000732 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000733 case langkind_c_cpp:
734 case langkind_objc:
735 case langkind_objc_cpp:
736 LangStd = lang_gnu99;
737 break;
738 case langkind_cxx:
739 case langkind_cxx_cpp:
740 case langkind_objcxx:
741 case langkind_objcxx_cpp:
742 LangStd = lang_gnucxx98;
743 break;
744 }
745 }
746
747 switch (LangStd) {
748 default: assert(0 && "Unknown language standard!");
749
750 // Fall through from newer standards to older ones. This isn't really right.
751 // FIXME: Enable specifically the right features based on the language stds.
752 case lang_gnucxx0x:
753 case lang_cxx0x:
754 Options.CPlusPlus0x = 1;
755 // FALL THROUGH
756 case lang_gnucxx98:
757 case lang_cxx98:
758 Options.CPlusPlus = 1;
759 Options.CXXOperatorNames = !NoOperatorNames;
760 // FALL THROUGH.
761 case lang_gnu99:
762 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000763 Options.C99 = 1;
764 Options.HexFloats = 1;
765 // FALL THROUGH.
766 case lang_gnu89:
767 Options.BCPLComment = 1; // Only for C99/C++.
768 // FALL THROUGH.
769 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000770 Options.Digraphs = 1; // C94, C99, C++.
771 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000772 case lang_c89:
773 break;
774 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000775
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000776 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
777 Options.GNUMode = LangStd >= lang_gnu_START;
778
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000779 if (Options.CPlusPlus) {
780 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000781 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000782 }
Chris Lattner4b009652007-07-25 00:24:17 +0000783
Chris Lattner6ab935b2008-04-05 06:32:51 +0000784 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
785 Options.ImplicitInt = 1;
786 else
787 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000788
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000789 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
790 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000791 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000792 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000793 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000794
Chris Lattner58d5ba52008-12-05 00:10:44 +0000795 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
796 // even if they are normally on for the target. In GNU modes (e.g.
797 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000798 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000799 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000800 Options.Blocks = 0;
801
Chris Lattner284784c2009-04-19 07:06:52 +0000802 // Default to not accepting '$' in identifiers when preprocessing assembler,
803 // but do accept when preprocessing C. FIXME: these defaults are right for
804 // darwin, are they right everywhere?
805 Options.DollarIdents = LK != langkind_asm_cpp;
806 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000807 Options.DollarIdents = DollarsInIdents;
808
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000809 if (PascalStrings.getPosition())
810 Options.PascalStrings = PascalStrings;
Eli Friedman6b6ca942009-06-08 06:11:14 +0000811 if (MSExtensions.getPosition())
812 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000813 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000814 if (NoLaxVectorConversions.getPosition())
815 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000816 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000817 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000818 Options.Blocks = EnableBlocks;
Eli Friedman449eb692009-06-05 07:12:17 +0000819 if (CharIsSigned.getPosition())
820 Options.CharIsSigned = CharIsSigned;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000821
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000822 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000823 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000824 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000825 Options.Freestanding = Options.NoBuiltin = 1;
826
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000827 if (EnableHeinousExtensions)
828 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000829
Anders Carlssonf2310142009-05-13 19:49:53 +0000830 if (AccessControl)
831 Options.AccessControl = 1;
832
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000833 Options.MathErrno = MathErrno;
834
Douglas Gregor375733c2009-03-10 00:06:19 +0000835 Options.InstantiationDepth = TemplateDepth;
836
Chris Lattnerddae7102008-12-04 22:54:33 +0000837 // Override the default runtime if the user requested it.
838 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000839 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000840 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000841 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000842
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000843 if (ObjCNonFragileABI)
844 Options.ObjCNonFragileABI = 1;
Fariborz Jahanianfefd5e82009-05-22 20:17:16 +0000845
846 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000847
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000848 if (EmitAllDecls)
849 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000850
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000851 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
852 // support.
853 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000854
855 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000856 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000857 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000858
859 assert(PICLevel <= 2 && "Invalid value for -pic-level");
860 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000861
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000862 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000863 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000864 Options.NoInline = !OptSize && !OptLevel;
865
866 Options.Static = StaticDefine;
867
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000868 if (MainFileName.getPosition())
869 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000870}
871
872//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000873// Target Triple Processing.
874//===----------------------------------------------------------------------===//
875
876static llvm::cl::opt<std::string>
877TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000878 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000879
Chris Lattnerfc457002008-03-05 01:18:20 +0000880static llvm::cl::opt<std::string>
Chris Lattner2b168e02008-09-30 01:13:12 +0000881MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000882 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000883
Chris Lattner01de9c82008-09-30 20:16:56 +0000884// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
885// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000886
887// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000888static void HandleMacOSVersionMin(std::string &Triple) {
889 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
890 if (DarwinDashIdx == std::string::npos) {
891 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000892 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000893 exit(1);
894 }
895 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
896
Chris Lattner01de9c82008-09-30 20:16:56 +0000897 // Remove the number.
898 Triple.resize(DarwinNumIdx);
899
900 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
901 bool MacOSVersionMinIsInvalid = false;
902 int VersionNum = 0;
903 if (MacOSVersionMin.size() < 4 ||
904 MacOSVersionMin.substr(0, 3) != "10." ||
905 !isdigit(MacOSVersionMin[3])) {
906 MacOSVersionMinIsInvalid = true;
907 } else {
908 const char *Start = MacOSVersionMin.c_str()+3;
909 char *End = 0;
910 VersionNum = (int)strtol(Start, &End, 10);
911
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000912 // The version number must be in the range 0-9.
913 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
914
Chris Lattner01de9c82008-09-30 20:16:56 +0000915 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
916 Triple += llvm::itostr(VersionNum+4);
917
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000918 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
919 // Add the period piece (.7) to the end of the triple. This gives us
920 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000921 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000922 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
923 MacOSVersionMinIsInvalid = true;
924 }
925 }
926
927 if (MacOSVersionMinIsInvalid) {
928 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000929 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000930 MacOSVersionMin.c_str());
931 exit(1);
932 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000933 else if (VersionNum <= 4 &&
934 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
935 fprintf(stderr,
936 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
937 MacOSVersionMin.c_str());
938 exit(1);
939 }
940
Chris Lattner01de9c82008-09-30 20:16:56 +0000941}
942
Daniel Dunbar93f64532009-04-10 19:52:24 +0000943static llvm::cl::opt<std::string>
944IPhoneOSVersionMin("miphoneos-version-min",
945 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
946
947// If -miphoneos-version-min=2.2 is specified, change the triple from being
948// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
949// 9 as the default major Darwin number, and encode the iPhone OS version
950// number in the minor version and revision.
951
952// FIXME: We should have the driver do this instead.
953static void HandleIPhoneOSVersionMin(std::string &Triple) {
954 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
955 if (DarwinDashIdx == std::string::npos) {
956 fprintf(stderr,
957 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
958 exit(1);
959 }
960 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
961
962 // Remove the number.
963 Triple.resize(DarwinNumIdx);
964
965 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
966 bool IPhoneOSVersionMinIsInvalid = false;
967 int VersionNum = 0;
968 if (IPhoneOSVersionMin.size() < 3 ||
969 !isdigit(IPhoneOSVersionMin[0])) {
970 IPhoneOSVersionMinIsInvalid = true;
971 } else {
972 const char *Start = IPhoneOSVersionMin.c_str();
973 char *End = 0;
974 VersionNum = (int)strtol(Start, &End, 10);
975
976 // The version number must be in the range 0-9.
977 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
978
979 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
980 Triple += "9." + llvm::itostr(VersionNum);
981
982 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
983 // Add the period piece (.2) to the end of the triple. This gives us
984 // something like ...-darwin9.2.2
985 Triple += End;
986 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
987 IPhoneOSVersionMinIsInvalid = true;
988 }
989 }
990
991 if (IPhoneOSVersionMinIsInvalid) {
992 fprintf(stderr,
993 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
994 IPhoneOSVersionMin.c_str());
995 exit(1);
996 }
997}
998
Chris Lattner01de9c82008-09-30 20:16:56 +0000999/// CreateTargetTriple - Process the various options that affect the target
1000/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +00001001static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +00001002 // Initialize base triple. If a -triple option has been specified, use
1003 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +00001004 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +00001005 if (Triple.empty())
1006 Triple = llvm::sys::getHostTriple();
Chris Lattner2b168e02008-09-30 01:13:12 +00001007
1008 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
1009 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +00001010 if (!MacOSVersionMin.empty())
1011 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +00001012 else if (!IPhoneOSVersionMin.empty())
1013 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +00001014
Chris Lattner2b168e02008-09-30 01:13:12 +00001015 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +00001016}
1017
1018//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001019// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001020//===----------------------------------------------------------------------===//
1021
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001022static bool InitializeSourceManager(Preprocessor &PP,
1023 const std::string &InFile) {
1024 // Figure out where to get and map in the main file.
1025 SourceManager &SourceMgr = PP.getSourceManager();
1026 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001027
1028 if (EmptyInputOnly) {
1029 const char *EmptyStr = "";
1030 llvm::MemoryBuffer *SB =
1031 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1032 SourceMgr.createMainFileIDForMemBuffer(SB);
1033 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001034 const FileEntry *File = FileMgr.getFile(InFile);
1035 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1036 if (SourceMgr.getMainFileID().isInvalid()) {
1037 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1038 << InFile.c_str();
1039 return true;
1040 }
1041 } else {
1042 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1043
1044 // If stdin was empty, SB is null. Cons up an empty memory
1045 // buffer now.
1046 if (!SB) {
1047 const char *EmptyStr = "";
1048 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1049 }
1050
1051 SourceMgr.createMainFileIDForMemBuffer(SB);
1052 if (SourceMgr.getMainFileID().isInvalid()) {
1053 PP.getDiagnostics().Report(FullSourceLoc(),
1054 diag::err_fe_error_reading_stdin);
1055 return true;
1056 }
1057 }
1058
1059 return false;
1060}
1061
Chris Lattner47b6a162008-04-19 23:09:31 +00001062
Chris Lattner94269d72009-04-21 05:40:52 +00001063//===----------------------------------------------------------------------===//
1064// Preprocessor Initialization
1065//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001066
Chris Lattner94269d72009-04-21 05:40:52 +00001067// FIXME: Preprocessor builtins to support.
1068// -A... - Play with #assertions
1069// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001070
Chris Lattner94269d72009-04-21 05:40:52 +00001071static llvm::cl::list<std::string>
1072D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1073 llvm::cl::desc("Predefine the specified macro"));
1074static llvm::cl::list<std::string>
1075U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1076 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001077
Chris Lattner94269d72009-04-21 05:40:52 +00001078static llvm::cl::list<std::string>
1079ImplicitIncludes("include", llvm::cl::value_desc("file"),
1080 llvm::cl::desc("Include file before parsing"));
1081static llvm::cl::list<std::string>
1082ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1083 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001084
Chris Lattner94269d72009-04-21 05:40:52 +00001085static llvm::cl::opt<std::string>
1086ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1087 llvm::cl::desc("Include precompiled header file"));
1088
1089static llvm::cl::opt<std::string>
1090ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1091 llvm::cl::desc("Include file before parsing"));
1092
Chris Lattner4b009652007-07-25 00:24:17 +00001093
1094//===----------------------------------------------------------------------===//
1095// Preprocessor include path information.
1096//===----------------------------------------------------------------------===//
1097
1098// This tool exports a large number of command line options to control how the
1099// preprocessor searches for header files. At root, however, the Preprocessor
1100// object takes a very simple interface: a list of directories to search for
1101//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001102// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001103// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001104//
Chris Lattner4b009652007-07-25 00:24:17 +00001105
1106static llvm::cl::opt<bool>
1107nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1108
1109// Various command line options. These four add directories to each chain.
1110static llvm::cl::list<std::string>
1111F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1112 llvm::cl::desc("Add directory to framework include search path"));
1113static llvm::cl::list<std::string>
1114I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1115 llvm::cl::desc("Add directory to include search path"));
1116static llvm::cl::list<std::string>
1117idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1118 llvm::cl::desc("Add directory to AFTER include search path"));
1119static llvm::cl::list<std::string>
1120iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1121 llvm::cl::desc("Add directory to QUOTE include search path"));
1122static llvm::cl::list<std::string>
1123isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1124 llvm::cl::desc("Add directory to SYSTEM include search path"));
1125
1126// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1127static llvm::cl::list<std::string>
1128iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1129 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1130static llvm::cl::list<std::string>
1131iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1132 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1133static llvm::cl::list<std::string>
1134iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1135 llvm::cl::Prefix,
1136 llvm::cl::desc("Set directory to include search path with prefix"));
1137
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001138static llvm::cl::opt<std::string>
1139isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1140 llvm::cl::desc("Set the system root directory (usually /)"));
1141
Chris Lattner4b009652007-07-25 00:24:17 +00001142// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001143
Chris Lattner4b009652007-07-25 00:24:17 +00001144/// InitializeIncludePaths - Process the -I options and set them in the
1145/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001146void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1147 FileManager &FM, const LangOptions &Lang) {
1148 InitHeaderSearch Init(Headers, Verbose, isysroot);
1149
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001150 // Handle -I... and -F... options, walking the lists in parallel.
1151 unsigned Iidx = 0, Fidx = 0;
1152 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1153 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001154 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001155 ++Iidx;
1156 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001157 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001158 ++Fidx;
1159 }
1160 }
Chris Lattner4b009652007-07-25 00:24:17 +00001161
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001162 // Consume what's left from whatever list was longer.
1163 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001164 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001165 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001166 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001167
1168 // Handle -idirafter... options.
1169 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001170 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1171 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001172
1173 // Handle -iquote... options.
1174 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001175 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001176
1177 // Handle -isystem... options.
1178 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001179 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001180
1181 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1182 // parallel, processing the values in order of occurance to get the right
1183 // prefixes.
1184 {
1185 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1186 unsigned iprefix_idx = 0;
1187 unsigned iwithprefix_idx = 0;
1188 unsigned iwithprefixbefore_idx = 0;
1189 bool iprefix_done = iprefix_vals.empty();
1190 bool iwithprefix_done = iwithprefix_vals.empty();
1191 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1192 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1193 if (!iprefix_done &&
1194 (iwithprefix_done ||
1195 iprefix_vals.getPosition(iprefix_idx) <
1196 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1197 (iwithprefixbefore_done ||
1198 iprefix_vals.getPosition(iprefix_idx) <
1199 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1200 Prefix = iprefix_vals[iprefix_idx];
1201 ++iprefix_idx;
1202 iprefix_done = iprefix_idx == iprefix_vals.size();
1203 } else if (!iwithprefix_done &&
1204 (iwithprefixbefore_done ||
1205 iwithprefix_vals.getPosition(iwithprefix_idx) <
1206 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001207 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1208 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001209 ++iwithprefix_idx;
1210 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1211 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001212 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1213 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001214 ++iwithprefixbefore_idx;
1215 iwithprefixbefore_done =
1216 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1217 }
1218 }
1219 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001220
Nico Weber770e3882008-08-22 09:25:22 +00001221 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001222
Daniel Dunbar4e604292009-02-21 20:52:41 +00001223 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001224 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001225 llvm::sys::Path::GetMainExecutable(Argv0,
1226 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001227 if (!MainExecutablePath.isEmpty()) {
1228 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1229 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001230
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001231 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001232 MainExecutablePath.appendComponent("lib");
1233 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001234 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001235 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001236
1237 // We pass true to ignore sysroot so that we *always* look for clang headers
1238 // relative to our executable, never relative to -isysroot.
1239 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1240 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001241 }
1242
Nico Weber770e3882008-08-22 09:25:22 +00001243 if (!nostdinc)
1244 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001245
1246 // Now that we have collected all of the include paths, merge them all
1247 // together and tell the preprocessor about them.
1248
Nico Weber770e3882008-08-22 09:25:22 +00001249 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001250}
1251
Chris Lattner94269d72009-04-21 05:40:52 +00001252void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1253{
1254 // Add macros from the command line.
1255 unsigned d = 0, D = D_macros.size();
1256 unsigned u = 0, U = U_macros.size();
1257 while (d < D || u < U) {
1258 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1259 InitOpts.addMacroDef(D_macros[d++]);
1260 else
1261 InitOpts.addMacroUndef(U_macros[u++]);
1262 }
1263
1264 // If -imacros are specified, include them now. These are processed before
1265 // any -include directives.
1266 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1267 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1268
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001269 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1270 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner94269d72009-04-21 05:40:52 +00001271 // We want to add these paths to the predefines buffer in order, make a
1272 // temporary vector to sort by their occurrence.
1273 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1274
1275 if (!ImplicitIncludePTH.empty())
1276 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1277 &ImplicitIncludePTH));
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001278 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1279 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1280 &ImplicitIncludePCH));
Chris Lattner94269d72009-04-21 05:40:52 +00001281 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1282 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1283 &ImplicitIncludes[i]));
1284 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1285
1286
1287 // Now that they are ordered by position, add to the predefines buffer.
1288 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1289 std::string *Ptr = OrderedPaths[i].second;
1290 if (!ImplicitIncludes.empty() &&
1291 Ptr >= &ImplicitIncludes[0] &&
1292 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1293 InitOpts.addInclude(*Ptr, false);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001294 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner94269d72009-04-21 05:40:52 +00001295 InitOpts.addInclude(*Ptr, true);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001296 } else {
1297 // We end up here when we're producing preprocessed output and
1298 // we loaded a PCH file. In this case, just include the header
1299 // file that was used to build the precompiled header.
1300 assert(Ptr == &ImplicitIncludePCH);
1301 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1302 if (!OriginalFile.empty()) {
1303 InitOpts.addInclude(OriginalFile, false);
1304 ImplicitIncludePCH.clear();
1305 }
Chris Lattner94269d72009-04-21 05:40:52 +00001306 }
1307 }
1308 }
1309}
1310
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001311//===----------------------------------------------------------------------===//
1312// Driver PreprocessorFactory - For lazily generating preprocessors ...
1313//===----------------------------------------------------------------------===//
1314
1315namespace {
1316class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1317 Diagnostic &Diags;
1318 const LangOptions &LangInfo;
1319 TargetInfo &Target;
1320 SourceManager &SourceMgr;
1321 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001322
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001323public:
Eli Friedmane934dca2009-05-18 07:39:39 +00001324 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001325 TargetInfo &target, SourceManager &SM,
1326 HeaderSearch &Headers)
Eli Friedmane934dca2009-05-18 07:39:39 +00001327 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001328 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001329
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001330
1331 virtual ~DriverPreprocessorFactory() {}
1332
1333 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001334 llvm::OwningPtr<PTHManager> PTHMgr;
1335
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001336 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1337 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1338 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001339 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001340 }
1341
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001342 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001343 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1344 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001345 PTHMgr.reset(PTHManager::Create(x, &Diags,
1346 TokenCache.empty() ? Diagnostic::Error
1347 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001348 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001349
Ted Kremenek6348cc62009-03-22 06:42:39 +00001350 if (Diags.hasErrorOccurred())
1351 exit(1);
1352
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001353 // Create the Preprocessor.
1354 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1355 SourceMgr, HeaderInfo,
1356 PTHMgr.get()));
1357
1358 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1359 // That argument is used as the IdentifierInfoLookup argument to
1360 // IdentifierTable's ctor.
1361 if (PTHMgr) {
1362 PTHMgr->setPreprocessor(PP.get());
1363 PP->setPTHManager(PTHMgr.take());
1364 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001365
Chris Lattner94269d72009-04-21 05:40:52 +00001366 PreprocessorInitOptions InitOpts;
1367 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmane934dca2009-05-18 07:39:39 +00001368 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001369 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001370
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001371 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001372 }
1373};
1374}
Chris Lattner4b009652007-07-25 00:24:17 +00001375
Chris Lattner4b009652007-07-25 00:24:17 +00001376//===----------------------------------------------------------------------===//
1377// Basic Parser driver
1378//===----------------------------------------------------------------------===//
1379
Chris Lattner9d818a22008-04-19 23:25:44 +00001380static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001381 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001382 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001383
1384 // Parsing the specified input file.
1385 P.ParseTranslationUnit();
1386 delete PA;
1387}
1388
1389//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001390// Code generation options
1391//===----------------------------------------------------------------------===//
1392
1393static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001394GenerateDebugInfo("g",
1395 llvm::cl::desc("Generate source level debug information"));
1396
Daniel Dunbar9101a632009-02-17 19:47:34 +00001397static llvm::cl::opt<std::string>
1398TargetCPU("mcpu",
1399 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1400
Daniel Dunbar07181d72009-05-06 03:16:41 +00001401static llvm::cl::list<std::string>
1402TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1403
Devang Patela3707f12009-06-04 23:32:02 +00001404
1405static llvm::cl::opt<bool>
1406DisableRedZone("disable-red-zone",
1407 llvm::cl::desc("Do not emit code that uses the red zone."),
1408 llvm::cl::init(false));
1409
Devang Patel62c2cca2009-06-05 22:05:48 +00001410static llvm::cl::opt<bool>
1411NoImplicitFloat("no-implicit-float",
1412 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1413 llvm::cl::init(false));
1414
Daniel Dunbar07181d72009-05-06 03:16:41 +00001415/// ComputeTargetFeatures - Recompute the target feature list to only
1416/// be the list of things that are enabled, based on the target cpu
1417/// and feature list.
1418static void ComputeFeatureMap(TargetInfo *Target,
1419 llvm::StringMap<bool> &Features) {
1420 assert(Features.empty() && "invalid map");
1421
1422 // Initialize the feature map based on the target.
1423 Target->getDefaultFeatures(TargetCPU, Features);
1424
1425 // Apply the user specified deltas.
1426 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1427 ie = TargetFeatures.end(); it != ie; ++it) {
1428 const char *Name = it->c_str();
1429
1430 // FIXME: Don't handle errors like this.
1431 if (Name[0] != '-' && Name[0] != '+') {
1432 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1433 Name);
1434 exit(1);
1435 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001436 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1437 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1438 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001439 exit(1);
1440 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001441 }
1442}
1443
Chris Lattner8a9615c2009-03-16 18:41:18 +00001444static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001445 const LangOptions &LangOpts,
1446 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001447 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001448 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard27b66b2009-06-02 22:07:45 +00001449
1450 if (DisableLLVMOptimizations) {
1451 Opts.OptimizationLevel = 0;
1452 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbard725b162008-10-29 07:56:11 +00001453 } else {
Daniel Dunbard27b66b2009-06-02 22:07:45 +00001454 if (OptSize) {
1455 // -Os implies -O2
1456 Opts.OptimizationLevel = 2;
1457 } else {
1458 Opts.OptimizationLevel = OptLevel;
1459 }
1460
1461 // We must always run at least the always inlining pass.
1462 if (Opts.OptimizationLevel > 1)
1463 Opts.Inlining = CompileOptions::NormalInlining;
1464 else
1465 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbard725b162008-10-29 07:56:11 +00001466 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001467
1468 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001469 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001470 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001471
1472#ifdef NDEBUG
1473 Opts.VerifyModule = 0;
1474#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001475
1476 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001477 Opts.Features.clear();
1478 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1479 ie = Features.end(); it != ie; ++it) {
1480 // FIXME: If we are completely confident that we have the right
1481 // set, we only need to pass the minuses.
1482 std::string Name(it->second ? "+" : "-");
1483 Name += it->first();
1484 Opts.Features.push_back(Name);
1485 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001486
Chris Lattnerf04a7562009-03-26 05:00:52 +00001487 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1488
Chris Lattnere8f70712009-02-18 01:23:44 +00001489 // Handle -ftime-report.
1490 Opts.TimePasses = TimeReport;
Devang Patela3707f12009-06-04 23:32:02 +00001491
1492 Opts.DisableRedZone = DisableRedZone;
Devang Patel62c2cca2009-06-05 22:05:48 +00001493 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001494}
1495
1496//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001497// Fix-It Options
1498//===----------------------------------------------------------------------===//
1499static llvm::cl::list<ParsedSourceLocation>
1500FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1501 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1502
1503//===----------------------------------------------------------------------===//
Eli Friedman35ba7a62009-05-18 22:39:16 +00001504// ObjC Rewriter Options
1505//===----------------------------------------------------------------------===//
1506static llvm::cl::opt<bool>
1507SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1508 llvm::cl::desc("Silence ObjC rewriting warnings"));
1509
1510//===----------------------------------------------------------------------===//
Eli Friedman4d03d382009-05-19 01:17:04 +00001511// Warning Options
1512//===----------------------------------------------------------------------===//
1513
1514// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1515// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1516// -Wextra, so we don't need to worry about it.
1517static llvm::cl::list<std::string>
1518OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1519
1520static llvm::cl::opt<bool> OptPedantic("pedantic");
1521static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1522static llvm::cl::opt<bool> OptNoWarnings("w");
1523
1524//===----------------------------------------------------------------------===//
Eli Friedmane2554252009-05-19 03:06:47 +00001525// Preprocessing (-E mode) Options
1526//===----------------------------------------------------------------------===//
1527static llvm::cl::opt<bool>
1528DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1529static llvm::cl::opt<bool>
1530EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1531static llvm::cl::opt<bool>
1532EnableMacroCommentOutput("CC",
1533 llvm::cl::desc("Enable comment output in -E mode, "
1534 "even from macro expansions"));
1535static llvm::cl::opt<bool>
1536DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1537 " normal output"));
1538static llvm::cl::opt<bool>
1539DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1540 "addition to normal output"));
Eli Friedmane595fe92009-05-19 03:35:57 +00001541
1542//===----------------------------------------------------------------------===//
1543// Dependency file options
1544//===----------------------------------------------------------------------===//
1545static llvm::cl::opt<std::string>
1546DependencyFile("dependency-file",
1547 llvm::cl::desc("Filename (or -) to write dependency output to"));
1548
1549static llvm::cl::opt<bool>
1550DependenciesIncludeSystemHeaders("sys-header-deps",
1551 llvm::cl::desc("Include system headers in dependency output"));
1552
1553static llvm::cl::list<std::string>
1554DependencyTargets("MT",
1555 llvm::cl::desc("Specify target for dependency"));
1556
1557// FIXME: Implement feature
1558static llvm::cl::opt<bool>
1559PhonyDependencyTarget("MP",
1560 llvm::cl::desc("Create phony target for each dependency "
1561 "(other than main file)"));
1562
Eli Friedmane2554252009-05-19 03:06:47 +00001563//===----------------------------------------------------------------------===//
Eli Friedman78a57622009-05-19 10:18:02 +00001564// Analysis options
1565//===----------------------------------------------------------------------===//
1566
1567static llvm::cl::list<Analyses>
1568AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1569llvm::cl::values(
1570#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1571clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001572#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001573clEnumValEnd));
1574
1575static llvm::cl::opt<AnalysisStores>
1576AnalysisStoreOpt("analyzer-store",
1577 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1578 llvm::cl::init(BasicStoreModel),
1579 llvm::cl::values(
1580#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1581clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001582#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001583clEnumValEnd));
1584
1585static llvm::cl::opt<AnalysisConstraints>
1586AnalysisConstraintsOpt("analyzer-constraints",
1587 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1588 llvm::cl::init(RangeConstraintsModel),
1589 llvm::cl::values(
1590#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1591clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001592#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001593clEnumValEnd));
1594
1595static llvm::cl::opt<AnalysisDiagClients>
1596AnalysisDiagOpt("analyzer-output",
1597 llvm::cl::desc("Source Code Analysis - Output Options"),
1598 llvm::cl::init(PD_HTML),
1599 llvm::cl::values(
1600#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1601clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001602#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001603clEnumValEnd));
1604
1605static llvm::cl::opt<bool>
1606VisualizeEGDot("analyzer-viz-egraph-graphviz",
1607 llvm::cl::desc("Display exploded graph using GraphViz"));
1608
1609static llvm::cl::opt<bool>
1610VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1611 llvm::cl::desc("Display exploded graph using Ubigraph"));
1612
1613static llvm::cl::opt<bool>
1614AnalyzeAll("analyzer-opt-analyze-headers",
1615 llvm::cl::desc("Force the static analyzer to analyze "
1616 "functions defined in header files"));
1617
1618static llvm::cl::opt<bool>
1619AnalyzerDisplayProgress("analyzer-display-progress",
1620 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1621
1622static llvm::cl::opt<bool>
1623PurgeDead("analyzer-purge-dead",
1624 llvm::cl::init(true),
1625 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1626 " processing a statement."));
1627
1628static llvm::cl::opt<bool>
1629EagerlyAssume("analyzer-eagerly-assume",
1630 llvm::cl::init(false),
1631 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1632 "symbolic constraints."));
1633
1634static llvm::cl::opt<std::string>
1635AnalyzeSpecificFunction("analyze-function",
1636 llvm::cl::desc("Run analysis on specific function"));
1637
1638static llvm::cl::opt<bool>
1639TrimGraph("trim-egraph",
1640 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1641
1642static AnalyzerOptions ReadAnalyzerOptions() {
1643 AnalyzerOptions Opts;
1644 Opts.AnalysisList = AnalysisList;
1645 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1646 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1647 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1648 Opts.VisualizeEGDot = VisualizeEGDot;
1649 Opts.VisualizeEGUbi = VisualizeEGUbi;
1650 Opts.AnalyzeAll = AnalyzeAll;
1651 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1652 Opts.PurgeDead = PurgeDead;
1653 Opts.EagerlyAssume = EagerlyAssume;
1654 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1655 Opts.TrimGraph = TrimGraph;
1656 return Opts;
1657}
1658
1659//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001660// -dump-build-information Stuff
1661//===----------------------------------------------------------------------===//
1662
1663static llvm::cl::opt<std::string>
1664DumpBuildInformation("dump-build-information",
1665 llvm::cl::value_desc("filename"),
1666 llvm::cl::desc("output a dump of some build information to a file"));
1667
1668static llvm::raw_ostream *BuildLogFile = 0;
1669
1670/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1671/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1672namespace {
1673class LoggingDiagnosticClient : public DiagnosticClient {
1674 llvm::OwningPtr<DiagnosticClient> Chain1;
1675 llvm::OwningPtr<DiagnosticClient> Chain2;
1676public:
1677
1678 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1679 // Output diags both where requested...
1680 Chain1.reset(Normal);
1681 // .. and to our log file.
1682 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1683 !NoShowColumn,
1684 !NoCaretDiagnostics,
1685 !NoShowLocation,
1686 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001687 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001688 !NoDiagnosticsFixIt,
1689 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001690 }
1691
1692 virtual void setLangOptions(const LangOptions *LO) {
1693 Chain1->setLangOptions(LO);
1694 Chain2->setLangOptions(LO);
1695 }
1696
1697 virtual bool IncludeInDiagnosticCounts() const {
1698 return Chain1->IncludeInDiagnosticCounts();
1699 }
1700
1701 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1702 const DiagnosticInfo &Info) {
1703 Chain1->HandleDiagnostic(DiagLevel, Info);
1704 Chain2->HandleDiagnostic(DiagLevel, Info);
1705 }
1706};
1707} // end anonymous namespace.
1708
1709static void SetUpBuildDumpLog(unsigned argc, char **argv,
1710 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1711
1712 std::string ErrorInfo;
1713 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1714 ErrorInfo);
1715
1716 if (!ErrorInfo.empty()) {
1717 llvm::errs() << "error opening -dump-build-information file '"
1718 << DumpBuildInformation << "', option ignored!\n";
1719 delete BuildLogFile;
1720 BuildLogFile = 0;
1721 DumpBuildInformation = "";
1722 return;
1723 }
1724
1725 (*BuildLogFile) << "clang-cc command line arguments: ";
1726 for (unsigned i = 0; i != argc; ++i)
1727 (*BuildLogFile) << argv[i] << ' ';
1728 (*BuildLogFile) << '\n';
1729
1730 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1731 // the diagnostic producers and the normal receiver.
1732 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1733}
1734
1735
1736
1737//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001738// Main driver
1739//===----------------------------------------------------------------------===//
1740
Eli Friedmana9c310842009-05-18 22:20:00 +00001741static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1742 const char* Extension,
1743 bool Binary,
1744 llvm::sys::Path& OutPath) {
1745 llvm::raw_ostream* Ret;
1746 bool UseStdout = false;
1747 std::string OutFile;
1748 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1749 UseStdout = true;
1750 } else if (!OutputFile.empty()) {
1751 OutFile = OutputFile;
1752 } else if (Extension) {
1753 llvm::sys::Path Path(InFile);
1754 Path.eraseSuffix();
1755 Path.appendSuffix(Extension);
1756 OutFile = Path.toString();
1757 } else {
1758 UseStdout = true;
Chris Lattner7f902922009-02-18 01:20:05 +00001759 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001760
Eli Friedmana9c310842009-05-18 22:20:00 +00001761 if (UseStdout) {
1762 Ret = new llvm::raw_stdout_ostream();
1763 if (Binary)
1764 llvm::sys::Program::ChangeStdoutToBinary();
1765 } else {
1766 std::string Error;
1767 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1768 if (!Error.empty()) {
1769 // FIXME: Don't fail this way.
1770 llvm::cerr << "ERROR: " << Error << "\n";
1771 ::exit(1);
1772 }
1773 OutPath = OutFile;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001774 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001775
1776 return Ret;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001777}
1778
Chris Lattner4b009652007-07-25 00:24:17 +00001779/// ProcessInputFile - Process a single input file with the specified state.
1780///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001781static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001782 const std::string &InFile, ProgActions PA,
1783 const llvm::StringMap<bool> &Features) {
Eli Friedmana9c310842009-05-18 22:20:00 +00001784 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek50aab982008-08-08 02:46:37 +00001785 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001786 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001787 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001788 bool CompleteTranslationUnit = true;
Eli Friedmana9c310842009-05-18 22:20:00 +00001789 llvm::sys::Path OutPath;
Douglas Gregor133d2552009-04-02 01:08:08 +00001790
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001791 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001792 default:
Eli Friedmana9c310842009-05-18 22:20:00 +00001793 fprintf(stderr, "Unexpected program action!\n");
1794 HadErrors = true;
1795 return;
1796
1797 case ASTPrint:
1798 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1799 Consumer.reset(CreateASTPrinter(OS.get()));
1800 break;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001801
Douglas Gregor8987c032009-05-21 20:55:50 +00001802 case ASTPrintXML:
1803 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1804 Consumer.reset(CreateASTPrinterXML(OS.get()));
1805 break;
1806
Eli Friedmana9c310842009-05-18 22:20:00 +00001807 case ASTDump:
Douglas Gregor996677c2009-05-30 00:08:05 +00001808 Consumer.reset(CreateASTDumper());
Eli Friedmana9c310842009-05-18 22:20:00 +00001809 break;
1810
Eli Friedmana9c310842009-05-18 22:20:00 +00001811 case ASTView:
Douglas Gregor996677c2009-05-30 00:08:05 +00001812 Consumer.reset(CreateASTViewer());
Eli Friedmana9c310842009-05-18 22:20:00 +00001813 break;
1814
1815 case PrintDeclContext:
1816 Consumer.reset(CreateDeclContextPrinter());
1817 break;
1818
1819 case EmitHTML:
1820 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1821 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1822 break;
1823
1824 case InheritanceView:
1825 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1826 break;
1827
1828 case EmitAssembly:
1829 case EmitLLVM:
1830 case EmitBC:
1831 case EmitLLVMOnly: {
1832 BackendAction Act;
1833 if (ProgAction == EmitAssembly) {
1834 Act = Backend_EmitAssembly;
1835 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1836 } else if (ProgAction == EmitLLVM) {
1837 Act = Backend_EmitLL;
1838 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1839 } else if (ProgAction == EmitLLVMOnly) {
1840 Act = Backend_EmitNothing;
1841 } else {
1842 Act = Backend_EmitBC;
1843 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001844 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001845
Eli Friedmana9c310842009-05-18 22:20:00 +00001846 CompileOptions Opts;
1847 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1848 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1849 PP.getLangOptions(), Opts, InFile,
1850 OS.get()));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001851 break;
Eli Friedmana9c310842009-05-18 22:20:00 +00001852 }
1853
1854 case GeneratePCH:
1855 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1856 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1857 CompleteTranslationUnit = false;
1858 break;
1859
1860 case RewriteObjC:
1861 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedman848763f2009-05-18 22:29:17 +00001862 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedman35ba7a62009-05-18 22:39:16 +00001863 PP.getLangOptions(),
1864 SilenceRewriteMacroWarning));
Eli Friedmana9c310842009-05-18 22:20:00 +00001865 break;
1866
1867 case RewriteBlocks:
1868 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1869 PP.getLangOptions()));
1870 break;
1871
Eli Friedman78a57622009-05-19 10:18:02 +00001872 case RunAnalysis: {
Eli Friedmana9c310842009-05-18 22:20:00 +00001873 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedman78a57622009-05-19 10:18:02 +00001874 PP.getLangOptions(), OutputFile,
1875 ReadAnalyzerOptions()));
Eli Friedmana9c310842009-05-18 22:20:00 +00001876 break;
Eli Friedman78a57622009-05-19 10:18:02 +00001877 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001878
Chris Lattneraf669fb2008-10-12 05:03:36 +00001879 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001880 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001881 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001882 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001883 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001884 RawLex.SetKeepWhitespaceMode(true);
1885
1886 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001887 RawLex.LexFromRawLexer(RawTok);
1888 while (RawTok.isNot(tok::eof)) {
1889 PP.DumpToken(RawTok, true);
1890 fprintf(stderr, "\n");
1891 RawLex.LexFromRawLexer(RawTok);
1892 }
1893 ClearSourceMgr = true;
1894 break;
1895 }
Chris Lattner4b009652007-07-25 00:24:17 +00001896 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001897 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001898 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001899 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001900 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001901 do {
1902 PP.Lex(Tok);
1903 PP.DumpToken(Tok, true);
1904 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001905 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001906 ClearSourceMgr = true;
1907 break;
1908 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001909 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001910 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001911
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001912 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001913 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001914 if (OutputFile.empty() || OutputFile == "-") {
1915 // FIXME: Don't fail this way.
1916 // FIXME: Verify that we can actually seek in the given file.
1917 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1918 ::exit(1);
1919 }
1920 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1921 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001922 ClearSourceMgr = true;
1923 break;
1924 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001925
Chris Lattner772a7c12009-04-27 22:02:30 +00001926 case PrintPreprocessedInput:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001927 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Chris Lattner4b009652007-07-25 00:24:17 +00001928 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001929
Chris Lattner270d29a2009-04-27 21:45:14 +00001930 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001931 break;
1932
Chris Lattnerefe33382009-02-18 01:51:21 +00001933 case ParsePrintCallbacks: {
1934 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001935 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1936 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattner4b009652007-07-25 00:24:17 +00001937 ClearSourceMgr = true;
1938 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001939 }
1940
1941 case ParseSyntaxOnly: { // -fsyntax-only
1942 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001943 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001944 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001945 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001946
1947 case RewriteMacros:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001948 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1949 RewriteMacrosInInput(PP, OS.get());
Chris Lattner1665a9f2008-05-08 06:52:13 +00001950 ClearSourceMgr = true;
1951 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001952
Eli Friedman4ae15b92009-05-19 01:02:07 +00001953 case RewriteTest:
1954 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1955 DoRewriteTest(PP, OS.get());
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001956 ClearSourceMgr = true;
1957 break;
Douglas Gregor133d2552009-04-02 01:08:08 +00001958
1959 case FixIt:
1960 llvm::TimeRegion Timer(ClangFrontendTimer);
1961 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001962 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001963 PP.getSourceManager(),
1964 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001965 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001966 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001967
Chris Lattner38a4f182009-04-27 21:25:27 +00001968 if (FixItAtLocations.size() > 0) {
1969 // Even without the "-fixit" flag, with may have some specific
1970 // locations where the user has requested fixes. Process those
1971 // locations now.
1972 if (!FixItRewrite)
1973 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1974 PP.getSourceManager(),
1975 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001976
Chris Lattner38a4f182009-04-27 21:25:27 +00001977 bool AddedFixitLocation = false;
1978 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1979 Idx != Last; ++Idx) {
1980 RequestedSourceLocation Requested;
1981 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1982 Requested)) {
1983 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1984 FixItAtLocations[Idx].FileName.c_str());
1985 } else {
1986 FixItRewrite->addFixItLocation(Requested);
1987 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001988 }
1989 }
1990
Chris Lattner38a4f182009-04-27 21:25:27 +00001991 if (!AddedFixitLocation) {
1992 // All of the fix-it locations were bad. Don't fix anything.
1993 delete FixItRewrite;
1994 FixItRewrite = 0;
1995 }
1996 }
1997
1998 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001999 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00002000 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
2001 PP.getSourceManager(),
2002 PP.getTargetInfo(),
2003 PP.getIdentifierTable(),
2004 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00002005 /* FreeMemory = */ !DisableFree,
2006 /* size_reserve = */0,
2007 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00002008 llvm::OwningPtr<PCHReader> Reader;
2009 llvm::OwningPtr<ExternalASTSource> Source;
2010
Chris Lattner270d29a2009-04-27 21:45:14 +00002011 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00002012 Reader.reset(new PCHReader(PP, ContextOwner.get()));
2013
Chris Lattner270d29a2009-04-27 21:45:14 +00002014 // The user has asked us to include a precompiled header. Load
2015 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00002016 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2017 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00002018 // Set the predefines buffer as suggested by the PCH
2019 // reader. Typically, the predefines buffer will be empty.
2020 PP.setPredefines(Reader->getSuggestedPredefines());
2021
Chris Lattner270d29a2009-04-27 21:45:14 +00002022 // Attach the PCH reader to the AST context as an external AST
2023 // source, so that declarations will be deserialized from the
2024 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00002025 if (ContextOwner) {
2026 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002027 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00002028 }
Chris Lattner270d29a2009-04-27 21:45:14 +00002029 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00002030 }
2031
Chris Lattner270d29a2009-04-27 21:45:14 +00002032 case PCHReader::Failure:
2033 // Unrecoverable failure: don't even try to process the input
2034 // file.
2035 return;
2036
2037 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002038 // No suitable PCH file could be found. Return an error.
2039 return;
2040
2041#if 0
2042 // FIXME: We can recover from failed attempts to load PCH
2043 // files. This code will do so, if we ever want to enable it.
2044
Chris Lattner270d29a2009-04-27 21:45:14 +00002045 // We delayed the initialization of builtins in the hope of
2046 // loading the PCH file. Since the PCH file could not be
2047 // loaded, initialize builtins now.
2048 if (ContextOwner)
2049 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002050#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00002051 }
2052
2053 // Finish preprocessor initialization. We do this now (rather
2054 // than earlier) because this initialization creates new source
2055 // location entries in the source manager, which must come after
2056 // the source location entries for the PCH file.
2057 if (InitializeSourceManager(PP, InFile))
2058 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00002059 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002060
Chris Lattner270d29a2009-04-27 21:45:14 +00002061
2062 // If we have an ASTConsumer, run the parser with it.
2063 if (Consumer)
2064 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2065 CompleteTranslationUnit);
2066
2067 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2068 llvm::TimeRegion Timer(ClangFrontendTimer);
2069 Token Tok;
2070 // Start parsing the specified input file.
2071 PP.EnterMainSourceFile();
2072 do {
2073 PP.Lex(Tok);
2074 } while (Tok.isNot(tok::eof));
2075 ClearSourceMgr = true;
2076 } else if (PA == ParseNoop) { // -parse-noop
2077 llvm::TimeRegion Timer(ClangFrontendTimer);
2078 ParseFile(PP, new MinimalAction(PP));
2079 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00002080 } else if (PA == PrintPreprocessedInput){ // -E mode.
2081 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmane2554252009-05-19 03:06:47 +00002082 if (DumpMacros)
2083 DoPrintMacros(PP, OS.get());
2084 else
2085 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2086 EnableMacroCommentOutput,
2087 DisableLineMarkers, DumpDefines);
Chris Lattner772a7c12009-04-27 22:02:30 +00002088 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00002089 }
2090
Chris Lattner38a4f182009-04-27 21:25:27 +00002091 if (FixItRewrite)
2092 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2093
2094 // If in -disable-free mode, don't deallocate ASTContext.
2095 if (DisableFree)
2096 ContextOwner.take();
2097 else
2098 ContextOwner.reset(); // Delete ASTContext
Eli Friedmana9c310842009-05-18 22:20:00 +00002099
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002100 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002101 if (CheckDiagnostics(PP))
2102 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002103
Chris Lattner4b009652007-07-25 00:24:17 +00002104 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002105 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002106 PP.PrintStats();
2107 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002108 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002109 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002110 fprintf(stderr, "\n");
2111 }
2112
2113 // For a multi-file compilation, some things are ok with nuking the source
2114 // manager tables, other require stable fileid/macroid's across multiple
2115 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002116 if (ClearSourceMgr)
2117 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002118
2119 if (DisableFree)
2120 Consumer.take();
Eli Friedmana9c310842009-05-18 22:20:00 +00002121 else
2122 Consumer.reset();
2123
2124 // Always delete the output stream because we don't want to leak file
2125 // handles. Also, we don't want to try to erase an open file.
2126 OS.reset();
2127
2128 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2129 !OutPath.isEmpty()) {
2130 // If we had errors, try to erase the output file.
2131 OutPath.eraseFromDisk();
2132 }
Chris Lattner4b009652007-07-25 00:24:17 +00002133}
2134
2135static llvm::cl::list<std::string>
2136InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2137
Chris Lattner4b009652007-07-25 00:24:17 +00002138int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002139 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002140 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002141 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002142 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002143
Chris Lattnerefe33382009-02-18 01:51:21 +00002144 if (TimeReport)
2145 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2146
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002147 if (Verbose)
2148 fprintf(stderr, "clang-cc version 1.0 based upon " PACKAGE_STRING
2149 " hosted on " LLVM_HOSTTRIPLE "\n");
2150
Chris Lattner4b009652007-07-25 00:24:17 +00002151 // If no input was specified, read from stdin.
2152 if (InputFilenames.empty())
2153 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00002154
Ted Kremenekb240e822007-12-11 23:28:38 +00002155 // Create the diagnostic client for reporting errors or for
2156 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002157 llvm::OwningPtr<DiagnosticClient> DiagClient;
2158 if (VerifyDiagnostics) {
2159 // When checking diagnostics, just buffer them up.
2160 DiagClient.reset(new TextDiagnosticBuffer());
2161 if (InputFilenames.size() != 1) {
2162 fprintf(stderr, "-verify only works on single input files for now.\n");
2163 return 1;
2164 }
2165 if (!HTMLDiag.empty()) {
2166 fprintf(stderr, "-verify and -html-diags don't work together\n");
2167 return 1;
2168 }
2169 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002170 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00002171
2172 // If -fmessage-length=N was not specified, determine whether this
2173 // is a terminal and, if so, implicitly define -fmessage-length
2174 // appropriately.
2175 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00002176 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00002177
Edwin Törökeff37122009-06-04 07:18:23 +00002178 if (!NoColorDiagnostic) {
2179 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2180 }
2181
Chris Lattner5f7937d2009-04-17 20:40:01 +00002182 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002183 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002184 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002185 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002186 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00002187 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00002188 !NoDiagnosticsFixIt,
Edwin Törökeff37122009-06-04 07:18:23 +00002189 MessageLength,
2190 !NoColorDiagnostic));
Ted Kremenek5c341732008-08-07 17:49:57 +00002191 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002192 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002193 }
Chris Lattner94859302009-04-17 21:05:01 +00002194
2195 if (!DumpBuildInformation.empty()) {
2196 if (!HTMLDiag.empty()) {
2197 fprintf(stderr,
2198 "-dump-build-information and -html-diags don't work together\n");
2199 return 1;
2200 }
2201
2202 SetUpBuildDumpLog(argc, argv, DiagClient);
2203 }
2204
Ted Kremenek5c341732008-08-07 17:49:57 +00002205
Chris Lattner4b009652007-07-25 00:24:17 +00002206 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002207 Diagnostic Diags(DiagClient.get());
Eli Friedman4d03d382009-05-19 01:17:04 +00002208 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2209 OptNoWarnings))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002210 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002211
Chris Lattner45a56e02007-12-05 23:24:17 +00002212 // -I- is a deprecated GCC feature, scan for it and reject it.
2213 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2214 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002215 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002216 I_dirs.erase(I_dirs.begin()+i);
2217 --i;
2218 }
2219 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002220
2221 // Get information about the target being compiled for.
2222 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002223 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2224
Chris Lattner2c77d852008-03-14 06:12:05 +00002225 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002226 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2227 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002228 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002229 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002230
Daniel Dunbar9c321102009-01-20 23:17:32 +00002231 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002232 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002233
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002234 llvm::OwningPtr<SourceManager> SourceMgr;
2235
Chris Lattnere1be6022009-04-14 23:22:57 +00002236 // Create a file manager object to provide access to and cache the filesystem.
2237 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002238
Daniel Dunbar07181d72009-05-06 03:16:41 +00002239 // Compute the feature set, unfortunately this effects the language!
2240 llvm::StringMap<bool> Features;
2241 ComputeFeatureMap(Target.get(), Features);
2242
Chris Lattner4b009652007-07-25 00:24:17 +00002243 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002244 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002245
Chris Lattner2b989562009-03-04 21:40:56 +00002246 /// Create a SourceManager object. This tracks and owns all the file
2247 /// buffers allocated to a translation unit.
2248 if (!SourceMgr)
2249 SourceMgr.reset(new SourceManager());
2250 else
2251 SourceMgr->clearIDTables();
2252
2253 // Initialize language options, inferring file types from input filenames.
2254 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002255 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002256
Chris Lattner2b989562009-03-04 21:40:56 +00002257 InitializeBaseLanguage();
2258 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002259 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002260 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002261
2262 // Process the -I options and set them in the HeaderInfo.
2263 HeaderSearch HeaderInfo(FileMgr);
2264
Chris Lattnere1be6022009-04-14 23:22:57 +00002265
Chris Lattner2b989562009-03-04 21:40:56 +00002266 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2267
2268 // Set up the preprocessor with these options.
Eli Friedmane934dca2009-05-18 07:39:39 +00002269 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattner2b989562009-03-04 21:40:56 +00002270 *SourceMgr.get(), HeaderInfo);
2271
2272 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2273
2274 if (!PP)
2275 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002276
Eli Friedmane595fe92009-05-19 03:35:57 +00002277 // Handle generating dependencies, if requested
2278 if (!DependencyFile.empty()) {
2279 llvm::raw_ostream *DependencyOS;
2280 if (DependencyTargets.empty()) {
2281 // FIXME: Use a proper diagnostic
2282 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2283 HadErrors = true;
2284 continue;
2285 }
2286 std::string ErrStr;
2287 DependencyOS =
2288 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2289 if (!ErrStr.empty()) {
2290 // FIXME: Use a proper diagnostic
2291 llvm::cerr << "unable to open dependency file: " + ErrStr;
2292 HadErrors = true;
2293 continue;
2294 }
2295
2296 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2297 DependenciesIncludeSystemHeaders,
2298 PhonyDependencyTarget);
2299 }
2300
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002301 if (ImplicitIncludePCH.empty() &&
2302 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002303 continue;
2304
Chris Lattner5f7937d2009-04-17 20:40:01 +00002305 if (!HTMLDiag.empty())
2306 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002307
2308 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002309 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002310
Chris Lattner2961dc52009-04-17 20:16:08 +00002311 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002312 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002313 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002314
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002315 if (!NoCaretDiagnostics)
2316 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2317 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2318 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002319
2320 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002321 FileMgr.PrintStats();
2322 fprintf(stderr, "\n");
2323 }
Chris Lattner94859302009-04-17 21:05:01 +00002324
2325 delete ClangFrontendTimer;
2326 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002327
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002328 // If verifying diagnostics and we reached here, all is well.
2329 if (VerifyDiagnostics)
2330 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002331
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002332 // Managed static deconstruction. Useful for making things like
2333 // -time-passes usable.
2334 llvm::llvm_shutdown();
2335
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002336 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002337}