blob: 671fc35d182b95642be8da4d0d40c1907bec2a82 [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 Dunbare1bd4e62009-03-02 06:16:29 +000028#include "clang/Frontend/CompileOptions.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000029#include "clang/Frontend/DiagnosticOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000030#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000032#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000033#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000034#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000036#include "clang/Frontend/TextDiagnosticBuffer.h"
37#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000038#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000039#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000040#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000041#include "clang/CodeGen/ModuleBuilder.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000042#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000043#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000044#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000045#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000046#include "clang/AST/ASTContext.h"
47#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000048#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "clang/Parse/Parser.h"
50#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000051#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052#include "clang/Basic/FileManager.h"
53#include "clang/Basic/SourceManager.h"
54#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000055#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000056#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000057#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000058#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000060#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000061#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000062#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000063#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000064#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000065#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000066#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000067#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000068#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000069#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000070#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000071#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000072#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000073#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000074#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000075#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000076#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000077#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000078# include <sys/types.h>
79#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000080
Reid Spencer5f016e22007-07-11 17:01:13 +000081using namespace clang;
82
83//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000084// Source Location Parser
85//===----------------------------------------------------------------------===//
86
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000087static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
88 FileManager &FileMgr,
89 RequestedSourceLocation &Result) {
90 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000091 if (!File)
92 return true;
93
94 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000095 Result.Line = ParsedLoc.Line;
96 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000097 return false;
98}
99
Douglas Gregor26df2f02009-04-02 19:05:20 +0000100//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000101// Global options.
102//===----------------------------------------------------------------------===//
103
Chris Lattner47099742009-02-18 01:51:21 +0000104/// ClangFrontendTimer - The front-end activities should charge time to it with
105/// TimeRegion. The -ftime-report option controls whether this will do
106/// anything.
107llvm::Timer *ClangFrontendTimer = 0;
108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109static llvm::cl::opt<bool>
110Verbose("v", llvm::cl::desc("Enable verbose output"));
111static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000112Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000113 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000114static llvm::cl::opt<bool>
115DisableFree("disable-free",
116 llvm::cl::desc("Disable freeing of memory on exit"),
117 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000118static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000119EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000120 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000121
122enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000124 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000125 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000126 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000127 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000128 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000129 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000131 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000132 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000133 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000135 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 ASTDump, // Parse ASTs and dump them.
137 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000138 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000139 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 ParsePrintCallbacks, // Parse and print each callback.
141 ParseSyntaxOnly, // Parse and perform semantic analysis.
142 ParseNoop, // Parse with noop callbacks.
143 RunPreprocessorOnly, // Just lex, no output.
144 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000145 DumpTokens, // Dump out preprocessed tokens.
146 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000147 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000148 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000149 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000150 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000151};
152
Mike Stump1eb44332009-09-09 15:08:12 +0000153static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000154ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
155 llvm::cl::init(ParseSyntaxOnly),
156 llvm::cl::values(
157 clEnumValN(RunPreprocessorOnly, "Eonly",
158 "Just run preprocessor, no output (for timings)"),
159 clEnumValN(PrintPreprocessedInput, "E",
160 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000161 clEnumValN(DumpRawTokens, "dump-raw-tokens",
162 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000163 clEnumValN(RunAnalysis, "analyze",
164 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000165 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 "Run preprocessor, dump internal rep of tokens"),
167 clEnumValN(ParseNoop, "parse-noop",
168 "Run parser with noop callbacks (for timings)"),
169 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
170 "Run parser and perform semantic analysis"),
171 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
172 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000173 clEnumValN(EmitHTML, "emit-html",
174 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000175 clEnumValN(ASTPrint, "ast-print",
176 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000177 clEnumValN(ASTPrintXML, "ast-print-xml",
178 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000179 clEnumValN(ASTDump, "ast-dump",
180 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000181 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000182 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000183 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000184 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000185 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
186 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000187 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000188 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000189 clEnumValN(GeneratePCH, "emit-pch",
190 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000191 clEnumValN(EmitAssembly, "S",
192 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000194 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000195 clEnumValN(EmitBC, "emit-llvm-bc",
196 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000197 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
198 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000199 clEnumValN(RewriteTest, "rewrite-test",
200 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000201 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000202 "Rewrite ObjC into C (code rewriter example)"),
203 clEnumValN(RewriteMacros, "rewrite-macros",
204 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000205 clEnumValN(RewriteBlocks, "rewrite-blocks",
206 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000207 clEnumValN(FixIt, "fixit",
208 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 clEnumValEnd));
210
Ted Kremenekccc76472007-12-19 19:47:59 +0000211
212static llvm::cl::opt<std::string>
213OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000214 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000215 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000216
Ted Kremenekc2e72992008-12-02 19:57:31 +0000217
Douglas Gregorb657f112009-09-22 21:11:38 +0000218static llvm::cl::opt<ParsedSourceLocation>
219CodeCompletionAt("code-completion-at",
220 llvm::cl::value_desc("file:line:column"),
221 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000222
223/// \brief Buld a new code-completion consumer that prints the results of
224/// code completion to standard output.
225static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
226 return new PrintingCodeCompleteConsumer(S, llvm::outs());
227}
228
Ted Kremenekc2e72992008-12-02 19:57:31 +0000229//===----------------------------------------------------------------------===//
230// PTH.
231//===----------------------------------------------------------------------===//
232
233static llvm::cl::opt<std::string>
234TokenCache("token-cache", llvm::cl::value_desc("path"),
235 llvm::cl::desc("Use specified token cache file"));
236
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000237//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000238// Diagnostic Options
239//===----------------------------------------------------------------------===//
240
Daniel Dunbareace8742009-11-04 06:24:30 +0000241static DiagnosticOptions DiagOpts;
242
Ted Kremenek41193e42007-09-26 19:42:19 +0000243static llvm::cl::opt<bool>
244VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000245 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000246
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000247static llvm::cl::opt<std::string>
248HTMLDiag("html-diags",
249 llvm::cl::desc("Generate HTML to report diagnostics"),
250 llvm::cl::value_desc("HTML directory"));
251
Nico Weberfd54ebc2008-08-05 23:33:20 +0000252static llvm::cl::opt<bool>
253NoShowColumn("fno-show-column",
254 llvm::cl::desc("Do not include column number on diagnostics"));
255
256static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000257NoShowLocation("fno-show-source-location",
258 llvm::cl::desc("Do not include source location information with"
259 " diagnostics"));
260
261static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000262NoCaretDiagnostics("fno-caret-diagnostics",
263 llvm::cl::desc("Do not include source line and caret with"
264 " diagnostics"));
265
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000266static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000267NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
268 llvm::cl::desc("Do not include fixit information in"
269 " diagnostics"));
270
271static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000272PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
273 llvm::cl::desc("Print source range spans in numeric form"));
274
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000275static llvm::cl::opt<bool>
276PrintDiagnosticOption("fdiagnostics-show-option",
277 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000278
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000279static llvm::cl::opt<unsigned>
280MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000281 llvm::cl::desc("Format message diagnostics so that they fit "
282 "within N columns or fewer, when possible."),
283 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000284
Torok Edwin603fca72009-06-04 07:18:23 +0000285static llvm::cl::opt<bool>
Daniel Dunbar838be482009-11-04 06:24:57 +0000286PrintColorDiagnostic("fcolor-diagnostics",
287 llvm::cl::desc("Use colors in diagnostics"));
288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000290// C++ Visualization.
291//===----------------------------------------------------------------------===//
292
293static llvm::cl::opt<std::string>
294InheritanceViewCls("cxx-inheritance-view",
295 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000296 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000297
298//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000299// Builtin Options
300//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000301
302static llvm::cl::opt<bool>
303TimeReport("ftime-report",
304 llvm::cl::desc("Print the amount of time each "
305 "phase of compilation takes"));
306
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000307static llvm::cl::opt<bool>
308Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000309 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000310 "freestanding environment"));
311
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000312static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000313AllowBuiltins("fbuiltin", llvm::cl::init(true),
314 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000315
316
317static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000318MathErrno("fmath-errno", llvm::cl::init(true),
319 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000320
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000321//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000322// Language Options
323//===----------------------------------------------------------------------===//
324
325enum LangKind {
326 langkind_unspecified,
327 langkind_c,
328 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000329 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 langkind_cxx,
331 langkind_cxx_cpp,
332 langkind_objc,
333 langkind_objc_cpp,
334 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000335 langkind_objcxx_cpp,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000336 langkind_ocl,
337 langkind_ast
Reid Spencer5f016e22007-07-11 17:01:13 +0000338};
339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340static llvm::cl::opt<LangKind>
341BaseLang("x", llvm::cl::desc("Base language to compile"),
342 llvm::cl::init(langkind_unspecified),
343 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000344 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 clEnumValN(langkind_cxx, "c++", "C++"),
346 clEnumValN(langkind_objc, "objective-c", "Objective C"),
347 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000348 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000350 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
351 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000353 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
355 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000356 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000358 clEnumValN(langkind_c, "c-header",
359 "C header"),
360 clEnumValN(langkind_objc, "objective-c-header",
361 "Objective-C header"),
362 clEnumValN(langkind_cxx, "c++-header",
363 "C++ header"),
364 clEnumValN(langkind_objcxx, "objective-c++-header",
365 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000366 clEnumValN(langkind_ast, "ast",
367 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 clEnumValEnd));
369
370static llvm::cl::opt<bool>
Chris Lattner2c78b872009-04-14 23:22:57 +0000371ObjCExclusiveGC("fobjc-gc-only",
372 llvm::cl::desc("Use GC exclusively for Objective-C related "
373 "memory management"));
374
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000375static llvm::cl::opt<std::string>
376ObjCConstantStringClass("fconstant-string-class",
377 llvm::cl::value_desc("class name"),
378 llvm::cl::desc("Specify the class to use for constant "
379 "Objective-C string objects."));
380
Chris Lattner2c78b872009-04-14 23:22:57 +0000381static llvm::cl::opt<bool>
382ObjCEnableGC("fobjc-gc",
383 llvm::cl::desc("Enable Objective-C garbage collection"));
384
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000385static llvm::cl::opt<bool>
386ObjCEnableGCBitmapPrint("print-ivar-layout",
387 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
388
Chris Lattner2c78b872009-04-14 23:22:57 +0000389static llvm::cl::opt<LangOptions::VisibilityMode>
390SymbolVisibility("fvisibility",
391 llvm::cl::desc("Set the default symbol visibility:"),
392 llvm::cl::init(LangOptions::Default),
393 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
394 "Use default symbol visibility"),
395 clEnumValN(LangOptions::Hidden, "hidden",
396 "Use hidden symbol visibility"),
397 clEnumValN(LangOptions::Protected,"protected",
398 "Use protected symbol visibility"),
399 clEnumValEnd));
400
401static llvm::cl::opt<bool>
402OverflowChecking("ftrapv",
403 llvm::cl::desc("Trap on integer overflow"),
404 llvm::cl::init(false));
405
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000406static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000407AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
408 llvm::cl::init(false));
409
410static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000411PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
412 llvm::cl::init(false));
413
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000414static LangKind GetLanguage(llvm::StringRef Filename) {
Ted Kremenek8904f152007-12-05 23:49:08 +0000415 if (BaseLang != langkind_unspecified)
416 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000418 llvm::StringRef Ext = Filename.rsplit('.').second;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000419 if (Ext == "ast")
420 return langkind_ast;
421 else if (Ext == "c")
Ted Kremenek8904f152007-12-05 23:49:08 +0000422 return langkind_c;
Daniel Dunbar9f435342009-09-17 00:47:27 +0000423 else if (Ext == "S" || Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000424 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000425 else if (Ext == "i")
426 return langkind_c_cpp;
427 else if (Ext == "ii")
428 return langkind_cxx_cpp;
429 else if (Ext == "m")
430 return langkind_objc;
431 else if (Ext == "mi")
432 return langkind_objc_cpp;
433 else if (Ext == "mm" || Ext == "M")
434 return langkind_objcxx;
435 else if (Ext == "mii")
436 return langkind_objcxx_cpp;
437 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
438 Ext == "c++" || Ext == "cp" || Ext == "cxx")
439 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000440 else if (Ext == "cl")
441 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000442 else
443 return langkind_c;
444}
445
446
Ted Kremenek85888962008-10-21 00:54:44 +0000447static void InitializeCOptions(LangOptions &Options) {
448 // Do nothing.
449}
450
451static void InitializeObjCOptions(LangOptions &Options) {
452 Options.ObjC1 = Options.ObjC2 = 1;
453}
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Ted Kremenek85888962008-10-21 00:54:44 +0000455
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000456static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // FIXME: implement -fpreprocessed mode.
458 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Ted Kremenek8904f152007-12-05 23:49:08 +0000460 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000462 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000463 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000464 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 case langkind_c_cpp:
466 NoPreprocess = true;
467 // FALLTHROUGH
468 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000469 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 break;
471 case langkind_cxx_cpp:
472 NoPreprocess = true;
473 // FALLTHROUGH
474 case langkind_cxx:
475 Options.CPlusPlus = 1;
476 break;
477 case langkind_objc_cpp:
478 NoPreprocess = true;
479 // FALLTHROUGH
480 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000481 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 break;
483 case langkind_objcxx_cpp:
484 NoPreprocess = true;
485 // FALLTHROUGH
486 case langkind_objcxx:
487 Options.ObjC1 = Options.ObjC2 = 1;
488 Options.CPlusPlus = 1;
489 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000490 case langkind_ocl:
491 Options.OpenCL = 1;
492 Options.AltiVec = 1;
493 Options.CXXOperatorNames = 1;
494 Options.LaxVectorConversions = 1;
495 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Chris Lattner2c78b872009-04-14 23:22:57 +0000498 if (ObjCExclusiveGC)
499 Options.setGCMode(LangOptions::GCOnly);
500 else if (ObjCEnableGC)
501 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000503 if (ObjCEnableGCBitmapPrint)
504 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Nate Begeman2ef13e52009-08-10 23:49:36 +0000506 if (AltiVec)
507 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000508
509 if (PThread)
510 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner2c78b872009-04-14 23:22:57 +0000512 Options.setVisibilityMode(SymbolVisibility);
513 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000514}
515
516/// LangStds - Language standards we support.
517enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000518 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 lang_c89, lang_c94, lang_c99,
Douglas Gregor214904e2009-09-29 14:42:43 +0000520 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000521 lang_cxx98, lang_gnucxx98,
522 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000523};
524
525static llvm::cl::opt<LangStds>
526LangStd("std", llvm::cl::desc("Language standard to compile for"),
527 llvm::cl::init(lang_unspecified),
528 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
529 clEnumValN(lang_c89, "c90", "ISO C 1990"),
530 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
531 clEnumValN(lang_c94, "iso9899:199409",
532 "ISO C 1990 with amendment 1"),
533 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000534 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000536 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000538 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000540 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000541 clEnumValN(lang_gnu99, "gnu9x",
542 "ISO C 1999 with GNU extensions"),
543 clEnumValN(lang_cxx98, "c++98",
544 "ISO C++ 1998 with amendments"),
545 clEnumValN(lang_gnucxx98, "gnu++98",
546 "ISO C++ 1998 with amendments and GNU "
547 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000548 clEnumValN(lang_cxx0x, "c++0x",
549 "Upcoming ISO C++ 200x with amendments"),
550 clEnumValN(lang_gnucxx0x, "gnu++0x",
551 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000552 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 clEnumValEnd));
554
555static llvm::cl::opt<bool>
556NoOperatorNames("fno-operator-names",
557 llvm::cl::desc("Do not treat C++ operator name keywords as "
558 "synonyms for operators"));
559
Anders Carlssonee98ac52007-10-15 02:50:23 +0000560static llvm::cl::opt<bool>
561PascalStrings("fpascal-strings",
562 llvm::cl::desc("Recognize and construct Pascal-style "
563 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Steve Naroffd62701b2008-02-07 03:50:06 +0000565static llvm::cl::opt<bool>
566MSExtensions("fms-extensions",
567 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000568 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000569
570static llvm::cl::opt<bool>
571WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000572 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000573
574static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000575NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000576 llvm::cl::desc("Disallow implicit conversions between "
577 "vectors with a different number of "
578 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000579
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000580static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000581EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000582
583static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000584EnableHeinousExtensions("fheinous-gnu-extensions",
585 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
586 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
587
588static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000589ObjCNonFragileABI("fobjc-nonfragile-abi",
590 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000591
Daniel Dunbard6884a02009-05-04 05:16:21 +0000592
593static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000594EmitAllDecls("femit-all-decls",
595 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000596
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000597static llvm::cl::opt<bool>
598Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000599 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000600
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000601static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000602Rtti("frtti", llvm::cl::init(true),
603 llvm::cl::desc("Enable generation of rtti information"));
604
605static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000606GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000607 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000608 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000609
610static llvm::cl::opt<bool>
611NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000612 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000613 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000614
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000615static llvm::cl::opt<bool>
616CharIsSigned("fsigned-char",
617 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000618
619
620static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000621Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000622
Douglas Gregor26dce442009-03-10 00:06:19 +0000623static llvm::cl::opt<unsigned>
624TemplateDepth("ftemplate-depth", llvm::cl::init(99),
625 llvm::cl::desc("Maximum depth of recursive template "
626 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000627static llvm::cl::opt<bool>
628DollarsInIdents("fdollars-in-identifiers",
629 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000630
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000631
632static llvm::cl::opt<bool>
633OptSize("Os", llvm::cl::desc("Optimize for size"));
634
635static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000636DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000637 llvm::cl::desc("Don't run LLVM optimization passes"));
638
639static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000640NoCommon("fno-common",
641 llvm::cl::desc("Compile common globals like normal definitions"),
642 llvm::cl::ValueDisallowed);
643
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000644static llvm::cl::opt<std::string>
645MainFileName("main-file-name",
646 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000647
Anders Carlssona33d9b42009-05-13 19:49:53 +0000648// FIXME: Also add an "-fno-access-control" option.
649static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000650AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000651 llvm::cl::desc("Enable C++ access control"));
652
Anders Carlsson92f58222009-08-22 22:30:33 +0000653static llvm::cl::opt<bool>
654NoElideConstructors("fno-elide-constructors",
655 llvm::cl::desc("Disable C++ copy constructor elision"));
656
Tanya Lattner59876c22009-11-04 01:18:09 +0000657static llvm::cl::opt<bool>
658NoMergeConstants("fno-merge-all-constants",
659 llvm::cl::desc("Disallow merging of constants."));
660
Daniel Dunbar73b79592009-09-14 00:02:12 +0000661static llvm::cl::opt<std::string>
662TargetABI("target-abi",
663 llvm::cl::desc("Target a particular ABI type"));
664
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000665static llvm::cl::opt<std::string>
666TargetTriple("triple",
667 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
668
Anders Carlsson92f58222009-08-22 22:30:33 +0000669
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000670// It might be nice to add bounds to the CommandLine library directly.
671struct OptLevelParser : public llvm::cl::parser<unsigned> {
Chris Lattner59b21722009-09-20 00:39:15 +0000672 bool parse(llvm::cl::Option &O, llvm::StringRef ArgName,
673 llvm::StringRef Arg, unsigned &Val) {
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000674 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
675 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000676 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000677 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000678 return false;
679 }
680};
681static llvm::cl::opt<unsigned, false, OptLevelParser>
682OptLevel("O", llvm::cl::Prefix,
683 llvm::cl::desc("Optimization level"),
684 llvm::cl::init(0));
685
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000686static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000687PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
688
689static llvm::cl::opt<bool>
690StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000691
Bill Wendling45483f72009-06-28 07:36:13 +0000692static llvm::cl::opt<int>
693StackProtector("stack-protector",
694 llvm::cl::desc("Enable stack protectors"),
695 llvm::cl::init(-1));
696
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000697static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000698 TargetInfo *Target,
699 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000700 // Allow the target to set the default the langauge options as it sees fit.
701 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000702
703 // Pass the map of target features to the target for validation and
704 // processing.
705 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 if (LangStd == lang_unspecified) {
708 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000709 switch (LK) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000710 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000711 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000712 case langkind_ocl:
713 LangStd = lang_c99;
714 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000716 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 case langkind_c_cpp:
718 case langkind_objc:
719 case langkind_objc_cpp:
720 LangStd = lang_gnu99;
721 break;
722 case langkind_cxx:
723 case langkind_cxx_cpp:
724 case langkind_objcxx:
725 case langkind_objcxx_cpp:
726 LangStd = lang_gnucxx98;
727 break;
728 }
729 }
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 switch (LangStd) {
732 default: assert(0 && "Unknown language standard!");
733
734 // Fall through from newer standards to older ones. This isn't really right.
735 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000736 case lang_gnucxx0x:
737 case lang_cxx0x:
738 Options.CPlusPlus0x = 1;
739 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 case lang_gnucxx98:
741 case lang_cxx98:
742 Options.CPlusPlus = 1;
743 Options.CXXOperatorNames = !NoOperatorNames;
744 // FALL THROUGH.
745 case lang_gnu99:
746 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 Options.C99 = 1;
748 Options.HexFloats = 1;
749 // FALL THROUGH.
750 case lang_gnu89:
751 Options.BCPLComment = 1; // Only for C99/C++.
752 // FALL THROUGH.
753 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000754 Options.Digraphs = 1; // C94, C99, C++.
755 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 case lang_c89:
757 break;
758 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000759
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000760 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
Douglas Gregor214904e2009-09-29 14:42:43 +0000761 switch (LangStd) {
762 default: assert(0 && "Unknown language standard!");
763 case lang_gnucxx0x:
764 case lang_gnucxx98:
765 case lang_gnu99:
766 case lang_gnu89:
767 Options.GNUMode = 1;
768 break;
769 case lang_cxx0x:
770 case lang_cxx98:
771 case lang_c99:
772 case lang_c94:
773 case lang_c89:
774 Options.GNUMode = 0;
775 break;
776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000778 if (Options.CPlusPlus) {
779 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000780 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000781 }
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattnerd658b562008-04-05 06:32:51 +0000783 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
784 Options.ImplicitInt = 1;
785 else
786 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Daniel Dunbard573d262009-04-07 22:13:21 +0000788 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
789 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000790 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000791 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000792 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000793
Chris Lattner802db9b2008-12-05 00:10:44 +0000794 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
795 // even if they are normally on for the target. In GNU modes (e.g.
796 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000797 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000798 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000799 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Chris Lattner01638a62009-04-19 07:06:52 +0000801 // Default to not accepting '$' in identifiers when preprocessing assembler,
802 // but do accept when preprocessing C. FIXME: these defaults are right for
803 // darwin, are they right everywhere?
804 Options.DollarIdents = LK != langkind_asm_cpp;
805 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000806 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Chris Lattnerae0ee032008-12-04 23:20:07 +0000808 if (PascalStrings.getPosition())
809 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000810 if (MSExtensions.getPosition())
811 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000812 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000813 if (NoLaxVectorConversions.getPosition())
814 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000815 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000816 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000817 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000818 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000819 if (CharIsSigned.getPosition())
820 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000821
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000822 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000823 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000824 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000825 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattner810f6d52009-03-13 17:38:01 +0000827 if (EnableHeinousExtensions)
828 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000829
Anders Carlssona33d9b42009-05-13 19:49:53 +0000830 if (AccessControl)
831 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Anders Carlsson92f58222009-08-22 22:30:33 +0000833 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Chris Lattnere4f21422009-06-30 01:26:17 +0000835 // OpenCL and C++ both have bool, true, false keywords.
836 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000838 Options.MathErrno = MathErrno;
839
Douglas Gregor26dce442009-03-10 00:06:19 +0000840 Options.InstantiationDepth = TemplateDepth;
841
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000842 // Override the default runtime if the user requested it.
843 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000844 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000845 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000846 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000847
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000848 if (!ObjCConstantStringClass.empty())
849 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
850
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000851 if (ObjCNonFragileABI)
852 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000853
Daniel Dunbard604c402009-02-04 21:19:06 +0000854 if (EmitAllDecls)
855 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000856
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000857 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
858 // support.
859 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000861 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000862 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000863 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000864
865 assert(PICLevel <= 2 && "Invalid value for -pic-level");
866 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000867
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000868 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000869 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000870 Options.NoInline = !OptSize && !OptLevel;
871
872 Options.Static = StaticDefine;
873
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000874 switch (StackProtector) {
875 default:
876 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
877 case -1: break;
878 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
879 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
880 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
881 }
Bill Wendling45483f72009-06-28 07:36:13 +0000882
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000883 if (MainFileName.getPosition())
884 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000885}
886
887//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000888// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000889//===----------------------------------------------------------------------===//
890
Douglas Gregore1d918e2009-04-10 23:10:45 +0000891static bool InitializeSourceManager(Preprocessor &PP,
892 const std::string &InFile) {
893 // Figure out where to get and map in the main file.
894 SourceManager &SourceMgr = PP.getSourceManager();
895 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000896
897 if (EmptyInputOnly) {
898 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000899 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000900 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
901 SourceMgr.createMainFileIDForMemBuffer(SB);
902 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000903 const FileEntry *File = FileMgr.getFile(InFile);
904 if (File) SourceMgr.createMainFileID(File, SourceLocation());
905 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000906 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +0000907 << InFile.c_str();
908 return true;
909 }
910 } else {
911 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
912
913 // If stdin was empty, SB is null. Cons up an empty memory
914 // buffer now.
915 if (!SB) {
916 const char *EmptyStr = "";
917 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
918 }
919
920 SourceMgr.createMainFileIDForMemBuffer(SB);
921 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000922 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +0000923 diag::err_fe_error_reading_stdin);
924 return true;
925 }
926 }
927
928 return false;
929}
930
Chris Lattneraa391972008-04-19 23:09:31 +0000931
Chris Lattnere116ccf2009-04-21 05:40:52 +0000932//===----------------------------------------------------------------------===//
933// Preprocessor Initialization
934//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000935
Chris Lattnere116ccf2009-04-21 05:40:52 +0000936// FIXME: Preprocessor builtins to support.
937// -A... - Play with #assertions
938// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +0000939
Chris Lattnere6113de2009-11-03 19:50:27 +0000940static llvm::cl::opt<bool>
941undef_macros("undef", llvm::cl::value_desc("macro"), llvm::cl::desc("undef all system defines"));
942
Chris Lattnere116ccf2009-04-21 05:40:52 +0000943static llvm::cl::list<std::string>
944D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
945 llvm::cl::desc("Predefine the specified macro"));
946static llvm::cl::list<std::string>
947U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
948 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000949
Chris Lattnere116ccf2009-04-21 05:40:52 +0000950static llvm::cl::list<std::string>
951ImplicitIncludes("include", llvm::cl::value_desc("file"),
952 llvm::cl::desc("Include file before parsing"));
953static llvm::cl::list<std::string>
954ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
955 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000956
Chris Lattnere116ccf2009-04-21 05:40:52 +0000957static llvm::cl::opt<std::string>
958ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
959 llvm::cl::desc("Include precompiled header file"));
960
961static llvm::cl::opt<std::string>
962ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
963 llvm::cl::desc("Include file before parsing"));
964
Douglas Gregore650c8c2009-07-07 00:12:59 +0000965static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000966RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000967 llvm::cl::desc("Whether to build a relocatable precompiled "
968 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000969
970//===----------------------------------------------------------------------===//
971// Preprocessor include path information.
972//===----------------------------------------------------------------------===//
973
974// This tool exports a large number of command line options to control how the
975// preprocessor searches for header files. At root, however, the Preprocessor
976// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +0000977//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +0000978// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000979// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000980//
Reid Spencer5f016e22007-07-11 17:01:13 +0000981
982static llvm::cl::opt<bool>
983nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
984
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000985static llvm::cl::opt<bool>
Rafael Espindola8d737cc2009-10-26 13:36:57 +0000986nobuiltininc("nobuiltininc",
987 llvm::cl::desc("Disable builtin #include directories"));
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000988
Reid Spencer5f016e22007-07-11 17:01:13 +0000989// Various command line options. These four add directories to each chain.
990static llvm::cl::list<std::string>
991F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
992 llvm::cl::desc("Add directory to framework include search path"));
993static llvm::cl::list<std::string>
994I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
995 llvm::cl::desc("Add directory to include search path"));
996static llvm::cl::list<std::string>
997idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
998 llvm::cl::desc("Add directory to AFTER include search path"));
999static llvm::cl::list<std::string>
1000iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1001 llvm::cl::desc("Add directory to QUOTE include search path"));
1002static llvm::cl::list<std::string>
1003isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1004 llvm::cl::desc("Add directory to SYSTEM include search path"));
1005
1006// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1007static llvm::cl::list<std::string>
1008iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1009 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1010static llvm::cl::list<std::string>
1011iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1012 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1013static llvm::cl::list<std::string>
1014iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1015 llvm::cl::Prefix,
1016 llvm::cl::desc("Set directory to include search path with prefix"));
1017
Chris Lattner0c946412007-08-26 17:47:35 +00001018static llvm::cl::opt<std::string>
1019isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1020 llvm::cl::desc("Set the system root directory (usually /)"));
1021
Reid Spencer5f016e22007-07-11 17:01:13 +00001022// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001023
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001024// Add the clang headers, which are relative to the clang binary.
1025void AddClangIncludePaths(const char *Argv0, InitHeaderSearch *Init) {
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001026 llvm::sys::Path MainExecutablePath =
1027 llvm::sys::Path::GetMainExecutable(Argv0,
1028 (void*)(intptr_t)AddClangIncludePaths);
1029 if (MainExecutablePath.isEmpty())
1030 return;
1031
1032 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1033 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1034
1035 // Get foo/lib/clang/<version>/include
1036 MainExecutablePath.appendComponent("lib");
1037 MainExecutablePath.appendComponent("clang");
1038 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
1039 MainExecutablePath.appendComponent("include");
1040
1041 // We pass true to ignore sysroot so that we *always* look for clang headers
1042 // relative to our executable, never relative to -isysroot.
1043 Init->AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1044 false, false, false, true /*ignore sysroot*/);
1045}
1046
Reid Spencer5f016e22007-07-11 17:01:13 +00001047/// InitializeIncludePaths - Process the -I options and set them in the
1048/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001049void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
Mike Stump43d81762009-10-08 23:29:47 +00001050 FileManager &FM, const LangOptions &Lang,
1051 llvm::Triple &triple) {
Nico Weber0fca0222008-08-22 09:25:22 +00001052 InitHeaderSearch Init(Headers, Verbose, isysroot);
1053
Ted Kremenekf3721112008-05-31 00:27:00 +00001054 // Handle -I... and -F... options, walking the lists in parallel.
1055 unsigned Iidx = 0, Fidx = 0;
1056 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1057 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001058 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001059 ++Iidx;
1060 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001061 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001062 ++Fidx;
1063 }
1064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Ted Kremenekf3721112008-05-31 00:27:00 +00001066 // Consume what's left from whatever list was longer.
1067 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001068 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001069 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001070 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 // Handle -idirafter... options.
1073 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001074 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1075 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 // Handle -iquote... options.
1078 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001079 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 // Handle -isystem... options.
1082 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001083 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001084
1085 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1086 // parallel, processing the values in order of occurance to get the right
1087 // prefixes.
1088 {
1089 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1090 unsigned iprefix_idx = 0;
1091 unsigned iwithprefix_idx = 0;
1092 unsigned iwithprefixbefore_idx = 0;
1093 bool iprefix_done = iprefix_vals.empty();
1094 bool iwithprefix_done = iwithprefix_vals.empty();
1095 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1096 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1097 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001098 (iwithprefix_done ||
1099 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001101 (iwithprefixbefore_done ||
1102 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1104 Prefix = iprefix_vals[iprefix_idx];
1105 ++iprefix_idx;
1106 iprefix_done = iprefix_idx == iprefix_vals.size();
1107 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001108 (iwithprefixbefore_done ||
1109 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001111 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001112 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 ++iwithprefix_idx;
1114 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1115 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001116 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001117 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001119 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1121 }
1122 }
1123 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001124
Nico Weber0fca0222008-08-22 09:25:22 +00001125 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001126
Rafael Espindola8d737cc2009-10-26 13:36:57 +00001127 if (!nobuiltininc)
Daniel Dunbar8b88ca62009-10-17 09:04:56 +00001128 AddClangIncludePaths(Argv0, &Init);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
1130 if (!nostdinc)
Mike Stump43d81762009-10-08 23:29:47 +00001131 Init.AddDefaultSystemIncludePaths(Lang, triple);
Reid Spencer5f016e22007-07-11 17:01:13 +00001132
1133 // Now that we have collected all of the include paths, merge them all
1134 // together and tell the preprocessor about them.
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Nico Weber0fca0222008-08-22 09:25:22 +00001136 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001137}
1138
Mike Stump1eb44332009-09-09 15:08:12 +00001139void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001140 // Add macros from the command line.
1141 unsigned d = 0, D = D_macros.size();
1142 unsigned u = 0, U = U_macros.size();
1143 while (d < D || u < U) {
1144 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1145 InitOpts.addMacroDef(D_macros[d++]);
1146 else
1147 InitOpts.addMacroUndef(U_macros[u++]);
1148 }
1149
1150 // If -imacros are specified, include them now. These are processed before
1151 // any -include directives.
1152 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1153 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1154
Douglas Gregorb64c1932009-05-12 01:31:05 +00001155 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1156 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001157 // We want to add these paths to the predefines buffer in order, make a
1158 // temporary vector to sort by their occurrence.
1159 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1160
1161 if (!ImplicitIncludePTH.empty())
1162 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1163 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001164 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1165 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1166 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001167 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1168 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1169 &ImplicitIncludes[i]));
1170 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1171
1172
1173 // Now that they are ordered by position, add to the predefines buffer.
1174 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1175 std::string *Ptr = OrderedPaths[i].second;
1176 if (!ImplicitIncludes.empty() &&
1177 Ptr >= &ImplicitIncludes[0] &&
1178 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1179 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001180 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001181 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001182 } else {
1183 // We end up here when we're producing preprocessed output and
1184 // we loaded a PCH file. In this case, just include the header
1185 // file that was used to build the precompiled header.
1186 assert(Ptr == &ImplicitIncludePCH);
1187 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1188 if (!OriginalFile.empty()) {
1189 InitOpts.addInclude(OriginalFile, false);
1190 ImplicitIncludePCH.clear();
1191 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001192 }
1193 }
1194 }
1195}
1196
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001197//===----------------------------------------------------------------------===//
1198// Driver PreprocessorFactory - For lazily generating preprocessors ...
1199//===----------------------------------------------------------------------===//
1200
1201namespace {
1202class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1203 Diagnostic &Diags;
1204 const LangOptions &LangInfo;
1205 TargetInfo &Target;
1206 SourceManager &SourceMgr;
1207 HeaderSearch &HeaderInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001209public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001210 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001211 TargetInfo &target, SourceManager &SM,
Mike Stump1eb44332009-09-09 15:08:12 +00001212 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001213 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001214 SourceMgr(SM), HeaderInfo(Headers) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001215
1216
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001217 virtual ~DriverPreprocessorFactory() {}
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001219 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001220 llvm::OwningPtr<PTHManager> PTHMgr;
1221
Ted Kremenek748d5d62009-03-20 00:26:38 +00001222 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1223 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1224 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001225 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Ted Kremenek72b1b152009-01-15 18:47:46 +00001228 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001229 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1230 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Mike Stump1eb44332009-09-09 15:08:12 +00001231 PTHMgr.reset(PTHManager::Create(x, &Diags,
Ted Kremenek22f0d092009-03-22 06:42:39 +00001232 TokenCache.empty() ? Diagnostic::Error
1233 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Ted Kremenek22f0d092009-03-22 06:42:39 +00001236 if (Diags.hasErrorOccurred())
1237 exit(1);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Ted Kremenek72b1b152009-01-15 18:47:46 +00001239 // Create the Preprocessor.
1240 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1241 SourceMgr, HeaderInfo,
1242 PTHMgr.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Ted Kremenek72b1b152009-01-15 18:47:46 +00001244 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1245 // That argument is used as the IdentifierInfoLookup argument to
1246 // IdentifierTable's ctor.
1247 if (PTHMgr) {
1248 PTHMgr->setPreprocessor(PP.get());
1249 PP->setPTHManager(PTHMgr.take());
1250 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001251
Chris Lattnere116ccf2009-04-21 05:40:52 +00001252 PreprocessorInitOptions InitOpts;
1253 InitializePreprocessorInitOptions(InitOpts);
Chris Lattnere6113de2009-11-03 19:50:27 +00001254 if (InitializePreprocessor(*PP, InitOpts, undef_macros))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001255 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001256
Douglas Gregore1d918e2009-04-10 23:10:45 +00001257 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001258 }
1259};
1260}
Reid Spencer5f016e22007-07-11 17:01:13 +00001261
Reid Spencer5f016e22007-07-11 17:01:13 +00001262//===----------------------------------------------------------------------===//
1263// Basic Parser driver
1264//===----------------------------------------------------------------------===//
1265
Chris Lattner51574ea2008-04-19 23:25:44 +00001266static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001268 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 // Parsing the specified input file.
1271 P.ParseTranslationUnit();
1272 delete PA;
1273}
1274
1275//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001276// Code generation options
1277//===----------------------------------------------------------------------===//
1278
1279static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001280GenerateDebugInfo("g",
1281 llvm::cl::desc("Generate source level debug information"));
1282
Daniel Dunbara034ba82009-02-17 19:47:34 +00001283static llvm::cl::opt<std::string>
1284TargetCPU("mcpu",
1285 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1286
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001287static llvm::cl::list<std::string>
1288TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1289
Devang Patel24095da2009-06-04 23:32:02 +00001290
1291static llvm::cl::opt<bool>
1292DisableRedZone("disable-red-zone",
1293 llvm::cl::desc("Do not emit code that uses the red zone."),
1294 llvm::cl::init(false));
1295
Devang Patelacebb392009-06-05 22:05:48 +00001296static llvm::cl::opt<bool>
1297NoImplicitFloat("no-implicit-float",
1298 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1299 llvm::cl::init(false));
1300
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001301/// ComputeTargetFeatures - Recompute the target feature list to only
1302/// be the list of things that are enabled, based on the target cpu
1303/// and feature list.
1304static void ComputeFeatureMap(TargetInfo *Target,
1305 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001306 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001307
1308 // Initialize the feature map based on the target.
1309 Target->getDefaultFeatures(TargetCPU, Features);
1310
1311 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001312 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001313 ie = TargetFeatures.end(); it != ie; ++it) {
1314 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001316 // FIXME: Don't handle errors like this.
1317 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001318 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001319 Name);
1320 exit(1);
1321 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001322 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001323 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001324 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001325 exit(1);
1326 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001327 }
1328}
1329
Chris Lattner7afae712009-03-16 18:41:18 +00001330static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001331 const LangOptions &LangOpts,
1332 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001333 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001334 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001335
1336 if (DisableLLVMOptimizations) {
1337 Opts.OptimizationLevel = 0;
1338 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001339 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001340 if (OptSize) {
1341 // -Os implies -O2
1342 Opts.OptimizationLevel = 2;
1343 } else {
1344 Opts.OptimizationLevel = OptLevel;
1345 }
1346
1347 // We must always run at least the always inlining pass.
1348 if (Opts.OptimizationLevel > 1)
1349 Opts.Inlining = CompileOptions::NormalInlining;
1350 else
1351 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001352 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001353
1354 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001355 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001356 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001357
1358#ifdef NDEBUG
1359 Opts.VerifyModule = 0;
1360#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001361
1362 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001363 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001364 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001365 ie = Features.end(); it != ie; ++it) {
1366 // FIXME: If we are completely confident that we have the right
1367 // set, we only need to pass the minuses.
1368 std::string Name(it->second ? "+" : "-");
1369 Name += it->first();
1370 Opts.Features.push_back(Name);
1371 }
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Chris Lattnerbd360642009-03-26 05:00:52 +00001373 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Chris Lattner44502662009-02-18 01:23:44 +00001375 // Handle -ftime-report.
1376 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001377
1378 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001379 Opts.NoImplicitFloat = NoImplicitFloat;
Tanya Lattner59876c22009-11-04 01:18:09 +00001380
1381 Opts.MergeAllConstants = !NoMergeConstants;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001382}
1383
1384//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001385// Fix-It Options
1386//===----------------------------------------------------------------------===//
1387static llvm::cl::list<ParsedSourceLocation>
1388FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1389 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1390
1391//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001392// ObjC Rewriter Options
1393//===----------------------------------------------------------------------===//
1394static llvm::cl::opt<bool>
1395SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1396 llvm::cl::desc("Silence ObjC rewriting warnings"));
1397
1398//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001399// Warning Options
1400//===----------------------------------------------------------------------===//
1401
1402// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1403// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1404// -Wextra, so we don't need to worry about it.
1405static llvm::cl::list<std::string>
1406OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1407
1408static llvm::cl::opt<bool> OptPedantic("pedantic");
1409static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1410static llvm::cl::opt<bool> OptNoWarnings("w");
1411
1412//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001413// Preprocessing (-E mode) Options
1414//===----------------------------------------------------------------------===//
1415static llvm::cl::opt<bool>
1416DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1417static llvm::cl::opt<bool>
1418EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1419static llvm::cl::opt<bool>
1420EnableMacroCommentOutput("CC",
1421 llvm::cl::desc("Enable comment output in -E mode, "
1422 "even from macro expansions"));
1423static llvm::cl::opt<bool>
1424DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1425 " normal output"));
1426static llvm::cl::opt<bool>
1427DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1428 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001429
1430//===----------------------------------------------------------------------===//
1431// Dependency file options
1432//===----------------------------------------------------------------------===//
1433static llvm::cl::opt<std::string>
1434DependencyFile("dependency-file",
1435 llvm::cl::desc("Filename (or -) to write dependency output to"));
1436
1437static llvm::cl::opt<bool>
1438DependenciesIncludeSystemHeaders("sys-header-deps",
1439 llvm::cl::desc("Include system headers in dependency output"));
1440
1441static llvm::cl::list<std::string>
1442DependencyTargets("MT",
1443 llvm::cl::desc("Specify target for dependency"));
1444
1445// FIXME: Implement feature
1446static llvm::cl::opt<bool>
1447PhonyDependencyTarget("MP",
1448 llvm::cl::desc("Create phony target for each dependency "
1449 "(other than main file)"));
1450
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001451//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001452// Analysis options
1453//===----------------------------------------------------------------------===//
1454
1455static llvm::cl::list<Analyses>
1456AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1457llvm::cl::values(
1458#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1459clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001460#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001461clEnumValEnd));
1462
Mike Stump1eb44332009-09-09 15:08:12 +00001463static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001464AnalysisStoreOpt("analyzer-store",
1465 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1466 llvm::cl::init(BasicStoreModel),
1467 llvm::cl::values(
1468#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1469clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001470#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001471clEnumValEnd));
1472
Mike Stump1eb44332009-09-09 15:08:12 +00001473static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001474AnalysisConstraintsOpt("analyzer-constraints",
1475 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1476 llvm::cl::init(RangeConstraintsModel),
1477 llvm::cl::values(
1478#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1479clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001480#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001481clEnumValEnd));
1482
1483static llvm::cl::opt<AnalysisDiagClients>
1484AnalysisDiagOpt("analyzer-output",
1485 llvm::cl::desc("Source Code Analysis - Output Options"),
1486 llvm::cl::init(PD_HTML),
1487 llvm::cl::values(
1488#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1489clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001490#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001491clEnumValEnd));
1492
1493static llvm::cl::opt<bool>
1494VisualizeEGDot("analyzer-viz-egraph-graphviz",
1495 llvm::cl::desc("Display exploded graph using GraphViz"));
1496
1497static llvm::cl::opt<bool>
1498VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1499 llvm::cl::desc("Display exploded graph using Ubigraph"));
1500
1501static llvm::cl::opt<bool>
1502AnalyzeAll("analyzer-opt-analyze-headers",
1503 llvm::cl::desc("Force the static analyzer to analyze "
1504 "functions defined in header files"));
1505
1506static llvm::cl::opt<bool>
1507AnalyzerDisplayProgress("analyzer-display-progress",
1508 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1509
1510static llvm::cl::opt<bool>
1511PurgeDead("analyzer-purge-dead",
1512 llvm::cl::init(true),
1513 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1514 " processing a statement."));
1515
1516static llvm::cl::opt<bool>
1517EagerlyAssume("analyzer-eagerly-assume",
1518 llvm::cl::init(false),
1519 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1520 "symbolic constraints."));
1521
1522static llvm::cl::opt<std::string>
1523AnalyzeSpecificFunction("analyze-function",
1524 llvm::cl::desc("Run analysis on specific function"));
1525
1526static llvm::cl::opt<bool>
1527TrimGraph("trim-egraph",
1528 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1529
1530static AnalyzerOptions ReadAnalyzerOptions() {
1531 AnalyzerOptions Opts;
1532 Opts.AnalysisList = AnalysisList;
1533 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1534 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1535 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1536 Opts.VisualizeEGDot = VisualizeEGDot;
1537 Opts.VisualizeEGUbi = VisualizeEGUbi;
1538 Opts.AnalyzeAll = AnalyzeAll;
1539 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1540 Opts.PurgeDead = PurgeDead;
1541 Opts.EagerlyAssume = EagerlyAssume;
1542 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1543 Opts.TrimGraph = TrimGraph;
1544 return Opts;
1545}
1546
1547//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001548// -dump-build-information Stuff
1549//===----------------------------------------------------------------------===//
1550
1551static llvm::cl::opt<std::string>
1552DumpBuildInformation("dump-build-information",
1553 llvm::cl::value_desc("filename"),
1554 llvm::cl::desc("output a dump of some build information to a file"));
1555
1556static llvm::raw_ostream *BuildLogFile = 0;
1557
1558/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1559/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1560namespace {
1561class LoggingDiagnosticClient : public DiagnosticClient {
1562 llvm::OwningPtr<DiagnosticClient> Chain1;
1563 llvm::OwningPtr<DiagnosticClient> Chain2;
1564public:
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Chris Lattner75a97cb2009-04-17 21:05:01 +00001566 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1567 // Output diags both where requested...
1568 Chain1.reset(Normal);
1569 // .. and to our log file.
Daniel Dunbareace8742009-11-04 06:24:30 +00001570 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile, DiagOpts));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001571 }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Chris Lattner75a97cb2009-04-17 21:05:01 +00001573 virtual void setLangOptions(const LangOptions *LO) {
1574 Chain1->setLangOptions(LO);
1575 Chain2->setLangOptions(LO);
1576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattner75a97cb2009-04-17 21:05:01 +00001578 virtual bool IncludeInDiagnosticCounts() const {
1579 return Chain1->IncludeInDiagnosticCounts();
1580 }
1581
1582 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1583 const DiagnosticInfo &Info) {
1584 Chain1->HandleDiagnostic(DiagLevel, Info);
1585 Chain2->HandleDiagnostic(DiagLevel, Info);
1586 }
1587};
1588} // end anonymous namespace.
1589
1590static void SetUpBuildDumpLog(unsigned argc, char **argv,
1591 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Chris Lattner75a97cb2009-04-17 21:05:01 +00001593 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001594 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001595 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Chris Lattner75a97cb2009-04-17 21:05:01 +00001597 if (!ErrorInfo.empty()) {
1598 llvm::errs() << "error opening -dump-build-information file '"
1599 << DumpBuildInformation << "', option ignored!\n";
1600 delete BuildLogFile;
1601 BuildLogFile = 0;
1602 DumpBuildInformation = "";
1603 return;
1604 }
1605
1606 (*BuildLogFile) << "clang-cc command line arguments: ";
1607 for (unsigned i = 0; i != argc; ++i)
1608 (*BuildLogFile) << argv[i] << ' ';
1609 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Chris Lattner75a97cb2009-04-17 21:05:01 +00001611 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1612 // the diagnostic producers and the normal receiver.
1613 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1614}
1615
1616
1617
1618//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001619// Main driver
1620//===----------------------------------------------------------------------===//
1621
Chris Lattner92bcc272009-08-23 02:59:41 +00001622static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1623 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001624 bool Binary,
1625 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001626 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001627 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001628 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001629 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001630 else if (InFile == "-") {
1631 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001632 } else if (Extension) {
1633 llvm::sys::Path Path(InFile);
1634 Path.eraseSuffix();
1635 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001636 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001637 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001638 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001639 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001640
Chris Lattner92bcc272009-08-23 02:59:41 +00001641 std::string Error;
1642 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001643 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001644 if (!Error.empty()) {
1645 // FIXME: Don't fail this way.
1646 llvm::errs() << "ERROR: " << Error << "\n";
1647 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001648 }
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Chris Lattner92bcc272009-08-23 02:59:41 +00001650 if (OutFile != "-")
1651 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001652
1653 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001654}
1655
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001656static ASTConsumer *CreateConsumerAction(Preprocessor &PP,
1657 const std::string &InFile,
1658 ProgActions PA,
1659 llvm::OwningPtr<llvm::raw_ostream> &OS,
1660 llvm::sys::Path &OutPath,
1661 const llvm::StringMap<bool> &Features,
1662 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +00001663 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001665 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +00001666
1667 case ASTPrint:
1668 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001669 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Douglas Gregoree75c052009-05-21 20:55:50 +00001671 case ASTPrintXML:
1672 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001673 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +00001674
Eli Friedman66d6f042009-05-18 22:20:00 +00001675 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001676 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +00001677
Eli Friedman66d6f042009-05-18 22:20:00 +00001678 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001679 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +00001680
1681 case PrintDeclContext:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001682 return CreateDeclContextPrinter();
Eli Friedman66d6f042009-05-18 22:20:00 +00001683
Anders Carlsson78762eb2009-09-24 18:54:49 +00001684 case DumpRecordLayouts:
1685 return CreateRecordLayoutDumper();
1686
Eli Friedman66d6f042009-05-18 22:20:00 +00001687 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001688 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +00001689
1690 case EmitAssembly:
1691 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001692 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001693 case EmitLLVMOnly: {
1694 BackendAction Act;
1695 if (ProgAction == EmitAssembly) {
1696 Act = Backend_EmitAssembly;
1697 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1698 } else if (ProgAction == EmitLLVM) {
1699 Act = Backend_EmitLL;
1700 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1701 } else if (ProgAction == EmitLLVMOnly) {
1702 Act = Backend_EmitNothing;
1703 } else {
1704 Act = Backend_EmitBC;
1705 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001706 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001707
Eli Friedman66d6f042009-05-18 22:20:00 +00001708 CompileOptions Opts;
1709 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001710 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
1711 Opts, InFile, OS.get(), Context);
Eli Friedman66d6f042009-05-18 22:20:00 +00001712 }
1713
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001714 case RewriteObjC:
1715 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
1716 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1717 PP.getLangOptions(), SilenceRewriteMacroWarning);
1718
1719 case RewriteBlocks:
1720 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1721 PP.getLangOptions());
1722 }
1723}
1724
1725/// ProcessInputFile - Process a single input file with the specified state.
1726///
1727static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1728 const std::string &InFile, ProgActions PA,
1729 const llvm::StringMap<bool> &Features,
1730 llvm::LLVMContext& Context) {
1731 llvm::OwningPtr<llvm::raw_ostream> OS;
1732 llvm::OwningPtr<ASTConsumer> Consumer;
1733 bool ClearSourceMgr = false;
1734 FixItRewriter *FixItRewrite = 0;
1735 bool CompleteTranslationUnit = true;
1736 llvm::sys::Path OutPath;
1737
1738 switch (PA) {
1739 default:
1740 Consumer.reset(CreateConsumerAction(PP, InFile, PA, OS, OutPath,
1741 Features, Context));
1742
1743 if (!Consumer.get()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001744 PP.getDiagnostics().Report(FullSourceLoc(),
1745 diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001746 return;
1747 }
1748
1749 break;;
1750
1751 case EmitHTML:
1752 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1753 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1754 break;
1755
1756 case RunAnalysis:
1757 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
1758 PP.getLangOptions(), OutputFile,
1759 ReadAnalyzerOptions()));
1760 break;
1761
Eli Friedman66d6f042009-05-18 22:20:00 +00001762 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001763 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1764 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1765 RelocatablePCH.setValue(false);
1766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Eli Friedman66d6f042009-05-18 22:20:00 +00001768 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001769 if (RelocatablePCH.getValue())
1770 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1771 else
1772 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001773 CompleteTranslationUnit = false;
1774 break;
1775
Chris Lattnerc106c102008-10-12 05:03:36 +00001776 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001777 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001778 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001779 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001780 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001781 RawLex.SetKeepWhitespaceMode(true);
1782
1783 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001784 RawLex.LexFromRawLexer(RawTok);
1785 while (RawTok.isNot(tok::eof)) {
1786 PP.DumpToken(RawTok, true);
1787 fprintf(stderr, "\n");
1788 RawLex.LexFromRawLexer(RawTok);
1789 }
1790 ClearSourceMgr = true;
1791 break;
1792 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001794 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001795 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001796 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001797 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 do {
1799 PP.Lex(Tok);
1800 PP.DumpToken(Tok, true);
1801 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001802 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001803 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 break;
1805 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001806 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001809 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001810 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001811 if (OutputFile.empty() || OutputFile == "-") {
1812 // FIXME: Don't fail this way.
1813 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001814 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001815 ::exit(1);
1816 }
1817 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1818 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001819 ClearSourceMgr = true;
1820 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001821 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001822
Chris Lattnercc7dea82009-04-27 22:02:30 +00001823 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001824 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001827 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Chris Lattner47099742009-02-18 01:51:21 +00001830 case ParsePrintCallbacks: {
1831 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001832 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1833 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001834 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 break;
Chris Lattner47099742009-02-18 01:51:21 +00001836 }
1837
1838 case ParseSyntaxOnly: { // -fsyntax-only
1839 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001840 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001841 break;
Chris Lattner47099742009-02-18 01:51:21 +00001842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001844 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001845 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1846 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001847 ClearSourceMgr = true;
1848 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Eli Friedmanf54fce82009-05-19 01:02:07 +00001850 case RewriteTest:
1851 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1852 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001853 ClearSourceMgr = true;
1854 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001855
1856 case FixIt:
1857 llvm::TimeRegion Timer(ClangFrontendTimer);
1858 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001859 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001860 PP.getSourceManager(),
1861 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001862 break;
Chris Lattner47099742009-02-18 01:51:21 +00001863 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001864
Chris Lattner1aee61a2009-04-27 21:25:27 +00001865 if (FixItAtLocations.size() > 0) {
1866 // Even without the "-fixit" flag, with may have some specific
1867 // locations where the user has requested fixes. Process those
1868 // locations now.
1869 if (!FixItRewrite)
1870 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1871 PP.getSourceManager(),
1872 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001873
Chris Lattner1aee61a2009-04-27 21:25:27 +00001874 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001875 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001876 Idx != Last; ++Idx) {
1877 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001878 if (ResolveParsedLocation(FixItAtLocations[Idx],
1879 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001880 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1881 FixItAtLocations[Idx].FileName.c_str());
1882 } else {
1883 FixItRewrite->addFixItLocation(Requested);
1884 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001885 }
1886 }
1887
Chris Lattner1aee61a2009-04-27 21:25:27 +00001888 if (!AddedFixitLocation) {
1889 // All of the fix-it locations were bad. Don't fix anything.
1890 delete FixItRewrite;
1891 FixItRewrite = 0;
1892 }
1893 }
1894
1895 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001896 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001897 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1898 PP.getSourceManager(),
1899 PP.getTargetInfo(),
1900 PP.getIdentifierTable(),
1901 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001902 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001903 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001904 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Chris Lattnercc7dea82009-04-27 22:02:30 +00001906 llvm::OwningPtr<PCHReader> Reader;
1907 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001909 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001910 // If the user specified -isysroot, it will be used for relocatable PCH
1911 // files.
1912 const char *isysrootPCH = 0;
1913 if (isysroot.getNumOccurrences() != 0)
1914 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Douglas Gregore650c8c2009-07-07 00:12:59 +00001916 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001918 // The user has asked us to include a precompiled header. Load
1919 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001920 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1921 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001922 // Set the predefines buffer as suggested by the PCH
1923 // reader. Typically, the predefines buffer will be empty.
1924 PP.setPredefines(Reader->getSuggestedPredefines());
1925
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001926 // Attach the PCH reader to the AST context as an external AST
1927 // source, so that declarations will be deserialized from the
1928 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001929 if (ContextOwner) {
1930 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001931 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001932 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001933 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001934 }
1935
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001936 case PCHReader::Failure:
1937 // Unrecoverable failure: don't even try to process the input
1938 // file.
1939 return;
1940
1941 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001942 // No suitable PCH file could be found. Return an error.
1943 return;
1944
1945#if 0
1946 // FIXME: We can recover from failed attempts to load PCH
1947 // files. This code will do so, if we ever want to enable it.
1948
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001949 // We delayed the initialization of builtins in the hope of
1950 // loading the PCH file. Since the PCH file could not be
1951 // loaded, initialize builtins now.
1952 if (ContextOwner)
1953 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001954#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001955 }
1956
1957 // Finish preprocessor initialization. We do this now (rather
1958 // than earlier) because this initialization creates new source
1959 // location entries in the source manager, which must come after
1960 // the source location entries for the PCH file.
1961 if (InitializeSourceManager(PP, InFile))
1962 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001963 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001964
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001965 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00001966 if (Consumer) {
1967 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
1968 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001969
Douglas Gregorb657f112009-09-22 21:11:38 +00001970 if (!CodeCompletionAt.FileName.empty()) {
1971 // Tell the source manager to chop off the given file at a specific
1972 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001973 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +00001974 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
1975 // Truncate the named file at the given line/column.
1976 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
1977 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001978
Douglas Gregorb657f112009-09-22 21:11:38 +00001979 // Set up the creation routine for code-completion.
1980 CreateCodeCompleter = BuildPrintingCodeCompleter;
1981 } else {
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001982 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregorb657f112009-09-22 21:11:38 +00001983 diag::err_fe_invalid_code_complete_file)
1984 << CodeCompletionAt.FileName;
1985 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00001986 }
1987
Mike Stump1eb44332009-09-09 15:08:12 +00001988 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00001989 CompleteTranslationUnit,
1990 CreateCodeCompleter, CreateCodeCompleterData);
1991 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001992
1993 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
1994 llvm::TimeRegion Timer(ClangFrontendTimer);
1995 Token Tok;
1996 // Start parsing the specified input file.
1997 PP.EnterMainSourceFile();
1998 do {
1999 PP.Lex(Tok);
2000 } while (Tok.isNot(tok::eof));
2001 ClearSourceMgr = true;
2002 } else if (PA == ParseNoop) { // -parse-noop
2003 llvm::TimeRegion Timer(ClangFrontendTimer);
2004 ParseFile(PP, new MinimalAction(PP));
2005 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002006 } else if (PA == PrintPreprocessedInput){ // -E mode.
2007 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002008 if (DumpMacros)
2009 DoPrintMacros(PP, OS.get());
2010 else
2011 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2012 EnableMacroCommentOutput,
2013 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002014 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Chris Lattner1aee61a2009-04-27 21:25:27 +00002017 if (FixItRewrite)
2018 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002019
2020 // Disable the consumer prior to the context, the consumer may perform actions
2021 // in its destructor which require the context.
2022 if (DisableFree)
2023 Consumer.take();
2024 else
2025 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Chris Lattner1aee61a2009-04-27 21:25:27 +00002027 // If in -disable-free mode, don't deallocate ASTContext.
2028 if (DisableFree)
2029 ContextOwner.take();
2030 else
2031 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002032
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002033 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002034 if (CheckDiagnostics(PP))
2035 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002036
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002038 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 PP.PrintStats();
2040 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002041 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002042 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 fprintf(stderr, "\n");
2044 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002045
Mike Stump1eb44332009-09-09 15:08:12 +00002046 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002047 // manager tables, other require stable fileid/macroid's across multiple
2048 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002049 if (ClearSourceMgr)
2050 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002051
Eli Friedman66d6f042009-05-18 22:20:00 +00002052 // Always delete the output stream because we don't want to leak file
2053 // handles. Also, we don't want to try to erase an open file.
2054 OS.reset();
2055
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002056 // If we had errors, try to erase the output file.
2057 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +00002058 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +00002059}
2060
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002061/// ProcessInputFile - Process a single AST input file with the specified state.
2062///
2063static void ProcessASTInputFile(const std::string &InFile, ProgActions PA,
2064 const llvm::StringMap<bool> &Features,
2065 Diagnostic &Diags, FileManager &FileMgr,
2066 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002067 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +00002068 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002069 if (!AST) {
2070 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
2071 return;
2072 }
2073
2074 Preprocessor &PP = AST->getPreprocessor();
2075
2076 llvm::OwningPtr<llvm::raw_ostream> OS;
2077 llvm::sys::Path OutPath;
2078 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(PP, InFile, PA, OS,
2079 OutPath, Features,
2080 Context));
2081
2082 if (!Consumer.get()) {
2083 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
2084 return;
2085 }
2086
Daniel Dunbara674bf42009-09-21 03:03:56 +00002087 // Set the main file ID to an empty file.
2088 //
2089 // FIXME: We probably shouldn't need this, but for now this is the simplest
2090 // way to reuse the logic in ParseAST.
2091 const char *EmptyStr = "";
2092 llvm::MemoryBuffer *SB =
2093 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
2094 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002095
Daniel Dunbara674bf42009-09-21 03:03:56 +00002096 // Stream the input AST to the consumer.
2097 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002098
2099 // Release the consumer and the AST, in that order since the consumer may
2100 // perform actions in its destructor which require the context.
2101 if (DisableFree) {
2102 Consumer.take();
2103 AST.take();
2104 } else {
2105 Consumer.reset();
2106 AST.reset();
2107 }
2108
2109 // Always delete the output stream because we don't want to leak file
2110 // handles. Also, we don't want to try to erase an open file.
2111 OS.reset();
2112
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002113 // If we had errors, try to erase the output file.
2114 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002115 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002116}
2117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118static llvm::cl::list<std::string>
2119InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2120
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002121static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2122 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2123
2124 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2125
2126 // We cannot recover from llvm errors.
2127 exit(1);
2128}
2129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002132 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002133 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002134
Daniel Dunbar4d861512009-09-03 04:54:12 +00002135 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002136 llvm::InitializeAllTargets();
2137 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002138
2139 llvm::cl::ParseCommandLineOptions(argc, argv,
2140 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Chris Lattner47099742009-02-18 01:51:21 +00002142 if (TimeReport)
2143 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002145 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002146 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2147 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002148 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 // If no input was specified, read from stdin.
2151 if (InputFilenames.empty())
2152 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002153
Daniel Dunbareace8742009-11-04 06:24:30 +00002154 // Initialize the diagnostic options.
2155 DiagOpts.ShowColumn = !NoShowColumn;
2156 DiagOpts.ShowLocation = !NoShowLocation;
2157 DiagOpts.ShowCarets = !NoCaretDiagnostics;
2158 DiagOpts.ShowFixits = !NoDiagnosticsFixIt;
2159 DiagOpts.ShowSourceRanges = PrintSourceRangeInfo;
2160 DiagOpts.ShowOptionNames = PrintDiagnosticOption;
Daniel Dunbar838be482009-11-04 06:24:57 +00002161 DiagOpts.ShowColors = PrintColorDiagnostic;
Daniel Dunbareace8742009-11-04 06:24:30 +00002162 DiagOpts.MessageLength = MessageLength;
2163
Ted Kremenek31e703b2007-12-11 23:28:38 +00002164 // Create the diagnostic client for reporting errors or for
2165 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002166 llvm::OwningPtr<DiagnosticClient> DiagClient;
2167 if (VerifyDiagnostics) {
2168 // When checking diagnostics, just buffer them up.
2169 DiagClient.reset(new TextDiagnosticBuffer());
2170 if (InputFilenames.size() != 1) {
2171 fprintf(stderr, "-verify only works on single input files for now.\n");
2172 return 1;
2173 }
2174 if (!HTMLDiag.empty()) {
2175 fprintf(stderr, "-verify and -html-diags don't work together\n");
2176 return 1;
2177 }
2178 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002179 // Print diagnostics to stderr by default.
Daniel Dunbareace8742009-11-04 06:24:30 +00002180 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002181 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002182 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 }
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Chris Lattner75a97cb2009-04-17 21:05:01 +00002185 if (!DumpBuildInformation.empty()) {
2186 if (!HTMLDiag.empty()) {
2187 fprintf(stderr,
2188 "-dump-build-information and -html-diags don't work together\n");
2189 return 1;
2190 }
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Chris Lattner75a97cb2009-04-17 21:05:01 +00002192 SetUpBuildDumpLog(argc, argv, DiagClient);
2193 }
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002195
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002197 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002198 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2199 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002200 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002201
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002202 // Set an error handler, so that any LLVM backend diagnostics go through our
2203 // error handler.
2204 llvm::llvm_install_error_handler(LLVMErrorHandler,
2205 static_cast<void*>(&Diags));
2206
Daniel Dunbar7c15e712009-10-30 18:12:31 +00002207 // Initialize base triple. If a -triple option has been specified, use
2208 // that triple. Otherwise, default to the host triple.
2209 llvm::Triple Triple(TargetTriple);
2210 if (Triple.getTriple().empty())
2211 Triple = llvm::Triple(llvm::sys::getHostTriple());
2212
Chris Lattner11215192008-03-14 06:12:05 +00002213 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002214 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00002215 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Chris Lattner11215192008-03-14 06:12:05 +00002217 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002218 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002219 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002220 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002221 }
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Daniel Dunbar73b79592009-09-14 00:02:12 +00002223 // Set the target ABI if specified.
2224 if (!TargetABI.empty()) {
2225 if (!Target->setABI(TargetABI)) {
2226 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2227 << TargetABI;
2228 return 1;
2229 }
2230 }
2231
Daniel Dunbard4270232009-01-20 23:17:32 +00002232 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002233 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002235 llvm::OwningPtr<SourceManager> SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Chris Lattner2c78b872009-04-14 23:22:57 +00002237 // Create a file manager object to provide access to and cache the filesystem.
2238 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002239
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002240 // Compute the feature set, unfortunately this effects the language!
2241 llvm::StringMap<bool> Features;
2242 ComputeFeatureMap(Target.get(), Features);
2243
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002245 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002247 LangKind LK = GetLanguage(InFile);
2248 // AST inputs are handled specially.
2249 if (LK == langkind_ast) {
2250 ProcessASTInputFile(InFile, ProgAction, Features,
2251 Diags, FileMgr, Context);
2252 continue;
2253 }
2254
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002255 // Create a SourceManager object. This tracks and owns all the file
2256 // buffers allocated to a translation unit.
Chris Lattnerf63aea32009-03-04 21:40:56 +00002257 if (!SourceMgr)
2258 SourceMgr.reset(new SourceManager());
2259 else
2260 SourceMgr->clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Chris Lattnerf63aea32009-03-04 21:40:56 +00002262 // Initialize language options, inferring file types from input filenames.
2263 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002264 DiagClient->setLangOptions(&LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002266 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002267 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Chris Lattnerf63aea32009-03-04 21:40:56 +00002269 // Process the -I options and set them in the HeaderInfo.
2270 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002271
2272
Mike Stump43d81762009-10-08 23:29:47 +00002273 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo, Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Chris Lattnerf63aea32009-03-04 21:40:56 +00002275 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002276 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002277 *SourceMgr.get(), HeaderInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Chris Lattnerf63aea32009-03-04 21:40:56 +00002279 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002280 if (!PP)
2281 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002282
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002283 // Handle generating dependencies, if requested.
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002284 if (!DependencyFile.empty()) {
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002285 if (DependencyTargets.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002286 Diags.Report(FullSourceLoc(), diag::err_fe_dependency_file_requires_MT);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002287 continue;
2288 }
2289 std::string ErrStr;
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002290 llvm::raw_ostream *DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002291 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002292 if (!ErrStr.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002293 Diags.Report(FullSourceLoc(), diag::err_fe_error_opening)
2294 << DependencyFile << ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002295 continue;
2296 }
2297
2298 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2299 DependenciesIncludeSystemHeaders,
2300 PhonyDependencyTarget);
2301 }
2302
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002303 if (ImplicitIncludePCH.empty()) {
2304 if (InitializeSourceManager(*PP.get(), InFile))
2305 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002307 // Initialize builtin info.
2308 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002309 PP->getLangOptions().NoBuiltin);
2310 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002311
Chris Lattner409d4e72009-04-17 20:40:01 +00002312 if (!HTMLDiag.empty())
2313 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002314
2315 // Process the source file.
Owen Andersonc93f4982009-07-01 21:23:16 +00002316 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Chris Lattner40469652009-04-17 20:16:08 +00002318 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002319 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 }
Chris Lattner11215192008-03-14 06:12:05 +00002321
Mike Stumpfc0fed32009-04-28 01:19:10 +00002322 if (!NoCaretDiagnostics)
2323 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2324 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2325 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 FileMgr.PrintStats();
2329 fprintf(stderr, "\n");
2330 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002331
2332 delete ClangFrontendTimer;
2333 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Daniel Dunbar276373d2008-10-27 22:10:13 +00002335 // If verifying diagnostics and we reached here, all is well.
2336 if (VerifyDiagnostics)
2337 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002339 // Managed static deconstruction. Useful for making things like
2340 // -time-passes usable.
2341 llvm::llvm_shutdown();
2342
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002343 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002344}