blob: 51a5b4a72d090a6924df839a5cfb8b2878390aca [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"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000063#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000064#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000065#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000066#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000067#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000068#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000069#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000070#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000071#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000072#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000073#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000074#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000075#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000076#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000077#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000078#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000079#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000080# include <sys/types.h>
81#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000082
Reid Spencer5f016e22007-07-11 17:01:13 +000083using namespace clang;
84
85//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000086// Source Location Parser
87//===----------------------------------------------------------------------===//
88
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000089static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
90 FileManager &FileMgr,
91 RequestedSourceLocation &Result) {
92 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000093 if (!File)
94 return true;
95
96 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000097 Result.Line = ParsedLoc.Line;
98 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000099 return false;
100}
101
Douglas Gregor26df2f02009-04-02 19:05:20 +0000102//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000103// Global options.
104//===----------------------------------------------------------------------===//
105
Chris Lattner47099742009-02-18 01:51:21 +0000106/// ClangFrontendTimer - The front-end activities should charge time to it with
107/// TimeRegion. The -ftime-report option controls whether this will do
108/// anything.
109llvm::Timer *ClangFrontendTimer = 0;
110
Reid Spencer5f016e22007-07-11 17:01:13 +0000111static llvm::cl::opt<bool>
112Verbose("v", llvm::cl::desc("Enable verbose output"));
113static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000114Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000115 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000116static llvm::cl::opt<bool>
117DisableFree("disable-free",
118 llvm::cl::desc("Disable freeing of memory on exit"),
119 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000120static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000121EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000122 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000123
124enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000125 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000126 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000127 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000128 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000129 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000130 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000131 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000133 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000134 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000135 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000137 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000138 ASTDump, // Parse ASTs and dump them.
139 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000140 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000141 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 ParsePrintCallbacks, // Parse and print each callback.
143 ParseSyntaxOnly, // Parse and perform semantic analysis.
144 ParseNoop, // Parse with noop callbacks.
145 RunPreprocessorOnly, // Just lex, no output.
146 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000147 DumpTokens, // Dump out preprocessed tokens.
148 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000149 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000150 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000151 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000152 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000153};
154
Mike Stump1eb44332009-09-09 15:08:12 +0000155static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000156ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
157 llvm::cl::init(ParseSyntaxOnly),
158 llvm::cl::values(
159 clEnumValN(RunPreprocessorOnly, "Eonly",
160 "Just run preprocessor, no output (for timings)"),
161 clEnumValN(PrintPreprocessedInput, "E",
162 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000163 clEnumValN(DumpRawTokens, "dump-raw-tokens",
164 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000165 clEnumValN(RunAnalysis, "analyze",
166 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000167 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 "Run preprocessor, dump internal rep of tokens"),
169 clEnumValN(ParseNoop, "parse-noop",
170 "Run parser with noop callbacks (for timings)"),
171 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
172 "Run parser and perform semantic analysis"),
173 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
174 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000175 clEnumValN(EmitHTML, "emit-html",
176 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000177 clEnumValN(ASTPrint, "ast-print",
178 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000179 clEnumValN(ASTPrintXML, "ast-print-xml",
180 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000181 clEnumValN(ASTDump, "ast-dump",
182 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000183 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000184 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000185 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000186 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000187 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
188 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000189 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000190 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000191 clEnumValN(GeneratePCH, "emit-pch",
192 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000193 clEnumValN(EmitAssembly, "S",
194 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000196 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000197 clEnumValN(EmitBC, "emit-llvm-bc",
198 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000199 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
200 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000201 clEnumValN(RewriteTest, "rewrite-test",
202 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000203 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000204 "Rewrite ObjC into C (code rewriter example)"),
205 clEnumValN(RewriteMacros, "rewrite-macros",
206 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000207 clEnumValN(RewriteBlocks, "rewrite-blocks",
208 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000209 clEnumValN(FixIt, "fixit",
210 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 clEnumValEnd));
212
Ted Kremenekccc76472007-12-19 19:47:59 +0000213
214static llvm::cl::opt<std::string>
215OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000216 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000217 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000218
Ted Kremenekc2e72992008-12-02 19:57:31 +0000219
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000220enum CodeCompletionPrinter {
221 CCP_Debug,
222 CCP_CIndex
223};
224
Douglas Gregorb657f112009-09-22 21:11:38 +0000225static llvm::cl::opt<ParsedSourceLocation>
226CodeCompletionAt("code-completion-at",
227 llvm::cl::value_desc("file:line:column"),
228 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000229
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000230static llvm::cl::opt<CodeCompletionPrinter>
231CodeCompletionPrinter("code-completion-printer",
232 llvm::cl::desc("Choose output type:"),
233 llvm::cl::init(CCP_Debug),
234 llvm::cl::values(
235 clEnumValN(CCP_Debug, "debug",
236 "Debug code-completion results"),
237 clEnumValN(CCP_CIndex, "cindex",
238 "Code-completion results for the CIndex library"),
239 clEnumValEnd));
240
241static llvm::cl::opt<bool>
242CodeCompletionWantsMacros("code-completion-macros",
243 llvm::cl::desc("Include macros in code-completion results"));
244
Douglas Gregor81b747b2009-09-17 21:32:03 +0000245/// \brief Buld a new code-completion consumer that prints the results of
246/// code completion to standard output.
247static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000248 switch (CodeCompletionPrinter.getValue()) {
249 case CCP_Debug:
250 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
251 llvm::outs());
252
253 case CCP_CIndex:
254 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
255 llvm::outs());
256 };
257
258 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000259}
260
Ted Kremenekc2e72992008-12-02 19:57:31 +0000261//===----------------------------------------------------------------------===//
262// PTH.
263//===----------------------------------------------------------------------===//
264
265static llvm::cl::opt<std::string>
266TokenCache("token-cache", llvm::cl::value_desc("path"),
267 llvm::cl::desc("Use specified token cache file"));
268
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000269//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000270// Diagnostic Options
271//===----------------------------------------------------------------------===//
272
Ted Kremenek41193e42007-09-26 19:42:19 +0000273static llvm::cl::opt<bool>
274VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000275 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000276
Nico Weberfd54ebc2008-08-05 23:33:20 +0000277static llvm::cl::opt<bool>
278NoShowColumn("fno-show-column",
279 llvm::cl::desc("Do not include column number on diagnostics"));
280
281static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000282NoShowLocation("fno-show-source-location",
283 llvm::cl::desc("Do not include source location information with"
284 " diagnostics"));
285
286static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000287NoCaretDiagnostics("fno-caret-diagnostics",
288 llvm::cl::desc("Do not include source line and caret with"
289 " diagnostics"));
290
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000291static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000292NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
293 llvm::cl::desc("Do not include fixit information in"
294 " diagnostics"));
295
296static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000297PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
298 llvm::cl::desc("Print source range spans in numeric form"));
299
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000300static llvm::cl::opt<bool>
301PrintDiagnosticOption("fdiagnostics-show-option",
302 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000303
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000304static llvm::cl::opt<unsigned>
305MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000306 llvm::cl::desc("Format message diagnostics so that they fit "
307 "within N columns or fewer, when possible."),
308 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000309
Torok Edwin603fca72009-06-04 07:18:23 +0000310static llvm::cl::opt<bool>
Daniel Dunbar838be482009-11-04 06:24:57 +0000311PrintColorDiagnostic("fcolor-diagnostics",
312 llvm::cl::desc("Use colors in diagnostics"));
313
Reid Spencer5f016e22007-07-11 17:01:13 +0000314//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000315// C++ Visualization.
316//===----------------------------------------------------------------------===//
317
318static llvm::cl::opt<std::string>
319InheritanceViewCls("cxx-inheritance-view",
320 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000321 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000322
323//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000324// Builtin Options
325//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000326
327static llvm::cl::opt<bool>
328TimeReport("ftime-report",
329 llvm::cl::desc("Print the amount of time each "
330 "phase of compilation takes"));
331
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000332static llvm::cl::opt<bool>
333Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000334 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000335 "freestanding environment"));
336
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000337static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000338AllowBuiltins("fbuiltin", llvm::cl::init(true),
339 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000340
341
342static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000343MathErrno("fmath-errno", llvm::cl::init(true),
344 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000345
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000346//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000347// Language Options
348//===----------------------------------------------------------------------===//
349
350enum LangKind {
351 langkind_unspecified,
352 langkind_c,
353 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000354 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 langkind_cxx,
356 langkind_cxx_cpp,
357 langkind_objc,
358 langkind_objc_cpp,
359 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000360 langkind_objcxx_cpp,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000361 langkind_ocl,
362 langkind_ast
Reid Spencer5f016e22007-07-11 17:01:13 +0000363};
364
Reid Spencer5f016e22007-07-11 17:01:13 +0000365static llvm::cl::opt<LangKind>
366BaseLang("x", llvm::cl::desc("Base language to compile"),
367 llvm::cl::init(langkind_unspecified),
368 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000369 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 clEnumValN(langkind_cxx, "c++", "C++"),
371 clEnumValN(langkind_objc, "objective-c", "Objective C"),
372 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000373 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000375 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
376 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000378 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
380 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000381 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000383 clEnumValN(langkind_c, "c-header",
384 "C header"),
385 clEnumValN(langkind_objc, "objective-c-header",
386 "Objective-C header"),
387 clEnumValN(langkind_cxx, "c++-header",
388 "C++ header"),
389 clEnumValN(langkind_objcxx, "objective-c++-header",
390 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000391 clEnumValN(langkind_ast, "ast",
392 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 clEnumValEnd));
394
395static llvm::cl::opt<bool>
Chris Lattner2c78b872009-04-14 23:22:57 +0000396ObjCExclusiveGC("fobjc-gc-only",
397 llvm::cl::desc("Use GC exclusively for Objective-C related "
398 "memory management"));
399
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000400static llvm::cl::opt<std::string>
401ObjCConstantStringClass("fconstant-string-class",
402 llvm::cl::value_desc("class name"),
403 llvm::cl::desc("Specify the class to use for constant "
404 "Objective-C string objects."));
405
Chris Lattner2c78b872009-04-14 23:22:57 +0000406static llvm::cl::opt<bool>
407ObjCEnableGC("fobjc-gc",
408 llvm::cl::desc("Enable Objective-C garbage collection"));
409
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000410static llvm::cl::opt<bool>
411ObjCEnableGCBitmapPrint("print-ivar-layout",
412 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
413
Chris Lattner2c78b872009-04-14 23:22:57 +0000414static llvm::cl::opt<LangOptions::VisibilityMode>
415SymbolVisibility("fvisibility",
416 llvm::cl::desc("Set the default symbol visibility:"),
417 llvm::cl::init(LangOptions::Default),
418 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
419 "Use default symbol visibility"),
420 clEnumValN(LangOptions::Hidden, "hidden",
421 "Use hidden symbol visibility"),
422 clEnumValN(LangOptions::Protected,"protected",
423 "Use protected symbol visibility"),
424 clEnumValEnd));
425
426static llvm::cl::opt<bool>
427OverflowChecking("ftrapv",
428 llvm::cl::desc("Trap on integer overflow"),
429 llvm::cl::init(false));
430
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000431static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000432AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
433 llvm::cl::init(false));
434
435static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000436PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
437 llvm::cl::init(false));
438
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000439static LangKind GetLanguage(llvm::StringRef Filename) {
Ted Kremenek8904f152007-12-05 23:49:08 +0000440 if (BaseLang != langkind_unspecified)
441 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000443 llvm::StringRef Ext = Filename.rsplit('.').second;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000444 if (Ext == "ast")
445 return langkind_ast;
446 else if (Ext == "c")
Ted Kremenek8904f152007-12-05 23:49:08 +0000447 return langkind_c;
Daniel Dunbar9f435342009-09-17 00:47:27 +0000448 else if (Ext == "S" || Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000449 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000450 else if (Ext == "i")
451 return langkind_c_cpp;
452 else if (Ext == "ii")
453 return langkind_cxx_cpp;
454 else if (Ext == "m")
455 return langkind_objc;
456 else if (Ext == "mi")
457 return langkind_objc_cpp;
458 else if (Ext == "mm" || Ext == "M")
459 return langkind_objcxx;
460 else if (Ext == "mii")
461 return langkind_objcxx_cpp;
462 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
463 Ext == "c++" || Ext == "cp" || Ext == "cxx")
464 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000465 else if (Ext == "cl")
466 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000467 else
468 return langkind_c;
469}
470
471
Ted Kremenek85888962008-10-21 00:54:44 +0000472static void InitializeCOptions(LangOptions &Options) {
473 // Do nothing.
474}
475
476static void InitializeObjCOptions(LangOptions &Options) {
477 Options.ObjC1 = Options.ObjC2 = 1;
478}
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Ted Kremenek85888962008-10-21 00:54:44 +0000480
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000481static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 // FIXME: implement -fpreprocessed mode.
483 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Ted Kremenek8904f152007-12-05 23:49:08 +0000485 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000487 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000488 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000489 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 case langkind_c_cpp:
491 NoPreprocess = true;
492 // FALLTHROUGH
493 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000494 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 break;
496 case langkind_cxx_cpp:
497 NoPreprocess = true;
498 // FALLTHROUGH
499 case langkind_cxx:
500 Options.CPlusPlus = 1;
501 break;
502 case langkind_objc_cpp:
503 NoPreprocess = true;
504 // FALLTHROUGH
505 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000506 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 break;
508 case langkind_objcxx_cpp:
509 NoPreprocess = true;
510 // FALLTHROUGH
511 case langkind_objcxx:
512 Options.ObjC1 = Options.ObjC2 = 1;
513 Options.CPlusPlus = 1;
514 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000515 case langkind_ocl:
516 Options.OpenCL = 1;
517 Options.AltiVec = 1;
518 Options.CXXOperatorNames = 1;
519 Options.LaxVectorConversions = 1;
520 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner2c78b872009-04-14 23:22:57 +0000523 if (ObjCExclusiveGC)
524 Options.setGCMode(LangOptions::GCOnly);
525 else if (ObjCEnableGC)
526 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000528 if (ObjCEnableGCBitmapPrint)
529 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Nate Begeman2ef13e52009-08-10 23:49:36 +0000531 if (AltiVec)
532 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000533
534 if (PThread)
535 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner2c78b872009-04-14 23:22:57 +0000537 Options.setVisibilityMode(SymbolVisibility);
538 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000539}
540
541/// LangStds - Language standards we support.
542enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000543 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 lang_c89, lang_c94, lang_c99,
Douglas Gregor214904e2009-09-29 14:42:43 +0000545 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000546 lang_cxx98, lang_gnucxx98,
547 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000548};
549
550static llvm::cl::opt<LangStds>
551LangStd("std", llvm::cl::desc("Language standard to compile for"),
552 llvm::cl::init(lang_unspecified),
553 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
554 clEnumValN(lang_c89, "c90", "ISO C 1990"),
555 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
556 clEnumValN(lang_c94, "iso9899:199409",
557 "ISO C 1990 with amendment 1"),
558 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000559 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000561 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000563 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000565 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 clEnumValN(lang_gnu99, "gnu9x",
567 "ISO C 1999 with GNU extensions"),
568 clEnumValN(lang_cxx98, "c++98",
569 "ISO C++ 1998 with amendments"),
570 clEnumValN(lang_gnucxx98, "gnu++98",
571 "ISO C++ 1998 with amendments and GNU "
572 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000573 clEnumValN(lang_cxx0x, "c++0x",
574 "Upcoming ISO C++ 200x with amendments"),
575 clEnumValN(lang_gnucxx0x, "gnu++0x",
576 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000577 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 clEnumValEnd));
579
580static llvm::cl::opt<bool>
581NoOperatorNames("fno-operator-names",
582 llvm::cl::desc("Do not treat C++ operator name keywords as "
583 "synonyms for operators"));
584
Anders Carlssonee98ac52007-10-15 02:50:23 +0000585static llvm::cl::opt<bool>
586PascalStrings("fpascal-strings",
587 llvm::cl::desc("Recognize and construct Pascal-style "
588 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Steve Naroffd62701b2008-02-07 03:50:06 +0000590static llvm::cl::opt<bool>
591MSExtensions("fms-extensions",
592 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000593 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000594
595static llvm::cl::opt<bool>
596WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000597 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000598
599static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000600NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000601 llvm::cl::desc("Disallow implicit conversions between "
602 "vectors with a different number of "
603 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000604
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000605static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000606EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000607
608static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000609EnableHeinousExtensions("fheinous-gnu-extensions",
610 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
611 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
612
613static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000614ObjCNonFragileABI("fobjc-nonfragile-abi",
615 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000616
Daniel Dunbard6884a02009-05-04 05:16:21 +0000617
618static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000619EmitAllDecls("femit-all-decls",
620 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000621
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000622static llvm::cl::opt<bool>
623Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000624 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000625
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000626static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000627Rtti("frtti", llvm::cl::init(true),
628 llvm::cl::desc("Enable generation of rtti information"));
629
630static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000631GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000632 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000633 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000634
635static llvm::cl::opt<bool>
636NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000637 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000638 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000639
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000640static llvm::cl::opt<bool>
641CharIsSigned("fsigned-char",
642 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000643
John Thompsona6fda122009-11-05 20:14:16 +0000644static llvm::cl::opt<bool>
645ShortWChar("fshort-wchar",
646 llvm::cl::desc("Force wchar_t to be a short unsigned int"));
647
Ted Kremenekea644d82008-09-03 21:22:16 +0000648
649static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000650Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000651
Douglas Gregor26dce442009-03-10 00:06:19 +0000652static llvm::cl::opt<unsigned>
653TemplateDepth("ftemplate-depth", llvm::cl::init(99),
654 llvm::cl::desc("Maximum depth of recursive template "
655 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000656static llvm::cl::opt<bool>
657DollarsInIdents("fdollars-in-identifiers",
658 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000659
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000660
661static llvm::cl::opt<bool>
662OptSize("Os", llvm::cl::desc("Optimize for size"));
663
664static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000665DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000666 llvm::cl::desc("Don't run LLVM optimization passes"));
667
668static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000669NoCommon("fno-common",
670 llvm::cl::desc("Compile common globals like normal definitions"),
671 llvm::cl::ValueDisallowed);
672
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000673static llvm::cl::opt<std::string>
674MainFileName("main-file-name",
675 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000676
Anders Carlssona33d9b42009-05-13 19:49:53 +0000677// FIXME: Also add an "-fno-access-control" option.
678static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000679AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000680 llvm::cl::desc("Enable C++ access control"));
681
Anders Carlsson92f58222009-08-22 22:30:33 +0000682static llvm::cl::opt<bool>
683NoElideConstructors("fno-elide-constructors",
684 llvm::cl::desc("Disable C++ copy constructor elision"));
685
Tanya Lattner59876c22009-11-04 01:18:09 +0000686static llvm::cl::opt<bool>
687NoMergeConstants("fno-merge-all-constants",
688 llvm::cl::desc("Disallow merging of constants."));
689
Daniel Dunbar73b79592009-09-14 00:02:12 +0000690static llvm::cl::opt<std::string>
691TargetABI("target-abi",
692 llvm::cl::desc("Target a particular ABI type"));
693
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000694static llvm::cl::opt<std::string>
695TargetTriple("triple",
696 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
697
Anders Carlsson92f58222009-08-22 22:30:33 +0000698
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000699// It might be nice to add bounds to the CommandLine library directly.
700struct OptLevelParser : public llvm::cl::parser<unsigned> {
Chris Lattner59b21722009-09-20 00:39:15 +0000701 bool parse(llvm::cl::Option &O, llvm::StringRef ArgName,
702 llvm::StringRef Arg, unsigned &Val) {
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000703 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
704 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000705 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000706 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000707 return false;
708 }
709};
710static llvm::cl::opt<unsigned, false, OptLevelParser>
711OptLevel("O", llvm::cl::Prefix,
712 llvm::cl::desc("Optimization level"),
713 llvm::cl::init(0));
714
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000715static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000716PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
717
718static llvm::cl::opt<bool>
719StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000720
Bill Wendling45483f72009-06-28 07:36:13 +0000721static llvm::cl::opt<int>
722StackProtector("stack-protector",
723 llvm::cl::desc("Enable stack protectors"),
724 llvm::cl::init(-1));
725
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000726static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000727 TargetInfo *Target,
728 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000729 // Allow the target to set the default the langauge options as it sees fit.
730 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000731
732 // Pass the map of target features to the target for validation and
733 // processing.
734 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 if (LangStd == lang_unspecified) {
737 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000738 switch (LK) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000739 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000740 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000741 case langkind_ocl:
742 LangStd = lang_c99;
743 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000745 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 case langkind_c_cpp:
747 case langkind_objc:
748 case langkind_objc_cpp:
749 LangStd = lang_gnu99;
750 break;
751 case langkind_cxx:
752 case langkind_cxx_cpp:
753 case langkind_objcxx:
754 case langkind_objcxx_cpp:
755 LangStd = lang_gnucxx98;
756 break;
757 }
758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 switch (LangStd) {
761 default: assert(0 && "Unknown language standard!");
762
763 // Fall through from newer standards to older ones. This isn't really right.
764 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000765 case lang_gnucxx0x:
766 case lang_cxx0x:
767 Options.CPlusPlus0x = 1;
768 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 case lang_gnucxx98:
770 case lang_cxx98:
771 Options.CPlusPlus = 1;
772 Options.CXXOperatorNames = !NoOperatorNames;
773 // FALL THROUGH.
774 case lang_gnu99:
775 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 Options.C99 = 1;
777 Options.HexFloats = 1;
778 // FALL THROUGH.
779 case lang_gnu89:
780 Options.BCPLComment = 1; // Only for C99/C++.
781 // FALL THROUGH.
782 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000783 Options.Digraphs = 1; // C94, C99, C++.
784 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 case lang_c89:
786 break;
787 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000788
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000789 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
Douglas Gregor214904e2009-09-29 14:42:43 +0000790 switch (LangStd) {
791 default: assert(0 && "Unknown language standard!");
792 case lang_gnucxx0x:
793 case lang_gnucxx98:
794 case lang_gnu99:
795 case lang_gnu89:
796 Options.GNUMode = 1;
797 break;
798 case lang_cxx0x:
799 case lang_cxx98:
800 case lang_c99:
801 case lang_c94:
802 case lang_c89:
803 Options.GNUMode = 0;
804 break;
805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000807 if (Options.CPlusPlus) {
808 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000809 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000810 }
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattnerd658b562008-04-05 06:32:51 +0000812 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
813 Options.ImplicitInt = 1;
814 else
815 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Daniel Dunbard573d262009-04-07 22:13:21 +0000817 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
818 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000819 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000820 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000821 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000822
Chris Lattner802db9b2008-12-05 00:10:44 +0000823 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
824 // even if they are normally on for the target. In GNU modes (e.g.
825 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000826 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000827 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000828 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattner01638a62009-04-19 07:06:52 +0000830 // Default to not accepting '$' in identifiers when preprocessing assembler,
831 // but do accept when preprocessing C. FIXME: these defaults are right for
832 // darwin, are they right everywhere?
833 Options.DollarIdents = LK != langkind_asm_cpp;
834 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000835 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Chris Lattnerae0ee032008-12-04 23:20:07 +0000837 if (PascalStrings.getPosition())
838 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000839 if (MSExtensions.getPosition())
840 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000841 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000842 if (NoLaxVectorConversions.getPosition())
843 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000844 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000845 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000846 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000847 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000848 if (CharIsSigned.getPosition())
849 Options.CharIsSigned = CharIsSigned;
John Thompson40d1bb62009-11-05 22:03:02 +0000850 if (ShortWChar.getPosition())
851 Options.ShortWChar = ShortWChar;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000852
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000853 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000854 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000855 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000856 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Chris Lattner810f6d52009-03-13 17:38:01 +0000858 if (EnableHeinousExtensions)
859 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000860
Anders Carlssona33d9b42009-05-13 19:49:53 +0000861 if (AccessControl)
862 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Anders Carlsson92f58222009-08-22 22:30:33 +0000864 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Chris Lattnere4f21422009-06-30 01:26:17 +0000866 // OpenCL and C++ both have bool, true, false keywords.
867 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000869 Options.MathErrno = MathErrno;
870
Douglas Gregor26dce442009-03-10 00:06:19 +0000871 Options.InstantiationDepth = TemplateDepth;
872
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000873 // Override the default runtime if the user requested it.
874 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000875 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000876 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000877 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000878
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000879 if (!ObjCConstantStringClass.empty())
880 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
881
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000882 if (ObjCNonFragileABI)
883 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000884
Daniel Dunbard604c402009-02-04 21:19:06 +0000885 if (EmitAllDecls)
886 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000887
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000888 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
889 // support.
890 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000892 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000893 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000894 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000895
896 assert(PICLevel <= 2 && "Invalid value for -pic-level");
897 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000898
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000899 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000900 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000901 Options.NoInline = !OptSize && !OptLevel;
902
903 Options.Static = StaticDefine;
904
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000905 switch (StackProtector) {
906 default:
907 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
908 case -1: break;
909 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
910 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
911 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
912 }
Bill Wendling45483f72009-06-28 07:36:13 +0000913
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000914 if (MainFileName.getPosition())
915 Options.setMainFileName(MainFileName.c_str());
John Thompsona6fda122009-11-05 20:14:16 +0000916
John Thompson40d1bb62009-11-05 22:03:02 +0000917 Target->setForcedLangOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000918}
919
920//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000921// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000922//===----------------------------------------------------------------------===//
923
Douglas Gregore1d918e2009-04-10 23:10:45 +0000924static bool InitializeSourceManager(Preprocessor &PP,
925 const std::string &InFile) {
926 // Figure out where to get and map in the main file.
927 SourceManager &SourceMgr = PP.getSourceManager();
928 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000929
930 if (EmptyInputOnly) {
931 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000932 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000933 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
934 SourceMgr.createMainFileIDForMemBuffer(SB);
935 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000936 const FileEntry *File = FileMgr.getFile(InFile);
937 if (File) SourceMgr.createMainFileID(File, SourceLocation());
938 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000939 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +0000940 << InFile.c_str();
941 return true;
942 }
943 } else {
944 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
945
946 // If stdin was empty, SB is null. Cons up an empty memory
947 // buffer now.
948 if (!SB) {
949 const char *EmptyStr = "";
950 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
951 }
952
953 SourceMgr.createMainFileIDForMemBuffer(SB);
954 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000955 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +0000956 diag::err_fe_error_reading_stdin);
957 return true;
958 }
959 }
960
961 return false;
962}
963
Chris Lattneraa391972008-04-19 23:09:31 +0000964
Chris Lattnere116ccf2009-04-21 05:40:52 +0000965//===----------------------------------------------------------------------===//
966// Preprocessor Initialization
967//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000968
Chris Lattnere6113de2009-11-03 19:50:27 +0000969static llvm::cl::opt<bool>
Daniel Dunbar468fe242009-11-04 21:13:02 +0000970UndefMacros("undef", llvm::cl::value_desc("macro"),
971 llvm::cl::desc("undef all system defines"));
Chris Lattnere6113de2009-11-03 19:50:27 +0000972
Chris Lattnere116ccf2009-04-21 05:40:52 +0000973static llvm::cl::list<std::string>
974D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
975 llvm::cl::desc("Predefine the specified macro"));
976static llvm::cl::list<std::string>
977U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
978 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000979
Chris Lattnere116ccf2009-04-21 05:40:52 +0000980static llvm::cl::list<std::string>
981ImplicitIncludes("include", llvm::cl::value_desc("file"),
982 llvm::cl::desc("Include file before parsing"));
983static llvm::cl::list<std::string>
984ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
985 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000986
Chris Lattnere116ccf2009-04-21 05:40:52 +0000987static llvm::cl::opt<std::string>
988ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
989 llvm::cl::desc("Include precompiled header file"));
990
991static llvm::cl::opt<std::string>
992ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
993 llvm::cl::desc("Include file before parsing"));
994
Douglas Gregore650c8c2009-07-07 00:12:59 +0000995static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000996RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000997 llvm::cl::desc("Whether to build a relocatable precompiled "
998 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000999
1000//===----------------------------------------------------------------------===//
1001// Preprocessor include path information.
1002//===----------------------------------------------------------------------===//
1003
1004// This tool exports a large number of command line options to control how the
1005// preprocessor searches for header files. At root, however, the Preprocessor
1006// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +00001007//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001008// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001009// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001010//
Reid Spencer5f016e22007-07-11 17:01:13 +00001011
1012static llvm::cl::opt<bool>
1013nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1014
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001015static llvm::cl::opt<bool>
Rafael Espindola8d737cc2009-10-26 13:36:57 +00001016nobuiltininc("nobuiltininc",
1017 llvm::cl::desc("Disable builtin #include directories"));
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001018
Reid Spencer5f016e22007-07-11 17:01:13 +00001019// Various command line options. These four add directories to each chain.
1020static llvm::cl::list<std::string>
1021F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1022 llvm::cl::desc("Add directory to framework include search path"));
1023static llvm::cl::list<std::string>
1024I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1025 llvm::cl::desc("Add directory to include search path"));
1026static llvm::cl::list<std::string>
1027idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1028 llvm::cl::desc("Add directory to AFTER include search path"));
1029static llvm::cl::list<std::string>
1030iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1031 llvm::cl::desc("Add directory to QUOTE include search path"));
1032static llvm::cl::list<std::string>
1033isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1034 llvm::cl::desc("Add directory to SYSTEM include search path"));
1035
1036// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1037static llvm::cl::list<std::string>
1038iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1039 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1040static llvm::cl::list<std::string>
1041iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1042 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1043static llvm::cl::list<std::string>
1044iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1045 llvm::cl::Prefix,
1046 llvm::cl::desc("Set directory to include search path with prefix"));
1047
Chris Lattner0c946412007-08-26 17:47:35 +00001048static llvm::cl::opt<std::string>
1049isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1050 llvm::cl::desc("Set the system root directory (usually /)"));
1051
Reid Spencer5f016e22007-07-11 17:01:13 +00001052// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001053
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001054// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +00001055std::string GetBuiltinIncludePath(const char *Argv0) {
1056 llvm::sys::Path P =
1057 llvm::sys::Path::GetMainExecutable(Argv0,
1058 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001059
Daniel Dunbar750156a2009-11-07 04:19:57 +00001060 if (!P.isEmpty()) {
1061 P.eraseComponent(); // Remove /clang from foo/bin/clang
1062 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001063
Daniel Dunbar750156a2009-11-07 04:19:57 +00001064 // Get foo/lib/clang/<version>/include
1065 P.appendComponent("lib");
1066 P.appendComponent("clang");
1067 P.appendComponent(CLANG_VERSION_STRING);
1068 P.appendComponent("include");
1069 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001070
Daniel Dunbar750156a2009-11-07 04:19:57 +00001071 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001072}
1073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074/// InitializeIncludePaths - Process the -I options and set them in the
1075/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001076void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
Mike Stump43d81762009-10-08 23:29:47 +00001077 FileManager &FM, const LangOptions &Lang,
1078 llvm::Triple &triple) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001079 HeaderSearchOptions Opts(isysroot);
1080
1081 Opts.Verbose = Verbose;
Nico Weber0fca0222008-08-22 09:25:22 +00001082
Ted Kremenekf3721112008-05-31 00:27:00 +00001083 // Handle -I... and -F... options, walking the lists in parallel.
1084 unsigned Iidx = 0, Fidx = 0;
1085 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1086 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001087 Opts.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001088 ++Iidx;
1089 } else {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001090 Opts.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001091 ++Fidx;
1092 }
1093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Ted Kremenekf3721112008-05-31 00:27:00 +00001095 // Consume what's left from whatever list was longer.
1096 for (; Iidx != I_dirs.size(); ++Iidx)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001097 Opts.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001098 for (; Fidx != F_dirs.size(); ++Fidx)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001099 Opts.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 // Handle -idirafter... options.
1102 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001103 Opts.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
Nico Weber0fca0222008-08-22 09:25:22 +00001104 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 // Handle -iquote... options.
1107 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001108 Opts.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 // Handle -isystem... options.
1111 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001112 Opts.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001113
1114 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1115 // parallel, processing the values in order of occurance to get the right
1116 // prefixes.
1117 {
1118 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1119 unsigned iprefix_idx = 0;
1120 unsigned iwithprefix_idx = 0;
1121 unsigned iwithprefixbefore_idx = 0;
1122 bool iprefix_done = iprefix_vals.empty();
1123 bool iwithprefix_done = iwithprefix_vals.empty();
1124 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1125 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1126 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001127 (iwithprefix_done ||
1128 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001130 (iwithprefixbefore_done ||
1131 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1133 Prefix = iprefix_vals[iprefix_idx];
1134 ++iprefix_idx;
1135 iprefix_done = iprefix_idx == iprefix_vals.size();
1136 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001137 (iwithprefixbefore_done ||
1138 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001140 Opts.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001141 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 ++iwithprefix_idx;
1143 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1144 } else {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001145 Opts.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001146 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001148 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001149 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1150 }
1151 }
1152 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001153
Daniel Dunbare1665822009-11-07 04:20:39 +00001154 // Add CPATH environment paths.
1155 if (const char *Env = getenv("CPATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001156 Opts.EnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001157
1158 // Add language specific environment paths.
1159 if (Lang.CPlusPlus && Lang.ObjC1) {
1160 if (const char *Env = getenv("OBJCPLUS_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001161 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001162 } else if (Lang.CPlusPlus) {
1163 if (const char *Env = getenv("CPLUS_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001164 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001165 } else if (Lang.ObjC1) {
1166 if (const char *Env = getenv("OBJC_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001167 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001168 } else {
1169 if (const char *Env = getenv("C_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001170 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001171 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001172
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001173 if (!nobuiltininc)
1174 Opts.BuiltinIncludePath = GetBuiltinIncludePath(Argv0);
Daniel Dunbar750156a2009-11-07 04:19:57 +00001175
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001176 Opts.UseStandardIncludes = !nostdinc;
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001178 // Apply all the options to the header search object.
1179 ApplyHeaderSearchOptions(Opts, Headers, Lang, triple);
Reid Spencer5f016e22007-07-11 17:01:13 +00001180}
1181
Daniel Dunbar8863b982009-11-07 04:20:15 +00001182void InitializePreprocessorOptions(PreprocessorOptions &InitOpts) {
Daniel Dunbar468fe242009-11-04 21:13:02 +00001183 // Use predefines?
1184 InitOpts.setUsePredefines(!UndefMacros);
1185
Chris Lattnere116ccf2009-04-21 05:40:52 +00001186 // Add macros from the command line.
1187 unsigned d = 0, D = D_macros.size();
1188 unsigned u = 0, U = U_macros.size();
1189 while (d < D || u < U) {
1190 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1191 InitOpts.addMacroDef(D_macros[d++]);
1192 else
1193 InitOpts.addMacroUndef(U_macros[u++]);
1194 }
1195
1196 // If -imacros are specified, include them now. These are processed before
1197 // any -include directives.
1198 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1199 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1200
Douglas Gregorb64c1932009-05-12 01:31:05 +00001201 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1202 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001203 // We want to add these paths to the predefines buffer in order, make a
1204 // temporary vector to sort by their occurrence.
1205 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1206
1207 if (!ImplicitIncludePTH.empty())
1208 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1209 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001210 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1211 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1212 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001213 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1214 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1215 &ImplicitIncludes[i]));
1216 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1217
1218
1219 // Now that they are ordered by position, add to the predefines buffer.
1220 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1221 std::string *Ptr = OrderedPaths[i].second;
1222 if (!ImplicitIncludes.empty() &&
1223 Ptr >= &ImplicitIncludes[0] &&
1224 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1225 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001226 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001227 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001228 } else {
1229 // We end up here when we're producing preprocessed output and
1230 // we loaded a PCH file. In this case, just include the header
1231 // file that was used to build the precompiled header.
1232 assert(Ptr == &ImplicitIncludePCH);
1233 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1234 if (!OriginalFile.empty()) {
1235 InitOpts.addInclude(OriginalFile, false);
1236 ImplicitIncludePCH.clear();
1237 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001238 }
1239 }
1240 }
1241}
1242
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001243//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +00001244// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001245//===----------------------------------------------------------------------===//
1246
Daniel Dunbar90b18272009-11-04 23:56:25 +00001247static Preprocessor *
1248CreatePreprocessor(Diagnostic &Diags,const LangOptions &LangInfo,
1249 TargetInfo &Target, SourceManager &SourceMgr,
1250 HeaderSearch &HeaderInfo) {
1251 PTHManager *PTHMgr = 0;
1252 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1253 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1254 "options\n");
1255 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001256 }
Daniel Dunbar90b18272009-11-04 23:56:25 +00001257
1258 // Use PTH?
1259 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1260 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
1261 PTHMgr = PTHManager::Create(x, &Diags,
1262 TokenCache.empty() ? Diagnostic::Error
1263 : Diagnostic::Warning);
1264 }
1265
1266 if (Diags.hasErrorOccurred())
1267 exit(1);
1268
1269 // Create the Preprocessor.
1270 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
1271 SourceMgr, HeaderInfo, PTHMgr);
1272
1273 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1274 // That argument is used as the IdentifierInfoLookup argument to
1275 // IdentifierTable's ctor.
1276 if (PTHMgr) {
1277 PTHMgr->setPreprocessor(PP);
1278 PP->setPTHManager(PTHMgr);
1279 }
1280
Daniel Dunbar8863b982009-11-07 04:20:15 +00001281 PreprocessorOptions InitOpts;
1282 InitializePreprocessorOptions(InitOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +00001283 InitializePreprocessor(*PP, InitOpts);
1284
1285 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001286}
Reid Spencer5f016e22007-07-11 17:01:13 +00001287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288//===----------------------------------------------------------------------===//
1289// Basic Parser driver
1290//===----------------------------------------------------------------------===//
1291
Chris Lattner51574ea2008-04-19 23:25:44 +00001292static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001294 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 // Parsing the specified input file.
1297 P.ParseTranslationUnit();
1298 delete PA;
1299}
1300
1301//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001302// Code generation options
1303//===----------------------------------------------------------------------===//
1304
1305static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001306GenerateDebugInfo("g",
1307 llvm::cl::desc("Generate source level debug information"));
1308
Daniel Dunbara034ba82009-02-17 19:47:34 +00001309static llvm::cl::opt<std::string>
1310TargetCPU("mcpu",
1311 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1312
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001313static llvm::cl::list<std::string>
1314TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1315
Devang Patel24095da2009-06-04 23:32:02 +00001316
1317static llvm::cl::opt<bool>
1318DisableRedZone("disable-red-zone",
1319 llvm::cl::desc("Do not emit code that uses the red zone."),
1320 llvm::cl::init(false));
1321
Devang Patelacebb392009-06-05 22:05:48 +00001322static llvm::cl::opt<bool>
1323NoImplicitFloat("no-implicit-float",
1324 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1325 llvm::cl::init(false));
1326
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001327/// ComputeTargetFeatures - Recompute the target feature list to only
1328/// be the list of things that are enabled, based on the target cpu
1329/// and feature list.
1330static void ComputeFeatureMap(TargetInfo *Target,
1331 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001332 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001333
1334 // Initialize the feature map based on the target.
1335 Target->getDefaultFeatures(TargetCPU, Features);
1336
1337 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001338 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001339 ie = TargetFeatures.end(); it != ie; ++it) {
1340 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001342 // FIXME: Don't handle errors like this.
1343 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001344 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001345 Name);
1346 exit(1);
1347 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001348 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001349 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001350 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001351 exit(1);
1352 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001353 }
1354}
1355
Chris Lattner7afae712009-03-16 18:41:18 +00001356static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001357 const LangOptions &LangOpts,
1358 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001359 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001360 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001361
1362 if (DisableLLVMOptimizations) {
1363 Opts.OptimizationLevel = 0;
1364 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001365 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001366 if (OptSize) {
1367 // -Os implies -O2
1368 Opts.OptimizationLevel = 2;
1369 } else {
1370 Opts.OptimizationLevel = OptLevel;
1371 }
1372
1373 // We must always run at least the always inlining pass.
1374 if (Opts.OptimizationLevel > 1)
1375 Opts.Inlining = CompileOptions::NormalInlining;
1376 else
1377 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001378 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001379
1380 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001381 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001382 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001383
1384#ifdef NDEBUG
1385 Opts.VerifyModule = 0;
1386#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001387
1388 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001389 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001390 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001391 ie = Features.end(); it != ie; ++it) {
1392 // FIXME: If we are completely confident that we have the right
1393 // set, we only need to pass the minuses.
1394 std::string Name(it->second ? "+" : "-");
1395 Name += it->first();
1396 Opts.Features.push_back(Name);
1397 }
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Chris Lattnerbd360642009-03-26 05:00:52 +00001399 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Chris Lattner44502662009-02-18 01:23:44 +00001401 // Handle -ftime-report.
1402 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001403
1404 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001405 Opts.NoImplicitFloat = NoImplicitFloat;
Tanya Lattner59876c22009-11-04 01:18:09 +00001406
1407 Opts.MergeAllConstants = !NoMergeConstants;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001408}
1409
1410//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001411// Fix-It Options
1412//===----------------------------------------------------------------------===//
1413static llvm::cl::list<ParsedSourceLocation>
1414FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1415 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1416
1417//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001418// ObjC Rewriter Options
1419//===----------------------------------------------------------------------===//
1420static llvm::cl::opt<bool>
1421SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1422 llvm::cl::desc("Silence ObjC rewriting warnings"));
1423
1424//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001425// Warning Options
1426//===----------------------------------------------------------------------===//
1427
1428// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1429// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1430// -Wextra, so we don't need to worry about it.
1431static llvm::cl::list<std::string>
1432OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1433
1434static llvm::cl::opt<bool> OptPedantic("pedantic");
1435static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1436static llvm::cl::opt<bool> OptNoWarnings("w");
1437
1438//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001439// Preprocessing (-E mode) Options
1440//===----------------------------------------------------------------------===//
1441static llvm::cl::opt<bool>
1442DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1443static llvm::cl::opt<bool>
1444EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1445static llvm::cl::opt<bool>
1446EnableMacroCommentOutput("CC",
1447 llvm::cl::desc("Enable comment output in -E mode, "
1448 "even from macro expansions"));
1449static llvm::cl::opt<bool>
1450DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1451 " normal output"));
1452static llvm::cl::opt<bool>
1453DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1454 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001455
1456//===----------------------------------------------------------------------===//
1457// Dependency file options
1458//===----------------------------------------------------------------------===//
1459static llvm::cl::opt<std::string>
1460DependencyFile("dependency-file",
1461 llvm::cl::desc("Filename (or -) to write dependency output to"));
1462
1463static llvm::cl::opt<bool>
1464DependenciesIncludeSystemHeaders("sys-header-deps",
1465 llvm::cl::desc("Include system headers in dependency output"));
1466
1467static llvm::cl::list<std::string>
1468DependencyTargets("MT",
1469 llvm::cl::desc("Specify target for dependency"));
1470
1471// FIXME: Implement feature
1472static llvm::cl::opt<bool>
1473PhonyDependencyTarget("MP",
1474 llvm::cl::desc("Create phony target for each dependency "
1475 "(other than main file)"));
1476
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001477//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001478// Analysis options
1479//===----------------------------------------------------------------------===//
1480
1481static llvm::cl::list<Analyses>
1482AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1483llvm::cl::values(
1484#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1485clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001486#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001487clEnumValEnd));
1488
Mike Stump1eb44332009-09-09 15:08:12 +00001489static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001490AnalysisStoreOpt("analyzer-store",
1491 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1492 llvm::cl::init(BasicStoreModel),
1493 llvm::cl::values(
1494#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1495clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001496#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001497clEnumValEnd));
1498
Mike Stump1eb44332009-09-09 15:08:12 +00001499static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001500AnalysisConstraintsOpt("analyzer-constraints",
1501 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1502 llvm::cl::init(RangeConstraintsModel),
1503 llvm::cl::values(
1504#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1505clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001506#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001507clEnumValEnd));
1508
1509static llvm::cl::opt<AnalysisDiagClients>
1510AnalysisDiagOpt("analyzer-output",
1511 llvm::cl::desc("Source Code Analysis - Output Options"),
1512 llvm::cl::init(PD_HTML),
1513 llvm::cl::values(
1514#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1515clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001516#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001517clEnumValEnd));
1518
1519static llvm::cl::opt<bool>
1520VisualizeEGDot("analyzer-viz-egraph-graphviz",
1521 llvm::cl::desc("Display exploded graph using GraphViz"));
1522
1523static llvm::cl::opt<bool>
1524VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1525 llvm::cl::desc("Display exploded graph using Ubigraph"));
1526
1527static llvm::cl::opt<bool>
1528AnalyzeAll("analyzer-opt-analyze-headers",
1529 llvm::cl::desc("Force the static analyzer to analyze "
1530 "functions defined in header files"));
1531
1532static llvm::cl::opt<bool>
1533AnalyzerDisplayProgress("analyzer-display-progress",
1534 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1535
1536static llvm::cl::opt<bool>
1537PurgeDead("analyzer-purge-dead",
1538 llvm::cl::init(true),
1539 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1540 " processing a statement."));
1541
1542static llvm::cl::opt<bool>
1543EagerlyAssume("analyzer-eagerly-assume",
1544 llvm::cl::init(false),
1545 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1546 "symbolic constraints."));
1547
1548static llvm::cl::opt<std::string>
1549AnalyzeSpecificFunction("analyze-function",
1550 llvm::cl::desc("Run analysis on specific function"));
1551
1552static llvm::cl::opt<bool>
1553TrimGraph("trim-egraph",
1554 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1555
1556static AnalyzerOptions ReadAnalyzerOptions() {
1557 AnalyzerOptions Opts;
1558 Opts.AnalysisList = AnalysisList;
1559 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1560 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1561 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1562 Opts.VisualizeEGDot = VisualizeEGDot;
1563 Opts.VisualizeEGUbi = VisualizeEGUbi;
1564 Opts.AnalyzeAll = AnalyzeAll;
1565 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1566 Opts.PurgeDead = PurgeDead;
1567 Opts.EagerlyAssume = EagerlyAssume;
1568 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1569 Opts.TrimGraph = TrimGraph;
1570 return Opts;
1571}
1572
1573//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001574// -dump-build-information Stuff
1575//===----------------------------------------------------------------------===//
1576
1577static llvm::cl::opt<std::string>
1578DumpBuildInformation("dump-build-information",
1579 llvm::cl::value_desc("filename"),
1580 llvm::cl::desc("output a dump of some build information to a file"));
1581
1582static llvm::raw_ostream *BuildLogFile = 0;
1583
1584/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1585/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1586namespace {
1587class LoggingDiagnosticClient : public DiagnosticClient {
1588 llvm::OwningPtr<DiagnosticClient> Chain1;
1589 llvm::OwningPtr<DiagnosticClient> Chain2;
1590public:
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Daniel Dunbare29709f2009-11-09 20:55:08 +00001592 LoggingDiagnosticClient(const CompilerInvocation &CompOpts,
1593 DiagnosticClient *Normal) {
Chris Lattner75a97cb2009-04-17 21:05:01 +00001594 // Output diags both where requested...
1595 Chain1.reset(Normal);
1596 // .. and to our log file.
Daniel Dunbare29709f2009-11-09 20:55:08 +00001597 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1598 CompOpts.getDiagnosticOpts()));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Daniel Dunbarefcbe942009-11-05 02:42:12 +00001601 virtual void BeginSourceFile(const LangOptions &LO) {
1602 Chain1->BeginSourceFile(LO);
1603 Chain2->BeginSourceFile(LO);
1604 }
1605
1606 virtual void EndSourceFile() {
1607 Chain1->EndSourceFile();
1608 Chain2->EndSourceFile();
Chris Lattner75a97cb2009-04-17 21:05:01 +00001609 }
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Chris Lattner75a97cb2009-04-17 21:05:01 +00001611 virtual bool IncludeInDiagnosticCounts() const {
1612 return Chain1->IncludeInDiagnosticCounts();
1613 }
1614
1615 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1616 const DiagnosticInfo &Info) {
1617 Chain1->HandleDiagnostic(DiagLevel, Info);
1618 Chain2->HandleDiagnostic(DiagLevel, Info);
1619 }
1620};
1621} // end anonymous namespace.
1622
Daniel Dunbare29709f2009-11-09 20:55:08 +00001623static void SetUpBuildDumpLog(const CompilerInvocation &CompOpts,
1624 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +00001625 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Chris Lattner75a97cb2009-04-17 21:05:01 +00001627 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001628 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001629 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Chris Lattner75a97cb2009-04-17 21:05:01 +00001631 if (!ErrorInfo.empty()) {
1632 llvm::errs() << "error opening -dump-build-information file '"
1633 << DumpBuildInformation << "', option ignored!\n";
1634 delete BuildLogFile;
1635 BuildLogFile = 0;
1636 DumpBuildInformation = "";
1637 return;
1638 }
1639
1640 (*BuildLogFile) << "clang-cc command line arguments: ";
1641 for (unsigned i = 0; i != argc; ++i)
1642 (*BuildLogFile) << argv[i] << ' ';
1643 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Chris Lattner75a97cb2009-04-17 21:05:01 +00001645 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1646 // the diagnostic producers and the normal receiver.
Daniel Dunbare29709f2009-11-09 20:55:08 +00001647 DiagClient.reset(new LoggingDiagnosticClient(CompOpts, DiagClient.take()));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001648}
1649
1650
1651
1652//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001653// Main driver
1654//===----------------------------------------------------------------------===//
1655
Daniel Dunbare29709f2009-11-09 20:55:08 +00001656static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
1657 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +00001658 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001659 bool Binary,
1660 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001661 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001662 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001663 if (!CompOpts.getOutputFile().empty())
1664 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +00001665 else if (InFile == "-") {
1666 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001667 } else if (Extension) {
1668 llvm::sys::Path Path(InFile);
1669 Path.eraseSuffix();
1670 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001671 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001672 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001673 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001674 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001675
Chris Lattner92bcc272009-08-23 02:59:41 +00001676 std::string Error;
1677 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001678 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001679 if (!Error.empty()) {
1680 // FIXME: Don't fail this way.
1681 llvm::errs() << "ERROR: " << Error << "\n";
1682 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Chris Lattner92bcc272009-08-23 02:59:41 +00001685 if (OutFile != "-")
1686 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001687
1688 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001689}
1690
Daniel Dunbare29709f2009-11-09 20:55:08 +00001691static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
1692 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001693 const std::string &InFile,
1694 ProgActions PA,
1695 llvm::OwningPtr<llvm::raw_ostream> &OS,
1696 llvm::sys::Path &OutPath,
1697 const llvm::StringMap<bool> &Features,
1698 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +00001699 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001701 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +00001702
1703 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001704 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001705 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Douglas Gregoree75c052009-05-21 20:55:50 +00001707 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001708 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001709 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +00001710
Eli Friedman66d6f042009-05-18 22:20:00 +00001711 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001712 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +00001713
Eli Friedman66d6f042009-05-18 22:20:00 +00001714 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001715 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +00001716
1717 case PrintDeclContext:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001718 return CreateDeclContextPrinter();
Eli Friedman66d6f042009-05-18 22:20:00 +00001719
Anders Carlsson78762eb2009-09-24 18:54:49 +00001720 case DumpRecordLayouts:
1721 return CreateRecordLayoutDumper();
1722
Eli Friedman66d6f042009-05-18 22:20:00 +00001723 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001724 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +00001725
1726 case EmitAssembly:
1727 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001728 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001729 case EmitLLVMOnly: {
1730 BackendAction Act;
1731 if (ProgAction == EmitAssembly) {
1732 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001733 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +00001734 } else if (ProgAction == EmitLLVM) {
1735 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001736 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +00001737 } else if (ProgAction == EmitLLVMOnly) {
1738 Act = Backend_EmitNothing;
1739 } else {
1740 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001741 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001742 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001743
Eli Friedman66d6f042009-05-18 22:20:00 +00001744 CompileOptions Opts;
1745 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001746 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
1747 Opts, InFile, OS.get(), Context);
Eli Friedman66d6f042009-05-18 22:20:00 +00001748 }
1749
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001750 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001751 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001752 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1753 PP.getLangOptions(), SilenceRewriteMacroWarning);
1754
1755 case RewriteBlocks:
1756 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1757 PP.getLangOptions());
1758 }
1759}
1760
1761/// ProcessInputFile - Process a single input file with the specified state.
1762///
Daniel Dunbare29709f2009-11-09 20:55:08 +00001763static void ProcessInputFile(const CompilerInvocation &CompOpts,
1764 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar90b18272009-11-04 23:56:25 +00001765 ProgActions PA,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001766 const llvm::StringMap<bool> &Features,
1767 llvm::LLVMContext& Context) {
1768 llvm::OwningPtr<llvm::raw_ostream> OS;
1769 llvm::OwningPtr<ASTConsumer> Consumer;
1770 bool ClearSourceMgr = false;
1771 FixItRewriter *FixItRewrite = 0;
1772 bool CompleteTranslationUnit = true;
1773 llvm::sys::Path OutPath;
1774
1775 switch (PA) {
1776 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001777 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001778 Features, Context));
1779
1780 if (!Consumer.get()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001781 PP.getDiagnostics().Report(FullSourceLoc(),
1782 diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001783 return;
1784 }
1785
1786 break;;
1787
1788 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001789 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +00001790 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001791 break;
1792
1793 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001794 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001795 ReadAnalyzerOptions()));
1796 break;
1797
Eli Friedman66d6f042009-05-18 22:20:00 +00001798 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001799 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1800 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1801 RelocatablePCH.setValue(false);
1802 }
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Daniel Dunbare29709f2009-11-09 20:55:08 +00001804 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001805 if (RelocatablePCH.getValue())
1806 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1807 else
1808 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001809 CompleteTranslationUnit = false;
1810 break;
1811
Chris Lattnerc106c102008-10-12 05:03:36 +00001812 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001813 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001814 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001815 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001816 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001817 RawLex.SetKeepWhitespaceMode(true);
1818
1819 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001820 RawLex.LexFromRawLexer(RawTok);
1821 while (RawTok.isNot(tok::eof)) {
1822 PP.DumpToken(RawTok, true);
1823 fprintf(stderr, "\n");
1824 RawLex.LexFromRawLexer(RawTok);
1825 }
1826 ClearSourceMgr = true;
1827 break;
1828 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001830 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001831 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001832 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001833 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 do {
1835 PP.Lex(Tok);
1836 PP.DumpToken(Tok, true);
1837 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001838 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001839 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 break;
1841 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001842 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001845 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001846 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +00001847 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +00001848 // FIXME: Don't fail this way.
1849 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001850 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001851 ::exit(1);
1852 }
Daniel Dunbare29709f2009-11-09 20:55:08 +00001853 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001854 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001855 ClearSourceMgr = true;
1856 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001857 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001858
Chris Lattnercc7dea82009-04-27 22:02:30 +00001859 case PrintPreprocessedInput:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001860 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001863 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Chris Lattner47099742009-02-18 01:51:21 +00001866 case ParsePrintCallbacks: {
1867 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +00001868 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001869 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001870 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 break;
Chris Lattner47099742009-02-18 01:51:21 +00001872 }
1873
1874 case ParseSyntaxOnly: { // -fsyntax-only
1875 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001876 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001877 break;
Chris Lattner47099742009-02-18 01:51:21 +00001878 }
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001880 case RewriteMacros:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001881 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001882 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001883 ClearSourceMgr = true;
1884 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Eli Friedmanf54fce82009-05-19 01:02:07 +00001886 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +00001887 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +00001888 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001889 ClearSourceMgr = true;
1890 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001891
1892 case FixIt:
1893 llvm::TimeRegion Timer(ClangFrontendTimer);
1894 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001895 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001896 PP.getSourceManager(),
1897 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001898 break;
Chris Lattner47099742009-02-18 01:51:21 +00001899 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001900
Chris Lattner1aee61a2009-04-27 21:25:27 +00001901 if (FixItAtLocations.size() > 0) {
1902 // Even without the "-fixit" flag, with may have some specific
1903 // locations where the user has requested fixes. Process those
1904 // locations now.
1905 if (!FixItRewrite)
1906 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1907 PP.getSourceManager(),
1908 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001909
Chris Lattner1aee61a2009-04-27 21:25:27 +00001910 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001911 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001912 Idx != Last; ++Idx) {
1913 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001914 if (ResolveParsedLocation(FixItAtLocations[Idx],
1915 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001916 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1917 FixItAtLocations[Idx].FileName.c_str());
1918 } else {
1919 FixItRewrite->addFixItLocation(Requested);
1920 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001921 }
1922 }
1923
Chris Lattner1aee61a2009-04-27 21:25:27 +00001924 if (!AddedFixitLocation) {
1925 // All of the fix-it locations were bad. Don't fix anything.
1926 delete FixItRewrite;
1927 FixItRewrite = 0;
1928 }
1929 }
1930
1931 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001932 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001933 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1934 PP.getSourceManager(),
1935 PP.getTargetInfo(),
1936 PP.getIdentifierTable(),
1937 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001938 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001939 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001940 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Chris Lattnercc7dea82009-04-27 22:02:30 +00001942 llvm::OwningPtr<PCHReader> Reader;
1943 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001945 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001946 // If the user specified -isysroot, it will be used for relocatable PCH
1947 // files.
1948 const char *isysrootPCH = 0;
1949 if (isysroot.getNumOccurrences() != 0)
1950 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Douglas Gregore650c8c2009-07-07 00:12:59 +00001952 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001954 // The user has asked us to include a precompiled header. Load
1955 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001956 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1957 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001958 // Set the predefines buffer as suggested by the PCH
1959 // reader. Typically, the predefines buffer will be empty.
1960 PP.setPredefines(Reader->getSuggestedPredefines());
1961
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001962 // Attach the PCH reader to the AST context as an external AST
1963 // source, so that declarations will be deserialized from the
1964 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001965 if (ContextOwner) {
1966 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001967 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001968 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001969 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001970 }
1971
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001972 case PCHReader::Failure:
1973 // Unrecoverable failure: don't even try to process the input
1974 // file.
1975 return;
1976
1977 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001978 // No suitable PCH file could be found. Return an error.
1979 return;
1980
1981#if 0
1982 // FIXME: We can recover from failed attempts to load PCH
1983 // files. This code will do so, if we ever want to enable it.
1984
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001985 // We delayed the initialization of builtins in the hope of
1986 // loading the PCH file. Since the PCH file could not be
1987 // loaded, initialize builtins now.
1988 if (ContextOwner)
1989 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001990#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001991 }
1992
1993 // Finish preprocessor initialization. We do this now (rather
1994 // than earlier) because this initialization creates new source
1995 // location entries in the source manager, which must come after
1996 // the source location entries for the PCH file.
1997 if (InitializeSourceManager(PP, InFile))
1998 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001999 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002000
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002001 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00002002 if (Consumer) {
2003 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
2004 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002005
Douglas Gregorb657f112009-09-22 21:11:38 +00002006 if (!CodeCompletionAt.FileName.empty()) {
2007 // Tell the source manager to chop off the given file at a specific
2008 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002009 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +00002010 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
2011 // Truncate the named file at the given line/column.
2012 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
2013 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002014
Douglas Gregorb657f112009-09-22 21:11:38 +00002015 // Set up the creation routine for code-completion.
2016 CreateCodeCompleter = BuildPrintingCodeCompleter;
2017 } else {
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002018 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregorb657f112009-09-22 21:11:38 +00002019 diag::err_fe_invalid_code_complete_file)
2020 << CodeCompletionAt.FileName;
2021 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00002022 }
2023
Mike Stump1eb44332009-09-09 15:08:12 +00002024 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002025 CompleteTranslationUnit,
2026 CreateCodeCompleter, CreateCodeCompleterData);
2027 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002028
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002029 // Perform post processing actions and actions which don't use a consumer.
2030 switch (PA) {
2031 default: break;
2032
2033 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002034 llvm::TimeRegion Timer(ClangFrontendTimer);
2035 Token Tok;
2036 // Start parsing the specified input file.
2037 PP.EnterMainSourceFile();
2038 do {
2039 PP.Lex(Tok);
2040 } while (Tok.isNot(tok::eof));
2041 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002042 break;
2043 }
2044
2045 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002046 llvm::TimeRegion Timer(ClangFrontendTimer);
2047 ParseFile(PP, new MinimalAction(PP));
2048 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002049 break;
2050 }
2051
2052 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +00002053 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002054 if (DumpMacros)
2055 DoPrintMacros(PP, OS.get());
2056 else
2057 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2058 EnableMacroCommentOutput,
2059 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002060 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002063 }
2064
Chris Lattner1aee61a2009-04-27 21:25:27 +00002065 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +00002066 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002067
2068 // Disable the consumer prior to the context, the consumer may perform actions
2069 // in its destructor which require the context.
2070 if (DisableFree)
2071 Consumer.take();
2072 else
2073 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Chris Lattner1aee61a2009-04-27 21:25:27 +00002075 // If in -disable-free mode, don't deallocate ASTContext.
2076 if (DisableFree)
2077 ContextOwner.take();
2078 else
2079 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002080
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002081 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002082 if (CheckDiagnostics(PP))
2083 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002084
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002086 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 PP.PrintStats();
2088 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002089 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002090 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 fprintf(stderr, "\n");
2092 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002093
Mike Stump1eb44332009-09-09 15:08:12 +00002094 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002095 // manager tables, other require stable fileid/macroid's across multiple
2096 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002097 if (ClearSourceMgr)
2098 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002099
Eli Friedman66d6f042009-05-18 22:20:00 +00002100 // Always delete the output stream because we don't want to leak file
2101 // handles. Also, we don't want to try to erase an open file.
2102 OS.reset();
2103
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002104 // If we had errors, try to erase the output file.
2105 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +00002106 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +00002107}
2108
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002109/// ProcessInputFile - Process a single AST input file with the specified state.
2110///
Daniel Dunbare29709f2009-11-09 20:55:08 +00002111static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
2112 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002113 const llvm::StringMap<bool> &Features,
2114 Diagnostic &Diags, FileManager &FileMgr,
2115 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002116 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +00002117 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002118 if (!AST) {
2119 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
2120 return;
2121 }
2122
2123 Preprocessor &PP = AST->getPreprocessor();
2124
2125 llvm::OwningPtr<llvm::raw_ostream> OS;
2126 llvm::sys::Path OutPath;
Daniel Dunbare29709f2009-11-09 20:55:08 +00002127 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
2128 InFile, PA, OS,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002129 OutPath, Features,
2130 Context));
2131
2132 if (!Consumer.get()) {
2133 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
2134 return;
2135 }
2136
Daniel Dunbara674bf42009-09-21 03:03:56 +00002137 // Set the main file ID to an empty file.
2138 //
2139 // FIXME: We probably shouldn't need this, but for now this is the simplest
2140 // way to reuse the logic in ParseAST.
2141 const char *EmptyStr = "";
2142 llvm::MemoryBuffer *SB =
2143 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
2144 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002145
Daniel Dunbara674bf42009-09-21 03:03:56 +00002146 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002147 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +00002148 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002149 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002150
2151 // Release the consumer and the AST, in that order since the consumer may
2152 // perform actions in its destructor which require the context.
2153 if (DisableFree) {
2154 Consumer.take();
2155 AST.take();
2156 } else {
2157 Consumer.reset();
2158 AST.reset();
2159 }
2160
2161 // Always delete the output stream because we don't want to leak file
2162 // handles. Also, we don't want to try to erase an open file.
2163 OS.reset();
2164
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002165 // If we had errors, try to erase the output file.
2166 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002167 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002168}
2169
Reid Spencer5f016e22007-07-11 17:01:13 +00002170static llvm::cl::list<std::string>
2171InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2172
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002173static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2174 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2175
2176 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2177
2178 // We cannot recover from llvm errors.
2179 exit(1);
2180}
2181
Daniel Dunbare29709f2009-11-09 20:55:08 +00002182static void ConstructCompilerInvocation(CompilerInvocation &Opts) {
2183 Opts.getOutputFile() = OutputFile;
2184
2185 // Initialize the diagnostic options.
2186 Opts.getDiagnosticOpts().ShowColumn = !NoShowColumn;
2187 Opts.getDiagnosticOpts().ShowLocation = !NoShowLocation;
2188 Opts.getDiagnosticOpts().ShowCarets = !NoCaretDiagnostics;
2189 Opts.getDiagnosticOpts().ShowFixits = !NoDiagnosticsFixIt;
2190 Opts.getDiagnosticOpts().ShowSourceRanges = PrintSourceRangeInfo;
2191 Opts.getDiagnosticOpts().ShowOptionNames = PrintDiagnosticOption;
2192 Opts.getDiagnosticOpts().ShowColors = PrintColorDiagnostic;
2193 Opts.getDiagnosticOpts().MessageLength = MessageLength;
2194}
2195
Reid Spencer5f016e22007-07-11 17:01:13 +00002196int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002197 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002198 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002199 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002200
Daniel Dunbar4d861512009-09-03 04:54:12 +00002201 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002202 llvm::InitializeAllTargets();
2203 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002204
2205 llvm::cl::ParseCommandLineOptions(argc, argv,
2206 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Chris Lattner47099742009-02-18 01:51:21 +00002208 if (TimeReport)
2209 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002211 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002212 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2213 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002214 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 // If no input was specified, read from stdin.
2217 if (InputFilenames.empty())
2218 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002219
Daniel Dunbare29709f2009-11-09 20:55:08 +00002220 CompilerInvocation CompOpts;
2221 ConstructCompilerInvocation(CompOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00002222
Ted Kremenek31e703b2007-12-11 23:28:38 +00002223 // Create the diagnostic client for reporting errors or for
2224 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002225 llvm::OwningPtr<DiagnosticClient> DiagClient;
2226 if (VerifyDiagnostics) {
2227 // When checking diagnostics, just buffer them up.
2228 DiagClient.reset(new TextDiagnosticBuffer());
2229 if (InputFilenames.size() != 1) {
2230 fprintf(stderr, "-verify only works on single input files for now.\n");
2231 return 1;
2232 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002233 } else {
Daniel Dunbare29709f2009-11-09 20:55:08 +00002234 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
2235 CompOpts.getDiagnosticOpts()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 }
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Daniel Dunbarad451cc2009-11-05 02:11:37 +00002238 if (!DumpBuildInformation.empty())
Daniel Dunbare29709f2009-11-09 20:55:08 +00002239 SetUpBuildDumpLog(CompOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002240
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002242 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002243 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2244 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002245 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002246
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002247 // Set an error handler, so that any LLVM backend diagnostics go through our
2248 // error handler.
2249 llvm::llvm_install_error_handler(LLVMErrorHandler,
2250 static_cast<void*>(&Diags));
2251
Daniel Dunbar7c15e712009-10-30 18:12:31 +00002252 // Initialize base triple. If a -triple option has been specified, use
2253 // that triple. Otherwise, default to the host triple.
2254 llvm::Triple Triple(TargetTriple);
2255 if (Triple.getTriple().empty())
2256 Triple = llvm::Triple(llvm::sys::getHostTriple());
2257
Chris Lattner11215192008-03-14 06:12:05 +00002258 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002259 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00002260 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Chris Lattner11215192008-03-14 06:12:05 +00002262 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002263 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002264 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002265 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002266 }
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Daniel Dunbar73b79592009-09-14 00:02:12 +00002268 // Set the target ABI if specified.
2269 if (!TargetABI.empty()) {
2270 if (!Target->setABI(TargetABI)) {
2271 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2272 << TargetABI;
2273 return 1;
2274 }
2275 }
2276
Daniel Dunbard4270232009-01-20 23:17:32 +00002277 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002278 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002280 // Create the source manager.
2281 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Chris Lattner2c78b872009-04-14 23:22:57 +00002283 // Create a file manager object to provide access to and cache the filesystem.
2284 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002285
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002286 // Compute the feature set, unfortunately this effects the language!
2287 llvm::StringMap<bool> Features;
2288 ComputeFeatureMap(Target.get(), Features);
2289
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002291 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002293 LangKind LK = GetLanguage(InFile);
2294 // AST inputs are handled specially.
2295 if (LK == langkind_ast) {
Daniel Dunbare29709f2009-11-09 20:55:08 +00002296 ProcessASTInputFile(CompOpts, InFile, ProgAction, Features,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002297 Diags, FileMgr, Context);
2298 continue;
2299 }
2300
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002301 // Reset the ID tables if we are reusing the SourceManager.
2302 if (i)
2303 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Chris Lattnerf63aea32009-03-04 21:40:56 +00002305 // Initialize language options, inferring file types from input filenames.
2306 LangOptions LangInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002308 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002309 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Chris Lattnerf63aea32009-03-04 21:40:56 +00002311 // Process the -I options and set them in the HeaderInfo.
2312 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002313
2314
Mike Stump43d81762009-10-08 23:29:47 +00002315 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo, Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Chris Lattnerf63aea32009-03-04 21:40:56 +00002317 // Set up the preprocessor with these options.
Daniel Dunbar90b18272009-11-04 23:56:25 +00002318 llvm::OwningPtr<Preprocessor> PP(CreatePreprocessor(Diags, LangInfo,
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002319 *Target, SourceMgr,
Daniel Dunbar90b18272009-11-04 23:56:25 +00002320 HeaderInfo));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002321
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002322 // Handle generating dependencies, if requested.
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002323 if (!DependencyFile.empty()) {
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002324 if (DependencyTargets.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002325 Diags.Report(FullSourceLoc(), diag::err_fe_dependency_file_requires_MT);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002326 continue;
2327 }
2328 std::string ErrStr;
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002329 llvm::raw_ostream *DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002330 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002331 if (!ErrStr.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002332 Diags.Report(FullSourceLoc(), diag::err_fe_error_opening)
2333 << DependencyFile << ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002334 continue;
2335 }
2336
2337 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2338 DependenciesIncludeSystemHeaders,
2339 PhonyDependencyTarget);
2340 }
2341
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002342 if (ImplicitIncludePCH.empty()) {
2343 if (InitializeSourceManager(*PP.get(), InFile))
2344 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002346 // Initialize builtin info.
2347 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002348 PP->getLangOptions().NoBuiltin);
2349 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002350
Chris Lattnerf63aea32009-03-04 21:40:56 +00002351 // Process the source file.
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002352 DiagClient->BeginSourceFile(LangInfo);
Daniel Dunbare29709f2009-11-09 20:55:08 +00002353 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Features, Context);
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002354 DiagClient->EndSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00002355
Chris Lattner40469652009-04-17 20:16:08 +00002356 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00002357 }
Chris Lattner11215192008-03-14 06:12:05 +00002358
Mike Stumpfc0fed32009-04-28 01:19:10 +00002359 if (!NoCaretDiagnostics)
2360 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2361 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2362 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002365 FileMgr.PrintStats();
2366 fprintf(stderr, "\n");
2367 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002368
2369 delete ClangFrontendTimer;
2370 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Daniel Dunbar276373d2008-10-27 22:10:13 +00002372 // If verifying diagnostics and we reached here, all is well.
2373 if (VerifyDiagnostics)
2374 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002376 // Managed static deconstruction. Useful for making things like
2377 // -time-passes usable.
2378 llvm::llvm_shutdown();
2379
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002380 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002381}