blob: 4a7d10b7a14a8d897c6426412147b85bc013b55c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman0ec78fa2009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000027#include "clang/Frontend/ASTUnit.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000028#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000029#include "clang/Frontend/CompileOptions.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000030#include "clang/Frontend/DiagnosticOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000031#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbardd35ce92009-11-07 04:58:12 +000033#include "clang/Frontend/HeaderSearchOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/InitHeaderSearch.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000036#include "clang/Frontend/PathDiagnosticClients.h"
37#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000038#include "clang/Frontend/TextDiagnosticBuffer.h"
39#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000040#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000041#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000042#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000043#include "clang/CodeGen/ModuleBuilder.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000044#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000045#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000046#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000047#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000048#include "clang/AST/ASTContext.h"
49#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000050#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000051#include "clang/Parse/Parser.h"
52#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000053#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054#include "clang/Basic/FileManager.h"
55#include "clang/Basic/SourceManager.h"
56#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000057#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000058#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000060#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000061#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000062#include "llvm/ADT/StringMap.h"
Daniel Dunbar227b2382009-11-09 22:45:57 +000063#include "llvm/ADT/StringSwitch.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000064#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000065#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000066#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000067#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000068#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000069#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000070#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000071#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000072#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000073#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000074#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000075#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000076#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000077#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000078#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000079#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000080#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000081# include <sys/types.h>
82#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000083
Reid Spencer5f016e22007-07-11 17:01:13 +000084using namespace clang;
85
86//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000087// Source Location Parser
88//===----------------------------------------------------------------------===//
89
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000090static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
91 FileManager &FileMgr,
92 RequestedSourceLocation &Result) {
93 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000094 if (!File)
95 return true;
96
97 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000098 Result.Line = ParsedLoc.Line;
99 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +0000100 return false;
101}
102
Douglas Gregor26df2f02009-04-02 19:05:20 +0000103//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000104// Global options.
105//===----------------------------------------------------------------------===//
106
Chris Lattner47099742009-02-18 01:51:21 +0000107/// ClangFrontendTimer - The front-end activities should charge time to it with
108/// TimeRegion. The -ftime-report option controls whether this will do
109/// anything.
110llvm::Timer *ClangFrontendTimer = 0;
111
Reid Spencer5f016e22007-07-11 17:01:13 +0000112static llvm::cl::opt<bool>
113Verbose("v", llvm::cl::desc("Enable verbose output"));
114static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000115Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000116 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000117static llvm::cl::opt<bool>
118DisableFree("disable-free",
119 llvm::cl::desc("Disable freeing of memory on exit"),
120 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000121static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000122EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000123 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000124
125enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000126 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000127 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000128 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000129 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000130 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000131 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000132 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000134 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000135 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000136 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000137 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000138 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000139 ASTDump, // Parse ASTs and dump them.
140 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000141 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000142 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 ParsePrintCallbacks, // Parse and print each callback.
144 ParseSyntaxOnly, // Parse and perform semantic analysis.
145 ParseNoop, // Parse with noop callbacks.
146 RunPreprocessorOnly, // Just lex, no output.
147 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000148 DumpTokens, // Dump out preprocessed tokens.
149 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000150 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000151 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000152 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000153 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000154};
155
Mike Stump1eb44332009-09-09 15:08:12 +0000156static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000157ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
158 llvm::cl::init(ParseSyntaxOnly),
159 llvm::cl::values(
160 clEnumValN(RunPreprocessorOnly, "Eonly",
161 "Just run preprocessor, no output (for timings)"),
162 clEnumValN(PrintPreprocessedInput, "E",
163 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000164 clEnumValN(DumpRawTokens, "dump-raw-tokens",
165 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000166 clEnumValN(RunAnalysis, "analyze",
167 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000168 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 "Run preprocessor, dump internal rep of tokens"),
170 clEnumValN(ParseNoop, "parse-noop",
171 "Run parser with noop callbacks (for timings)"),
172 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
173 "Run parser and perform semantic analysis"),
174 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
175 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000176 clEnumValN(EmitHTML, "emit-html",
177 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000178 clEnumValN(ASTPrint, "ast-print",
179 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000180 clEnumValN(ASTPrintXML, "ast-print-xml",
181 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000182 clEnumValN(ASTDump, "ast-dump",
183 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000184 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000185 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000186 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000187 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000188 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
189 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000190 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000191 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000192 clEnumValN(GeneratePCH, "emit-pch",
193 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000194 clEnumValN(EmitAssembly, "S",
195 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000197 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000198 clEnumValN(EmitBC, "emit-llvm-bc",
199 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000200 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
201 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000202 clEnumValN(RewriteTest, "rewrite-test",
203 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000204 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000205 "Rewrite ObjC into C (code rewriter example)"),
206 clEnumValN(RewriteMacros, "rewrite-macros",
207 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000208 clEnumValN(RewriteBlocks, "rewrite-blocks",
209 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000210 clEnumValN(FixIt, "fixit",
211 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 clEnumValEnd));
213
Ted Kremenekccc76472007-12-19 19:47:59 +0000214
215static llvm::cl::opt<std::string>
216OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000217 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000218 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000219
Ted Kremenekc2e72992008-12-02 19:57:31 +0000220
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000221enum CodeCompletionPrinter {
222 CCP_Debug,
223 CCP_CIndex
224};
225
Douglas Gregorb657f112009-09-22 21:11:38 +0000226static llvm::cl::opt<ParsedSourceLocation>
227CodeCompletionAt("code-completion-at",
228 llvm::cl::value_desc("file:line:column"),
229 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000230
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000231static llvm::cl::opt<CodeCompletionPrinter>
232CodeCompletionPrinter("code-completion-printer",
233 llvm::cl::desc("Choose output type:"),
234 llvm::cl::init(CCP_Debug),
235 llvm::cl::values(
236 clEnumValN(CCP_Debug, "debug",
237 "Debug code-completion results"),
238 clEnumValN(CCP_CIndex, "cindex",
239 "Code-completion results for the CIndex library"),
240 clEnumValEnd));
241
242static llvm::cl::opt<bool>
243CodeCompletionWantsMacros("code-completion-macros",
244 llvm::cl::desc("Include macros in code-completion results"));
245
Douglas Gregor81b747b2009-09-17 21:32:03 +0000246/// \brief Buld a new code-completion consumer that prints the results of
247/// code completion to standard output.
248static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000249 switch (CodeCompletionPrinter.getValue()) {
250 case CCP_Debug:
251 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
252 llvm::outs());
253
254 case CCP_CIndex:
255 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
256 llvm::outs());
257 };
258
259 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000260}
261
Ted Kremenekc2e72992008-12-02 19:57:31 +0000262//===----------------------------------------------------------------------===//
263// PTH.
264//===----------------------------------------------------------------------===//
265
266static llvm::cl::opt<std::string>
267TokenCache("token-cache", llvm::cl::value_desc("path"),
268 llvm::cl::desc("Use specified token cache file"));
269
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000270//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000271// Diagnostic Options
272//===----------------------------------------------------------------------===//
273
Ted Kremenek41193e42007-09-26 19:42:19 +0000274static llvm::cl::opt<bool>
275VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000276 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000277
Nico Weberfd54ebc2008-08-05 23:33:20 +0000278static llvm::cl::opt<bool>
279NoShowColumn("fno-show-column",
280 llvm::cl::desc("Do not include column number on diagnostics"));
281
282static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000283NoShowLocation("fno-show-source-location",
284 llvm::cl::desc("Do not include source location information with"
285 " diagnostics"));
286
287static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000288NoCaretDiagnostics("fno-caret-diagnostics",
289 llvm::cl::desc("Do not include source line and caret with"
290 " diagnostics"));
291
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000292static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000293NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
294 llvm::cl::desc("Do not include fixit information in"
295 " diagnostics"));
296
297static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000298PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
299 llvm::cl::desc("Print source range spans in numeric form"));
300
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000301static llvm::cl::opt<bool>
302PrintDiagnosticOption("fdiagnostics-show-option",
303 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000304
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000305static llvm::cl::opt<unsigned>
306MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000307 llvm::cl::desc("Format message diagnostics so that they fit "
308 "within N columns or fewer, when possible."),
309 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000310
Torok Edwin603fca72009-06-04 07:18:23 +0000311static llvm::cl::opt<bool>
Daniel Dunbar838be482009-11-04 06:24:57 +0000312PrintColorDiagnostic("fcolor-diagnostics",
313 llvm::cl::desc("Use colors in diagnostics"));
314
Reid Spencer5f016e22007-07-11 17:01:13 +0000315//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000316// C++ Visualization.
317//===----------------------------------------------------------------------===//
318
319static llvm::cl::opt<std::string>
320InheritanceViewCls("cxx-inheritance-view",
321 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000322 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000323
324//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000325// Builtin Options
326//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000327
328static llvm::cl::opt<bool>
329TimeReport("ftime-report",
330 llvm::cl::desc("Print the amount of time each "
331 "phase of compilation takes"));
332
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000333static llvm::cl::opt<bool>
334Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000335 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000336 "freestanding environment"));
337
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000338static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000339AllowBuiltins("fbuiltin", llvm::cl::init(true),
340 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000341
342
343static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000344MathErrno("fmath-errno", llvm::cl::init(true),
345 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000346
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000347//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000348// Language Options
349//===----------------------------------------------------------------------===//
350
351enum LangKind {
352 langkind_unspecified,
353 langkind_c,
354 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000355 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 langkind_cxx,
357 langkind_cxx_cpp,
358 langkind_objc,
359 langkind_objc_cpp,
360 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000361 langkind_objcxx_cpp,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000362 langkind_ocl,
363 langkind_ast
Reid Spencer5f016e22007-07-11 17:01:13 +0000364};
365
Reid Spencer5f016e22007-07-11 17:01:13 +0000366static llvm::cl::opt<LangKind>
367BaseLang("x", llvm::cl::desc("Base language to compile"),
368 llvm::cl::init(langkind_unspecified),
369 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000370 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 clEnumValN(langkind_cxx, "c++", "C++"),
372 clEnumValN(langkind_objc, "objective-c", "Objective C"),
373 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000374 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000376 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
377 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000379 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
381 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000382 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000384 clEnumValN(langkind_c, "c-header",
385 "C header"),
386 clEnumValN(langkind_objc, "objective-c-header",
387 "Objective-C header"),
388 clEnumValN(langkind_cxx, "c++-header",
389 "C++ header"),
390 clEnumValN(langkind_objcxx, "objective-c++-header",
391 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000392 clEnumValN(langkind_ast, "ast",
393 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 clEnumValEnd));
395
396static llvm::cl::opt<bool>
Chris Lattner2c78b872009-04-14 23:22:57 +0000397ObjCExclusiveGC("fobjc-gc-only",
398 llvm::cl::desc("Use GC exclusively for Objective-C related "
399 "memory management"));
400
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000401static llvm::cl::opt<std::string>
402ObjCConstantStringClass("fconstant-string-class",
403 llvm::cl::value_desc("class name"),
404 llvm::cl::desc("Specify the class to use for constant "
405 "Objective-C string objects."));
406
Chris Lattner2c78b872009-04-14 23:22:57 +0000407static llvm::cl::opt<bool>
408ObjCEnableGC("fobjc-gc",
409 llvm::cl::desc("Enable Objective-C garbage collection"));
410
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000411static llvm::cl::opt<bool>
412ObjCEnableGCBitmapPrint("print-ivar-layout",
413 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
414
Chris Lattner2c78b872009-04-14 23:22:57 +0000415static llvm::cl::opt<LangOptions::VisibilityMode>
416SymbolVisibility("fvisibility",
417 llvm::cl::desc("Set the default symbol visibility:"),
418 llvm::cl::init(LangOptions::Default),
419 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
420 "Use default symbol visibility"),
421 clEnumValN(LangOptions::Hidden, "hidden",
422 "Use hidden symbol visibility"),
423 clEnumValN(LangOptions::Protected,"protected",
424 "Use protected symbol visibility"),
425 clEnumValEnd));
426
427static llvm::cl::opt<bool>
428OverflowChecking("ftrapv",
429 llvm::cl::desc("Trap on integer overflow"),
430 llvm::cl::init(false));
431
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000432static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000433AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
434 llvm::cl::init(false));
435
436static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000437PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
438 llvm::cl::init(false));
439
Ted Kremenek85888962008-10-21 00:54:44 +0000440static void InitializeCOptions(LangOptions &Options) {
441 // Do nothing.
442}
443
444static void InitializeObjCOptions(LangOptions &Options) {
445 Options.ObjC1 = Options.ObjC2 = 1;
446}
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Ted Kremenek85888962008-10-21 00:54:44 +0000448
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000449static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 // FIXME: implement -fpreprocessed mode.
451 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Ted Kremenek8904f152007-12-05 23:49:08 +0000453 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000455 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000456 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000457 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 case langkind_c_cpp:
459 NoPreprocess = true;
460 // FALLTHROUGH
461 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000462 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 break;
464 case langkind_cxx_cpp:
465 NoPreprocess = true;
466 // FALLTHROUGH
467 case langkind_cxx:
468 Options.CPlusPlus = 1;
469 break;
470 case langkind_objc_cpp:
471 NoPreprocess = true;
472 // FALLTHROUGH
473 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000474 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 break;
476 case langkind_objcxx_cpp:
477 NoPreprocess = true;
478 // FALLTHROUGH
479 case langkind_objcxx:
480 Options.ObjC1 = Options.ObjC2 = 1;
481 Options.CPlusPlus = 1;
482 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000483 case langkind_ocl:
484 Options.OpenCL = 1;
485 Options.AltiVec = 1;
486 Options.CXXOperatorNames = 1;
487 Options.LaxVectorConversions = 1;
488 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Chris Lattner2c78b872009-04-14 23:22:57 +0000491 if (ObjCExclusiveGC)
492 Options.setGCMode(LangOptions::GCOnly);
493 else if (ObjCEnableGC)
494 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000496 if (ObjCEnableGCBitmapPrint)
497 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Nate Begeman2ef13e52009-08-10 23:49:36 +0000499 if (AltiVec)
500 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000501
502 if (PThread)
503 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner2c78b872009-04-14 23:22:57 +0000505 Options.setVisibilityMode(SymbolVisibility);
506 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000507}
508
509/// LangStds - Language standards we support.
510enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000511 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000512 lang_c89, lang_c94, lang_c99,
Douglas Gregor214904e2009-09-29 14:42:43 +0000513 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000514 lang_cxx98, lang_gnucxx98,
515 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000516};
517
518static llvm::cl::opt<LangStds>
519LangStd("std", llvm::cl::desc("Language standard to compile for"),
520 llvm::cl::init(lang_unspecified),
521 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
522 clEnumValN(lang_c89, "c90", "ISO C 1990"),
523 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
524 clEnumValN(lang_c94, "iso9899:199409",
525 "ISO C 1990 with amendment 1"),
526 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000527 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000529 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000531 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000533 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 clEnumValN(lang_gnu99, "gnu9x",
535 "ISO C 1999 with GNU extensions"),
536 clEnumValN(lang_cxx98, "c++98",
537 "ISO C++ 1998 with amendments"),
538 clEnumValN(lang_gnucxx98, "gnu++98",
539 "ISO C++ 1998 with amendments and GNU "
540 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000541 clEnumValN(lang_cxx0x, "c++0x",
542 "Upcoming ISO C++ 200x with amendments"),
543 clEnumValN(lang_gnucxx0x, "gnu++0x",
544 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000545 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 clEnumValEnd));
547
548static llvm::cl::opt<bool>
549NoOperatorNames("fno-operator-names",
550 llvm::cl::desc("Do not treat C++ operator name keywords as "
551 "synonyms for operators"));
552
Anders Carlssonee98ac52007-10-15 02:50:23 +0000553static llvm::cl::opt<bool>
554PascalStrings("fpascal-strings",
555 llvm::cl::desc("Recognize and construct Pascal-style "
556 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Steve Naroffd62701b2008-02-07 03:50:06 +0000558static llvm::cl::opt<bool>
559MSExtensions("fms-extensions",
560 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000561 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000562
563static llvm::cl::opt<bool>
564WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000565 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000566
567static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000568NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000569 llvm::cl::desc("Disallow implicit conversions between "
570 "vectors with a different number of "
571 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000572
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000573static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000574EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000575
576static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000577EnableHeinousExtensions("fheinous-gnu-extensions",
578 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
579 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
580
581static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000582ObjCNonFragileABI("fobjc-nonfragile-abi",
583 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000584
Daniel Dunbard6884a02009-05-04 05:16:21 +0000585
586static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000587EmitAllDecls("femit-all-decls",
588 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000589
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000590static llvm::cl::opt<bool>
591Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000592 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000593
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000594static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000595Rtti("frtti", llvm::cl::init(true),
596 llvm::cl::desc("Enable generation of rtti information"));
597
598static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000599GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000600 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000601 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000602
603static llvm::cl::opt<bool>
604NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000605 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000606 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000607
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000608static llvm::cl::opt<bool>
609CharIsSigned("fsigned-char",
610 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000611
John Thompsona6fda122009-11-05 20:14:16 +0000612static llvm::cl::opt<bool>
613ShortWChar("fshort-wchar",
614 llvm::cl::desc("Force wchar_t to be a short unsigned int"));
615
Ted Kremenekea644d82008-09-03 21:22:16 +0000616
617static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000618Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000619
Douglas Gregor26dce442009-03-10 00:06:19 +0000620static llvm::cl::opt<unsigned>
621TemplateDepth("ftemplate-depth", llvm::cl::init(99),
622 llvm::cl::desc("Maximum depth of recursive template "
623 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000624static llvm::cl::opt<bool>
625DollarsInIdents("fdollars-in-identifiers",
626 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000627
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000628
629static llvm::cl::opt<bool>
630OptSize("Os", llvm::cl::desc("Optimize for size"));
631
632static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000633DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000634 llvm::cl::desc("Don't run LLVM optimization passes"));
635
636static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000637NoCommon("fno-common",
638 llvm::cl::desc("Compile common globals like normal definitions"),
639 llvm::cl::ValueDisallowed);
640
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000641static llvm::cl::opt<std::string>
642MainFileName("main-file-name",
643 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000644
Anders Carlssona33d9b42009-05-13 19:49:53 +0000645// FIXME: Also add an "-fno-access-control" option.
646static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000647AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000648 llvm::cl::desc("Enable C++ access control"));
649
Anders Carlsson92f58222009-08-22 22:30:33 +0000650static llvm::cl::opt<bool>
651NoElideConstructors("fno-elide-constructors",
652 llvm::cl::desc("Disable C++ copy constructor elision"));
653
Tanya Lattner59876c22009-11-04 01:18:09 +0000654static llvm::cl::opt<bool>
655NoMergeConstants("fno-merge-all-constants",
656 llvm::cl::desc("Disallow merging of constants."));
657
Daniel Dunbar73b79592009-09-14 00:02:12 +0000658static llvm::cl::opt<std::string>
659TargetABI("target-abi",
660 llvm::cl::desc("Target a particular ABI type"));
661
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000662static llvm::cl::opt<std::string>
663TargetTriple("triple",
664 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
665
Anders Carlsson92f58222009-08-22 22:30:33 +0000666
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000667// It might be nice to add bounds to the CommandLine library directly.
668struct OptLevelParser : public llvm::cl::parser<unsigned> {
Chris Lattner59b21722009-09-20 00:39:15 +0000669 bool parse(llvm::cl::Option &O, llvm::StringRef ArgName,
670 llvm::StringRef Arg, unsigned &Val) {
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000671 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
672 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000673 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000674 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000675 return false;
676 }
677};
678static llvm::cl::opt<unsigned, false, OptLevelParser>
679OptLevel("O", llvm::cl::Prefix,
680 llvm::cl::desc("Optimization level"),
681 llvm::cl::init(0));
682
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000683static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000684PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
685
686static llvm::cl::opt<bool>
687StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000688
Bill Wendling45483f72009-06-28 07:36:13 +0000689static llvm::cl::opt<int>
690StackProtector("stack-protector",
691 llvm::cl::desc("Enable stack protectors"),
692 llvm::cl::init(-1));
693
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000694static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000695 TargetInfo *Target,
696 const llvm::StringMap<bool> &Features) {
Daniel Dunbar227b2382009-11-09 22:45:57 +0000697 // Allow the target to set the default the language options as it sees fit.
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000698 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000699
700 // Pass the map of target features to the target for validation and
701 // processing.
702 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 if (LangStd == lang_unspecified) {
705 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000706 switch (LK) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000707 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000708 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000709 case langkind_ocl:
710 LangStd = lang_c99;
711 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000713 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 case langkind_c_cpp:
715 case langkind_objc:
716 case langkind_objc_cpp:
717 LangStd = lang_gnu99;
718 break;
719 case langkind_cxx:
720 case langkind_cxx_cpp:
721 case langkind_objcxx:
722 case langkind_objcxx_cpp:
723 LangStd = lang_gnucxx98;
724 break;
725 }
726 }
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 switch (LangStd) {
729 default: assert(0 && "Unknown language standard!");
730
731 // Fall through from newer standards to older ones. This isn't really right.
732 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000733 case lang_gnucxx0x:
734 case lang_cxx0x:
735 Options.CPlusPlus0x = 1;
736 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 case lang_gnucxx98:
738 case lang_cxx98:
739 Options.CPlusPlus = 1;
740 Options.CXXOperatorNames = !NoOperatorNames;
741 // FALL THROUGH.
742 case lang_gnu99:
743 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 Options.C99 = 1;
745 Options.HexFloats = 1;
746 // FALL THROUGH.
747 case lang_gnu89:
748 Options.BCPLComment = 1; // Only for C99/C++.
749 // FALL THROUGH.
750 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000751 Options.Digraphs = 1; // C94, C99, C++.
752 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 case lang_c89:
754 break;
755 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000756
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000757 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
Douglas Gregor214904e2009-09-29 14:42:43 +0000758 switch (LangStd) {
759 default: assert(0 && "Unknown language standard!");
760 case lang_gnucxx0x:
761 case lang_gnucxx98:
762 case lang_gnu99:
763 case lang_gnu89:
764 Options.GNUMode = 1;
765 break;
766 case lang_cxx0x:
767 case lang_cxx98:
768 case lang_c99:
769 case lang_c94:
770 case lang_c89:
771 Options.GNUMode = 0;
772 break;
773 }
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000775 if (Options.CPlusPlus) {
776 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000777 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattnerd658b562008-04-05 06:32:51 +0000780 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
781 Options.ImplicitInt = 1;
782 else
783 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Daniel Dunbard573d262009-04-07 22:13:21 +0000785 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
786 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000787 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000788 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000789 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000790
Chris Lattner802db9b2008-12-05 00:10:44 +0000791 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
792 // even if they are normally on for the target. In GNU modes (e.g.
793 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000794 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000795 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000796 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattner01638a62009-04-19 07:06:52 +0000798 // Default to not accepting '$' in identifiers when preprocessing assembler,
799 // but do accept when preprocessing C. FIXME: these defaults are right for
800 // darwin, are they right everywhere?
801 Options.DollarIdents = LK != langkind_asm_cpp;
802 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000803 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Chris Lattnerae0ee032008-12-04 23:20:07 +0000805 if (PascalStrings.getPosition())
806 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000807 if (MSExtensions.getPosition())
808 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000809 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000810 if (NoLaxVectorConversions.getPosition())
811 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000812 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000813 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000814 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000815 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000816 if (CharIsSigned.getPosition())
817 Options.CharIsSigned = CharIsSigned;
John Thompson40d1bb62009-11-05 22:03:02 +0000818 if (ShortWChar.getPosition())
819 Options.ShortWChar = ShortWChar;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000820
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000821 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000822 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000823 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000824 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Chris Lattner810f6d52009-03-13 17:38:01 +0000826 if (EnableHeinousExtensions)
827 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000828
Anders Carlssona33d9b42009-05-13 19:49:53 +0000829 if (AccessControl)
830 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Anders Carlsson92f58222009-08-22 22:30:33 +0000832 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Chris Lattnere4f21422009-06-30 01:26:17 +0000834 // OpenCL and C++ both have bool, true, false keywords.
835 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000837 Options.MathErrno = MathErrno;
838
Douglas Gregor26dce442009-03-10 00:06:19 +0000839 Options.InstantiationDepth = TemplateDepth;
840
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000841 // Override the default runtime if the user requested it.
842 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000843 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000844 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000845 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000846
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000847 if (!ObjCConstantStringClass.empty())
848 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
849
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000850 if (ObjCNonFragileABI)
851 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000852
Daniel Dunbard604c402009-02-04 21:19:06 +0000853 if (EmitAllDecls)
854 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000855
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000856 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
857 // support.
858 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000860 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000861 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000862 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000863
864 assert(PICLevel <= 2 && "Invalid value for -pic-level");
865 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000866
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000867 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000868 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000869 Options.NoInline = !OptSize && !OptLevel;
870
871 Options.Static = StaticDefine;
872
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000873 switch (StackProtector) {
874 default:
875 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
876 case -1: break;
877 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
878 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
879 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
880 }
Bill Wendling45483f72009-06-28 07:36:13 +0000881
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000882 if (MainFileName.getPosition())
883 Options.setMainFileName(MainFileName.c_str());
John Thompsona6fda122009-11-05 20:14:16 +0000884
John Thompson40d1bb62009-11-05 22:03:02 +0000885 Target->setForcedLangOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000886}
887
888//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000889// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000890//===----------------------------------------------------------------------===//
891
Douglas Gregore1d918e2009-04-10 23:10:45 +0000892static bool InitializeSourceManager(Preprocessor &PP,
893 const std::string &InFile) {
894 // Figure out where to get and map in the main file.
895 SourceManager &SourceMgr = PP.getSourceManager();
896 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000897
898 if (EmptyInputOnly) {
899 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000900 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000901 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
902 SourceMgr.createMainFileIDForMemBuffer(SB);
903 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000904 const FileEntry *File = FileMgr.getFile(InFile);
905 if (File) SourceMgr.createMainFileID(File, SourceLocation());
906 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000907 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +0000908 << InFile.c_str();
909 return true;
910 }
911 } else {
912 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
913
914 // If stdin was empty, SB is null. Cons up an empty memory
915 // buffer now.
916 if (!SB) {
917 const char *EmptyStr = "";
918 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
919 }
920
921 SourceMgr.createMainFileIDForMemBuffer(SB);
922 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000923 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +0000924 diag::err_fe_error_reading_stdin);
925 return true;
926 }
927 }
928
929 return false;
930}
931
Chris Lattneraa391972008-04-19 23:09:31 +0000932
Chris Lattnere116ccf2009-04-21 05:40:52 +0000933//===----------------------------------------------------------------------===//
934// Preprocessor Initialization
935//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000936
Chris Lattnere6113de2009-11-03 19:50:27 +0000937static llvm::cl::opt<bool>
Daniel Dunbar468fe242009-11-04 21:13:02 +0000938UndefMacros("undef", llvm::cl::value_desc("macro"),
939 llvm::cl::desc("undef all system defines"));
Chris Lattnere6113de2009-11-03 19:50:27 +0000940
Chris Lattnere116ccf2009-04-21 05:40:52 +0000941static llvm::cl::list<std::string>
942D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
943 llvm::cl::desc("Predefine the specified macro"));
944static llvm::cl::list<std::string>
945U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
946 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000947
Chris Lattnere116ccf2009-04-21 05:40:52 +0000948static llvm::cl::list<std::string>
949ImplicitIncludes("include", llvm::cl::value_desc("file"),
950 llvm::cl::desc("Include file before parsing"));
951static llvm::cl::list<std::string>
952ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
953 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000954
Chris Lattnere116ccf2009-04-21 05:40:52 +0000955static llvm::cl::opt<std::string>
956ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
957 llvm::cl::desc("Include precompiled header file"));
958
959static llvm::cl::opt<std::string>
960ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
961 llvm::cl::desc("Include file before parsing"));
962
Douglas Gregore650c8c2009-07-07 00:12:59 +0000963static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000964RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000965 llvm::cl::desc("Whether to build a relocatable precompiled "
966 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000967
968//===----------------------------------------------------------------------===//
969// Preprocessor include path information.
970//===----------------------------------------------------------------------===//
971
972// This tool exports a large number of command line options to control how the
973// preprocessor searches for header files. At root, however, the Preprocessor
974// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +0000975//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +0000976// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000977// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000978//
Reid Spencer5f016e22007-07-11 17:01:13 +0000979
980static llvm::cl::opt<bool>
981nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
982
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000983static llvm::cl::opt<bool>
Rafael Espindola8d737cc2009-10-26 13:36:57 +0000984nobuiltininc("nobuiltininc",
985 llvm::cl::desc("Disable builtin #include directories"));
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000986
Reid Spencer5f016e22007-07-11 17:01:13 +0000987// Various command line options. These four add directories to each chain.
988static llvm::cl::list<std::string>
989F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
990 llvm::cl::desc("Add directory to framework include search path"));
991static llvm::cl::list<std::string>
992I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
993 llvm::cl::desc("Add directory to include search path"));
994static llvm::cl::list<std::string>
995idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
996 llvm::cl::desc("Add directory to AFTER include search path"));
997static llvm::cl::list<std::string>
998iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
999 llvm::cl::desc("Add directory to QUOTE include search path"));
1000static llvm::cl::list<std::string>
1001isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1002 llvm::cl::desc("Add directory to SYSTEM include search path"));
1003
1004// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1005static llvm::cl::list<std::string>
1006iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1007 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1008static llvm::cl::list<std::string>
1009iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1010 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1011static llvm::cl::list<std::string>
1012iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1013 llvm::cl::Prefix,
1014 llvm::cl::desc("Set directory to include search path with prefix"));
1015
Chris Lattner0c946412007-08-26 17:47:35 +00001016static llvm::cl::opt<std::string>
1017isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1018 llvm::cl::desc("Set the system root directory (usually /)"));
1019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001021
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001022// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +00001023std::string GetBuiltinIncludePath(const char *Argv0) {
1024 llvm::sys::Path P =
1025 llvm::sys::Path::GetMainExecutable(Argv0,
1026 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001027
Daniel Dunbar750156a2009-11-07 04:19:57 +00001028 if (!P.isEmpty()) {
1029 P.eraseComponent(); // Remove /clang from foo/bin/clang
1030 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001031
Daniel Dunbar750156a2009-11-07 04:19:57 +00001032 // Get foo/lib/clang/<version>/include
1033 P.appendComponent("lib");
1034 P.appendComponent("clang");
1035 P.appendComponent(CLANG_VERSION_STRING);
1036 P.appendComponent("include");
1037 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001038
Daniel Dunbar750156a2009-11-07 04:19:57 +00001039 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001040}
1041
Reid Spencer5f016e22007-07-11 17:01:13 +00001042/// InitializeIncludePaths - Process the -I options and set them in the
1043/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001044void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
Mike Stump43d81762009-10-08 23:29:47 +00001045 FileManager &FM, const LangOptions &Lang,
1046 llvm::Triple &triple) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001047 HeaderSearchOptions Opts(isysroot);
1048
1049 Opts.Verbose = Verbose;
Nico Weber0fca0222008-08-22 09:25:22 +00001050
Ted Kremenekf3721112008-05-31 00:27:00 +00001051 // Handle -I... and -F... options, walking the lists in parallel.
1052 unsigned Iidx = 0, Fidx = 0;
1053 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1054 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001055 Opts.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001056 ++Iidx;
1057 } else {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001058 Opts.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001059 ++Fidx;
1060 }
1061 }
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Ted Kremenekf3721112008-05-31 00:27:00 +00001063 // Consume what's left from whatever list was longer.
1064 for (; Iidx != I_dirs.size(); ++Iidx)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001065 Opts.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001066 for (; Fidx != F_dirs.size(); ++Fidx)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001067 Opts.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 // Handle -idirafter... options.
1070 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001071 Opts.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
Nico Weber0fca0222008-08-22 09:25:22 +00001072 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 // Handle -iquote... options.
1075 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001076 Opts.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Reid Spencer5f016e22007-07-11 17:01:13 +00001078 // Handle -isystem... options.
1079 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001080 Opts.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001081
1082 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1083 // parallel, processing the values in order of occurance to get the right
1084 // prefixes.
1085 {
1086 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1087 unsigned iprefix_idx = 0;
1088 unsigned iwithprefix_idx = 0;
1089 unsigned iwithprefixbefore_idx = 0;
1090 bool iprefix_done = iprefix_vals.empty();
1091 bool iwithprefix_done = iwithprefix_vals.empty();
1092 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1093 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1094 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001095 (iwithprefix_done ||
1096 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001098 (iwithprefixbefore_done ||
1099 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1101 Prefix = iprefix_vals[iprefix_idx];
1102 ++iprefix_idx;
1103 iprefix_done = iprefix_idx == iprefix_vals.size();
1104 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001105 (iwithprefixbefore_done ||
1106 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001108 Opts.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001109 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 ++iwithprefix_idx;
1111 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1112 } else {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001113 Opts.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001114 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001116 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1118 }
1119 }
1120 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001121
Daniel Dunbare1665822009-11-07 04:20:39 +00001122 // Add CPATH environment paths.
1123 if (const char *Env = getenv("CPATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001124 Opts.EnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001125
1126 // Add language specific environment paths.
1127 if (Lang.CPlusPlus && Lang.ObjC1) {
1128 if (const char *Env = getenv("OBJCPLUS_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001129 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001130 } else if (Lang.CPlusPlus) {
1131 if (const char *Env = getenv("CPLUS_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001132 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001133 } else if (Lang.ObjC1) {
1134 if (const char *Env = getenv("OBJC_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001135 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001136 } else {
1137 if (const char *Env = getenv("C_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001138 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001139 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001140
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001141 if (!nobuiltininc)
1142 Opts.BuiltinIncludePath = GetBuiltinIncludePath(Argv0);
Daniel Dunbar750156a2009-11-07 04:19:57 +00001143
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001144 Opts.UseStandardIncludes = !nostdinc;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001146 // Apply all the options to the header search object.
1147 ApplyHeaderSearchOptions(Opts, Headers, Lang, triple);
Reid Spencer5f016e22007-07-11 17:01:13 +00001148}
1149
Daniel Dunbar8863b982009-11-07 04:20:15 +00001150void InitializePreprocessorOptions(PreprocessorOptions &InitOpts) {
Daniel Dunbar468fe242009-11-04 21:13:02 +00001151 // Use predefines?
1152 InitOpts.setUsePredefines(!UndefMacros);
1153
Chris Lattnere116ccf2009-04-21 05:40:52 +00001154 // Add macros from the command line.
1155 unsigned d = 0, D = D_macros.size();
1156 unsigned u = 0, U = U_macros.size();
1157 while (d < D || u < U) {
1158 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1159 InitOpts.addMacroDef(D_macros[d++]);
1160 else
1161 InitOpts.addMacroUndef(U_macros[u++]);
1162 }
1163
1164 // If -imacros are specified, include them now. These are processed before
1165 // any -include directives.
1166 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1167 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1168
Douglas Gregorb64c1932009-05-12 01:31:05 +00001169 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1170 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001171 // We want to add these paths to the predefines buffer in order, make a
1172 // temporary vector to sort by their occurrence.
1173 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1174
1175 if (!ImplicitIncludePTH.empty())
1176 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1177 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001178 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1179 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1180 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001181 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1182 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1183 &ImplicitIncludes[i]));
1184 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1185
1186
1187 // Now that they are ordered by position, add to the predefines buffer.
1188 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1189 std::string *Ptr = OrderedPaths[i].second;
1190 if (!ImplicitIncludes.empty() &&
1191 Ptr >= &ImplicitIncludes[0] &&
1192 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1193 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001194 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001195 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001196 } else {
1197 // We end up here when we're producing preprocessed output and
1198 // we loaded a PCH file. In this case, just include the header
1199 // file that was used to build the precompiled header.
1200 assert(Ptr == &ImplicitIncludePCH);
1201 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1202 if (!OriginalFile.empty()) {
1203 InitOpts.addInclude(OriginalFile, false);
1204 ImplicitIncludePCH.clear();
1205 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001206 }
1207 }
1208 }
1209}
1210
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001211//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +00001212// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001213//===----------------------------------------------------------------------===//
1214
Daniel Dunbar90b18272009-11-04 23:56:25 +00001215static Preprocessor *
1216CreatePreprocessor(Diagnostic &Diags,const LangOptions &LangInfo,
1217 TargetInfo &Target, SourceManager &SourceMgr,
1218 HeaderSearch &HeaderInfo) {
1219 PTHManager *PTHMgr = 0;
1220 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1221 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1222 "options\n");
1223 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001224 }
Daniel Dunbar90b18272009-11-04 23:56:25 +00001225
1226 // Use PTH?
1227 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1228 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
1229 PTHMgr = PTHManager::Create(x, &Diags,
1230 TokenCache.empty() ? Diagnostic::Error
1231 : Diagnostic::Warning);
1232 }
1233
1234 if (Diags.hasErrorOccurred())
1235 exit(1);
1236
1237 // Create the Preprocessor.
1238 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
1239 SourceMgr, HeaderInfo, PTHMgr);
1240
1241 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1242 // That argument is used as the IdentifierInfoLookup argument to
1243 // IdentifierTable's ctor.
1244 if (PTHMgr) {
1245 PTHMgr->setPreprocessor(PP);
1246 PP->setPTHManager(PTHMgr);
1247 }
1248
Daniel Dunbar8863b982009-11-07 04:20:15 +00001249 PreprocessorOptions InitOpts;
1250 InitializePreprocessorOptions(InitOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +00001251 InitializePreprocessor(*PP, InitOpts);
1252
1253 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001254}
Reid Spencer5f016e22007-07-11 17:01:13 +00001255
Reid Spencer5f016e22007-07-11 17:01:13 +00001256//===----------------------------------------------------------------------===//
1257// Basic Parser driver
1258//===----------------------------------------------------------------------===//
1259
Chris Lattner51574ea2008-04-19 23:25:44 +00001260static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001262 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 // Parsing the specified input file.
1265 P.ParseTranslationUnit();
1266 delete PA;
1267}
1268
1269//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001270// Code generation options
1271//===----------------------------------------------------------------------===//
1272
1273static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001274GenerateDebugInfo("g",
1275 llvm::cl::desc("Generate source level debug information"));
1276
Daniel Dunbara034ba82009-02-17 19:47:34 +00001277static llvm::cl::opt<std::string>
1278TargetCPU("mcpu",
1279 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1280
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001281static llvm::cl::list<std::string>
1282TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1283
Devang Patel24095da2009-06-04 23:32:02 +00001284
1285static llvm::cl::opt<bool>
1286DisableRedZone("disable-red-zone",
1287 llvm::cl::desc("Do not emit code that uses the red zone."),
1288 llvm::cl::init(false));
1289
Devang Patelacebb392009-06-05 22:05:48 +00001290static llvm::cl::opt<bool>
1291NoImplicitFloat("no-implicit-float",
1292 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1293 llvm::cl::init(false));
1294
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001295/// ComputeTargetFeatures - Recompute the target feature list to only
1296/// be the list of things that are enabled, based on the target cpu
1297/// and feature list.
1298static void ComputeFeatureMap(TargetInfo *Target,
1299 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001300 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001301
1302 // Initialize the feature map based on the target.
1303 Target->getDefaultFeatures(TargetCPU, Features);
1304
1305 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001306 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001307 ie = TargetFeatures.end(); it != ie; ++it) {
1308 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001310 // FIXME: Don't handle errors like this.
1311 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001312 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001313 Name);
1314 exit(1);
1315 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001316 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001317 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001318 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001319 exit(1);
1320 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001321 }
1322}
1323
Chris Lattner7afae712009-03-16 18:41:18 +00001324static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001325 const LangOptions &LangOpts,
1326 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001327 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001328 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001329
1330 if (DisableLLVMOptimizations) {
1331 Opts.OptimizationLevel = 0;
1332 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001333 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001334 if (OptSize) {
1335 // -Os implies -O2
1336 Opts.OptimizationLevel = 2;
1337 } else {
1338 Opts.OptimizationLevel = OptLevel;
1339 }
1340
1341 // We must always run at least the always inlining pass.
1342 if (Opts.OptimizationLevel > 1)
1343 Opts.Inlining = CompileOptions::NormalInlining;
1344 else
1345 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001346 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001347
1348 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001349 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001350 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001351
1352#ifdef NDEBUG
1353 Opts.VerifyModule = 0;
1354#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001355
1356 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001357 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001358 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001359 ie = Features.end(); it != ie; ++it) {
1360 // FIXME: If we are completely confident that we have the right
1361 // set, we only need to pass the minuses.
1362 std::string Name(it->second ? "+" : "-");
1363 Name += it->first();
1364 Opts.Features.push_back(Name);
1365 }
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattnerbd360642009-03-26 05:00:52 +00001367 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Chris Lattner44502662009-02-18 01:23:44 +00001369 // Handle -ftime-report.
1370 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001371
1372 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001373 Opts.NoImplicitFloat = NoImplicitFloat;
Tanya Lattner59876c22009-11-04 01:18:09 +00001374
1375 Opts.MergeAllConstants = !NoMergeConstants;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001376}
1377
1378//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001379// Fix-It Options
1380//===----------------------------------------------------------------------===//
1381static llvm::cl::list<ParsedSourceLocation>
1382FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1383 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1384
1385//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001386// ObjC Rewriter Options
1387//===----------------------------------------------------------------------===//
1388static llvm::cl::opt<bool>
1389SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1390 llvm::cl::desc("Silence ObjC rewriting warnings"));
1391
1392//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001393// Warning Options
1394//===----------------------------------------------------------------------===//
1395
1396// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1397// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1398// -Wextra, so we don't need to worry about it.
1399static llvm::cl::list<std::string>
1400OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1401
1402static llvm::cl::opt<bool> OptPedantic("pedantic");
1403static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1404static llvm::cl::opt<bool> OptNoWarnings("w");
1405
1406//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001407// Preprocessing (-E mode) Options
1408//===----------------------------------------------------------------------===//
1409static llvm::cl::opt<bool>
1410DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1411static llvm::cl::opt<bool>
1412EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1413static llvm::cl::opt<bool>
1414EnableMacroCommentOutput("CC",
1415 llvm::cl::desc("Enable comment output in -E mode, "
1416 "even from macro expansions"));
1417static llvm::cl::opt<bool>
1418DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1419 " normal output"));
1420static llvm::cl::opt<bool>
1421DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1422 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001423
1424//===----------------------------------------------------------------------===//
1425// Dependency file options
1426//===----------------------------------------------------------------------===//
1427static llvm::cl::opt<std::string>
1428DependencyFile("dependency-file",
1429 llvm::cl::desc("Filename (or -) to write dependency output to"));
1430
1431static llvm::cl::opt<bool>
1432DependenciesIncludeSystemHeaders("sys-header-deps",
1433 llvm::cl::desc("Include system headers in dependency output"));
1434
1435static llvm::cl::list<std::string>
1436DependencyTargets("MT",
1437 llvm::cl::desc("Specify target for dependency"));
1438
1439// FIXME: Implement feature
1440static llvm::cl::opt<bool>
1441PhonyDependencyTarget("MP",
1442 llvm::cl::desc("Create phony target for each dependency "
1443 "(other than main file)"));
1444
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001445//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001446// Analysis options
1447//===----------------------------------------------------------------------===//
1448
1449static llvm::cl::list<Analyses>
1450AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1451llvm::cl::values(
1452#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1453clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001454#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001455clEnumValEnd));
1456
Mike Stump1eb44332009-09-09 15:08:12 +00001457static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001458AnalysisStoreOpt("analyzer-store",
1459 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1460 llvm::cl::init(BasicStoreModel),
1461 llvm::cl::values(
1462#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1463clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001464#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001465clEnumValEnd));
1466
Mike Stump1eb44332009-09-09 15:08:12 +00001467static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001468AnalysisConstraintsOpt("analyzer-constraints",
1469 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1470 llvm::cl::init(RangeConstraintsModel),
1471 llvm::cl::values(
1472#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1473clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001474#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001475clEnumValEnd));
1476
1477static llvm::cl::opt<AnalysisDiagClients>
1478AnalysisDiagOpt("analyzer-output",
1479 llvm::cl::desc("Source Code Analysis - Output Options"),
1480 llvm::cl::init(PD_HTML),
1481 llvm::cl::values(
1482#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1483clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001484#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001485clEnumValEnd));
1486
1487static llvm::cl::opt<bool>
1488VisualizeEGDot("analyzer-viz-egraph-graphviz",
1489 llvm::cl::desc("Display exploded graph using GraphViz"));
1490
1491static llvm::cl::opt<bool>
1492VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1493 llvm::cl::desc("Display exploded graph using Ubigraph"));
1494
1495static llvm::cl::opt<bool>
1496AnalyzeAll("analyzer-opt-analyze-headers",
1497 llvm::cl::desc("Force the static analyzer to analyze "
1498 "functions defined in header files"));
1499
1500static llvm::cl::opt<bool>
1501AnalyzerDisplayProgress("analyzer-display-progress",
1502 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1503
1504static llvm::cl::opt<bool>
1505PurgeDead("analyzer-purge-dead",
1506 llvm::cl::init(true),
1507 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1508 " processing a statement."));
1509
1510static llvm::cl::opt<bool>
1511EagerlyAssume("analyzer-eagerly-assume",
1512 llvm::cl::init(false),
1513 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1514 "symbolic constraints."));
1515
1516static llvm::cl::opt<std::string>
1517AnalyzeSpecificFunction("analyze-function",
1518 llvm::cl::desc("Run analysis on specific function"));
1519
1520static llvm::cl::opt<bool>
1521TrimGraph("trim-egraph",
1522 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1523
1524static AnalyzerOptions ReadAnalyzerOptions() {
1525 AnalyzerOptions Opts;
1526 Opts.AnalysisList = AnalysisList;
1527 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1528 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1529 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1530 Opts.VisualizeEGDot = VisualizeEGDot;
1531 Opts.VisualizeEGUbi = VisualizeEGUbi;
1532 Opts.AnalyzeAll = AnalyzeAll;
1533 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1534 Opts.PurgeDead = PurgeDead;
1535 Opts.EagerlyAssume = EagerlyAssume;
1536 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1537 Opts.TrimGraph = TrimGraph;
1538 return Opts;
1539}
1540
1541//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001542// -dump-build-information Stuff
1543//===----------------------------------------------------------------------===//
1544
1545static llvm::cl::opt<std::string>
1546DumpBuildInformation("dump-build-information",
1547 llvm::cl::value_desc("filename"),
1548 llvm::cl::desc("output a dump of some build information to a file"));
1549
1550static llvm::raw_ostream *BuildLogFile = 0;
1551
1552/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1553/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1554namespace {
1555class LoggingDiagnosticClient : public DiagnosticClient {
1556 llvm::OwningPtr<DiagnosticClient> Chain1;
1557 llvm::OwningPtr<DiagnosticClient> Chain2;
1558public:
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Daniel Dunbar227b2382009-11-09 22:45:57 +00001560 LoggingDiagnosticClient(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +00001561 DiagnosticClient *Normal) {
Chris Lattner75a97cb2009-04-17 21:05:01 +00001562 // Output diags both where requested...
1563 Chain1.reset(Normal);
1564 // .. and to our log file.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001565 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile, DiagOpts));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Daniel Dunbarefcbe942009-11-05 02:42:12 +00001568 virtual void BeginSourceFile(const LangOptions &LO) {
1569 Chain1->BeginSourceFile(LO);
1570 Chain2->BeginSourceFile(LO);
1571 }
1572
1573 virtual void EndSourceFile() {
1574 Chain1->EndSourceFile();
1575 Chain2->EndSourceFile();
Chris Lattner75a97cb2009-04-17 21:05:01 +00001576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattner75a97cb2009-04-17 21:05:01 +00001578 virtual bool IncludeInDiagnosticCounts() const {
1579 return Chain1->IncludeInDiagnosticCounts();
1580 }
1581
1582 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1583 const DiagnosticInfo &Info) {
1584 Chain1->HandleDiagnostic(DiagLevel, Info);
1585 Chain2->HandleDiagnostic(DiagLevel, Info);
1586 }
1587};
1588} // end anonymous namespace.
1589
Daniel Dunbar227b2382009-11-09 22:45:57 +00001590static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +00001591 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +00001592 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Chris Lattner75a97cb2009-04-17 21:05:01 +00001594 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001595 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001596 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Chris Lattner75a97cb2009-04-17 21:05:01 +00001598 if (!ErrorInfo.empty()) {
1599 llvm::errs() << "error opening -dump-build-information file '"
1600 << DumpBuildInformation << "', option ignored!\n";
1601 delete BuildLogFile;
1602 BuildLogFile = 0;
1603 DumpBuildInformation = "";
1604 return;
1605 }
1606
1607 (*BuildLogFile) << "clang-cc command line arguments: ";
1608 for (unsigned i = 0; i != argc; ++i)
1609 (*BuildLogFile) << argv[i] << ' ';
1610 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattner75a97cb2009-04-17 21:05:01 +00001612 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1613 // the diagnostic producers and the normal receiver.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001614 DiagClient.reset(new LoggingDiagnosticClient(DiagOpts, DiagClient.take()));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001615}
1616
1617
1618
1619//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001620// Main driver
1621//===----------------------------------------------------------------------===//
1622
Daniel Dunbare29709f2009-11-09 20:55:08 +00001623static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
1624 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +00001625 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001626 bool Binary,
1627 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001628 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001629 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001630 if (!CompOpts.getOutputFile().empty())
1631 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +00001632 else if (InFile == "-") {
1633 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001634 } else if (Extension) {
1635 llvm::sys::Path Path(InFile);
1636 Path.eraseSuffix();
1637 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001638 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001639 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001640 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001641 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001642
Chris Lattner92bcc272009-08-23 02:59:41 +00001643 std::string Error;
1644 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001645 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001646 if (!Error.empty()) {
1647 // FIXME: Don't fail this way.
1648 llvm::errs() << "ERROR: " << Error << "\n";
1649 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Chris Lattner92bcc272009-08-23 02:59:41 +00001652 if (OutFile != "-")
1653 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001654
1655 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001656}
1657
Daniel Dunbare29709f2009-11-09 20:55:08 +00001658static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
1659 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001660 const std::string &InFile,
1661 ProgActions PA,
1662 llvm::OwningPtr<llvm::raw_ostream> &OS,
1663 llvm::sys::Path &OutPath,
1664 const llvm::StringMap<bool> &Features,
1665 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +00001666 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001668 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +00001669
1670 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001671 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001672 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Douglas Gregoree75c052009-05-21 20:55:50 +00001674 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001675 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001676 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +00001677
Eli Friedman66d6f042009-05-18 22:20:00 +00001678 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001679 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +00001680
Eli Friedman66d6f042009-05-18 22:20:00 +00001681 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001682 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +00001683
1684 case PrintDeclContext:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001685 return CreateDeclContextPrinter();
Eli Friedman66d6f042009-05-18 22:20:00 +00001686
Anders Carlsson78762eb2009-09-24 18:54:49 +00001687 case DumpRecordLayouts:
1688 return CreateRecordLayoutDumper();
1689
Eli Friedman66d6f042009-05-18 22:20:00 +00001690 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001691 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +00001692
1693 case EmitAssembly:
1694 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001695 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001696 case EmitLLVMOnly: {
1697 BackendAction Act;
1698 if (ProgAction == EmitAssembly) {
1699 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001700 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +00001701 } else if (ProgAction == EmitLLVM) {
1702 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001703 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +00001704 } else if (ProgAction == EmitLLVMOnly) {
1705 Act = Backend_EmitNothing;
1706 } else {
1707 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001708 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001709 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001710
Eli Friedman66d6f042009-05-18 22:20:00 +00001711 CompileOptions Opts;
1712 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001713 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
1714 Opts, InFile, OS.get(), Context);
Eli Friedman66d6f042009-05-18 22:20:00 +00001715 }
1716
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001717 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001718 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001719 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1720 PP.getLangOptions(), SilenceRewriteMacroWarning);
1721
1722 case RewriteBlocks:
1723 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1724 PP.getLangOptions());
1725 }
1726}
1727
1728/// ProcessInputFile - Process a single input file with the specified state.
1729///
Daniel Dunbare29709f2009-11-09 20:55:08 +00001730static void ProcessInputFile(const CompilerInvocation &CompOpts,
1731 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar90b18272009-11-04 23:56:25 +00001732 ProgActions PA,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001733 const llvm::StringMap<bool> &Features,
1734 llvm::LLVMContext& Context) {
1735 llvm::OwningPtr<llvm::raw_ostream> OS;
1736 llvm::OwningPtr<ASTConsumer> Consumer;
1737 bool ClearSourceMgr = false;
1738 FixItRewriter *FixItRewrite = 0;
1739 bool CompleteTranslationUnit = true;
1740 llvm::sys::Path OutPath;
1741
1742 switch (PA) {
1743 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001744 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001745 Features, Context));
1746
1747 if (!Consumer.get()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001748 PP.getDiagnostics().Report(FullSourceLoc(),
1749 diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001750 return;
1751 }
1752
1753 break;;
1754
1755 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001756 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +00001757 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001758 break;
1759
1760 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001761 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001762 ReadAnalyzerOptions()));
1763 break;
1764
Eli Friedman66d6f042009-05-18 22:20:00 +00001765 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001766 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1767 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1768 RelocatablePCH.setValue(false);
1769 }
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Daniel Dunbare29709f2009-11-09 20:55:08 +00001771 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001772 if (RelocatablePCH.getValue())
1773 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1774 else
1775 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001776 CompleteTranslationUnit = false;
1777 break;
1778
Chris Lattnerc106c102008-10-12 05:03:36 +00001779 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001780 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001781 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001782 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001783 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001784 RawLex.SetKeepWhitespaceMode(true);
1785
1786 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001787 RawLex.LexFromRawLexer(RawTok);
1788 while (RawTok.isNot(tok::eof)) {
1789 PP.DumpToken(RawTok, true);
1790 fprintf(stderr, "\n");
1791 RawLex.LexFromRawLexer(RawTok);
1792 }
1793 ClearSourceMgr = true;
1794 break;
1795 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001797 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001798 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001799 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001800 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 do {
1802 PP.Lex(Tok);
1803 PP.DumpToken(Tok, true);
1804 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001805 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001806 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 break;
1808 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001809 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001812 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001813 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +00001814 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +00001815 // FIXME: Don't fail this way.
1816 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001817 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001818 ::exit(1);
1819 }
Daniel Dunbare29709f2009-11-09 20:55:08 +00001820 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001821 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001822 ClearSourceMgr = true;
1823 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001824 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001825
Chris Lattnercc7dea82009-04-27 22:02:30 +00001826 case PrintPreprocessedInput:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001827 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001830 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001831 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Chris Lattner47099742009-02-18 01:51:21 +00001833 case ParsePrintCallbacks: {
1834 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +00001835 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001836 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001837 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 break;
Chris Lattner47099742009-02-18 01:51:21 +00001839 }
1840
1841 case ParseSyntaxOnly: { // -fsyntax-only
1842 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001843 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001844 break;
Chris Lattner47099742009-02-18 01:51:21 +00001845 }
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001847 case RewriteMacros:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001848 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001849 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001850 ClearSourceMgr = true;
1851 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Eli Friedmanf54fce82009-05-19 01:02:07 +00001853 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001854 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001855 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001856 ClearSourceMgr = true;
1857 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001858
1859 case FixIt:
1860 llvm::TimeRegion Timer(ClangFrontendTimer);
1861 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001862 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001863 PP.getSourceManager(),
1864 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001865 break;
Chris Lattner47099742009-02-18 01:51:21 +00001866 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001867
Chris Lattner1aee61a2009-04-27 21:25:27 +00001868 if (FixItAtLocations.size() > 0) {
1869 // Even without the "-fixit" flag, with may have some specific
1870 // locations where the user has requested fixes. Process those
1871 // locations now.
1872 if (!FixItRewrite)
1873 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1874 PP.getSourceManager(),
1875 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001876
Chris Lattner1aee61a2009-04-27 21:25:27 +00001877 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001878 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001879 Idx != Last; ++Idx) {
1880 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001881 if (ResolveParsedLocation(FixItAtLocations[Idx],
1882 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001883 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1884 FixItAtLocations[Idx].FileName.c_str());
1885 } else {
1886 FixItRewrite->addFixItLocation(Requested);
1887 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001888 }
1889 }
1890
Chris Lattner1aee61a2009-04-27 21:25:27 +00001891 if (!AddedFixitLocation) {
1892 // All of the fix-it locations were bad. Don't fix anything.
1893 delete FixItRewrite;
1894 FixItRewrite = 0;
1895 }
1896 }
1897
1898 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001899 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001900 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1901 PP.getSourceManager(),
1902 PP.getTargetInfo(),
1903 PP.getIdentifierTable(),
1904 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001905 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001906 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001907 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Chris Lattnercc7dea82009-04-27 22:02:30 +00001909 llvm::OwningPtr<PCHReader> Reader;
1910 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001912 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001913 // If the user specified -isysroot, it will be used for relocatable PCH
1914 // files.
1915 const char *isysrootPCH = 0;
1916 if (isysroot.getNumOccurrences() != 0)
1917 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Douglas Gregore650c8c2009-07-07 00:12:59 +00001919 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001921 // The user has asked us to include a precompiled header. Load
1922 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001923 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1924 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001925 // Set the predefines buffer as suggested by the PCH
1926 // reader. Typically, the predefines buffer will be empty.
1927 PP.setPredefines(Reader->getSuggestedPredefines());
1928
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001929 // Attach the PCH reader to the AST context as an external AST
1930 // source, so that declarations will be deserialized from the
1931 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001932 if (ContextOwner) {
1933 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001934 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001935 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001936 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001937 }
1938
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001939 case PCHReader::Failure:
1940 // Unrecoverable failure: don't even try to process the input
1941 // file.
1942 return;
1943
1944 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001945 // No suitable PCH file could be found. Return an error.
1946 return;
1947
1948#if 0
1949 // FIXME: We can recover from failed attempts to load PCH
1950 // files. This code will do so, if we ever want to enable it.
1951
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001952 // We delayed the initialization of builtins in the hope of
1953 // loading the PCH file. Since the PCH file could not be
1954 // loaded, initialize builtins now.
1955 if (ContextOwner)
1956 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001957#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001958 }
1959
1960 // Finish preprocessor initialization. We do this now (rather
1961 // than earlier) because this initialization creates new source
1962 // location entries in the source manager, which must come after
1963 // the source location entries for the PCH file.
1964 if (InitializeSourceManager(PP, InFile))
1965 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001966 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001967
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001968 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00001969 if (Consumer) {
1970 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
1971 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001972
Douglas Gregorb657f112009-09-22 21:11:38 +00001973 if (!CodeCompletionAt.FileName.empty()) {
1974 // Tell the source manager to chop off the given file at a specific
1975 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001976 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +00001977 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
1978 // Truncate the named file at the given line/column.
1979 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
1980 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001981
Douglas Gregorb657f112009-09-22 21:11:38 +00001982 // Set up the creation routine for code-completion.
1983 CreateCodeCompleter = BuildPrintingCodeCompleter;
1984 } else {
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001985 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregorb657f112009-09-22 21:11:38 +00001986 diag::err_fe_invalid_code_complete_file)
1987 << CodeCompletionAt.FileName;
1988 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00001989 }
1990
Mike Stump1eb44332009-09-09 15:08:12 +00001991 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00001992 CompleteTranslationUnit,
1993 CreateCodeCompleter, CreateCodeCompleterData);
1994 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001995
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001996 // Perform post processing actions and actions which don't use a consumer.
1997 switch (PA) {
1998 default: break;
1999
2000 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002001 llvm::TimeRegion Timer(ClangFrontendTimer);
2002 Token Tok;
2003 // Start parsing the specified input file.
2004 PP.EnterMainSourceFile();
2005 do {
2006 PP.Lex(Tok);
2007 } while (Tok.isNot(tok::eof));
2008 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002009 break;
2010 }
2011
2012 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002013 llvm::TimeRegion Timer(ClangFrontendTimer);
2014 ParseFile(PP, new MinimalAction(PP));
2015 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002016 break;
2017 }
2018
2019 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +00002020 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002021 if (DumpMacros)
2022 DoPrintMacros(PP, OS.get());
2023 else
2024 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2025 EnableMacroCommentOutput,
2026 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002027 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002030 }
2031
Chris Lattner1aee61a2009-04-27 21:25:27 +00002032 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +00002033 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002034
2035 // Disable the consumer prior to the context, the consumer may perform actions
2036 // in its destructor which require the context.
2037 if (DisableFree)
2038 Consumer.take();
2039 else
2040 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Chris Lattner1aee61a2009-04-27 21:25:27 +00002042 // If in -disable-free mode, don't deallocate ASTContext.
2043 if (DisableFree)
2044 ContextOwner.take();
2045 else
2046 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002047
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002048 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002049 if (CheckDiagnostics(PP))
2050 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002051
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002053 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 PP.PrintStats();
2055 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002056 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002057 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 fprintf(stderr, "\n");
2059 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002060
Mike Stump1eb44332009-09-09 15:08:12 +00002061 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002062 // manager tables, other require stable fileid/macroid's across multiple
2063 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002064 if (ClearSourceMgr)
2065 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002066
Eli Friedman66d6f042009-05-18 22:20:00 +00002067 // Always delete the output stream because we don't want to leak file
2068 // handles. Also, we don't want to try to erase an open file.
2069 OS.reset();
2070
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002071 // If we had errors, try to erase the output file.
2072 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +00002073 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +00002074}
2075
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002076/// ProcessInputFile - Process a single AST input file with the specified state.
2077///
Daniel Dunbare29709f2009-11-09 20:55:08 +00002078static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
2079 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002080 const llvm::StringMap<bool> &Features,
2081 Diagnostic &Diags, FileManager &FileMgr,
2082 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002083 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +00002084 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002085 if (!AST) {
2086 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
2087 return;
2088 }
2089
2090 Preprocessor &PP = AST->getPreprocessor();
2091
2092 llvm::OwningPtr<llvm::raw_ostream> OS;
2093 llvm::sys::Path OutPath;
Daniel Dunbare29709f2009-11-09 20:55:08 +00002094 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
2095 InFile, PA, OS,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002096 OutPath, Features,
2097 Context));
2098
2099 if (!Consumer.get()) {
2100 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
2101 return;
2102 }
2103
Daniel Dunbara674bf42009-09-21 03:03:56 +00002104 // Set the main file ID to an empty file.
2105 //
2106 // FIXME: We probably shouldn't need this, but for now this is the simplest
2107 // way to reuse the logic in ParseAST.
2108 const char *EmptyStr = "";
2109 llvm::MemoryBuffer *SB =
2110 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
2111 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002112
Daniel Dunbara674bf42009-09-21 03:03:56 +00002113 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002114 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +00002115 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002116 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002117
2118 // Release the consumer and the AST, in that order since the consumer may
2119 // perform actions in its destructor which require the context.
2120 if (DisableFree) {
2121 Consumer.take();
2122 AST.take();
2123 } else {
2124 Consumer.reset();
2125 AST.reset();
2126 }
2127
2128 // Always delete the output stream because we don't want to leak file
2129 // handles. Also, we don't want to try to erase an open file.
2130 OS.reset();
2131
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002132 // If we had errors, try to erase the output file.
2133 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002134 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002135}
2136
Reid Spencer5f016e22007-07-11 17:01:13 +00002137static llvm::cl::list<std::string>
2138InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2139
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002140static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2141 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2142
2143 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2144
2145 // We cannot recover from llvm errors.
2146 exit(1);
2147}
2148
Daniel Dunbar227b2382009-11-09 22:45:57 +00002149static LangKind GetLanguage() {
2150 // If -x was given, that's the language.
2151 if (BaseLang != langkind_unspecified)
2152 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +00002153
Daniel Dunbar227b2382009-11-09 22:45:57 +00002154 // Otherwise guess it from the input filenames;
2155 LangKind LK = langkind_unspecified;
2156 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
2157 llvm::StringRef Name(InputFilenames[i]);
2158 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
2159 .Case("ast", langkind_ast)
2160 .Case("c", langkind_c)
2161 .Cases("S", "s", langkind_asm_cpp)
2162 .Case("i", langkind_c_cpp)
2163 .Case("ii", langkind_cxx_cpp)
2164 .Case("m", langkind_objc)
2165 .Case("mi", langkind_objc_cpp)
2166 .Cases("mm", "M", langkind_objcxx)
2167 .Case("mii", langkind_objcxx_cpp)
2168 .Case("C", langkind_cxx)
2169 .Cases("C", "cc", "cp", langkind_cxx)
2170 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
2171 .Case("cl", langkind_ocl)
2172 .Default(langkind_c);
2173
2174 if (LK != langkind_unspecified && ThisKind != LK) {
2175 llvm::errs() << "error: cannot have multiple input files of distinct "
2176 << "language kinds without -x\n";
2177 exit(1);
2178 }
2179
2180 LK = ThisKind;
2181 }
2182
2183 return LK;
2184}
2185
2186static void ConstructDiagnosticOptions(DiagnosticOptions &Opts) {
Daniel Dunbare29709f2009-11-09 20:55:08 +00002187 // Initialize the diagnostic options.
Daniel Dunbar227b2382009-11-09 22:45:57 +00002188 Opts.ShowColumn = !NoShowColumn;
2189 Opts.ShowLocation = !NoShowLocation;
2190 Opts.ShowCarets = !NoCaretDiagnostics;
2191 Opts.ShowFixits = !NoDiagnosticsFixIt;
2192 Opts.ShowSourceRanges = PrintSourceRangeInfo;
2193 Opts.ShowOptionNames = PrintDiagnosticOption;
2194 Opts.ShowColors = PrintColorDiagnostic;
2195 Opts.MessageLength = MessageLength;
2196}
2197
2198static void ConstructCompilerInvocation(CompilerInvocation &Opts,
2199 const DiagnosticOptions &DiagOpts,
2200 const TargetInfo &Target) {
2201 Opts.getDiagnosticOpts() = DiagOpts;
2202
2203 Opts.getOutputFile() = OutputFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +00002204}
2205
Reid Spencer5f016e22007-07-11 17:01:13 +00002206int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002208 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002209 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002210
Daniel Dunbar4d861512009-09-03 04:54:12 +00002211 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002212 llvm::InitializeAllTargets();
2213 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002214
2215 llvm::cl::ParseCommandLineOptions(argc, argv,
2216 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Chris Lattner47099742009-02-18 01:51:21 +00002218 if (TimeReport)
2219 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002221 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002222 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2223 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002224 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 // If no input was specified, read from stdin.
2227 if (InputFilenames.empty())
2228 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002229
Daniel Dunbar227b2382009-11-09 22:45:57 +00002230 // Construct the diagnostic options first, which cannot fail, so that we can
2231 // build a diagnostic client to use for any errors during option handling.
2232 DiagnosticOptions DiagOpts;
2233 ConstructDiagnosticOptions(DiagOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00002234
Ted Kremenek31e703b2007-12-11 23:28:38 +00002235 // Create the diagnostic client for reporting errors or for
2236 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002237 llvm::OwningPtr<DiagnosticClient> DiagClient;
2238 if (VerifyDiagnostics) {
2239 // When checking diagnostics, just buffer them up.
2240 DiagClient.reset(new TextDiagnosticBuffer());
2241 if (InputFilenames.size() != 1) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00002242 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner409d4e72009-04-17 20:40:01 +00002243 return 1;
2244 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002245 } else {
Daniel Dunbar227b2382009-11-09 22:45:57 +00002246 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 }
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Daniel Dunbarad451cc2009-11-05 02:11:37 +00002249 if (!DumpBuildInformation.empty())
Daniel Dunbar227b2382009-11-09 22:45:57 +00002250 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002251
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002253 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002254 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2255 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002256 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002257
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002258 // Set an error handler, so that any LLVM backend diagnostics go through our
2259 // error handler.
2260 llvm::llvm_install_error_handler(LLVMErrorHandler,
2261 static_cast<void*>(&Diags));
2262
Daniel Dunbar7c15e712009-10-30 18:12:31 +00002263 // Initialize base triple. If a -triple option has been specified, use
2264 // that triple. Otherwise, default to the host triple.
2265 llvm::Triple Triple(TargetTriple);
2266 if (Triple.getTriple().empty())
2267 Triple = llvm::Triple(llvm::sys::getHostTriple());
2268
Chris Lattner11215192008-03-14 06:12:05 +00002269 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002270 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00002271 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Chris Lattner11215192008-03-14 06:12:05 +00002273 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002274 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002275 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002276 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002277 }
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Daniel Dunbar73b79592009-09-14 00:02:12 +00002279 // Set the target ABI if specified.
2280 if (!TargetABI.empty()) {
2281 if (!Target->setABI(TargetABI)) {
2282 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2283 << TargetABI;
2284 return 1;
2285 }
2286 }
2287
Daniel Dunbard4270232009-01-20 23:17:32 +00002288 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002289 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Daniel Dunbar227b2382009-11-09 22:45:57 +00002291 // Infer the input language.
2292 //
2293 // FIXME: We should move .ast inputs to taking a separate path, they are
2294 // really quite different.
2295 LangKind LK = GetLanguage();
2296
2297 // Now that we have initialized the diagnostics engine and the target, finish
2298 // setting up the compiler invocation.
2299 CompilerInvocation CompOpts;
2300 ConstructCompilerInvocation(CompOpts, DiagOpts, *Target);
2301
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002302 // Create the source manager.
2303 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Chris Lattner2c78b872009-04-14 23:22:57 +00002305 // Create a file manager object to provide access to and cache the filesystem.
2306 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002307
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002308 // Compute the feature set, unfortunately this effects the language!
2309 llvm::StringMap<bool> Features;
2310 ComputeFeatureMap(Target.get(), Features);
2311
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002313 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002315 // AST inputs are handled specially.
2316 if (LK == langkind_ast) {
Daniel Dunbare29709f2009-11-09 20:55:08 +00002317 ProcessASTInputFile(CompOpts, InFile, ProgAction, Features,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002318 Diags, FileMgr, Context);
2319 continue;
2320 }
2321
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002322 // Reset the ID tables if we are reusing the SourceManager.
2323 if (i)
2324 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Chris Lattnerf63aea32009-03-04 21:40:56 +00002326 // Initialize language options, inferring file types from input filenames.
2327 LangOptions LangInfo;
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002328 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002329 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Chris Lattnerf63aea32009-03-04 21:40:56 +00002331 // Process the -I options and set them in the HeaderInfo.
2332 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002333
2334
Mike Stump43d81762009-10-08 23:29:47 +00002335 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo, Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Chris Lattnerf63aea32009-03-04 21:40:56 +00002337 // Set up the preprocessor with these options.
Daniel Dunbar90b18272009-11-04 23:56:25 +00002338 llvm::OwningPtr<Preprocessor> PP(CreatePreprocessor(Diags, LangInfo,
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002339 *Target, SourceMgr,
Daniel Dunbar90b18272009-11-04 23:56:25 +00002340 HeaderInfo));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002341
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002342 // Handle generating dependencies, if requested.
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002343 if (!DependencyFile.empty()) {
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002344 if (DependencyTargets.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002345 Diags.Report(FullSourceLoc(), diag::err_fe_dependency_file_requires_MT);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002346 continue;
2347 }
2348 std::string ErrStr;
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002349 llvm::raw_ostream *DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002350 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002351 if (!ErrStr.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002352 Diags.Report(FullSourceLoc(), diag::err_fe_error_opening)
2353 << DependencyFile << ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002354 continue;
2355 }
2356
2357 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2358 DependenciesIncludeSystemHeaders,
2359 PhonyDependencyTarget);
2360 }
2361
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002362 if (ImplicitIncludePCH.empty()) {
2363 if (InitializeSourceManager(*PP.get(), InFile))
2364 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002366 // Initialize builtin info.
2367 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002368 PP->getLangOptions().NoBuiltin);
2369 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002370
Chris Lattnerf63aea32009-03-04 21:40:56 +00002371 // Process the source file.
Daniel Dunbar227b2382009-11-09 22:45:57 +00002372 Diags.getClient()->BeginSourceFile(LangInfo);
Daniel Dunbare29709f2009-11-09 20:55:08 +00002373 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Features, Context);
Daniel Dunbar227b2382009-11-09 22:45:57 +00002374 Diags.getClient()->EndSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Chris Lattner40469652009-04-17 20:16:08 +00002376 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00002377 }
Chris Lattner11215192008-03-14 06:12:05 +00002378
Mike Stumpfc0fed32009-04-28 01:19:10 +00002379 if (!NoCaretDiagnostics)
2380 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2381 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2382 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Reid Spencer5f016e22007-07-11 17:01:13 +00002384 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002385 FileMgr.PrintStats();
2386 fprintf(stderr, "\n");
2387 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002388
2389 delete ClangFrontendTimer;
2390 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Daniel Dunbar276373d2008-10-27 22:10:13 +00002392 // If verifying diagnostics and we reached here, all is well.
2393 if (VerifyDiagnostics)
2394 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002396 // Managed static deconstruction. Useful for making things like
2397 // -time-passes usable.
2398 llvm::llvm_shutdown();
2399
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002400 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002401}