blob: f2f05237a2aaefcd351b21f4042e7d2c82eebc0b [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.
Douglas Gregord7915fd2009-04-26 02:02:08 +0000199 ASTDumpFull, // Parse ASTs and dump them, including the
200 // contents of a PCH file.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000201 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000202 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +0000203 ParsePrintCallbacks, // Parse and print each callback.
204 ParseSyntaxOnly, // Parse and perform semantic analysis.
205 ParseNoop, // Parse with noop callbacks.
206 RunPreprocessorOnly, // Just lex, no output.
207 PrintPreprocessedInput, // -E mode.
Chris Lattneraf669fb2008-10-12 05:03:36 +0000208 DumpTokens, // Dump out preprocessed tokens.
209 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000210 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000211 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000212 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000213 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +0000214};
215
216static llvm::cl::opt<ProgActions>
217ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
218 llvm::cl::init(ParseSyntaxOnly),
219 llvm::cl::values(
220 clEnumValN(RunPreprocessorOnly, "Eonly",
221 "Just run preprocessor, no output (for timings)"),
222 clEnumValN(PrintPreprocessedInput, "E",
223 "Run preprocessor, emit preprocessed file"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000224 clEnumValN(DumpRawTokens, "dump-raw-tokens",
225 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000226 clEnumValN(RunAnalysis, "analyze",
227 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000228 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +0000229 "Run preprocessor, dump internal rep of tokens"),
230 clEnumValN(ParseNoop, "parse-noop",
231 "Run parser with noop callbacks (for timings)"),
232 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
233 "Run parser and perform semantic analysis"),
234 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
235 "Run parser and print each callback invoked"),
Ted Kremenek24612ae2008-03-18 21:19:49 +0000236 clEnumValN(EmitHTML, "emit-html",
237 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000238 clEnumValN(ASTPrint, "ast-print",
239 "Build ASTs and then pretty-print them"),
Douglas Gregor8987c032009-05-21 20:55:50 +0000240 clEnumValN(ASTPrintXML, "ast-print-xml",
241 "Build ASTs and then print them in XML format"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000242 clEnumValN(ASTDump, "ast-dump",
243 "Build ASTs and then debug dump them"),
Douglas Gregord7915fd2009-04-26 02:02:08 +0000244 clEnumValN(ASTDumpFull, "ast-dump-full",
245 "Build ASTs and then debug dump them, including PCH"),
Chris Lattner664dd082007-10-11 00:37:43 +0000246 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000247 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000248 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000249 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000250 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000251 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000252 clEnumValN(GeneratePCH, "emit-pch",
253 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000254 clEnumValN(EmitAssembly, "S",
255 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000256 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000257 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000258 clEnumValN(EmitBC, "emit-llvm-bc",
259 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000260 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
261 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000262 clEnumValN(RewriteTest, "rewrite-test",
263 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000264 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-05-08 06:52:13 +0000265 "Rewrite ObjC into C (code rewriter example)"),
266 clEnumValN(RewriteMacros, "rewrite-macros",
267 "Expand macros without full preprocessing"),
Steve Naroff93c18352008-09-18 14:10:13 +0000268 clEnumValN(RewriteBlocks, "rewrite-blocks",
269 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000270 clEnumValN(FixIt, "fixit",
271 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000272 clEnumValEnd));
273
Ted Kremenekd01eae62007-12-19 19:47:59 +0000274
275static llvm::cl::opt<std::string>
276OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000277 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000278 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000279
Ted Kremenek57f25b22008-12-02 19:57:31 +0000280
281//===----------------------------------------------------------------------===//
282// PTH.
283//===----------------------------------------------------------------------===//
284
285static llvm::cl::opt<std::string>
286TokenCache("token-cache", llvm::cl::value_desc("path"),
287 llvm::cl::desc("Use specified token cache file"));
288
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000289//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000290// Diagnostic Options
291//===----------------------------------------------------------------------===//
292
Ted Kremenek10389cf2007-09-26 19:42:19 +0000293static llvm::cl::opt<bool>
294VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000295 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000296
Ted Kremenekfd75e312008-03-27 06:17:42 +0000297static llvm::cl::opt<std::string>
298HTMLDiag("html-diags",
299 llvm::cl::desc("Generate HTML to report diagnostics"),
300 llvm::cl::value_desc("HTML directory"));
301
Nico Weber0e13eaa2008-08-05 23:33:20 +0000302static llvm::cl::opt<bool>
303NoShowColumn("fno-show-column",
304 llvm::cl::desc("Do not include column number on diagnostics"));
305
306static llvm::cl::opt<bool>
Chris Lattnerb96a04f2009-01-30 19:01:41 +0000307NoShowLocation("fno-show-source-location",
308 llvm::cl::desc("Do not include source location information with"
309 " diagnostics"));
310
311static llvm::cl::opt<bool>
Nico Weber0e13eaa2008-08-05 23:33:20 +0000312NoCaretDiagnostics("fno-caret-diagnostics",
313 llvm::cl::desc("Do not include source line and caret with"
314 " diagnostics"));
315
Chris Lattner695a4f52009-03-13 01:08:23 +0000316static llvm::cl::opt<bool>
Chris Lattner041bd732009-04-19 07:44:08 +0000317NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
318 llvm::cl::desc("Do not include fixit information in"
319 " diagnostics"));
320
321static llvm::cl::opt<bool>
Chris Lattner13bac9e2009-04-21 05:34:31 +0000322PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
323 llvm::cl::desc("Print source range spans in numeric form"));
324
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000325static llvm::cl::opt<bool>
326PrintDiagnosticOption("fdiagnostics-show-option",
327 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weber0e13eaa2008-08-05 23:33:20 +0000328
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000329static llvm::cl::opt<unsigned>
330MessageLength("fmessage-length",
331 llvm::cl::desc("Format message diagnostics so that they fit "
332 "within N columns or fewer, when possible."),
333 llvm::cl::value_desc("N"));
334
Chris Lattner4b009652007-07-25 00:24:17 +0000335//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000336// C++ Visualization.
337//===----------------------------------------------------------------------===//
338
339static llvm::cl::opt<std::string>
340InheritanceViewCls("cxx-inheritance-view",
341 llvm::cl::value_desc("class name"),
Daniel Dunbar47f0b0f2009-01-14 18:56:36 +0000342 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000343
344//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000345// Builtin Options
346//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-02-18 01:12:43 +0000347
348static llvm::cl::opt<bool>
349TimeReport("ftime-report",
350 llvm::cl::desc("Print the amount of time each "
351 "phase of compilation takes"));
352
Douglas Gregor23d23262009-02-14 20:49:29 +0000353static llvm::cl::opt<bool>
354Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000355 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000356 "freestanding environment"));
357
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000358static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000359AllowBuiltins("fbuiltin", llvm::cl::init(true),
360 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000361
362
363static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000364MathErrno("fmath-errno", llvm::cl::init(true),
365 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000366
Douglas Gregor23d23262009-02-14 20:49:29 +0000367//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000368// Language Options
369//===----------------------------------------------------------------------===//
370
371enum LangKind {
372 langkind_unspecified,
373 langkind_c,
374 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000375 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000376 langkind_cxx,
377 langkind_cxx_cpp,
378 langkind_objc,
379 langkind_objc_cpp,
380 langkind_objcxx,
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000381 langkind_objcxx_cpp
Chris Lattner4b009652007-07-25 00:24:17 +0000382};
383
Chris Lattner4b009652007-07-25 00:24:17 +0000384static llvm::cl::opt<LangKind>
385BaseLang("x", llvm::cl::desc("Base language to compile"),
386 llvm::cl::init(langkind_unspecified),
387 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
388 clEnumValN(langkind_cxx, "c++", "C++"),
389 clEnumValN(langkind_objc, "objective-c", "Objective C"),
390 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000391 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000392 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000393 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
394 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000395 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000396 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000397 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
398 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000399 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000400 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000401 clEnumValN(langkind_c, "c-header",
402 "C header"),
403 clEnumValN(langkind_objc, "objective-c-header",
404 "Objective-C header"),
405 clEnumValN(langkind_cxx, "c++-header",
406 "C++ header"),
407 clEnumValN(langkind_objcxx, "objective-c++-header",
408 "Objective-C++ header"),
Chris Lattner4b009652007-07-25 00:24:17 +0000409 clEnumValEnd));
410
411static llvm::cl::opt<bool>
412LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
413 llvm::cl::Hidden);
414static llvm::cl::opt<bool>
415LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
416 llvm::cl::Hidden);
417
Chris Lattnere1be6022009-04-14 23:22:57 +0000418static llvm::cl::opt<bool>
419ObjCExclusiveGC("fobjc-gc-only",
420 llvm::cl::desc("Use GC exclusively for Objective-C related "
421 "memory management"));
422
423static llvm::cl::opt<bool>
424ObjCEnableGC("fobjc-gc",
425 llvm::cl::desc("Enable Objective-C garbage collection"));
426
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000427static llvm::cl::opt<bool>
428ObjCEnableGCBitmapPrint("print-ivar-layout",
429 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
430
Chris Lattnere1be6022009-04-14 23:22:57 +0000431static llvm::cl::opt<LangOptions::VisibilityMode>
432SymbolVisibility("fvisibility",
433 llvm::cl::desc("Set the default symbol visibility:"),
434 llvm::cl::init(LangOptions::Default),
435 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
436 "Use default symbol visibility"),
437 clEnumValN(LangOptions::Hidden, "hidden",
438 "Use hidden symbol visibility"),
439 clEnumValN(LangOptions::Protected,"protected",
440 "Use protected symbol visibility"),
441 clEnumValEnd));
442
443static llvm::cl::opt<bool>
444OverflowChecking("ftrapv",
445 llvm::cl::desc("Trap on integer overflow"),
446 llvm::cl::init(false));
447
448
Ted Kremenek11ad8952007-12-05 23:49:08 +0000449/// InitializeBaseLanguage - Handle the -x foo options.
450static void InitializeBaseLanguage() {
451 if (LangObjC)
452 BaseLang = langkind_objc;
453 else if (LangObjCXX)
454 BaseLang = langkind_objcxx;
455}
456
457static LangKind GetLanguage(const std::string &Filename) {
458 if (BaseLang != langkind_unspecified)
459 return BaseLang;
460
461 std::string::size_type DotPos = Filename.rfind('.');
462
463 if (DotPos == std::string::npos) {
464 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner4eac0502008-01-04 19:12:28 +0000465 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000466 }
467
Ted Kremenek11ad8952007-12-05 23:49:08 +0000468 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
469 // C header: .h
470 // C++ header: .hh or .H;
471 // assembler no preprocessing: .s
472 // assembler: .S
473 if (Ext == "c")
474 return langkind_c;
Chris Lattner5dc0c1b2009-03-23 16:24:37 +0000475 else if (Ext == "S" ||
476 // If the compiler is run on a .s file, preprocess it as .S
477 Ext == "s")
Chris Lattnera19689a2008-10-22 17:29:21 +0000478 return langkind_asm_cpp;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000479 else if (Ext == "i")
480 return langkind_c_cpp;
481 else if (Ext == "ii")
482 return langkind_cxx_cpp;
483 else if (Ext == "m")
484 return langkind_objc;
485 else if (Ext == "mi")
486 return langkind_objc_cpp;
487 else if (Ext == "mm" || Ext == "M")
488 return langkind_objcxx;
489 else if (Ext == "mii")
490 return langkind_objcxx_cpp;
491 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
492 Ext == "c++" || Ext == "cp" || Ext == "cxx")
493 return langkind_cxx;
494 else
495 return langkind_c;
496}
497
498
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000499static void InitializeCOptions(LangOptions &Options) {
500 // Do nothing.
501}
502
503static void InitializeObjCOptions(LangOptions &Options) {
504 Options.ObjC1 = Options.ObjC2 = 1;
505}
506
507
Daniel Dunbardb6126e2009-04-01 05:09:09 +0000508static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000509 // FIXME: implement -fpreprocessed mode.
510 bool NoPreprocess = false;
511
Ted Kremenek11ad8952007-12-05 23:49:08 +0000512 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000513 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000514 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000515 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000516 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000517 case langkind_c_cpp:
518 NoPreprocess = true;
519 // FALLTHROUGH
520 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000521 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000522 break;
523 case langkind_cxx_cpp:
524 NoPreprocess = true;
525 // FALLTHROUGH
526 case langkind_cxx:
527 Options.CPlusPlus = 1;
528 break;
529 case langkind_objc_cpp:
530 NoPreprocess = true;
531 // FALLTHROUGH
532 case langkind_objc:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000533 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +0000534 break;
535 case langkind_objcxx_cpp:
536 NoPreprocess = true;
537 // FALLTHROUGH
538 case langkind_objcxx:
539 Options.ObjC1 = Options.ObjC2 = 1;
540 Options.CPlusPlus = 1;
541 break;
542 }
Chris Lattnere1be6022009-04-14 23:22:57 +0000543
544 if (ObjCExclusiveGC)
545 Options.setGCMode(LangOptions::GCOnly);
546 else if (ObjCEnableGC)
547 Options.setGCMode(LangOptions::HybridGC);
548
Fariborz Jahanian2ccf6172009-04-17 03:04:15 +0000549 if (ObjCEnableGCBitmapPrint)
550 Options.ObjCGCBitmapPrint = 1;
551
Chris Lattnere1be6022009-04-14 23:22:57 +0000552 Options.setVisibilityMode(SymbolVisibility);
553 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
556/// LangStds - Language standards we support.
557enum LangStds {
558 lang_unspecified,
559 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000560 lang_gnu_START,
561 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000562 lang_cxx98, lang_gnucxx98,
563 lang_cxx0x, lang_gnucxx0x
564};
565
566static llvm::cl::opt<LangStds>
567LangStd("std", llvm::cl::desc("Language standard to compile for"),
568 llvm::cl::init(lang_unspecified),
569 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
570 clEnumValN(lang_c89, "c90", "ISO C 1990"),
571 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
572 clEnumValN(lang_c94, "iso9899:199409",
573 "ISO C 1990 with amendment 1"),
574 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000575 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000576 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000577 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000578 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000579 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000580 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000581 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +0000582 clEnumValN(lang_gnu99, "gnu9x",
583 "ISO C 1999 with GNU extensions"),
584 clEnumValN(lang_cxx98, "c++98",
585 "ISO C++ 1998 with amendments"),
586 clEnumValN(lang_gnucxx98, "gnu++98",
587 "ISO C++ 1998 with amendments and GNU "
588 "extensions (default for C++)"),
589 clEnumValN(lang_cxx0x, "c++0x",
590 "Upcoming ISO C++ 200x with amendments"),
591 clEnumValN(lang_gnucxx0x, "gnu++0x",
592 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif46612282009-03-11 23:07:18 +0000593 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000594 clEnumValEnd));
595
596static llvm::cl::opt<bool>
597NoOperatorNames("fno-operator-names",
598 llvm::cl::desc("Do not treat C++ operator name keywords as "
599 "synonyms for operators"));
600
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000601static llvm::cl::opt<bool>
602PascalStrings("fpascal-strings",
603 llvm::cl::desc("Recognize and construct Pascal-style "
604 "string literals"));
Steve Naroff73a07032008-02-07 03:50:06 +0000605
606static llvm::cl::opt<bool>
607MSExtensions("fms-extensions",
608 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta69683532008-05-08 08:28:14 +0000609 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000610
611static llvm::cl::opt<bool>
612WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000613 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000614
615static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000616NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-01-30 23:17:46 +0000617 llvm::cl::desc("Disallow implicit conversions between "
618 "vectors with a different number of "
619 "elements or different element types"));
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000620
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000621static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000622EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000623
624static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000625EnableHeinousExtensions("fheinous-gnu-extensions",
626 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
627 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
628
629static llvm::cl::opt<bool>
Mike Stump9093c742009-02-02 22:57:57 +0000630ObjCNonFragileABI("fobjc-nonfragile-abi",
631 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000632
Daniel Dunbar5523e862009-05-04 05:16:21 +0000633
634static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000635EmitAllDecls("femit-all-decls",
636 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000637
Daniel Dunbar91692d92008-08-11 17:36:14 +0000638static llvm::cl::opt<bool>
639Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000640 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000641
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000642static llvm::cl::opt<bool>
643GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000644 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000645 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000646
647static llvm::cl::opt<bool>
648NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000649 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000650 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000651
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000652
653
654static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000655Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000656
Douglas Gregor375733c2009-03-10 00:06:19 +0000657static llvm::cl::opt<unsigned>
658TemplateDepth("ftemplate-depth", llvm::cl::init(99),
659 llvm::cl::desc("Maximum depth of recursive template "
660 "instantiation"));
Chris Lattner77c04832009-04-19 07:00:02 +0000661static llvm::cl::opt<bool>
662DollarsInIdents("fdollars-in-identifiers",
663 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000664
Anders Carlssondfd77642009-04-06 17:37:10 +0000665
666static llvm::cl::opt<bool>
667OptSize("Os", llvm::cl::desc("Optimize for size"));
668
669static llvm::cl::opt<bool>
670NoCommon("fno-common",
671 llvm::cl::desc("Compile common globals like normal definitions"),
672 llvm::cl::ValueDisallowed);
673
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000674static llvm::cl::opt<std::string>
675MainFileName("main-file-name",
676 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlssondfd77642009-04-06 17:37:10 +0000677
Anders Carlssonf2310142009-05-13 19:49:53 +0000678// FIXME: Also add an "-fno-access-control" option.
679static llvm::cl::opt<bool>
680AccessControl("faccess-control",
681 llvm::cl::desc("Enable C++ access control"));
682
Anders Carlssondfd77642009-04-06 17:37:10 +0000683// It might be nice to add bounds to the CommandLine library directly.
684struct OptLevelParser : public llvm::cl::parser<unsigned> {
685 bool parse(llvm::cl::Option &O, const char *ArgName,
686 const std::string &Arg, unsigned &Val) {
687 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
688 return true;
Anders Carlssondfd77642009-04-06 17:37:10 +0000689 if (Val > 3)
690 return O.error(": '" + Arg + "' invalid optimization level!");
691 return false;
692 }
693};
694static llvm::cl::opt<unsigned, false, OptLevelParser>
695OptLevel("O", llvm::cl::Prefix,
696 llvm::cl::desc("Optimization level"),
697 llvm::cl::init(0));
698
Daniel Dunbare079c712009-04-08 03:03:23 +0000699static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000700PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
701
702static llvm::cl::opt<bool>
703StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbare079c712009-04-08 03:03:23 +0000704
Daniel Dunbar34542952008-08-23 08:43:39 +0000705static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000706 TargetInfo *Target,
707 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-12-04 22:54:33 +0000708 // Allow the target to set the default the langauge options as it sees fit.
709 Target->getDefaultLangOptions(Options);
Daniel Dunbar07181d72009-05-06 03:16:41 +0000710
711 // Pass the map of target features to the target for validation and
712 // processing.
713 Target->HandleTargetFeatures(Features);
Chris Lattner738d3f62009-03-02 22:11:07 +0000714
Chris Lattner4b009652007-07-25 00:24:17 +0000715 if (LangStd == lang_unspecified) {
716 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000717 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000718 case lang_unspecified: assert(0 && "Unknown base language");
Chris Lattner4b009652007-07-25 00:24:17 +0000719 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000720 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +0000721 case langkind_c_cpp:
722 case langkind_objc:
723 case langkind_objc_cpp:
724 LangStd = lang_gnu99;
725 break;
726 case langkind_cxx:
727 case langkind_cxx_cpp:
728 case langkind_objcxx:
729 case langkind_objcxx_cpp:
730 LangStd = lang_gnucxx98;
731 break;
732 }
733 }
734
735 switch (LangStd) {
736 default: assert(0 && "Unknown language standard!");
737
738 // Fall through from newer standards to older ones. This isn't really right.
739 // FIXME: Enable specifically the right features based on the language stds.
740 case lang_gnucxx0x:
741 case lang_cxx0x:
742 Options.CPlusPlus0x = 1;
743 // FALL THROUGH
744 case lang_gnucxx98:
745 case lang_cxx98:
746 Options.CPlusPlus = 1;
747 Options.CXXOperatorNames = !NoOperatorNames;
748 // FALL THROUGH.
749 case lang_gnu99:
750 case lang_c99:
Chris Lattner4b009652007-07-25 00:24:17 +0000751 Options.C99 = 1;
752 Options.HexFloats = 1;
753 // FALL THROUGH.
754 case lang_gnu89:
755 Options.BCPLComment = 1; // Only for C99/C++.
756 // FALL THROUGH.
757 case lang_c94:
Chris Lattner0297c762008-02-25 04:01:39 +0000758 Options.Digraphs = 1; // C94, C99, C++.
759 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000760 case lang_c89:
761 break;
762 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000763
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000764 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
765 Options.GNUMode = LangStd >= lang_gnu_START;
766
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000767 if (Options.CPlusPlus) {
768 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000769 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000770 }
Chris Lattner4b009652007-07-25 00:24:17 +0000771
Chris Lattner6ab935b2008-04-05 06:32:51 +0000772 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
773 Options.ImplicitInt = 1;
774 else
775 Options.ImplicitInt = 0;
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000776
Daniel Dunbarfacf3512009-04-07 22:13:21 +0000777 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
778 // is specified, or -std is set to a conforming mode.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000779 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000780 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000781 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000782
Chris Lattner58d5ba52008-12-05 00:10:44 +0000783 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
784 // even if they are normally on for the target. In GNU modes (e.g.
785 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlsson8ffcf732009-01-21 18:47:36 +0000786 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000787 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000788 Options.Blocks = 0;
789
Chris Lattner284784c2009-04-19 07:06:52 +0000790 // Default to not accepting '$' in identifiers when preprocessing assembler,
791 // but do accept when preprocessing C. FIXME: these defaults are right for
792 // darwin, are they right everywhere?
793 Options.DollarIdents = LK != langkind_asm_cpp;
794 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner77c04832009-04-19 07:00:02 +0000795 Options.DollarIdents = DollarsInIdents;
796
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000797 if (PascalStrings.getPosition())
798 Options.PascalStrings = PascalStrings;
Steve Naroff73a07032008-02-07 03:50:06 +0000799 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000800 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000801 if (NoLaxVectorConversions.getPosition())
802 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000803 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000804 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000805 Options.Blocks = EnableBlocks;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000806
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000807 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000808 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000809 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000810 Options.Freestanding = Options.NoBuiltin = 1;
811
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000812 if (EnableHeinousExtensions)
813 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000814
Anders Carlssonf2310142009-05-13 19:49:53 +0000815 if (AccessControl)
816 Options.AccessControl = 1;
817
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000818 Options.MathErrno = MathErrno;
819
Douglas Gregor375733c2009-03-10 00:06:19 +0000820 Options.InstantiationDepth = TemplateDepth;
821
Chris Lattnerddae7102008-12-04 22:54:33 +0000822 // Override the default runtime if the user requested it.
823 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000824 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000825 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000826 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000827
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000828 if (ObjCNonFragileABI)
829 Options.ObjCNonFragileABI = 1;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000830
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000831 if (EmitAllDecls)
832 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000833
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000834 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
835 // support.
836 Options.OptimizeSize = 0;
Anders Carlssondfd77642009-04-06 17:37:10 +0000837
838 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000839 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000840 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000841
842 assert(PICLevel <= 2 && "Invalid value for -pic-level");
843 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000844
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000845 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000846 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000847 Options.NoInline = !OptSize && !OptLevel;
848
849 Options.Static = StaticDefine;
850
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000851 if (MainFileName.getPosition())
852 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000853}
854
855//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000856// Target Triple Processing.
857//===----------------------------------------------------------------------===//
858
859static llvm::cl::opt<std::string>
860TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000861 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000862
Chris Lattnerfc457002008-03-05 01:18:20 +0000863static llvm::cl::opt<std::string>
Chris Lattner2b168e02008-09-30 01:13:12 +0000864MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000865 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000866
Chris Lattner01de9c82008-09-30 20:16:56 +0000867// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
868// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000869
870// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000871static void HandleMacOSVersionMin(std::string &Triple) {
872 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
873 if (DarwinDashIdx == std::string::npos) {
874 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000875 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000876 exit(1);
877 }
878 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
879
Chris Lattner01de9c82008-09-30 20:16:56 +0000880 // Remove the number.
881 Triple.resize(DarwinNumIdx);
882
883 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
884 bool MacOSVersionMinIsInvalid = false;
885 int VersionNum = 0;
886 if (MacOSVersionMin.size() < 4 ||
887 MacOSVersionMin.substr(0, 3) != "10." ||
888 !isdigit(MacOSVersionMin[3])) {
889 MacOSVersionMinIsInvalid = true;
890 } else {
891 const char *Start = MacOSVersionMin.c_str()+3;
892 char *End = 0;
893 VersionNum = (int)strtol(Start, &End, 10);
894
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000895 // The version number must be in the range 0-9.
896 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
897
Chris Lattner01de9c82008-09-30 20:16:56 +0000898 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
899 Triple += llvm::itostr(VersionNum+4);
900
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000901 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
902 // Add the period piece (.7) to the end of the triple. This gives us
903 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000904 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000905 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
906 MacOSVersionMinIsInvalid = true;
907 }
908 }
909
910 if (MacOSVersionMinIsInvalid) {
911 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000912 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000913 MacOSVersionMin.c_str());
914 exit(1);
915 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000916 else if (VersionNum <= 4 &&
917 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
918 fprintf(stderr,
919 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
920 MacOSVersionMin.c_str());
921 exit(1);
922 }
923
Chris Lattner01de9c82008-09-30 20:16:56 +0000924}
925
Daniel Dunbar93f64532009-04-10 19:52:24 +0000926static llvm::cl::opt<std::string>
927IPhoneOSVersionMin("miphoneos-version-min",
928 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
929
930// If -miphoneos-version-min=2.2 is specified, change the triple from being
931// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
932// 9 as the default major Darwin number, and encode the iPhone OS version
933// number in the minor version and revision.
934
935// FIXME: We should have the driver do this instead.
936static void HandleIPhoneOSVersionMin(std::string &Triple) {
937 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
938 if (DarwinDashIdx == std::string::npos) {
939 fprintf(stderr,
940 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
941 exit(1);
942 }
943 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
944
945 // Remove the number.
946 Triple.resize(DarwinNumIdx);
947
948 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
949 bool IPhoneOSVersionMinIsInvalid = false;
950 int VersionNum = 0;
951 if (IPhoneOSVersionMin.size() < 3 ||
952 !isdigit(IPhoneOSVersionMin[0])) {
953 IPhoneOSVersionMinIsInvalid = true;
954 } else {
955 const char *Start = IPhoneOSVersionMin.c_str();
956 char *End = 0;
957 VersionNum = (int)strtol(Start, &End, 10);
958
959 // The version number must be in the range 0-9.
960 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
961
962 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
963 Triple += "9." + llvm::itostr(VersionNum);
964
965 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
966 // Add the period piece (.2) to the end of the triple. This gives us
967 // something like ...-darwin9.2.2
968 Triple += End;
969 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
970 IPhoneOSVersionMinIsInvalid = true;
971 }
972 }
973
974 if (IPhoneOSVersionMinIsInvalid) {
975 fprintf(stderr,
976 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
977 IPhoneOSVersionMin.c_str());
978 exit(1);
979 }
980}
981
Chris Lattner01de9c82008-09-30 20:16:56 +0000982/// CreateTargetTriple - Process the various options that affect the target
983/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000984static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000985 // Initialize base triple. If a -triple option has been specified, use
986 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000987 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000988 if (Triple.empty())
989 Triple = llvm::sys::getHostTriple();
Chris Lattner2b168e02008-09-30 01:13:12 +0000990
991 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
992 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000993 if (!MacOSVersionMin.empty())
994 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +0000995 else if (!IPhoneOSVersionMin.empty())
996 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +0000997
Chris Lattner2b168e02008-09-30 01:13:12 +0000998 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000999}
1000
1001//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +00001002// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +00001003//===----------------------------------------------------------------------===//
1004
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001005static bool InitializeSourceManager(Preprocessor &PP,
1006 const std::string &InFile) {
1007 // Figure out where to get and map in the main file.
1008 SourceManager &SourceMgr = PP.getSourceManager();
1009 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +00001010
1011 if (EmptyInputOnly) {
1012 const char *EmptyStr = "";
1013 llvm::MemoryBuffer *SB =
1014 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1015 SourceMgr.createMainFileIDForMemBuffer(SB);
1016 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001017 const FileEntry *File = FileMgr.getFile(InFile);
1018 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1019 if (SourceMgr.getMainFileID().isInvalid()) {
1020 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1021 << InFile.c_str();
1022 return true;
1023 }
1024 } else {
1025 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1026
1027 // If stdin was empty, SB is null. Cons up an empty memory
1028 // buffer now.
1029 if (!SB) {
1030 const char *EmptyStr = "";
1031 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1032 }
1033
1034 SourceMgr.createMainFileIDForMemBuffer(SB);
1035 if (SourceMgr.getMainFileID().isInvalid()) {
1036 PP.getDiagnostics().Report(FullSourceLoc(),
1037 diag::err_fe_error_reading_stdin);
1038 return true;
1039 }
1040 }
1041
1042 return false;
1043}
1044
Chris Lattner47b6a162008-04-19 23:09:31 +00001045
Chris Lattner94269d72009-04-21 05:40:52 +00001046//===----------------------------------------------------------------------===//
1047// Preprocessor Initialization
1048//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001049
Chris Lattner94269d72009-04-21 05:40:52 +00001050// FIXME: Preprocessor builtins to support.
1051// -A... - Play with #assertions
1052// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001053
Chris Lattner94269d72009-04-21 05:40:52 +00001054static llvm::cl::list<std::string>
1055D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1056 llvm::cl::desc("Predefine the specified macro"));
1057static llvm::cl::list<std::string>
1058U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1059 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001060
Chris Lattner94269d72009-04-21 05:40:52 +00001061static llvm::cl::list<std::string>
1062ImplicitIncludes("include", llvm::cl::value_desc("file"),
1063 llvm::cl::desc("Include file before parsing"));
1064static llvm::cl::list<std::string>
1065ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1066 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001067
Chris Lattner94269d72009-04-21 05:40:52 +00001068static llvm::cl::opt<std::string>
1069ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1070 llvm::cl::desc("Include precompiled header file"));
1071
1072static llvm::cl::opt<std::string>
1073ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1074 llvm::cl::desc("Include file before parsing"));
1075
Chris Lattner4b009652007-07-25 00:24:17 +00001076
1077//===----------------------------------------------------------------------===//
1078// Preprocessor include path information.
1079//===----------------------------------------------------------------------===//
1080
1081// This tool exports a large number of command line options to control how the
1082// preprocessor searches for header files. At root, however, the Preprocessor
1083// object takes a very simple interface: a list of directories to search for
1084//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001085// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001086// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001087//
Chris Lattner4b009652007-07-25 00:24:17 +00001088
1089static llvm::cl::opt<bool>
1090nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1091
1092// Various command line options. These four add directories to each chain.
1093static llvm::cl::list<std::string>
1094F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1095 llvm::cl::desc("Add directory to framework include search path"));
1096static llvm::cl::list<std::string>
1097I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1098 llvm::cl::desc("Add directory to include search path"));
1099static llvm::cl::list<std::string>
1100idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1101 llvm::cl::desc("Add directory to AFTER include search path"));
1102static llvm::cl::list<std::string>
1103iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1104 llvm::cl::desc("Add directory to QUOTE include search path"));
1105static llvm::cl::list<std::string>
1106isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1107 llvm::cl::desc("Add directory to SYSTEM include search path"));
1108
1109// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1110static llvm::cl::list<std::string>
1111iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1112 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1113static llvm::cl::list<std::string>
1114iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1115 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1116static llvm::cl::list<std::string>
1117iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1118 llvm::cl::Prefix,
1119 llvm::cl::desc("Set directory to include search path with prefix"));
1120
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001121static llvm::cl::opt<std::string>
1122isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1123 llvm::cl::desc("Set the system root directory (usually /)"));
1124
Chris Lattner4b009652007-07-25 00:24:17 +00001125// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001126
Chris Lattner4b009652007-07-25 00:24:17 +00001127/// InitializeIncludePaths - Process the -I options and set them in the
1128/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001129void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1130 FileManager &FM, const LangOptions &Lang) {
1131 InitHeaderSearch Init(Headers, Verbose, isysroot);
1132
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001133 // Handle -I... and -F... options, walking the lists in parallel.
1134 unsigned Iidx = 0, Fidx = 0;
1135 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1136 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001137 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001138 ++Iidx;
1139 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001140 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001141 ++Fidx;
1142 }
1143 }
Chris Lattner4b009652007-07-25 00:24:17 +00001144
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001145 // Consume what's left from whatever list was longer.
1146 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001147 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001148 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001149 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001150
1151 // Handle -idirafter... options.
1152 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001153 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1154 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001155
1156 // Handle -iquote... options.
1157 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001158 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001159
1160 // Handle -isystem... options.
1161 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001162 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001163
1164 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1165 // parallel, processing the values in order of occurance to get the right
1166 // prefixes.
1167 {
1168 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1169 unsigned iprefix_idx = 0;
1170 unsigned iwithprefix_idx = 0;
1171 unsigned iwithprefixbefore_idx = 0;
1172 bool iprefix_done = iprefix_vals.empty();
1173 bool iwithprefix_done = iwithprefix_vals.empty();
1174 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1175 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1176 if (!iprefix_done &&
1177 (iwithprefix_done ||
1178 iprefix_vals.getPosition(iprefix_idx) <
1179 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1180 (iwithprefixbefore_done ||
1181 iprefix_vals.getPosition(iprefix_idx) <
1182 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1183 Prefix = iprefix_vals[iprefix_idx];
1184 ++iprefix_idx;
1185 iprefix_done = iprefix_idx == iprefix_vals.size();
1186 } else if (!iwithprefix_done &&
1187 (iwithprefixbefore_done ||
1188 iwithprefix_vals.getPosition(iwithprefix_idx) <
1189 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001190 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1191 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001192 ++iwithprefix_idx;
1193 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1194 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001195 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1196 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001197 ++iwithprefixbefore_idx;
1198 iwithprefixbefore_done =
1199 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1200 }
1201 }
1202 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001203
Nico Weber770e3882008-08-22 09:25:22 +00001204 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001205
Daniel Dunbar4e604292009-02-21 20:52:41 +00001206 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001207 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001208 llvm::sys::Path::GetMainExecutable(Argv0,
1209 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001210 if (!MainExecutablePath.isEmpty()) {
1211 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1212 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001213
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001214 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001215 MainExecutablePath.appendComponent("lib");
1216 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001217 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001218 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001219
1220 // We pass true to ignore sysroot so that we *always* look for clang headers
1221 // relative to our executable, never relative to -isysroot.
1222 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1223 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001224 }
1225
Nico Weber770e3882008-08-22 09:25:22 +00001226 if (!nostdinc)
1227 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001228
1229 // Now that we have collected all of the include paths, merge them all
1230 // together and tell the preprocessor about them.
1231
Nico Weber770e3882008-08-22 09:25:22 +00001232 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001233}
1234
Chris Lattner94269d72009-04-21 05:40:52 +00001235void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1236{
1237 // Add macros from the command line.
1238 unsigned d = 0, D = D_macros.size();
1239 unsigned u = 0, U = U_macros.size();
1240 while (d < D || u < U) {
1241 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1242 InitOpts.addMacroDef(D_macros[d++]);
1243 else
1244 InitOpts.addMacroUndef(U_macros[u++]);
1245 }
1246
1247 // If -imacros are specified, include them now. These are processed before
1248 // any -include directives.
1249 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1250 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1251
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001252 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1253 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner94269d72009-04-21 05:40:52 +00001254 // We want to add these paths to the predefines buffer in order, make a
1255 // temporary vector to sort by their occurrence.
1256 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1257
1258 if (!ImplicitIncludePTH.empty())
1259 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1260 &ImplicitIncludePTH));
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001261 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1262 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1263 &ImplicitIncludePCH));
Chris Lattner94269d72009-04-21 05:40:52 +00001264 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1265 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1266 &ImplicitIncludes[i]));
1267 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1268
1269
1270 // Now that they are ordered by position, add to the predefines buffer.
1271 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1272 std::string *Ptr = OrderedPaths[i].second;
1273 if (!ImplicitIncludes.empty() &&
1274 Ptr >= &ImplicitIncludes[0] &&
1275 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1276 InitOpts.addInclude(*Ptr, false);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001277 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner94269d72009-04-21 05:40:52 +00001278 InitOpts.addInclude(*Ptr, true);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001279 } else {
1280 // We end up here when we're producing preprocessed output and
1281 // we loaded a PCH file. In this case, just include the header
1282 // file that was used to build the precompiled header.
1283 assert(Ptr == &ImplicitIncludePCH);
1284 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1285 if (!OriginalFile.empty()) {
1286 InitOpts.addInclude(OriginalFile, false);
1287 ImplicitIncludePCH.clear();
1288 }
Chris Lattner94269d72009-04-21 05:40:52 +00001289 }
1290 }
1291 }
1292}
1293
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001294//===----------------------------------------------------------------------===//
1295// Driver PreprocessorFactory - For lazily generating preprocessors ...
1296//===----------------------------------------------------------------------===//
1297
1298namespace {
1299class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1300 Diagnostic &Diags;
1301 const LangOptions &LangInfo;
1302 TargetInfo &Target;
1303 SourceManager &SourceMgr;
1304 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001305
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001306public:
Eli Friedmane934dca2009-05-18 07:39:39 +00001307 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001308 TargetInfo &target, SourceManager &SM,
1309 HeaderSearch &Headers)
Eli Friedmane934dca2009-05-18 07:39:39 +00001310 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001311 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001312
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001313
1314 virtual ~DriverPreprocessorFactory() {}
1315
1316 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001317 llvm::OwningPtr<PTHManager> PTHMgr;
1318
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001319 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1320 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1321 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001322 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001323 }
1324
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001325 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001326 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1327 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001328 PTHMgr.reset(PTHManager::Create(x, &Diags,
1329 TokenCache.empty() ? Diagnostic::Error
1330 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001331 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001332
Ted Kremenek6348cc62009-03-22 06:42:39 +00001333 if (Diags.hasErrorOccurred())
1334 exit(1);
1335
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001336 // Create the Preprocessor.
1337 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1338 SourceMgr, HeaderInfo,
1339 PTHMgr.get()));
1340
1341 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1342 // That argument is used as the IdentifierInfoLookup argument to
1343 // IdentifierTable's ctor.
1344 if (PTHMgr) {
1345 PTHMgr->setPreprocessor(PP.get());
1346 PP->setPTHManager(PTHMgr.take());
1347 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001348
Chris Lattner94269d72009-04-21 05:40:52 +00001349 PreprocessorInitOptions InitOpts;
1350 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmane934dca2009-05-18 07:39:39 +00001351 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001352 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001353
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001354 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001355 }
1356};
1357}
Chris Lattner4b009652007-07-25 00:24:17 +00001358
Chris Lattner4b009652007-07-25 00:24:17 +00001359//===----------------------------------------------------------------------===//
1360// Basic Parser driver
1361//===----------------------------------------------------------------------===//
1362
Chris Lattner9d818a22008-04-19 23:25:44 +00001363static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001364 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001365 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001366
1367 // Parsing the specified input file.
1368 P.ParseTranslationUnit();
1369 delete PA;
1370}
1371
1372//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001373// Code generation options
1374//===----------------------------------------------------------------------===//
1375
1376static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001377GenerateDebugInfo("g",
1378 llvm::cl::desc("Generate source level debug information"));
1379
Daniel Dunbar9101a632009-02-17 19:47:34 +00001380static llvm::cl::opt<std::string>
1381TargetCPU("mcpu",
1382 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1383
Daniel Dunbar07181d72009-05-06 03:16:41 +00001384static llvm::cl::list<std::string>
1385TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1386
1387/// ComputeTargetFeatures - Recompute the target feature list to only
1388/// be the list of things that are enabled, based on the target cpu
1389/// and feature list.
1390static void ComputeFeatureMap(TargetInfo *Target,
1391 llvm::StringMap<bool> &Features) {
1392 assert(Features.empty() && "invalid map");
1393
1394 // Initialize the feature map based on the target.
1395 Target->getDefaultFeatures(TargetCPU, Features);
1396
1397 // Apply the user specified deltas.
1398 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1399 ie = TargetFeatures.end(); it != ie; ++it) {
1400 const char *Name = it->c_str();
1401
1402 // FIXME: Don't handle errors like this.
1403 if (Name[0] != '-' && Name[0] != '+') {
1404 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1405 Name);
1406 exit(1);
1407 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001408 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1409 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1410 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001411 exit(1);
1412 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001413 }
1414}
1415
Chris Lattner8a9615c2009-03-16 18:41:18 +00001416static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001417 const LangOptions &LangOpts,
1418 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001419 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001420 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard725b162008-10-29 07:56:11 +00001421 if (OptSize) {
1422 // -Os implies -O2
1423 // FIXME: Diagnose conflicting options.
1424 Opts.OptimizationLevel = 2;
1425 } else {
1426 Opts.OptimizationLevel = OptLevel;
1427 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001428
1429 // FIXME: There are llvm-gcc options to control these selectively.
1430 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1431 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001432 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001433
1434#ifdef NDEBUG
1435 Opts.VerifyModule = 0;
1436#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001437
1438 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001439 Opts.Features.clear();
1440 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1441 ie = Features.end(); it != ie; ++it) {
1442 // FIXME: If we are completely confident that we have the right
1443 // set, we only need to pass the minuses.
1444 std::string Name(it->second ? "+" : "-");
1445 Name += it->first();
1446 Opts.Features.push_back(Name);
1447 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001448
Chris Lattnerf04a7562009-03-26 05:00:52 +00001449 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1450
Chris Lattnere8f70712009-02-18 01:23:44 +00001451 // Handle -ftime-report.
1452 Opts.TimePasses = TimeReport;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001453}
1454
1455//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001456// Fix-It Options
1457//===----------------------------------------------------------------------===//
1458static llvm::cl::list<ParsedSourceLocation>
1459FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1460 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1461
1462//===----------------------------------------------------------------------===//
Eli Friedman35ba7a62009-05-18 22:39:16 +00001463// ObjC Rewriter Options
1464//===----------------------------------------------------------------------===//
1465static llvm::cl::opt<bool>
1466SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1467 llvm::cl::desc("Silence ObjC rewriting warnings"));
1468
1469//===----------------------------------------------------------------------===//
Eli Friedman4d03d382009-05-19 01:17:04 +00001470// Warning Options
1471//===----------------------------------------------------------------------===//
1472
1473// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1474// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1475// -Wextra, so we don't need to worry about it.
1476static llvm::cl::list<std::string>
1477OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1478
1479static llvm::cl::opt<bool> OptPedantic("pedantic");
1480static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1481static llvm::cl::opt<bool> OptNoWarnings("w");
1482
1483//===----------------------------------------------------------------------===//
Eli Friedmane2554252009-05-19 03:06:47 +00001484// Preprocessing (-E mode) Options
1485//===----------------------------------------------------------------------===//
1486static llvm::cl::opt<bool>
1487DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1488static llvm::cl::opt<bool>
1489EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1490static llvm::cl::opt<bool>
1491EnableMacroCommentOutput("CC",
1492 llvm::cl::desc("Enable comment output in -E mode, "
1493 "even from macro expansions"));
1494static llvm::cl::opt<bool>
1495DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1496 " normal output"));
1497static llvm::cl::opt<bool>
1498DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1499 "addition to normal output"));
Eli Friedmane595fe92009-05-19 03:35:57 +00001500
1501//===----------------------------------------------------------------------===//
1502// Dependency file options
1503//===----------------------------------------------------------------------===//
1504static llvm::cl::opt<std::string>
1505DependencyFile("dependency-file",
1506 llvm::cl::desc("Filename (or -) to write dependency output to"));
1507
1508static llvm::cl::opt<bool>
1509DependenciesIncludeSystemHeaders("sys-header-deps",
1510 llvm::cl::desc("Include system headers in dependency output"));
1511
1512static llvm::cl::list<std::string>
1513DependencyTargets("MT",
1514 llvm::cl::desc("Specify target for dependency"));
1515
1516// FIXME: Implement feature
1517static llvm::cl::opt<bool>
1518PhonyDependencyTarget("MP",
1519 llvm::cl::desc("Create phony target for each dependency "
1520 "(other than main file)"));
1521
Eli Friedmane2554252009-05-19 03:06:47 +00001522//===----------------------------------------------------------------------===//
Eli Friedman78a57622009-05-19 10:18:02 +00001523// Analysis options
1524//===----------------------------------------------------------------------===//
1525
1526static llvm::cl::list<Analyses>
1527AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1528llvm::cl::values(
1529#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1530clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001531#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001532clEnumValEnd));
1533
1534static llvm::cl::opt<AnalysisStores>
1535AnalysisStoreOpt("analyzer-store",
1536 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1537 llvm::cl::init(BasicStoreModel),
1538 llvm::cl::values(
1539#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1540clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001541#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001542clEnumValEnd));
1543
1544static llvm::cl::opt<AnalysisConstraints>
1545AnalysisConstraintsOpt("analyzer-constraints",
1546 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1547 llvm::cl::init(RangeConstraintsModel),
1548 llvm::cl::values(
1549#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1550clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001551#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001552clEnumValEnd));
1553
1554static llvm::cl::opt<AnalysisDiagClients>
1555AnalysisDiagOpt("analyzer-output",
1556 llvm::cl::desc("Source Code Analysis - Output Options"),
1557 llvm::cl::init(PD_HTML),
1558 llvm::cl::values(
1559#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1560clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001561#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001562clEnumValEnd));
1563
1564static llvm::cl::opt<bool>
1565VisualizeEGDot("analyzer-viz-egraph-graphviz",
1566 llvm::cl::desc("Display exploded graph using GraphViz"));
1567
1568static llvm::cl::opt<bool>
1569VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1570 llvm::cl::desc("Display exploded graph using Ubigraph"));
1571
1572static llvm::cl::opt<bool>
1573AnalyzeAll("analyzer-opt-analyze-headers",
1574 llvm::cl::desc("Force the static analyzer to analyze "
1575 "functions defined in header files"));
1576
1577static llvm::cl::opt<bool>
1578AnalyzerDisplayProgress("analyzer-display-progress",
1579 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1580
1581static llvm::cl::opt<bool>
1582PurgeDead("analyzer-purge-dead",
1583 llvm::cl::init(true),
1584 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1585 " processing a statement."));
1586
1587static llvm::cl::opt<bool>
1588EagerlyAssume("analyzer-eagerly-assume",
1589 llvm::cl::init(false),
1590 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1591 "symbolic constraints."));
1592
1593static llvm::cl::opt<std::string>
1594AnalyzeSpecificFunction("analyze-function",
1595 llvm::cl::desc("Run analysis on specific function"));
1596
1597static llvm::cl::opt<bool>
1598TrimGraph("trim-egraph",
1599 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1600
1601static AnalyzerOptions ReadAnalyzerOptions() {
1602 AnalyzerOptions Opts;
1603 Opts.AnalysisList = AnalysisList;
1604 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1605 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1606 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1607 Opts.VisualizeEGDot = VisualizeEGDot;
1608 Opts.VisualizeEGUbi = VisualizeEGUbi;
1609 Opts.AnalyzeAll = AnalyzeAll;
1610 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1611 Opts.PurgeDead = PurgeDead;
1612 Opts.EagerlyAssume = EagerlyAssume;
1613 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1614 Opts.TrimGraph = TrimGraph;
1615 return Opts;
1616}
1617
1618//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001619// -dump-build-information Stuff
1620//===----------------------------------------------------------------------===//
1621
1622static llvm::cl::opt<std::string>
1623DumpBuildInformation("dump-build-information",
1624 llvm::cl::value_desc("filename"),
1625 llvm::cl::desc("output a dump of some build information to a file"));
1626
1627static llvm::raw_ostream *BuildLogFile = 0;
1628
1629/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1630/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1631namespace {
1632class LoggingDiagnosticClient : public DiagnosticClient {
1633 llvm::OwningPtr<DiagnosticClient> Chain1;
1634 llvm::OwningPtr<DiagnosticClient> Chain2;
1635public:
1636
1637 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1638 // Output diags both where requested...
1639 Chain1.reset(Normal);
1640 // .. and to our log file.
1641 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1642 !NoShowColumn,
1643 !NoCaretDiagnostics,
1644 !NoShowLocation,
1645 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001646 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001647 !NoDiagnosticsFixIt,
1648 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001649 }
1650
1651 virtual void setLangOptions(const LangOptions *LO) {
1652 Chain1->setLangOptions(LO);
1653 Chain2->setLangOptions(LO);
1654 }
1655
1656 virtual bool IncludeInDiagnosticCounts() const {
1657 return Chain1->IncludeInDiagnosticCounts();
1658 }
1659
1660 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1661 const DiagnosticInfo &Info) {
1662 Chain1->HandleDiagnostic(DiagLevel, Info);
1663 Chain2->HandleDiagnostic(DiagLevel, Info);
1664 }
1665};
1666} // end anonymous namespace.
1667
1668static void SetUpBuildDumpLog(unsigned argc, char **argv,
1669 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1670
1671 std::string ErrorInfo;
1672 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1673 ErrorInfo);
1674
1675 if (!ErrorInfo.empty()) {
1676 llvm::errs() << "error opening -dump-build-information file '"
1677 << DumpBuildInformation << "', option ignored!\n";
1678 delete BuildLogFile;
1679 BuildLogFile = 0;
1680 DumpBuildInformation = "";
1681 return;
1682 }
1683
1684 (*BuildLogFile) << "clang-cc command line arguments: ";
1685 for (unsigned i = 0; i != argc; ++i)
1686 (*BuildLogFile) << argv[i] << ' ';
1687 (*BuildLogFile) << '\n';
1688
1689 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1690 // the diagnostic producers and the normal receiver.
1691 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1692}
1693
1694
1695
1696//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001697// Main driver
1698//===----------------------------------------------------------------------===//
1699
Eli Friedmana9c310842009-05-18 22:20:00 +00001700static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1701 const char* Extension,
1702 bool Binary,
1703 llvm::sys::Path& OutPath) {
1704 llvm::raw_ostream* Ret;
1705 bool UseStdout = false;
1706 std::string OutFile;
1707 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1708 UseStdout = true;
1709 } else if (!OutputFile.empty()) {
1710 OutFile = OutputFile;
1711 } else if (Extension) {
1712 llvm::sys::Path Path(InFile);
1713 Path.eraseSuffix();
1714 Path.appendSuffix(Extension);
1715 OutFile = Path.toString();
1716 } else {
1717 UseStdout = true;
Chris Lattner7f902922009-02-18 01:20:05 +00001718 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001719
Eli Friedmana9c310842009-05-18 22:20:00 +00001720 if (UseStdout) {
1721 Ret = new llvm::raw_stdout_ostream();
1722 if (Binary)
1723 llvm::sys::Program::ChangeStdoutToBinary();
1724 } else {
1725 std::string Error;
1726 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1727 if (!Error.empty()) {
1728 // FIXME: Don't fail this way.
1729 llvm::cerr << "ERROR: " << Error << "\n";
1730 ::exit(1);
1731 }
1732 OutPath = OutFile;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001733 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001734
1735 return Ret;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001736}
1737
Chris Lattner4b009652007-07-25 00:24:17 +00001738/// ProcessInputFile - Process a single input file with the specified state.
1739///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001740static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001741 const std::string &InFile, ProgActions PA,
1742 const llvm::StringMap<bool> &Features) {
Eli Friedmana9c310842009-05-18 22:20:00 +00001743 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek50aab982008-08-08 02:46:37 +00001744 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001745 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001746 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001747 bool CompleteTranslationUnit = true;
Eli Friedmana9c310842009-05-18 22:20:00 +00001748 llvm::sys::Path OutPath;
Douglas Gregor133d2552009-04-02 01:08:08 +00001749
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001750 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001751 default:
Eli Friedmana9c310842009-05-18 22:20:00 +00001752 fprintf(stderr, "Unexpected program action!\n");
1753 HadErrors = true;
1754 return;
1755
1756 case ASTPrint:
1757 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1758 Consumer.reset(CreateASTPrinter(OS.get()));
1759 break;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001760
Douglas Gregor8987c032009-05-21 20:55:50 +00001761 case ASTPrintXML:
1762 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1763 Consumer.reset(CreateASTPrinterXML(OS.get()));
1764 break;
1765
Eli Friedmana9c310842009-05-18 22:20:00 +00001766 case ASTDump:
1767 Consumer.reset(CreateASTDumper(false));
1768 break;
1769
1770 case ASTDumpFull:
1771 Consumer.reset(CreateASTDumper(true));
1772 break;
1773
1774 case ASTView:
1775 Consumer.reset(CreateASTViewer());
1776 break;
1777
1778 case PrintDeclContext:
1779 Consumer.reset(CreateDeclContextPrinter());
1780 break;
1781
1782 case EmitHTML:
1783 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1784 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1785 break;
1786
1787 case InheritanceView:
1788 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1789 break;
1790
1791 case EmitAssembly:
1792 case EmitLLVM:
1793 case EmitBC:
1794 case EmitLLVMOnly: {
1795 BackendAction Act;
1796 if (ProgAction == EmitAssembly) {
1797 Act = Backend_EmitAssembly;
1798 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1799 } else if (ProgAction == EmitLLVM) {
1800 Act = Backend_EmitLL;
1801 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1802 } else if (ProgAction == EmitLLVMOnly) {
1803 Act = Backend_EmitNothing;
1804 } else {
1805 Act = Backend_EmitBC;
1806 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001807 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001808
Eli Friedmana9c310842009-05-18 22:20:00 +00001809 CompileOptions Opts;
1810 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1811 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1812 PP.getLangOptions(), Opts, InFile,
1813 OS.get()));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001814 break;
Eli Friedmana9c310842009-05-18 22:20:00 +00001815 }
1816
1817 case GeneratePCH:
1818 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1819 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1820 CompleteTranslationUnit = false;
1821 break;
1822
1823 case RewriteObjC:
1824 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedman848763f2009-05-18 22:29:17 +00001825 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedman35ba7a62009-05-18 22:39:16 +00001826 PP.getLangOptions(),
1827 SilenceRewriteMacroWarning));
Eli Friedmana9c310842009-05-18 22:20:00 +00001828 break;
1829
1830 case RewriteBlocks:
1831 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1832 PP.getLangOptions()));
1833 break;
1834
Eli Friedman78a57622009-05-19 10:18:02 +00001835 case RunAnalysis: {
Eli Friedmana9c310842009-05-18 22:20:00 +00001836 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedman78a57622009-05-19 10:18:02 +00001837 PP.getLangOptions(), OutputFile,
1838 ReadAnalyzerOptions()));
Eli Friedmana9c310842009-05-18 22:20:00 +00001839 break;
Eli Friedman78a57622009-05-19 10:18:02 +00001840 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001841
Chris Lattneraf669fb2008-10-12 05:03:36 +00001842 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001843 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001844 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001845 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001846 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001847 RawLex.SetKeepWhitespaceMode(true);
1848
1849 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001850 RawLex.LexFromRawLexer(RawTok);
1851 while (RawTok.isNot(tok::eof)) {
1852 PP.DumpToken(RawTok, true);
1853 fprintf(stderr, "\n");
1854 RawLex.LexFromRawLexer(RawTok);
1855 }
1856 ClearSourceMgr = true;
1857 break;
1858 }
Chris Lattner4b009652007-07-25 00:24:17 +00001859 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001860 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001861 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001862 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001863 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001864 do {
1865 PP.Lex(Tok);
1866 PP.DumpToken(Tok, true);
1867 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001868 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001869 ClearSourceMgr = true;
1870 break;
1871 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001872 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001873 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001874
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001875 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001876 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001877 if (OutputFile.empty() || OutputFile == "-") {
1878 // FIXME: Don't fail this way.
1879 // FIXME: Verify that we can actually seek in the given file.
1880 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1881 ::exit(1);
1882 }
1883 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1884 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001885 ClearSourceMgr = true;
1886 break;
1887 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001888
Chris Lattner772a7c12009-04-27 22:02:30 +00001889 case PrintPreprocessedInput:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001890 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Chris Lattner4b009652007-07-25 00:24:17 +00001891 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001892
Chris Lattner270d29a2009-04-27 21:45:14 +00001893 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001894 break;
1895
Chris Lattnerefe33382009-02-18 01:51:21 +00001896 case ParsePrintCallbacks: {
1897 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001898 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1899 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattner4b009652007-07-25 00:24:17 +00001900 ClearSourceMgr = true;
1901 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001902 }
1903
1904 case ParseSyntaxOnly: { // -fsyntax-only
1905 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001906 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001907 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001908 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001909
1910 case RewriteMacros:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001911 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1912 RewriteMacrosInInput(PP, OS.get());
Chris Lattner1665a9f2008-05-08 06:52:13 +00001913 ClearSourceMgr = true;
1914 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001915
Eli Friedman4ae15b92009-05-19 01:02:07 +00001916 case RewriteTest:
1917 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1918 DoRewriteTest(PP, OS.get());
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001919 ClearSourceMgr = true;
1920 break;
Douglas Gregor133d2552009-04-02 01:08:08 +00001921
1922 case FixIt:
1923 llvm::TimeRegion Timer(ClangFrontendTimer);
1924 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001925 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001926 PP.getSourceManager(),
1927 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001928 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001929 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001930
Chris Lattner38a4f182009-04-27 21:25:27 +00001931 if (FixItAtLocations.size() > 0) {
1932 // Even without the "-fixit" flag, with may have some specific
1933 // locations where the user has requested fixes. Process those
1934 // locations now.
1935 if (!FixItRewrite)
1936 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1937 PP.getSourceManager(),
1938 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001939
Chris Lattner38a4f182009-04-27 21:25:27 +00001940 bool AddedFixitLocation = false;
1941 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1942 Idx != Last; ++Idx) {
1943 RequestedSourceLocation Requested;
1944 if (FixItAtLocations[Idx].ResolveLocation(PP.getFileManager(),
1945 Requested)) {
1946 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1947 FixItAtLocations[Idx].FileName.c_str());
1948 } else {
1949 FixItRewrite->addFixItLocation(Requested);
1950 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001951 }
1952 }
1953
Chris Lattner38a4f182009-04-27 21:25:27 +00001954 if (!AddedFixitLocation) {
1955 // All of the fix-it locations were bad. Don't fix anything.
1956 delete FixItRewrite;
1957 FixItRewrite = 0;
1958 }
1959 }
1960
1961 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001962 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001963 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1964 PP.getSourceManager(),
1965 PP.getTargetInfo(),
1966 PP.getIdentifierTable(),
1967 PP.getSelectorTable(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001968 /* FreeMemory = */ !DisableFree,
1969 /* size_reserve = */0,
1970 /* InitializeBuiltins = */ImplicitIncludePCH.empty()));
Chris Lattner772a7c12009-04-27 22:02:30 +00001971 llvm::OwningPtr<PCHReader> Reader;
1972 llvm::OwningPtr<ExternalASTSource> Source;
1973
Chris Lattner270d29a2009-04-27 21:45:14 +00001974 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001975 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1976
Chris Lattner270d29a2009-04-27 21:45:14 +00001977 // The user has asked us to include a precompiled header. Load
1978 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001979 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1980 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00001981 // Set the predefines buffer as suggested by the PCH
1982 // reader. Typically, the predefines buffer will be empty.
1983 PP.setPredefines(Reader->getSuggestedPredefines());
1984
Chris Lattner270d29a2009-04-27 21:45:14 +00001985 // Attach the PCH reader to the AST context as an external AST
1986 // source, so that declarations will be deserialized from the
1987 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00001988 if (ContextOwner) {
1989 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001990 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00001991 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001992 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001993 }
1994
Chris Lattner270d29a2009-04-27 21:45:14 +00001995 case PCHReader::Failure:
1996 // Unrecoverable failure: don't even try to process the input
1997 // file.
1998 return;
1999
2000 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002001 // No suitable PCH file could be found. Return an error.
2002 return;
2003
2004#if 0
2005 // FIXME: We can recover from failed attempts to load PCH
2006 // files. This code will do so, if we ever want to enable it.
2007
Chris Lattner270d29a2009-04-27 21:45:14 +00002008 // We delayed the initialization of builtins in the hope of
2009 // loading the PCH file. Since the PCH file could not be
2010 // loaded, initialize builtins now.
2011 if (ContextOwner)
2012 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002013#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00002014 }
2015
2016 // Finish preprocessor initialization. We do this now (rather
2017 // than earlier) because this initialization creates new source
2018 // location entries in the source manager, which must come after
2019 // the source location entries for the PCH file.
2020 if (InitializeSourceManager(PP, InFile))
2021 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00002022 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002023
Chris Lattner270d29a2009-04-27 21:45:14 +00002024
2025 // If we have an ASTConsumer, run the parser with it.
2026 if (Consumer)
2027 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2028 CompleteTranslationUnit);
2029
2030 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2031 llvm::TimeRegion Timer(ClangFrontendTimer);
2032 Token Tok;
2033 // Start parsing the specified input file.
2034 PP.EnterMainSourceFile();
2035 do {
2036 PP.Lex(Tok);
2037 } while (Tok.isNot(tok::eof));
2038 ClearSourceMgr = true;
2039 } else if (PA == ParseNoop) { // -parse-noop
2040 llvm::TimeRegion Timer(ClangFrontendTimer);
2041 ParseFile(PP, new MinimalAction(PP));
2042 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00002043 } else if (PA == PrintPreprocessedInput){ // -E mode.
2044 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmane2554252009-05-19 03:06:47 +00002045 if (DumpMacros)
2046 DoPrintMacros(PP, OS.get());
2047 else
2048 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2049 EnableMacroCommentOutput,
2050 DisableLineMarkers, DumpDefines);
Chris Lattner772a7c12009-04-27 22:02:30 +00002051 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00002052 }
2053
Chris Lattner38a4f182009-04-27 21:25:27 +00002054 if (FixItRewrite)
2055 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2056
2057 // If in -disable-free mode, don't deallocate ASTContext.
2058 if (DisableFree)
2059 ContextOwner.take();
2060 else
2061 ContextOwner.reset(); // Delete ASTContext
Eli Friedmana9c310842009-05-18 22:20:00 +00002062
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002063 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002064 if (CheckDiagnostics(PP))
2065 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002066
Chris Lattner4b009652007-07-25 00:24:17 +00002067 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002068 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002069 PP.PrintStats();
2070 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002071 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002072 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002073 fprintf(stderr, "\n");
2074 }
2075
2076 // For a multi-file compilation, some things are ok with nuking the source
2077 // manager tables, other require stable fileid/macroid's across multiple
2078 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002079 if (ClearSourceMgr)
2080 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002081
2082 if (DisableFree)
2083 Consumer.take();
Eli Friedmana9c310842009-05-18 22:20:00 +00002084 else
2085 Consumer.reset();
2086
2087 // Always delete the output stream because we don't want to leak file
2088 // handles. Also, we don't want to try to erase an open file.
2089 OS.reset();
2090
2091 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2092 !OutPath.isEmpty()) {
2093 // If we had errors, try to erase the output file.
2094 OutPath.eraseFromDisk();
2095 }
Chris Lattner4b009652007-07-25 00:24:17 +00002096}
2097
2098static llvm::cl::list<std::string>
2099InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2100
Chris Lattner4b009652007-07-25 00:24:17 +00002101int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002102 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002103 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002104 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002105 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Chris Lattner4b009652007-07-25 00:24:17 +00002106
Chris Lattnerefe33382009-02-18 01:51:21 +00002107 if (TimeReport)
2108 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2109
Chris Lattner4b009652007-07-25 00:24:17 +00002110 // If no input was specified, read from stdin.
2111 if (InputFilenames.empty())
2112 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00002113
Ted Kremenekb240e822007-12-11 23:28:38 +00002114 // Create the diagnostic client for reporting errors or for
2115 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002116 llvm::OwningPtr<DiagnosticClient> DiagClient;
2117 if (VerifyDiagnostics) {
2118 // When checking diagnostics, just buffer them up.
2119 DiagClient.reset(new TextDiagnosticBuffer());
2120 if (InputFilenames.size() != 1) {
2121 fprintf(stderr, "-verify only works on single input files for now.\n");
2122 return 1;
2123 }
2124 if (!HTMLDiag.empty()) {
2125 fprintf(stderr, "-verify and -html-diags don't work together\n");
2126 return 1;
2127 }
2128 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002129 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00002130
2131 // If -fmessage-length=N was not specified, determine whether this
2132 // is a terminal and, if so, implicitly define -fmessage-length
2133 // appropriately.
2134 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00002135 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00002136
Chris Lattner5f7937d2009-04-17 20:40:01 +00002137 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002138 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002139 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002140 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002141 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00002142 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00002143 !NoDiagnosticsFixIt,
2144 MessageLength));
Ted Kremenek5c341732008-08-07 17:49:57 +00002145 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002146 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002147 }
Chris Lattner94859302009-04-17 21:05:01 +00002148
2149 if (!DumpBuildInformation.empty()) {
2150 if (!HTMLDiag.empty()) {
2151 fprintf(stderr,
2152 "-dump-build-information and -html-diags don't work together\n");
2153 return 1;
2154 }
2155
2156 SetUpBuildDumpLog(argc, argv, DiagClient);
2157 }
2158
Ted Kremenek5c341732008-08-07 17:49:57 +00002159
Chris Lattner4b009652007-07-25 00:24:17 +00002160 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002161 Diagnostic Diags(DiagClient.get());
Eli Friedman4d03d382009-05-19 01:17:04 +00002162 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2163 OptNoWarnings))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002164 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002165
Chris Lattner45a56e02007-12-05 23:24:17 +00002166 // -I- is a deprecated GCC feature, scan for it and reject it.
2167 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2168 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002169 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002170 I_dirs.erase(I_dirs.begin()+i);
2171 --i;
2172 }
2173 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002174
2175 // Get information about the target being compiled for.
2176 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002177 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2178
Chris Lattner2c77d852008-03-14 06:12:05 +00002179 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002180 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2181 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002182 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002183 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002184
Daniel Dunbar9c321102009-01-20 23:17:32 +00002185 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002186 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002187
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002188 llvm::OwningPtr<SourceManager> SourceMgr;
2189
Chris Lattnere1be6022009-04-14 23:22:57 +00002190 // Create a file manager object to provide access to and cache the filesystem.
2191 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002192
Daniel Dunbar07181d72009-05-06 03:16:41 +00002193 // Compute the feature set, unfortunately this effects the language!
2194 llvm::StringMap<bool> Features;
2195 ComputeFeatureMap(Target.get(), Features);
2196
Chris Lattner4b009652007-07-25 00:24:17 +00002197 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002198 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002199
Chris Lattner2b989562009-03-04 21:40:56 +00002200 /// Create a SourceManager object. This tracks and owns all the file
2201 /// buffers allocated to a translation unit.
2202 if (!SourceMgr)
2203 SourceMgr.reset(new SourceManager());
2204 else
2205 SourceMgr->clearIDTables();
2206
2207 // Initialize language options, inferring file types from input filenames.
2208 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002209 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002210
Chris Lattner2b989562009-03-04 21:40:56 +00002211 InitializeBaseLanguage();
2212 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002213 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002214 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002215
2216 // Process the -I options and set them in the HeaderInfo.
2217 HeaderSearch HeaderInfo(FileMgr);
2218
Chris Lattnere1be6022009-04-14 23:22:57 +00002219
Chris Lattner2b989562009-03-04 21:40:56 +00002220 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2221
2222 // Set up the preprocessor with these options.
Eli Friedmane934dca2009-05-18 07:39:39 +00002223 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattner2b989562009-03-04 21:40:56 +00002224 *SourceMgr.get(), HeaderInfo);
2225
2226 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2227
2228 if (!PP)
2229 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002230
Eli Friedmane595fe92009-05-19 03:35:57 +00002231 // Handle generating dependencies, if requested
2232 if (!DependencyFile.empty()) {
2233 llvm::raw_ostream *DependencyOS;
2234 if (DependencyTargets.empty()) {
2235 // FIXME: Use a proper diagnostic
2236 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2237 HadErrors = true;
2238 continue;
2239 }
2240 std::string ErrStr;
2241 DependencyOS =
2242 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2243 if (!ErrStr.empty()) {
2244 // FIXME: Use a proper diagnostic
2245 llvm::cerr << "unable to open dependency file: " + ErrStr;
2246 HadErrors = true;
2247 continue;
2248 }
2249
2250 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2251 DependenciesIncludeSystemHeaders,
2252 PhonyDependencyTarget);
2253 }
2254
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002255 if (ImplicitIncludePCH.empty() &&
2256 InitializeSourceManager(*PP.get(), InFile))
Douglas Gregorab1cef72009-04-10 03:52:48 +00002257 continue;
2258
Chris Lattner5f7937d2009-04-17 20:40:01 +00002259 if (!HTMLDiag.empty())
2260 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002261
2262 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002263 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002264
Chris Lattner2961dc52009-04-17 20:16:08 +00002265 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002266 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002267 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002268
Mike Stump91d01352009-01-28 02:43:35 +00002269 if (Verbose)
2270 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
2271 " hosted on " LLVM_HOSTTRIPLE "\n");
2272
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002273 if (!NoCaretDiagnostics)
2274 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2275 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2276 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002277
2278 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002279 FileMgr.PrintStats();
2280 fprintf(stderr, "\n");
2281 }
Chris Lattner94859302009-04-17 21:05:01 +00002282
2283 delete ClangFrontendTimer;
2284 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002285
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002286 // If verifying diagnostics and we reached here, all is well.
2287 if (VerifyDiagnostics)
2288 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002289
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002290 // Managed static deconstruction. Useful for making things like
2291 // -time-passes usable.
2292 llvm::llvm_shutdown();
2293
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002294 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002295}