blob: 2648a0b4d85f02cf4a28db29746c6f53b9b35fb5 [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"
Daniel Dunbar0e0bae82009-11-11 21:43:12 +000035#include "clang/Frontend/DependencyOutputOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000036#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000037#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000039#include "clang/Frontend/PathDiagnosticClients.h"
40#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000041#include "clang/Frontend/PreprocessorOutputOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000042#include "clang/Frontend/TextDiagnosticBuffer.h"
43#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000044#include "clang/Frontend/Utils.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000045#include "clang/Lex/HeaderSearch.h"
46#include "clang/Lex/LexDiagnostic.h"
47#include "clang/Parse/Parser.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000048#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000049#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000050#include "clang/Sema/SemaDiagnostic.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000051#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000053#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000055#include "llvm/ADT/StringMap.h"
Daniel Dunbar227b2382009-11-09 22:45:57 +000056#include "llvm/ADT/StringSwitch.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000059#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000060#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000061#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000062#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000063#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000065#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000066#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000067#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000070#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000071#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000072#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000073# include <sys/types.h>
74#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000075
Reid Spencer5f016e22007-07-11 17:01:13 +000076using namespace clang;
77
78//===----------------------------------------------------------------------===//
79// Global options.
80//===----------------------------------------------------------------------===//
81
Chris Lattner47099742009-02-18 01:51:21 +000082/// ClangFrontendTimer - The front-end activities should charge time to it with
83/// TimeRegion. The -ftime-report option controls whether this will do
84/// anything.
85llvm::Timer *ClangFrontendTimer = 0;
86
Reid Spencer5f016e22007-07-11 17:01:13 +000087static llvm::cl::opt<bool>
88Verbose("v", llvm::cl::desc("Enable verbose output"));
89static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000090Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +000091 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000092static llvm::cl::opt<bool>
93DisableFree("disable-free",
94 llvm::cl::desc("Disable freeing of memory on exit"),
95 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000096static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000097EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000098 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +000099
100enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000101 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000102 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000103 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000104 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000105 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000106 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000107 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000109 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000110 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000111 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000112 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000113 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000114 ASTDump, // Parse ASTs and dump them.
115 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000116 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000117 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 ParsePrintCallbacks, // Parse and print each callback.
119 ParseSyntaxOnly, // Parse and perform semantic analysis.
120 ParseNoop, // Parse with noop callbacks.
121 RunPreprocessorOnly, // Just lex, no output.
122 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000123 DumpTokens, // Dump out preprocessed tokens.
124 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000125 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000126 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000127 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000128 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000129};
130
Mike Stump1eb44332009-09-09 15:08:12 +0000131static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000132ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
133 llvm::cl::init(ParseSyntaxOnly),
134 llvm::cl::values(
135 clEnumValN(RunPreprocessorOnly, "Eonly",
136 "Just run preprocessor, no output (for timings)"),
137 clEnumValN(PrintPreprocessedInput, "E",
138 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000139 clEnumValN(DumpRawTokens, "dump-raw-tokens",
140 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000141 clEnumValN(RunAnalysis, "analyze",
142 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000143 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 "Run preprocessor, dump internal rep of tokens"),
145 clEnumValN(ParseNoop, "parse-noop",
146 "Run parser with noop callbacks (for timings)"),
147 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
148 "Run parser and perform semantic analysis"),
149 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
150 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000151 clEnumValN(EmitHTML, "emit-html",
152 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000153 clEnumValN(ASTPrint, "ast-print",
154 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000155 clEnumValN(ASTPrintXML, "ast-print-xml",
156 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000157 clEnumValN(ASTDump, "ast-dump",
158 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000159 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000160 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000161 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000162 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000163 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
164 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000165 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000166 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000167 clEnumValN(GeneratePCH, "emit-pch",
168 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000169 clEnumValN(EmitAssembly, "S",
170 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000172 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000173 clEnumValN(EmitBC, "emit-llvm-bc",
174 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000175 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
176 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000177 clEnumValN(RewriteTest, "rewrite-test",
178 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000179 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000180 "Rewrite ObjC into C (code rewriter example)"),
181 clEnumValN(RewriteMacros, "rewrite-macros",
182 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000183 clEnumValN(RewriteBlocks, "rewrite-blocks",
184 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000185 clEnumValN(FixIt, "fixit",
186 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 clEnumValEnd));
188
Ted Kremenekccc76472007-12-19 19:47:59 +0000189
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000190enum CodeCompletionPrinter {
191 CCP_Debug,
192 CCP_CIndex
193};
194
Douglas Gregorb657f112009-09-22 21:11:38 +0000195static llvm::cl::opt<ParsedSourceLocation>
196CodeCompletionAt("code-completion-at",
197 llvm::cl::value_desc("file:line:column"),
198 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000199
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000200static llvm::cl::opt<CodeCompletionPrinter>
201CodeCompletionPrinter("code-completion-printer",
202 llvm::cl::desc("Choose output type:"),
203 llvm::cl::init(CCP_Debug),
204 llvm::cl::values(
205 clEnumValN(CCP_Debug, "debug",
206 "Debug code-completion results"),
207 clEnumValN(CCP_CIndex, "cindex",
208 "Code-completion results for the CIndex library"),
209 clEnumValEnd));
210
211static llvm::cl::opt<bool>
212CodeCompletionWantsMacros("code-completion-macros",
213 llvm::cl::desc("Include macros in code-completion results"));
214
Douglas Gregor81b747b2009-09-17 21:32:03 +0000215/// \brief Buld a new code-completion consumer that prints the results of
216/// code completion to standard output.
217static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000218 switch (CodeCompletionPrinter.getValue()) {
219 case CCP_Debug:
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000220 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000221 llvm::outs());
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000222
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000223 case CCP_CIndex:
224 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
225 llvm::outs());
226 };
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000227
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000228 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000229}
230
Ted Kremenekc2e72992008-12-02 19:57:31 +0000231//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000232// C++ Visualization.
233//===----------------------------------------------------------------------===//
234
235static llvm::cl::opt<std::string>
236InheritanceViewCls("cxx-inheritance-view",
237 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000238 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000239
240//===----------------------------------------------------------------------===//
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000241// Frontend Options
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000242//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000243
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000244static llvm::cl::list<std::string>
245InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
246
247static llvm::cl::opt<std::string>
248OutputFile("o",
249 llvm::cl::value_desc("path"),
250 llvm::cl::desc("Specify output file"));
251
Chris Lattnerb2509e12009-02-18 01:12:43 +0000252static llvm::cl::opt<bool>
253TimeReport("ftime-report",
254 llvm::cl::desc("Print the amount of time each "
255 "phase of compilation takes"));
256
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000257static llvm::cl::opt<std::string>
258TokenCache("token-cache", llvm::cl::value_desc("path"),
259 llvm::cl::desc("Use specified token cache file"));
260
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000261static llvm::cl::opt<bool>
262VerifyDiagnostics("verify",
263 llvm::cl::desc("Verify emitted diagnostics and warnings"));
264
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000265//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000266// Language Options
267//===----------------------------------------------------------------------===//
268
Reid Spencer5f016e22007-07-11 17:01:13 +0000269static llvm::cl::opt<LangKind>
270BaseLang("x", llvm::cl::desc("Base language to compile"),
271 llvm::cl::init(langkind_unspecified),
272 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000273 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 clEnumValN(langkind_cxx, "c++", "C++"),
275 clEnumValN(langkind_objc, "objective-c", "Objective C"),
276 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000277 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000279 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
280 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000282 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
284 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000285 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000287 clEnumValN(langkind_c, "c-header",
288 "C header"),
289 clEnumValN(langkind_objc, "objective-c-header",
290 "Objective-C header"),
291 clEnumValN(langkind_cxx, "c++-header",
292 "C++ header"),
293 clEnumValN(langkind_objcxx, "objective-c++-header",
294 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000295 clEnumValN(langkind_ast, "ast",
296 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 clEnumValEnd));
298
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000299static llvm::cl::opt<std::string>
300TargetTriple("triple",
301 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
302
Daniel Dunbar56749082009-11-11 07:26:12 +0000303static llvm::cl::opt<std::string>
304TargetABI("target-abi",
305 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000306
307//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000308// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000309//===----------------------------------------------------------------------===//
310
Douglas Gregore1d918e2009-04-10 23:10:45 +0000311static bool InitializeSourceManager(Preprocessor &PP,
312 const std::string &InFile) {
313 // Figure out where to get and map in the main file.
314 SourceManager &SourceMgr = PP.getSourceManager();
315 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000316
317 if (EmptyInputOnly) {
318 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000319 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000320 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
321 SourceMgr.createMainFileIDForMemBuffer(SB);
322 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000323 const FileEntry *File = FileMgr.getFile(InFile);
324 if (File) SourceMgr.createMainFileID(File, SourceLocation());
325 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000326 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000327 return true;
328 }
329 } else {
330 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000331 SourceMgr.createMainFileIDForMemBuffer(SB);
332 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000333 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000334 return true;
335 }
336 }
337
338 return false;
339}
340
Chris Lattneraa391972008-04-19 23:09:31 +0000341
Chris Lattnere116ccf2009-04-21 05:40:52 +0000342//===----------------------------------------------------------------------===//
343// Preprocessor Initialization
344//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000345
Chris Lattnere6113de2009-11-03 19:50:27 +0000346static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000347RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000348 llvm::cl::desc("Whether to build a relocatable precompiled "
349 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000350
Reid Spencer5f016e22007-07-11 17:01:13 +0000351// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000352
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000353// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +0000354std::string GetBuiltinIncludePath(const char *Argv0) {
355 llvm::sys::Path P =
356 llvm::sys::Path::GetMainExecutable(Argv0,
357 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000358
Daniel Dunbar750156a2009-11-07 04:19:57 +0000359 if (!P.isEmpty()) {
360 P.eraseComponent(); // Remove /clang from foo/bin/clang
361 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000362
Daniel Dunbar750156a2009-11-07 04:19:57 +0000363 // Get foo/lib/clang/<version>/include
364 P.appendComponent("lib");
365 P.appendComponent("clang");
366 P.appendComponent(CLANG_VERSION_STRING);
367 P.appendComponent("include");
368 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000369
Daniel Dunbar750156a2009-11-07 04:19:57 +0000370 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000371}
372
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000373//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +0000374// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000375//===----------------------------------------------------------------------===//
376
Daniel Dunbar90b18272009-11-04 23:56:25 +0000377static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000378CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000379 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000380 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000381 const DependencyOutputOptions &DepOpts,
382 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000383 FileManager &FileMgr) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000384 PTHManager *PTHMgr = 0;
Daniel Dunbare0a95812009-11-10 22:09:38 +0000385 if (!TokenCache.empty() && !PPOpts.getImplicitPTHInclude().empty()) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000386 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
387 "options\n");
388 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000389 }
Daniel Dunbar90b18272009-11-04 23:56:25 +0000390
391 // Use PTH?
Daniel Dunbare0a95812009-11-10 22:09:38 +0000392 if (!TokenCache.empty() || !PPOpts.getImplicitPTHInclude().empty()) {
393 const std::string& x = TokenCache.empty() ?
394 PPOpts.getImplicitPTHInclude() : TokenCache;
Daniel Dunbar90b18272009-11-04 23:56:25 +0000395 PTHMgr = PTHManager::Create(x, &Diags,
396 TokenCache.empty() ? Diagnostic::Error
397 : Diagnostic::Warning);
398 }
399
400 if (Diags.hasErrorOccurred())
401 exit(1);
402
403 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000404 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000405 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000406 SourceMgr, *HeaderInfo, PTHMgr,
407 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000408
409 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
410 // That argument is used as the IdentifierInfoLookup argument to
411 // IdentifierTable's ctor.
412 if (PTHMgr) {
413 PTHMgr->setPreprocessor(PP);
414 PP->setPTHManager(PTHMgr);
415 }
416
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000417 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000418
Daniel Dunbarca11f612009-11-11 21:44:00 +0000419 // Handle generating dependencies, if requested.
420 if (!DepOpts.OutputFile.empty())
421 AttachDependencyFileGen(*PP, DepOpts);
422
Daniel Dunbar90b18272009-11-04 23:56:25 +0000423 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000424}
Reid Spencer5f016e22007-07-11 17:01:13 +0000425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426//===----------------------------------------------------------------------===//
427// Basic Parser driver
428//===----------------------------------------------------------------------===//
429
Chris Lattner51574ea2008-04-19 23:25:44 +0000430static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000432 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 // Parsing the specified input file.
435 P.ParseTranslationUnit();
436 delete PA;
437}
438
439//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000440// Fix-It Options
441//===----------------------------------------------------------------------===//
442static llvm::cl::list<ParsedSourceLocation>
443FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
444 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
445
446//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000447// ObjC Rewriter Options
448//===----------------------------------------------------------------------===//
449static llvm::cl::opt<bool>
450SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
451 llvm::cl::desc("Silence ObjC rewriting warnings"));
452
453//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +0000454// Warning Options
455//===----------------------------------------------------------------------===//
456
457// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
458// driver has stripped off -Wa,foo etc. The driver has also translated -W to
459// -Wextra, so we don't need to worry about it.
460static llvm::cl::list<std::string>
461OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
462
463static llvm::cl::opt<bool> OptPedantic("pedantic");
464static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
465static llvm::cl::opt<bool> OptNoWarnings("w");
466
467//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +0000468// -dump-build-information Stuff
469//===----------------------------------------------------------------------===//
470
471static llvm::cl::opt<std::string>
472DumpBuildInformation("dump-build-information",
473 llvm::cl::value_desc("filename"),
474 llvm::cl::desc("output a dump of some build information to a file"));
475
Daniel Dunbar227b2382009-11-09 22:45:57 +0000476static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000477 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000478 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000479 std::string ErrorInfo;
Daniel Dunbaraea36412009-11-11 09:38:24 +0000480 llvm::raw_ostream *OS = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
481 ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000482 if (!ErrorInfo.empty()) {
483 llvm::errs() << "error opening -dump-build-information file '"
484 << DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000485 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000486 return;
487 }
488
Daniel Dunbaraea36412009-11-11 09:38:24 +0000489 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000490 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000491 (*OS) << argv[i] << ' ';
492 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000494 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000495 DiagnosticClient *Logger =
496 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000497 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000498}
499
Chris Lattner75a97cb2009-04-17 21:05:01 +0000500//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000501// Main driver
502//===----------------------------------------------------------------------===//
503
Daniel Dunbare29709f2009-11-09 20:55:08 +0000504static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
505 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000506 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000507 bool Binary,
508 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000509 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000510 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000511 if (!CompOpts.getOutputFile().empty())
512 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000513 else if (InFile == "-") {
514 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000515 } else if (Extension) {
516 llvm::sys::Path Path(InFile);
517 Path.eraseSuffix();
518 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000519 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000520 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000521 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000522 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000523
Chris Lattner92bcc272009-08-23 02:59:41 +0000524 std::string Error;
525 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000526 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000527 if (!Error.empty()) {
528 // FIXME: Don't fail this way.
529 llvm::errs() << "ERROR: " << Error << "\n";
530 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000531 }
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Chris Lattner92bcc272009-08-23 02:59:41 +0000533 if (OutFile != "-")
534 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000535
536 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000537}
538
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000539/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000540/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000541static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000542 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000543 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000544
545 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
546 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
547 RequestedSourceLocation Requested;
548 Requested.File = File;
549 Requested.Line = FixItAtLocations[i].Line;
550 Requested.Column = FixItAtLocations[i].Column;
551 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000552 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000553 } else {
554 llvm::errs() << "FIX-IT could not find file \""
555 << FixItAtLocations[i].FileName << "\"\n";
556 }
557 }
558
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000559 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000560}
561
Daniel Dunbare29709f2009-11-09 20:55:08 +0000562static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
563 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000564 const std::string &InFile,
565 ProgActions PA,
566 llvm::OwningPtr<llvm::raw_ostream> &OS,
567 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000568 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000569 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000571 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000572
573 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000574 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000575 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Douglas Gregoree75c052009-05-21 20:55:50 +0000577 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000578 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000579 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000580
Eli Friedman66d6f042009-05-18 22:20:00 +0000581 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000582 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000583
Eli Friedman66d6f042009-05-18 22:20:00 +0000584 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000585 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000586
Anders Carlsson78762eb2009-09-24 18:54:49 +0000587 case DumpRecordLayouts:
588 return CreateRecordLayoutDumper();
589
Eli Friedman66d6f042009-05-18 22:20:00 +0000590 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000591 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000592
593 case EmitAssembly:
594 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000595 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000596 case EmitLLVMOnly: {
597 BackendAction Act;
598 if (ProgAction == EmitAssembly) {
599 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000600 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000601 } else if (ProgAction == EmitLLVM) {
602 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000603 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000604 } else if (ProgAction == EmitLLVMOnly) {
605 Act = Backend_EmitNothing;
606 } else {
607 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000608 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000609 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000610
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000611 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000612 CompOpts.getCompileOpts(), InFile, OS.get(),
613 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000614 }
615
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000616 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000617 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000618 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
619 PP.getLangOptions(), SilenceRewriteMacroWarning);
620
621 case RewriteBlocks:
622 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
623 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000624
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000625 case FixIt: // We add the rewriter later.
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000626 case ParseSyntaxOnly:
627 return new ASTConsumer();
628
629 case PrintDeclContext:
630 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000631 }
632}
633
634/// ProcessInputFile - Process a single input file with the specified state.
635///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000636static void ProcessInputFile(const CompilerInvocation &CompOpts,
637 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000638 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000639 llvm::OwningPtr<llvm::raw_ostream> OS;
640 llvm::OwningPtr<ASTConsumer> Consumer;
641 bool ClearSourceMgr = false;
642 FixItRewriter *FixItRewrite = 0;
643 bool CompleteTranslationUnit = true;
644 llvm::sys::Path OutPath;
645
646 switch (PA) {
647 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000648 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000649 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000650 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000651 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000652 return;
653 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000654 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000655
656 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000657 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000658 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000659 break;
660
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000661 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000662 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000663 CompOpts.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000664 break;
665
Daniel Dunbarf7973292009-11-11 08:13:32 +0000666 case GeneratePCH: {
667 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
668 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000669 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
670 RelocatablePCH.setValue(false);
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Daniel Dunbare29709f2009-11-09 20:55:08 +0000673 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000674 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000675 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000676 else
677 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000678 CompleteTranslationUnit = false;
679 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000680 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000681
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000682 // Do any necessary set up for non-consumer actions.
683 case DumpRawTokens:
684 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000685 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000686 case ParseNoop:
687 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000689 case GeneratePTH:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000690 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000691 // FIXME: Don't fail this way.
692 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000693 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000694 ::exit(1);
695 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000696 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000697 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000698
Chris Lattnercc7dea82009-04-27 22:02:30 +0000699 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000700 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000701 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000702 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000703 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000704 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000705 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000706
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000707 // Check if we want a fix-it rewriter.
708 if (PA == FixIt || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000709 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000710 PP.getSourceManager(),
711 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000712 if (!FixItAtLocations.empty() &&
713 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000714 // All of the fix-it locations were bad. Don't fix anything.
715 delete FixItRewrite;
716 FixItRewrite = 0;
717 }
718 }
719
720 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000721 llvm::OwningPtr<ExternalASTSource> Source;
722 const std::string &ImplicitPCHInclude =
723 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000724 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000725 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
726 PP.getSourceManager(),
727 PP.getTargetInfo(),
728 PP.getIdentifierTable(),
729 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000730 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000731 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000732 /* size_reserve = */0));
Daniel Dunbar1ea52942009-11-12 01:36:20 +0000733 if (Consumer && !ImplicitPCHInclude.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000734 // If the user specified -isysroot, it will be used for relocatable PCH
735 // files.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000736 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
737 if (isysrootPCH[0] == '\0')
738 isysrootPCH = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Daniel Dunbar66068642009-11-12 02:53:13 +0000740 llvm::OwningPtr<PCHReader> Reader;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000741 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000743 // The user has asked us to include a precompiled header. Load
744 // the precompiled header into the AST context.
Daniel Dunbare0a95812009-11-10 22:09:38 +0000745 switch (Reader->ReadPCH(ImplicitPCHInclude)) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000746 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +0000747 // Set the predefines buffer as suggested by the PCH
748 // reader. Typically, the predefines buffer will be empty.
749 PP.setPredefines(Reader->getSuggestedPredefines());
750
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000751 // Attach the PCH reader to the AST context as an external AST
752 // source, so that declarations will be deserialized from the
753 // PCH file as needed.
Daniel Dunbar66068642009-11-12 02:53:13 +0000754 Source.reset(Reader.take());
755 ContextOwner->setExternalSource(Source);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000756 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000757 }
758
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000759 case PCHReader::Failure:
760 // Unrecoverable failure: don't even try to process the input
761 // file.
762 return;
763
764 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +0000765 // No suitable PCH file could be found. Return an error.
766 return;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000767 }
Ted Kremenek46157b52009-01-28 04:29:29 +0000768 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000769
Daniel Dunbarb4373b22009-11-12 02:53:06 +0000770 // Initialize the main file entry. This needs to be delayed until after PCH
771 // has loaded.
772 if (InitializeSourceManager(PP, InFile))
773 return;
774
775 // Initialize builtin info unless we are using PCH.
776 if (!Consumer || ImplicitPCHInclude.empty())
777 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
778 PP.getLangOptions().NoBuiltin);
779
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000780 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +0000781 if (Consumer) {
782 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
783 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000784
Douglas Gregorb657f112009-09-22 21:11:38 +0000785 if (!CodeCompletionAt.FileName.empty()) {
786 // Tell the source manager to chop off the given file at a specific
787 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000788 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000789 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
790 // Truncate the named file at the given line/column.
791 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
792 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000793
Douglas Gregorb657f112009-09-22 21:11:38 +0000794 // Set up the creation routine for code-completion.
795 CreateCodeCompleter = BuildPrintingCodeCompleter;
796 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000797 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000798 << CodeCompletionAt.FileName;
799 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000800 }
801
Mike Stump1eb44332009-09-09 15:08:12 +0000802 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000803 CompleteTranslationUnit,
804 CreateCodeCompleter, CreateCodeCompleterData);
805 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000806
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000807 // Perform post processing actions and actions which don't use a consumer.
808 switch (PA) {
809 default: break;
810
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000811 case DumpRawTokens: {
812 llvm::TimeRegion Timer(ClangFrontendTimer);
813 SourceManager &SM = PP.getSourceManager();
814 // Start lexing the specified input file.
815 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
816 RawLex.SetKeepWhitespaceMode(true);
817
818 Token RawTok;
819 RawLex.LexFromRawLexer(RawTok);
820 while (RawTok.isNot(tok::eof)) {
821 PP.DumpToken(RawTok, true);
822 fprintf(stderr, "\n");
823 RawLex.LexFromRawLexer(RawTok);
824 }
825 ClearSourceMgr = true;
826 break;
827 }
828
829 case DumpTokens: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000830 llvm::TimeRegion Timer(ClangFrontendTimer);
831 Token Tok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000832 // Start preprocessing the specified input file.
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000833 PP.EnterMainSourceFile();
834 do {
835 PP.Lex(Tok);
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000836 PP.DumpToken(Tok, true);
837 fprintf(stderr, "\n");
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000838 } while (Tok.isNot(tok::eof));
839 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000840 break;
841 }
842
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000843 case GeneratePTH: {
844 llvm::TimeRegion Timer(ClangFrontendTimer);
845 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
846 ClearSourceMgr = true;
847 break;
848 }
849
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000850 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000851 llvm::TimeRegion Timer(ClangFrontendTimer);
852 ParseFile(PP, new MinimalAction(PP));
853 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000854 break;
855 }
856
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000857 case ParsePrintCallbacks: {
858 llvm::TimeRegion Timer(ClangFrontendTimer);
859 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
860 ClearSourceMgr = true;
861 break;
862 }
863
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000864 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +0000865 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000866 DoPrintPreprocessedInput(PP, OS.get(),
867 CompOpts.getPreprocessorOutputOpts());
Chris Lattnercc7dea82009-04-27 22:02:30 +0000868 ClearSourceMgr = true;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000869 break;
870 }
871
872 case RewriteMacros: {
873 llvm::TimeRegion Timer(ClangFrontendTimer);
874 RewriteMacrosInInput(PP, OS.get());
875 ClearSourceMgr = true;
876 break;
877 }
878
879 case RewriteTest: {
880 llvm::TimeRegion Timer(ClangFrontendTimer);
881 DoRewriteTest(PP, OS.get());
882 ClearSourceMgr = true;
883 break;
884 }
885
886 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
887 llvm::TimeRegion Timer(ClangFrontendTimer);
888 Token Tok;
889 // Start parsing the specified input file.
890 PP.EnterMainSourceFile();
891 do {
892 PP.Lex(Tok);
893 } while (Tok.isNot(tok::eof));
894 ClearSourceMgr = true;
895 break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000898 }
899
Chris Lattner1aee61a2009-04-27 21:25:27 +0000900 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +0000901 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000902
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000903 // Release the consumer and the AST, in that order since the consumer may
904 // perform actions in its destructor which require the context.
905 if (DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000906 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000907 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000908 } else {
909 Consumer.reset();
910 ContextOwner.reset();
911 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000912
Daniel Dunbar879c3ea2008-10-27 22:03:52 +0000913 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000914 if (CheckDiagnostics(PP))
915 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000916
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000918 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 PP.PrintStats();
920 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000921 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000922 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 fprintf(stderr, "\n");
924 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000925
Mike Stump1eb44332009-09-09 15:08:12 +0000926 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +0000927 // manager tables, other require stable fileid/macroid's across multiple
928 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +0000929 if (ClearSourceMgr)
930 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000931
Eli Friedman66d6f042009-05-18 22:20:00 +0000932 // Always delete the output stream because we don't want to leak file
933 // handles. Also, we don't want to try to erase an open file.
934 OS.reset();
935
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000936 // If we had errors, try to erase the output file.
937 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000938 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000939}
940
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000941/// ProcessInputFile - Process a single AST input file with the specified state.
942///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000943static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
944 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000945 Diagnostic &Diags, FileManager &FileMgr,
946 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000947 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000948 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000949 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000950 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000951 return;
952 }
953
954 Preprocessor &PP = AST->getPreprocessor();
955
956 llvm::OwningPtr<llvm::raw_ostream> OS;
957 llvm::sys::Path OutPath;
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000958 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000959 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000960 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000961 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000962 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000963 return;
964 }
965
Daniel Dunbara674bf42009-09-21 03:03:56 +0000966 // Set the main file ID to an empty file.
967 //
968 // FIXME: We probably shouldn't need this, but for now this is the simplest
969 // way to reuse the logic in ParseAST.
970 const char *EmptyStr = "";
971 llvm::MemoryBuffer *SB =
972 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
973 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000974
Daniel Dunbara674bf42009-09-21 03:03:56 +0000975 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000976 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +0000977 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000978 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000979
980 // Release the consumer and the AST, in that order since the consumer may
981 // perform actions in its destructor which require the context.
982 if (DisableFree) {
983 Consumer.take();
984 AST.take();
985 } else {
986 Consumer.reset();
987 AST.reset();
988 }
989
990 // Always delete the output stream because we don't want to leak file
991 // handles. Also, we don't want to try to erase an open file.
992 OS.reset();
993
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000994 // If we had errors, try to erase the output file.
995 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000996 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000997}
998
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000999static void LLVMErrorHandler(void *UserData, const std::string &Message) {
1000 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
1001
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001002 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001003
1004 // We cannot recover from llvm errors.
1005 exit(1);
1006}
1007
Daniel Dunbar227b2382009-11-09 22:45:57 +00001008static LangKind GetLanguage() {
1009 // If -x was given, that's the language.
1010 if (BaseLang != langkind_unspecified)
1011 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001012
Daniel Dunbar227b2382009-11-09 22:45:57 +00001013 // Otherwise guess it from the input filenames;
1014 LangKind LK = langkind_unspecified;
1015 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1016 llvm::StringRef Name(InputFilenames[i]);
1017 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
1018 .Case("ast", langkind_ast)
1019 .Case("c", langkind_c)
1020 .Cases("S", "s", langkind_asm_cpp)
1021 .Case("i", langkind_c_cpp)
1022 .Case("ii", langkind_cxx_cpp)
1023 .Case("m", langkind_objc)
1024 .Case("mi", langkind_objc_cpp)
1025 .Cases("mm", "M", langkind_objcxx)
1026 .Case("mii", langkind_objcxx_cpp)
1027 .Case("C", langkind_cxx)
1028 .Cases("C", "cc", "cp", langkind_cxx)
1029 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
1030 .Case("cl", langkind_ocl)
1031 .Default(langkind_c);
1032
1033 if (LK != langkind_unspecified && ThisKind != LK) {
1034 llvm::errs() << "error: cannot have multiple input files of distinct "
1035 << "language kinds without -x\n";
1036 exit(1);
1037 }
1038
1039 LK = ThisKind;
1040 }
1041
1042 return LK;
1043}
1044
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001045static void FinalizeCompileOptions(CompileOptions &Opts,
1046 const LangOptions &Lang) {
1047 if (Lang.NoBuiltin)
1048 Opts.SimplifyLibCalls = 0;
1049 if (Lang.CPlusPlus)
1050 Opts.NoCommon = 1;
1051
1052 // Handle -ftime-report.
1053 Opts.TimePasses = TimeReport;
1054}
1055
Daniel Dunbar227b2382009-11-09 22:45:57 +00001056static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001057 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001058 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001059 TargetInfo &Target,
1060 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001061 Opts.getDiagnosticOpts() = DiagOpts;
1062
1063 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001064
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001065 // Initialize backend options, which may also be used to key some language
1066 // options.
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001067 InitializeCompileOptions(Opts.getCompileOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001068
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001069 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001070 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001071 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1072 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001073 if (LK != langkind_ast)
1074 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001075 Opts.getCompileOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001076
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001077 // Initialize the static analyzer options.
1078 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
1079
Daniel Dunbar0e0bae82009-11-11 21:43:12 +00001080 // Initialize the dependency output options (-M...).
1081 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
1082
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001083 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001084 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1085 GetBuiltinIncludePath(Argv0),
1086 Verbose,
1087 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001088
1089 // Initialize the other preprocessor options.
1090 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001091
Daniel Dunbar29cf7462009-11-11 10:07:44 +00001092 // Initialize the preprocessed output options.
1093 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
1094
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001095 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001096 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001097}
1098
Reid Spencer5f016e22007-07-11 17:01:13 +00001099int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001101 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001102 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001103
Daniel Dunbar4d861512009-09-03 04:54:12 +00001104 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001105 llvm::InitializeAllTargets();
1106 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001107
1108 llvm::cl::ParseCommandLineOptions(argc, argv,
1109 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Chris Lattner47099742009-02-18 01:51:21 +00001111 if (TimeReport)
1112 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001114 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001115 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1116 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001117 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 // If no input was specified, read from stdin.
1120 if (InputFilenames.empty())
1121 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001122
Daniel Dunbar227b2382009-11-09 22:45:57 +00001123 // Construct the diagnostic options first, which cannot fail, so that we can
1124 // build a diagnostic client to use for any errors during option handling.
1125 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001126 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00001127
Ted Kremenek31e703b2007-12-11 23:28:38 +00001128 // Create the diagnostic client for reporting errors or for
1129 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001130 llvm::OwningPtr<DiagnosticClient> DiagClient;
1131 if (VerifyDiagnostics) {
1132 // When checking diagnostics, just buffer them up.
1133 DiagClient.reset(new TextDiagnosticBuffer());
1134 if (InputFilenames.size() != 1) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001135 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner409d4e72009-04-17 20:40:01 +00001136 return 1;
1137 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001138 } else {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001139 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 }
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Daniel Dunbarad451cc2009-11-05 02:11:37 +00001142 if (!DumpBuildInformation.empty())
Daniel Dunbar227b2382009-11-09 22:45:57 +00001143 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001144
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001146 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001147 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
1148 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001149 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001150
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001151 // Set an error handler, so that any LLVM backend diagnostics go through our
1152 // error handler.
1153 llvm::llvm_install_error_handler(LLVMErrorHandler,
1154 static_cast<void*>(&Diags));
1155
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001156 // Initialize base triple. If a -triple option has been specified, use
1157 // that triple. Otherwise, default to the host triple.
1158 llvm::Triple Triple(TargetTriple);
1159 if (Triple.getTriple().empty())
1160 Triple = llvm::Triple(llvm::sys::getHostTriple());
1161
Chris Lattner11215192008-03-14 06:12:05 +00001162 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001163 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001164 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Chris Lattner11215192008-03-14 06:12:05 +00001166 if (Target == 0) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001167 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001168 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001169 }
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Daniel Dunbar73b79592009-09-14 00:02:12 +00001171 // Set the target ABI if specified.
1172 if (!TargetABI.empty()) {
1173 if (!Target->setABI(TargetABI)) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001174 Diags.Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001175 return 1;
1176 }
1177 }
1178
Daniel Dunbard4270232009-01-20 23:17:32 +00001179 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001180 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Daniel Dunbar227b2382009-11-09 22:45:57 +00001182 // Infer the input language.
1183 //
1184 // FIXME: We should move .ast inputs to taking a separate path, they are
1185 // really quite different.
1186 LangKind LK = GetLanguage();
1187
1188 // Now that we have initialized the diagnostics engine and the target, finish
1189 // setting up the compiler invocation.
1190 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001191 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001192
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001193 // Create the source manager.
1194 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Chris Lattner2c78b872009-04-14 23:22:57 +00001196 // Create a file manager object to provide access to and cache the filesystem.
1197 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001200 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001202 // AST inputs are handled specially.
1203 if (LK == langkind_ast) {
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001204 ProcessASTInputFile(CompOpts, InFile, ProgAction, Diags, FileMgr,
1205 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001206 continue;
1207 }
1208
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001209 // Reset the ID tables if we are reusing the SourceManager.
1210 if (i)
1211 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Chris Lattnerf63aea32009-03-04 21:40:56 +00001213 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001214 llvm::OwningPtr<Preprocessor>
1215 PP(CreatePreprocessor(Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001216 CompOpts.getPreprocessorOpts(),
Daniel Dunbar961c76e2009-11-11 21:44:42 +00001217 CompOpts.getHeaderSearchOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001218 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001219 *Target, SourceMgr, FileMgr));
1220
Chris Lattnerf63aea32009-03-04 21:40:56 +00001221 // Process the source file.
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001222 Diags.getClient()->BeginSourceFile(CompOpts.getLangOpts());
1223 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001224 Diags.getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 }
Chris Lattner11215192008-03-14 06:12:05 +00001226
Daniel Dunbar9253e492009-11-10 00:46:12 +00001227 if (CompOpts.getDiagnosticOpts().ShowCarets)
Mike Stumpfc0fed32009-04-28 01:19:10 +00001228 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
1229 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1230 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 FileMgr.PrintStats();
1234 fprintf(stderr, "\n");
1235 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001236
1237 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Daniel Dunbar276373d2008-10-27 22:10:13 +00001239 // If verifying diagnostics and we reached here, all is well.
1240 if (VerifyDiagnostics)
1241 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001243 // Managed static deconstruction. Useful for making things like
1244 // -time-passes usable.
1245 llvm::llvm_shutdown();
1246
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001247 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001248}