blob: e55deb51c980e6e3cd5f606e926e03078e02834c [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//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000017
Daniel Dunbar0498cfc2009-11-10 19:51:53 +000018#include "Options.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000019#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclGroup.h"
23#include "clang/Analysis/PathDiagnostic.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Basic/Version.h"
28#include "clang/CodeGen/ModuleBuilder.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000029#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000030#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000031#include "clang/Frontend/AnalysisConsumer.h"
Daniel Dunbardbf75fe2009-11-11 08:13:24 +000032#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000033#include "clang/Frontend/CommandLineSourceLoc.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000034#include "clang/Frontend/CompilerInvocation.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000035#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000036#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000037#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000038#include "clang/Frontend/PathDiagnosticClients.h"
39#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000040#include "clang/Frontend/PreprocessorOutputOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000041#include "clang/Frontend/TextDiagnosticBuffer.h"
42#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000043#include "clang/Frontend/Utils.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000044#include "clang/Lex/HeaderSearch.h"
45#include "clang/Lex/LexDiagnostic.h"
46#include "clang/Parse/Parser.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000047#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000048#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000049#include "clang/Sema/SemaDiagnostic.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000050#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000051#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000052#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000053#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000054#include "llvm/ADT/StringMap.h"
Daniel Dunbar227b2382009-11-09 22:45:57 +000055#include "llvm/ADT/StringSwitch.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000057#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000058#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000059#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000061#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000062#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000063#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000064#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000065#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000066#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000067#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000068#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000069#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000070#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000071#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000072# include <sys/types.h>
73#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000074
Reid Spencer5f016e22007-07-11 17:01:13 +000075using namespace clang;
76
77//===----------------------------------------------------------------------===//
78// Global options.
79//===----------------------------------------------------------------------===//
80
Chris Lattner47099742009-02-18 01:51:21 +000081/// ClangFrontendTimer - The front-end activities should charge time to it with
82/// TimeRegion. The -ftime-report option controls whether this will do
83/// anything.
84llvm::Timer *ClangFrontendTimer = 0;
85
Reid Spencer5f016e22007-07-11 17:01:13 +000086static llvm::cl::opt<bool>
87Verbose("v", llvm::cl::desc("Enable verbose output"));
88static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000089Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +000090 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000091static llvm::cl::opt<bool>
92DisableFree("disable-free",
93 llvm::cl::desc("Disable freeing of memory on exit"),
94 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000095static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000096EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000097 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +000098
99enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000100 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000101 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000102 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000103 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000104 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000105 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000106 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000108 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000109 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000110 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000111 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000112 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000113 ASTDump, // Parse ASTs and dump them.
114 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000115 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000116 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 ParsePrintCallbacks, // Parse and print each callback.
118 ParseSyntaxOnly, // Parse and perform semantic analysis.
119 ParseNoop, // Parse with noop callbacks.
120 RunPreprocessorOnly, // Just lex, no output.
121 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000122 DumpTokens, // Dump out preprocessed tokens.
123 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000124 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000125 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000126 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000127 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000128};
129
Mike Stump1eb44332009-09-09 15:08:12 +0000130static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000131ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
132 llvm::cl::init(ParseSyntaxOnly),
133 llvm::cl::values(
134 clEnumValN(RunPreprocessorOnly, "Eonly",
135 "Just run preprocessor, no output (for timings)"),
136 clEnumValN(PrintPreprocessedInput, "E",
137 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000138 clEnumValN(DumpRawTokens, "dump-raw-tokens",
139 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000140 clEnumValN(RunAnalysis, "analyze",
141 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000142 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 "Run preprocessor, dump internal rep of tokens"),
144 clEnumValN(ParseNoop, "parse-noop",
145 "Run parser with noop callbacks (for timings)"),
146 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
147 "Run parser and perform semantic analysis"),
148 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
149 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000150 clEnumValN(EmitHTML, "emit-html",
151 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000152 clEnumValN(ASTPrint, "ast-print",
153 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000154 clEnumValN(ASTPrintXML, "ast-print-xml",
155 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000156 clEnumValN(ASTDump, "ast-dump",
157 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000158 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000159 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000160 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000161 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000162 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
163 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000164 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000165 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000166 clEnumValN(GeneratePCH, "emit-pch",
167 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000168 clEnumValN(EmitAssembly, "S",
169 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000171 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000172 clEnumValN(EmitBC, "emit-llvm-bc",
173 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000174 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
175 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000176 clEnumValN(RewriteTest, "rewrite-test",
177 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000178 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000179 "Rewrite ObjC into C (code rewriter example)"),
180 clEnumValN(RewriteMacros, "rewrite-macros",
181 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000182 clEnumValN(RewriteBlocks, "rewrite-blocks",
183 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000184 clEnumValN(FixIt, "fixit",
185 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 clEnumValEnd));
187
Ted Kremenekccc76472007-12-19 19:47:59 +0000188
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000189enum CodeCompletionPrinter {
190 CCP_Debug,
191 CCP_CIndex
192};
193
Douglas Gregorb657f112009-09-22 21:11:38 +0000194static llvm::cl::opt<ParsedSourceLocation>
195CodeCompletionAt("code-completion-at",
196 llvm::cl::value_desc("file:line:column"),
197 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000198
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000199static llvm::cl::opt<CodeCompletionPrinter>
200CodeCompletionPrinter("code-completion-printer",
201 llvm::cl::desc("Choose output type:"),
202 llvm::cl::init(CCP_Debug),
203 llvm::cl::values(
204 clEnumValN(CCP_Debug, "debug",
205 "Debug code-completion results"),
206 clEnumValN(CCP_CIndex, "cindex",
207 "Code-completion results for the CIndex library"),
208 clEnumValEnd));
209
210static llvm::cl::opt<bool>
211CodeCompletionWantsMacros("code-completion-macros",
212 llvm::cl::desc("Include macros in code-completion results"));
213
Douglas Gregor81b747b2009-09-17 21:32:03 +0000214/// \brief Buld a new code-completion consumer that prints the results of
215/// code completion to standard output.
216static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000217 switch (CodeCompletionPrinter.getValue()) {
218 case CCP_Debug:
219 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
220 llvm::outs());
221
222 case CCP_CIndex:
223 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
224 llvm::outs());
225 };
226
227 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000228}
229
Ted Kremenekc2e72992008-12-02 19:57:31 +0000230//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000231// C++ Visualization.
232//===----------------------------------------------------------------------===//
233
234static llvm::cl::opt<std::string>
235InheritanceViewCls("cxx-inheritance-view",
236 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000237 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000238
239//===----------------------------------------------------------------------===//
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000240// Frontend Options
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000241//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000242
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000243static llvm::cl::list<std::string>
244InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
245
246static llvm::cl::opt<std::string>
247OutputFile("o",
248 llvm::cl::value_desc("path"),
249 llvm::cl::desc("Specify output file"));
250
Chris Lattnerb2509e12009-02-18 01:12:43 +0000251static llvm::cl::opt<bool>
252TimeReport("ftime-report",
253 llvm::cl::desc("Print the amount of time each "
254 "phase of compilation takes"));
255
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000256static llvm::cl::opt<std::string>
257TokenCache("token-cache", llvm::cl::value_desc("path"),
258 llvm::cl::desc("Use specified token cache file"));
259
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000260static llvm::cl::opt<bool>
261VerifyDiagnostics("verify",
262 llvm::cl::desc("Verify emitted diagnostics and warnings"));
263
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000264//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000265// Language Options
266//===----------------------------------------------------------------------===//
267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268static llvm::cl::opt<LangKind>
269BaseLang("x", llvm::cl::desc("Base language to compile"),
270 llvm::cl::init(langkind_unspecified),
271 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000272 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 clEnumValN(langkind_cxx, "c++", "C++"),
274 clEnumValN(langkind_objc, "objective-c", "Objective C"),
275 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000276 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000278 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
279 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000281 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
283 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000284 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000286 clEnumValN(langkind_c, "c-header",
287 "C header"),
288 clEnumValN(langkind_objc, "objective-c-header",
289 "Objective-C header"),
290 clEnumValN(langkind_cxx, "c++-header",
291 "C++ header"),
292 clEnumValN(langkind_objcxx, "objective-c++-header",
293 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000294 clEnumValN(langkind_ast, "ast",
295 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 clEnumValEnd));
297
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000298static llvm::cl::opt<std::string>
299TargetTriple("triple",
300 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
301
Daniel Dunbar56749082009-11-11 07:26:12 +0000302static llvm::cl::opt<std::string>
303TargetABI("target-abi",
304 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000305
306//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000307// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000308//===----------------------------------------------------------------------===//
309
Douglas Gregore1d918e2009-04-10 23:10:45 +0000310static bool InitializeSourceManager(Preprocessor &PP,
311 const std::string &InFile) {
312 // Figure out where to get and map in the main file.
313 SourceManager &SourceMgr = PP.getSourceManager();
314 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000315
316 if (EmptyInputOnly) {
317 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000318 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000319 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
320 SourceMgr.createMainFileIDForMemBuffer(SB);
321 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000322 const FileEntry *File = FileMgr.getFile(InFile);
323 if (File) SourceMgr.createMainFileID(File, SourceLocation());
324 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000325 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000326 return true;
327 }
328 } else {
329 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000330 SourceMgr.createMainFileIDForMemBuffer(SB);
331 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000332 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000333 return true;
334 }
335 }
336
337 return false;
338}
339
Chris Lattneraa391972008-04-19 23:09:31 +0000340
Chris Lattnere116ccf2009-04-21 05:40:52 +0000341//===----------------------------------------------------------------------===//
342// Preprocessor Initialization
343//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000344
Chris Lattnere6113de2009-11-03 19:50:27 +0000345static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000346RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000347 llvm::cl::desc("Whether to build a relocatable precompiled "
348 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000349
Reid Spencer5f016e22007-07-11 17:01:13 +0000350// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000351
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000352// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +0000353std::string GetBuiltinIncludePath(const char *Argv0) {
354 llvm::sys::Path P =
355 llvm::sys::Path::GetMainExecutable(Argv0,
356 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000357
Daniel Dunbar750156a2009-11-07 04:19:57 +0000358 if (!P.isEmpty()) {
359 P.eraseComponent(); // Remove /clang from foo/bin/clang
360 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000361
Daniel Dunbar750156a2009-11-07 04:19:57 +0000362 // Get foo/lib/clang/<version>/include
363 P.appendComponent("lib");
364 P.appendComponent("clang");
365 P.appendComponent(CLANG_VERSION_STRING);
366 P.appendComponent("include");
367 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000368
Daniel Dunbar750156a2009-11-07 04:19:57 +0000369 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000370}
371
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000372//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +0000373// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000374//===----------------------------------------------------------------------===//
375
Daniel Dunbar90b18272009-11-04 23:56:25 +0000376static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000377CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
378 const PreprocessorOptions &PPOpts, TargetInfo &Target,
379 SourceManager &SourceMgr, HeaderSearch &HeaderInfo) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000380 PTHManager *PTHMgr = 0;
Daniel Dunbare0a95812009-11-10 22:09:38 +0000381 if (!TokenCache.empty() && !PPOpts.getImplicitPTHInclude().empty()) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000382 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
383 "options\n");
384 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000385 }
Daniel Dunbar90b18272009-11-04 23:56:25 +0000386
387 // Use PTH?
Daniel Dunbare0a95812009-11-10 22:09:38 +0000388 if (!TokenCache.empty() || !PPOpts.getImplicitPTHInclude().empty()) {
389 const std::string& x = TokenCache.empty() ?
390 PPOpts.getImplicitPTHInclude() : TokenCache;
Daniel Dunbar90b18272009-11-04 23:56:25 +0000391 PTHMgr = PTHManager::Create(x, &Diags,
392 TokenCache.empty() ? Diagnostic::Error
393 : Diagnostic::Warning);
394 }
395
396 if (Diags.hasErrorOccurred())
397 exit(1);
398
399 // Create the Preprocessor.
400 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
401 SourceMgr, HeaderInfo, PTHMgr);
402
403 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
404 // That argument is used as the IdentifierInfoLookup argument to
405 // IdentifierTable's ctor.
406 if (PTHMgr) {
407 PTHMgr->setPreprocessor(PP);
408 PP->setPTHManager(PTHMgr);
409 }
410
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000411 InitializePreprocessor(*PP, PPOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000412
413 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000414}
Reid Spencer5f016e22007-07-11 17:01:13 +0000415
Reid Spencer5f016e22007-07-11 17:01:13 +0000416//===----------------------------------------------------------------------===//
417// Basic Parser driver
418//===----------------------------------------------------------------------===//
419
Chris Lattner51574ea2008-04-19 23:25:44 +0000420static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000422 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // Parsing the specified input file.
425 P.ParseTranslationUnit();
426 delete PA;
427}
428
429//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000430// Fix-It Options
431//===----------------------------------------------------------------------===//
432static llvm::cl::list<ParsedSourceLocation>
433FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
434 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
435
436//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000437// ObjC Rewriter Options
438//===----------------------------------------------------------------------===//
439static llvm::cl::opt<bool>
440SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
441 llvm::cl::desc("Silence ObjC rewriting warnings"));
442
443//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +0000444// Warning Options
445//===----------------------------------------------------------------------===//
446
447// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
448// driver has stripped off -Wa,foo etc. The driver has also translated -W to
449// -Wextra, so we don't need to worry about it.
450static llvm::cl::list<std::string>
451OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
452
453static llvm::cl::opt<bool> OptPedantic("pedantic");
454static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
455static llvm::cl::opt<bool> OptNoWarnings("w");
456
457//===----------------------------------------------------------------------===//
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +0000458// Dependency file options
459//===----------------------------------------------------------------------===//
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000460
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +0000461static llvm::cl::opt<std::string>
462DependencyFile("dependency-file",
463 llvm::cl::desc("Filename (or -) to write dependency output to"));
464
465static llvm::cl::opt<bool>
466DependenciesIncludeSystemHeaders("sys-header-deps",
467 llvm::cl::desc("Include system headers in dependency output"));
468
469static llvm::cl::list<std::string>
470DependencyTargets("MT",
471 llvm::cl::desc("Specify target for dependency"));
472
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +0000473static llvm::cl::opt<bool>
474PhonyDependencyTarget("MP",
475 llvm::cl::desc("Create phony target for each dependency "
476 "(other than main file)"));
477
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000478//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +0000479// -dump-build-information Stuff
480//===----------------------------------------------------------------------===//
481
482static llvm::cl::opt<std::string>
483DumpBuildInformation("dump-build-information",
484 llvm::cl::value_desc("filename"),
485 llvm::cl::desc("output a dump of some build information to a file"));
486
Daniel Dunbar227b2382009-11-09 22:45:57 +0000487static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000488 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000489 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000490 std::string ErrorInfo;
Daniel Dunbaraea36412009-11-11 09:38:24 +0000491 llvm::raw_ostream *OS = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
492 ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000493 if (!ErrorInfo.empty()) {
494 llvm::errs() << "error opening -dump-build-information file '"
495 << DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000496 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000497 return;
498 }
499
Daniel Dunbaraea36412009-11-11 09:38:24 +0000500 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000501 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000502 (*OS) << argv[i] << ' ';
503 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000505 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000506 DiagnosticClient *Logger =
507 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000508 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000509}
510
Chris Lattner75a97cb2009-04-17 21:05:01 +0000511//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000512// Main driver
513//===----------------------------------------------------------------------===//
514
Daniel Dunbare29709f2009-11-09 20:55:08 +0000515static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
516 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000517 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000518 bool Binary,
519 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000520 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000521 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000522 if (!CompOpts.getOutputFile().empty())
523 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000524 else if (InFile == "-") {
525 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000526 } else if (Extension) {
527 llvm::sys::Path Path(InFile);
528 Path.eraseSuffix();
529 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000530 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000531 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000532 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000533 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000534
Chris Lattner92bcc272009-08-23 02:59:41 +0000535 std::string Error;
536 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000537 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000538 if (!Error.empty()) {
539 // FIXME: Don't fail this way.
540 llvm::errs() << "ERROR: " << Error << "\n";
541 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000542 }
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner92bcc272009-08-23 02:59:41 +0000544 if (OutFile != "-")
545 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000546
547 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000548}
549
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000550/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000551/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000552static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000553 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000554 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000555
556 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
557 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
558 RequestedSourceLocation Requested;
559 Requested.File = File;
560 Requested.Line = FixItAtLocations[i].Line;
561 Requested.Column = FixItAtLocations[i].Column;
562 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000563 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000564 } else {
565 llvm::errs() << "FIX-IT could not find file \""
566 << FixItAtLocations[i].FileName << "\"\n";
567 }
568 }
569
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000570 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000571}
572
Daniel Dunbare29709f2009-11-09 20:55:08 +0000573static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
574 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000575 const std::string &InFile,
576 ProgActions PA,
577 llvm::OwningPtr<llvm::raw_ostream> &OS,
578 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000579 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000580 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000582 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000583
584 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000585 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000586 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Douglas Gregoree75c052009-05-21 20:55:50 +0000588 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000589 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000590 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000591
Eli Friedman66d6f042009-05-18 22:20:00 +0000592 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000593 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000594
Eli Friedman66d6f042009-05-18 22:20:00 +0000595 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000596 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000597
Anders Carlsson78762eb2009-09-24 18:54:49 +0000598 case DumpRecordLayouts:
599 return CreateRecordLayoutDumper();
600
Eli Friedman66d6f042009-05-18 22:20:00 +0000601 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000602 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000603
604 case EmitAssembly:
605 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000606 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000607 case EmitLLVMOnly: {
608 BackendAction Act;
609 if (ProgAction == EmitAssembly) {
610 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000611 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000612 } else if (ProgAction == EmitLLVM) {
613 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000614 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000615 } else if (ProgAction == EmitLLVMOnly) {
616 Act = Backend_EmitNothing;
617 } else {
618 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000619 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000620 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000621
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000622 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000623 CompOpts.getCompileOpts(), InFile, OS.get(),
624 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000625 }
626
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000627 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000628 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000629 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
630 PP.getLangOptions(), SilenceRewriteMacroWarning);
631
632 case RewriteBlocks:
633 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
634 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000635
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000636 case FixIt: // We add the rewriter later.
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000637 case ParseSyntaxOnly:
638 return new ASTConsumer();
639
640 case PrintDeclContext:
641 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000642 }
643}
644
645/// ProcessInputFile - Process a single input file with the specified state.
646///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000647static void ProcessInputFile(const CompilerInvocation &CompOpts,
648 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar90b18272009-11-04 23:56:25 +0000649 ProgActions PA,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000650 llvm::LLVMContext& Context) {
651 llvm::OwningPtr<llvm::raw_ostream> OS;
652 llvm::OwningPtr<ASTConsumer> Consumer;
653 bool ClearSourceMgr = false;
654 FixItRewriter *FixItRewrite = 0;
655 bool CompleteTranslationUnit = true;
656 llvm::sys::Path OutPath;
657
658 switch (PA) {
659 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000660 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000661 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000662 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000663 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000664 return;
665 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000666 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000667
668 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000669 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000670 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000671 break;
672
Daniel Dunbar339c1342009-11-11 08:13:55 +0000673 case RunAnalysis: {
674 AnalyzerOptions AnalyzerOpts;
675 // FIXME: Move into CompilerInvocation.
676 InitializeAnalyzerOptions(AnalyzerOpts);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000677 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar339c1342009-11-11 08:13:55 +0000678 AnalyzerOpts));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000679 break;
Daniel Dunbar339c1342009-11-11 08:13:55 +0000680 }
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000681
Daniel Dunbarf7973292009-11-11 08:13:32 +0000682 case GeneratePCH: {
683 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
684 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000685 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
686 RelocatablePCH.setValue(false);
687 }
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Daniel Dunbare29709f2009-11-09 20:55:08 +0000689 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000690 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000691 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000692 else
693 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000694 CompleteTranslationUnit = false;
695 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000696 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000697 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +0000698 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +0000699 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +0000700 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +0000701 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +0000702 RawLex.SetKeepWhitespaceMode(true);
703
704 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000705 RawLex.LexFromRawLexer(RawTok);
706 while (RawTok.isNot(tok::eof)) {
707 PP.DumpToken(RawTok, true);
708 fprintf(stderr, "\n");
709 RawLex.LexFromRawLexer(RawTok);
710 }
711 ClearSourceMgr = true;
712 break;
713 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +0000715 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +0000716 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000717 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000718 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 do {
720 PP.Lex(Tok);
721 PP.DumpToken(Tok, true);
722 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000723 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000724 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 break;
726 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000727 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000730 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +0000731 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000732 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000733 // FIXME: Don't fail this way.
734 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000735 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000736 ::exit(1);
737 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000738 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000739 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +0000740 ClearSourceMgr = true;
741 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000742 }
Douglas Gregor6ab35242009-04-09 21:40:53 +0000743
Chris Lattnercc7dea82009-04-27 22:02:30 +0000744 case PrintPreprocessedInput:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000745 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000748 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Chris Lattner47099742009-02-18 01:51:21 +0000751 case ParsePrintCallbacks: {
752 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000753 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000754 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000755 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 break;
Chris Lattner47099742009-02-18 01:51:21 +0000757 }
758
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000759 case RewriteMacros:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000760 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000761 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000762 ClearSourceMgr = true;
763 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Eli Friedmanf54fce82009-05-19 01:02:07 +0000765 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000766 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000767 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000768 ClearSourceMgr = true;
769 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000770 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000771
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000772 // Check if we want a fix-it rewriter.
773 if (PA == FixIt || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000774 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000775 PP.getSourceManager(),
776 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000777 if (!FixItAtLocations.empty() &&
778 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000779 // All of the fix-it locations were bad. Don't fix anything.
780 delete FixItRewrite;
781 FixItRewrite = 0;
782 }
783 }
784
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000785
Chris Lattner1aee61a2009-04-27 21:25:27 +0000786 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000787 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000788 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
789 PP.getSourceManager(),
790 PP.getTargetInfo(),
791 PP.getIdentifierTable(),
792 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000793 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000794 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000795 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattnercc7dea82009-04-27 22:02:30 +0000797 llvm::OwningPtr<PCHReader> Reader;
798 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Daniel Dunbare0a95812009-11-10 22:09:38 +0000800 const std::string &ImplicitPCHInclude =
801 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
802 if (!ImplicitPCHInclude.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000803 // If the user specified -isysroot, it will be used for relocatable PCH
804 // files.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000805 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
806 if (isysrootPCH[0] == '\0')
807 isysrootPCH = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Douglas Gregore650c8c2009-07-07 00:12:59 +0000809 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000811 // The user has asked us to include a precompiled header. Load
812 // the precompiled header into the AST context.
Daniel Dunbare0a95812009-11-10 22:09:38 +0000813 switch (Reader->ReadPCH(ImplicitPCHInclude)) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000814 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +0000815 // Set the predefines buffer as suggested by the PCH
816 // reader. Typically, the predefines buffer will be empty.
817 PP.setPredefines(Reader->getSuggestedPredefines());
818
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000819 // Attach the PCH reader to the AST context as an external AST
820 // source, so that declarations will be deserialized from the
821 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +0000822 if (ContextOwner) {
823 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +0000824 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +0000825 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000826 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000827 }
828
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000829 case PCHReader::Failure:
830 // Unrecoverable failure: don't even try to process the input
831 // file.
832 return;
833
834 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +0000835 // No suitable PCH file could be found. Return an error.
836 return;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000837 }
838
839 // Finish preprocessor initialization. We do this now (rather
840 // than earlier) because this initialization creates new source
841 // location entries in the source manager, which must come after
842 // the source location entries for the PCH file.
843 if (InitializeSourceManager(PP, InFile))
844 return;
Ted Kremenek46157b52009-01-28 04:29:29 +0000845 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000846
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000847 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +0000848 if (Consumer) {
849 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
850 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000851
Douglas Gregorb657f112009-09-22 21:11:38 +0000852 if (!CodeCompletionAt.FileName.empty()) {
853 // Tell the source manager to chop off the given file at a specific
854 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000855 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000856 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
857 // Truncate the named file at the given line/column.
858 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
859 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000860
Douglas Gregorb657f112009-09-22 21:11:38 +0000861 // Set up the creation routine for code-completion.
862 CreateCodeCompleter = BuildPrintingCodeCompleter;
863 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000864 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000865 << CodeCompletionAt.FileName;
866 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000867 }
868
Mike Stump1eb44332009-09-09 15:08:12 +0000869 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000870 CompleteTranslationUnit,
871 CreateCodeCompleter, CreateCodeCompleterData);
872 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000873
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000874 // Perform post processing actions and actions which don't use a consumer.
875 switch (PA) {
876 default: break;
877
878 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000879 llvm::TimeRegion Timer(ClangFrontendTimer);
880 Token Tok;
881 // Start parsing the specified input file.
882 PP.EnterMainSourceFile();
883 do {
884 PP.Lex(Tok);
885 } while (Tok.isNot(tok::eof));
886 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000887 break;
888 }
889
890 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000891 llvm::TimeRegion Timer(ClangFrontendTimer);
892 ParseFile(PP, new MinimalAction(PP));
893 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000894 break;
895 }
896
897 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +0000898 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000899 DoPrintPreprocessedInput(PP, OS.get(),
900 CompOpts.getPreprocessorOutputOpts());
Chris Lattnercc7dea82009-04-27 22:02:30 +0000901 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000904 }
905
Chris Lattner1aee61a2009-04-27 21:25:27 +0000906 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +0000907 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000908
909 // Disable the consumer prior to the context, the consumer may perform actions
910 // in its destructor which require the context.
911 if (DisableFree)
912 Consumer.take();
913 else
914 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Chris Lattner1aee61a2009-04-27 21:25:27 +0000916 // If in -disable-free mode, don't deallocate ASTContext.
917 if (DisableFree)
918 ContextOwner.take();
919 else
920 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +0000921
Daniel Dunbar879c3ea2008-10-27 22:03:52 +0000922 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000923 if (CheckDiagnostics(PP))
924 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000925
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000927 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 PP.PrintStats();
929 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000930 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000931 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 fprintf(stderr, "\n");
933 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000934
Mike Stump1eb44332009-09-09 15:08:12 +0000935 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +0000936 // manager tables, other require stable fileid/macroid's across multiple
937 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +0000938 if (ClearSourceMgr)
939 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000940
Eli Friedman66d6f042009-05-18 22:20:00 +0000941 // Always delete the output stream because we don't want to leak file
942 // handles. Also, we don't want to try to erase an open file.
943 OS.reset();
944
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000945 // If we had errors, try to erase the output file.
946 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000947 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000948}
949
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000950/// ProcessInputFile - Process a single AST input file with the specified state.
951///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000952static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
953 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000954 Diagnostic &Diags, FileManager &FileMgr,
955 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000956 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000957 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000958 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000959 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000960 return;
961 }
962
963 Preprocessor &PP = AST->getPreprocessor();
964
965 llvm::OwningPtr<llvm::raw_ostream> OS;
966 llvm::sys::Path OutPath;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000967 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
968 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000969 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000970
971 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000972 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000973 return;
974 }
975
Daniel Dunbara674bf42009-09-21 03:03:56 +0000976 // Set the main file ID to an empty file.
977 //
978 // FIXME: We probably shouldn't need this, but for now this is the simplest
979 // way to reuse the logic in ParseAST.
980 const char *EmptyStr = "";
981 llvm::MemoryBuffer *SB =
982 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
983 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000984
Daniel Dunbara674bf42009-09-21 03:03:56 +0000985 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000986 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +0000987 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000988 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000989
990 // Release the consumer and the AST, in that order since the consumer may
991 // perform actions in its destructor which require the context.
992 if (DisableFree) {
993 Consumer.take();
994 AST.take();
995 } else {
996 Consumer.reset();
997 AST.reset();
998 }
999
1000 // Always delete the output stream because we don't want to leak file
1001 // handles. Also, we don't want to try to erase an open file.
1002 OS.reset();
1003
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001004 // If we had errors, try to erase the output file.
1005 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001006 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001007}
1008
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001009static void LLVMErrorHandler(void *UserData, const std::string &Message) {
1010 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
1011
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001012 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001013
1014 // We cannot recover from llvm errors.
1015 exit(1);
1016}
1017
Daniel Dunbar227b2382009-11-09 22:45:57 +00001018static LangKind GetLanguage() {
1019 // If -x was given, that's the language.
1020 if (BaseLang != langkind_unspecified)
1021 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001022
Daniel Dunbar227b2382009-11-09 22:45:57 +00001023 // Otherwise guess it from the input filenames;
1024 LangKind LK = langkind_unspecified;
1025 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1026 llvm::StringRef Name(InputFilenames[i]);
1027 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
1028 .Case("ast", langkind_ast)
1029 .Case("c", langkind_c)
1030 .Cases("S", "s", langkind_asm_cpp)
1031 .Case("i", langkind_c_cpp)
1032 .Case("ii", langkind_cxx_cpp)
1033 .Case("m", langkind_objc)
1034 .Case("mi", langkind_objc_cpp)
1035 .Cases("mm", "M", langkind_objcxx)
1036 .Case("mii", langkind_objcxx_cpp)
1037 .Case("C", langkind_cxx)
1038 .Cases("C", "cc", "cp", langkind_cxx)
1039 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
1040 .Case("cl", langkind_ocl)
1041 .Default(langkind_c);
1042
1043 if (LK != langkind_unspecified && ThisKind != LK) {
1044 llvm::errs() << "error: cannot have multiple input files of distinct "
1045 << "language kinds without -x\n";
1046 exit(1);
1047 }
1048
1049 LK = ThisKind;
1050 }
1051
1052 return LK;
1053}
1054
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001055static void FinalizeCompileOptions(CompileOptions &Opts,
1056 const LangOptions &Lang) {
1057 if (Lang.NoBuiltin)
1058 Opts.SimplifyLibCalls = 0;
1059 if (Lang.CPlusPlus)
1060 Opts.NoCommon = 1;
1061
1062 // Handle -ftime-report.
1063 Opts.TimePasses = TimeReport;
1064}
1065
Daniel Dunbar227b2382009-11-09 22:45:57 +00001066static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001067 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001068 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001069 TargetInfo &Target,
1070 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001071 Opts.getDiagnosticOpts() = DiagOpts;
1072
1073 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001074
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001075 // Initialize backend options, which may also be used to key some language
1076 // options.
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001077 InitializeCompileOptions(Opts.getCompileOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001078
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001079 // Initialize language options.
1080 LangOptions LangInfo;
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001081
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001082 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1083 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001084 if (LK != langkind_ast)
1085 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001086 Opts.getCompileOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001087
1088 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001089 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1090 GetBuiltinIncludePath(Argv0),
1091 Verbose,
1092 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001093
1094 // Initialize the other preprocessor options.
1095 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001096
Daniel Dunbar29cf7462009-11-11 10:07:44 +00001097 // Initialize the preprocessed output options.
1098 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
1099
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001100 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001101 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001102}
1103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001106 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001107 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001108
Daniel Dunbar4d861512009-09-03 04:54:12 +00001109 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001110 llvm::InitializeAllTargets();
1111 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001112
1113 llvm::cl::ParseCommandLineOptions(argc, argv,
1114 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Chris Lattner47099742009-02-18 01:51:21 +00001116 if (TimeReport)
1117 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001119 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001120 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1121 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001122 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 // If no input was specified, read from stdin.
1125 if (InputFilenames.empty())
1126 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001127
Daniel Dunbar227b2382009-11-09 22:45:57 +00001128 // Construct the diagnostic options first, which cannot fail, so that we can
1129 // build a diagnostic client to use for any errors during option handling.
1130 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001131 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00001132
Ted Kremenek31e703b2007-12-11 23:28:38 +00001133 // Create the diagnostic client for reporting errors or for
1134 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001135 llvm::OwningPtr<DiagnosticClient> DiagClient;
1136 if (VerifyDiagnostics) {
1137 // When checking diagnostics, just buffer them up.
1138 DiagClient.reset(new TextDiagnosticBuffer());
1139 if (InputFilenames.size() != 1) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001140 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner409d4e72009-04-17 20:40:01 +00001141 return 1;
1142 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001143 } else {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001144 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 }
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Daniel Dunbarad451cc2009-11-05 02:11:37 +00001147 if (!DumpBuildInformation.empty())
Daniel Dunbar227b2382009-11-09 22:45:57 +00001148 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001151 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001152 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
1153 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001154 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001155
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001156 // Set an error handler, so that any LLVM backend diagnostics go through our
1157 // error handler.
1158 llvm::llvm_install_error_handler(LLVMErrorHandler,
1159 static_cast<void*>(&Diags));
1160
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001161 // Initialize base triple. If a -triple option has been specified, use
1162 // that triple. Otherwise, default to the host triple.
1163 llvm::Triple Triple(TargetTriple);
1164 if (Triple.getTriple().empty())
1165 Triple = llvm::Triple(llvm::sys::getHostTriple());
1166
Chris Lattner11215192008-03-14 06:12:05 +00001167 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001168 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001169 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Chris Lattner11215192008-03-14 06:12:05 +00001171 if (Target == 0) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001172 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001173 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Daniel Dunbar73b79592009-09-14 00:02:12 +00001176 // Set the target ABI if specified.
1177 if (!TargetABI.empty()) {
1178 if (!Target->setABI(TargetABI)) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001179 Diags.Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001180 return 1;
1181 }
1182 }
1183
Daniel Dunbard4270232009-01-20 23:17:32 +00001184 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001185 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Daniel Dunbar227b2382009-11-09 22:45:57 +00001187 // Infer the input language.
1188 //
1189 // FIXME: We should move .ast inputs to taking a separate path, they are
1190 // really quite different.
1191 LangKind LK = GetLanguage();
1192
1193 // Now that we have initialized the diagnostics engine and the target, finish
1194 // setting up the compiler invocation.
1195 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001196 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001197
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001198 // Create the source manager.
1199 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Chris Lattner2c78b872009-04-14 23:22:57 +00001201 // Create a file manager object to provide access to and cache the filesystem.
1202 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001205 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001207 // AST inputs are handled specially.
1208 if (LK == langkind_ast) {
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001209 ProcessASTInputFile(CompOpts, InFile, ProgAction, Diags, FileMgr,
1210 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001211 continue;
1212 }
1213
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001214 // Reset the ID tables if we are reusing the SourceManager.
1215 if (i)
1216 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Chris Lattnerf63aea32009-03-04 21:40:56 +00001218 // Process the -I options and set them in the HeaderInfo.
1219 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001221 // Apply all the options to the header search object.
1222 ApplyHeaderSearchOptions(CompOpts.getHeaderSearchOpts(), HeaderInfo,
1223 CompOpts.getLangOpts(), Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Chris Lattnerf63aea32009-03-04 21:40:56 +00001225 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001226 llvm::OwningPtr<Preprocessor>
1227 PP(CreatePreprocessor(Diags, CompOpts.getLangOpts(),
1228 CompOpts.getPreprocessorOpts(), *Target, SourceMgr,
1229 HeaderInfo));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001230
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001231 // Handle generating dependencies, if requested.
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001232 if (!DependencyFile.empty()) {
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001233 if (DependencyTargets.empty()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001234 Diags.Report(diag::err_fe_dependency_file_requires_MT);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001235 continue;
1236 }
1237 std::string ErrStr;
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001238 llvm::raw_ostream *DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00001239 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001240 if (!ErrStr.empty()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001241 Diags.Report(diag::err_fe_error_opening) << DependencyFile << ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001242 continue;
1243 }
1244
1245 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
1246 DependenciesIncludeSystemHeaders,
1247 PhonyDependencyTarget);
1248 }
1249
Daniel Dunbare0a95812009-11-10 22:09:38 +00001250 if (CompOpts.getPreprocessorOpts().getImplicitPCHInclude().empty()) {
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001251 if (InitializeSourceManager(*PP.get(), InFile))
1252 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001254 // Initialize builtin info.
1255 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001256 PP->getLangOptions().NoBuiltin);
1257 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001258
Chris Lattnerf63aea32009-03-04 21:40:56 +00001259 // Process the source file.
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001260 Diags.getClient()->BeginSourceFile(CompOpts.getLangOpts());
1261 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001262 Diags.getClient()->EndSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Chris Lattner40469652009-04-17 20:16:08 +00001264 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 }
Chris Lattner11215192008-03-14 06:12:05 +00001266
Daniel Dunbar9253e492009-11-10 00:46:12 +00001267 if (CompOpts.getDiagnosticOpts().ShowCarets)
Mike Stumpfc0fed32009-04-28 01:19:10 +00001268 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
1269 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1270 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 FileMgr.PrintStats();
1274 fprintf(stderr, "\n");
1275 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001276
1277 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Daniel Dunbar276373d2008-10-27 22:10:13 +00001279 // If verifying diagnostics and we reached here, all is well.
1280 if (VerifyDiagnostics)
1281 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001283 // Managed static deconstruction. Useful for making things like
1284 // -time-passes usable.
1285 llvm::llvm_shutdown();
1286
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001287 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001288}