blob: f2b38401e7b6f44cd63e9abab4e326ac3067124b [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
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"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 clEnumValEnd));
185
Ted Kremenekccc76472007-12-19 19:47:59 +0000186
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000187enum CodeCompletionPrinter {
188 CCP_Debug,
189 CCP_CIndex
190};
191
Douglas Gregorb657f112009-09-22 21:11:38 +0000192static llvm::cl::opt<ParsedSourceLocation>
193CodeCompletionAt("code-completion-at",
194 llvm::cl::value_desc("file:line:column"),
195 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000196
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000197static llvm::cl::opt<CodeCompletionPrinter>
198CodeCompletionPrinter("code-completion-printer",
199 llvm::cl::desc("Choose output type:"),
200 llvm::cl::init(CCP_Debug),
201 llvm::cl::values(
202 clEnumValN(CCP_Debug, "debug",
203 "Debug code-completion results"),
204 clEnumValN(CCP_CIndex, "cindex",
205 "Code-completion results for the CIndex library"),
206 clEnumValEnd));
207
208static llvm::cl::opt<bool>
209CodeCompletionWantsMacros("code-completion-macros",
210 llvm::cl::desc("Include macros in code-completion results"));
211
Douglas Gregor81b747b2009-09-17 21:32:03 +0000212/// \brief Buld a new code-completion consumer that prints the results of
213/// code completion to standard output.
214static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000215 switch (CodeCompletionPrinter.getValue()) {
216 case CCP_Debug:
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000217 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000218 llvm::outs());
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000219
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000220 case CCP_CIndex:
221 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
222 llvm::outs());
223 };
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000224
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000225 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000226}
227
Ted Kremenekc2e72992008-12-02 19:57:31 +0000228//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000229// C++ Visualization.
230//===----------------------------------------------------------------------===//
231
232static llvm::cl::opt<std::string>
233InheritanceViewCls("cxx-inheritance-view",
234 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000235 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000236
237//===----------------------------------------------------------------------===//
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000238// Frontend Options
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000239//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000240
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000241static llvm::cl::list<std::string>
242InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
243
244static llvm::cl::opt<std::string>
245OutputFile("o",
246 llvm::cl::value_desc("path"),
247 llvm::cl::desc("Specify output file"));
248
Chris Lattnerb2509e12009-02-18 01:12:43 +0000249static llvm::cl::opt<bool>
250TimeReport("ftime-report",
251 llvm::cl::desc("Print the amount of time each "
252 "phase of compilation takes"));
253
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000254static llvm::cl::opt<bool>
255VerifyDiagnostics("verify",
256 llvm::cl::desc("Verify emitted diagnostics and warnings"));
257
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000258//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000259// Language Options
260//===----------------------------------------------------------------------===//
261
Reid Spencer5f016e22007-07-11 17:01:13 +0000262static llvm::cl::opt<LangKind>
263BaseLang("x", llvm::cl::desc("Base language to compile"),
264 llvm::cl::init(langkind_unspecified),
265 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000266 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 clEnumValN(langkind_cxx, "c++", "C++"),
268 clEnumValN(langkind_objc, "objective-c", "Objective C"),
269 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000270 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000272 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
273 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000275 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
277 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000278 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000280 clEnumValN(langkind_c, "c-header",
281 "C header"),
282 clEnumValN(langkind_objc, "objective-c-header",
283 "Objective-C header"),
284 clEnumValN(langkind_cxx, "c++-header",
285 "C++ header"),
286 clEnumValN(langkind_objcxx, "objective-c++-header",
287 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000288 clEnumValN(langkind_ast, "ast",
289 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 clEnumValEnd));
291
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000292static llvm::cl::opt<std::string>
293TargetTriple("triple",
294 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
295
Daniel Dunbar56749082009-11-11 07:26:12 +0000296static llvm::cl::opt<std::string>
297TargetABI("target-abi",
298 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000299
300//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000301// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000302//===----------------------------------------------------------------------===//
303
Douglas Gregore1d918e2009-04-10 23:10:45 +0000304static bool InitializeSourceManager(Preprocessor &PP,
305 const std::string &InFile) {
306 // Figure out where to get and map in the main file.
307 SourceManager &SourceMgr = PP.getSourceManager();
308 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000309
310 if (EmptyInputOnly) {
311 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000312 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000313 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
314 SourceMgr.createMainFileIDForMemBuffer(SB);
315 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000316 const FileEntry *File = FileMgr.getFile(InFile);
317 if (File) SourceMgr.createMainFileID(File, SourceLocation());
318 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000319 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000320 return true;
321 }
322 } else {
323 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000324 SourceMgr.createMainFileIDForMemBuffer(SB);
325 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000326 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000327 return true;
328 }
329 }
330
331 return false;
332}
333
Chris Lattneraa391972008-04-19 23:09:31 +0000334
Chris Lattnere116ccf2009-04-21 05:40:52 +0000335//===----------------------------------------------------------------------===//
336// Preprocessor Initialization
337//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000338
Chris Lattnere6113de2009-11-03 19:50:27 +0000339static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000340RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000341 llvm::cl::desc("Whether to build a relocatable precompiled "
342 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000344//===----------------------------------------------------------------------===//
345// Preprocessor construction
346//===----------------------------------------------------------------------===//
Chris Lattner5f9eae52008-03-01 08:07:28 +0000347
Daniel Dunbar750156a2009-11-07 04:19:57 +0000348std::string GetBuiltinIncludePath(const char *Argv0) {
349 llvm::sys::Path P =
350 llvm::sys::Path::GetMainExecutable(Argv0,
351 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000352
Daniel Dunbar750156a2009-11-07 04:19:57 +0000353 if (!P.isEmpty()) {
354 P.eraseComponent(); // Remove /clang from foo/bin/clang
355 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000356
Daniel Dunbar750156a2009-11-07 04:19:57 +0000357 // Get foo/lib/clang/<version>/include
358 P.appendComponent("lib");
359 P.appendComponent("clang");
360 P.appendComponent(CLANG_VERSION_STRING);
361 P.appendComponent("include");
362 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000363
Daniel Dunbar750156a2009-11-07 04:19:57 +0000364 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000365}
366
Daniel Dunbar90b18272009-11-04 23:56:25 +0000367static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000368CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000369 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000370 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000371 const DependencyOutputOptions &DepOpts,
372 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000373 FileManager &FileMgr) {
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000374 // Create a PTH manager if we are using some form of a token cache.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000375 PTHManager *PTHMgr = 0;
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000376 if (!PPOpts.getTokenCache().empty())
377 PTHMgr = PTHManager::Create(PPOpts.getTokenCache(), Diags);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000378
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000379 // FIXME: Don't fail like this.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000380 if (Diags.hasErrorOccurred())
381 exit(1);
382
383 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000384 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000385 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000386 SourceMgr, *HeaderInfo, PTHMgr,
387 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000388
389 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
390 // That argument is used as the IdentifierInfoLookup argument to
391 // IdentifierTable's ctor.
392 if (PTHMgr) {
393 PTHMgr->setPreprocessor(PP);
394 PP->setPTHManager(PTHMgr);
395 }
396
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000397 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000398
Daniel Dunbarca11f612009-11-11 21:44:00 +0000399 // Handle generating dependencies, if requested.
400 if (!DepOpts.OutputFile.empty())
401 AttachDependencyFileGen(*PP, DepOpts);
402
Daniel Dunbar90b18272009-11-04 23:56:25 +0000403 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000404}
Reid Spencer5f016e22007-07-11 17:01:13 +0000405
Reid Spencer5f016e22007-07-11 17:01:13 +0000406//===----------------------------------------------------------------------===//
407// Basic Parser driver
408//===----------------------------------------------------------------------===//
409
Chris Lattner51574ea2008-04-19 23:25:44 +0000410static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000412 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 // Parsing the specified input file.
415 P.ParseTranslationUnit();
416 delete PA;
417}
418
419//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000420// Fix-It Options
421//===----------------------------------------------------------------------===//
Daniel Dunbarbfbeadb2009-11-12 06:48:24 +0000422
423static llvm::cl::opt<bool>
424FixItAll("fixit", llvm::cl::desc("Apply fix-it advice to the input source"));
425
Douglas Gregor26df2f02009-04-02 19:05:20 +0000426static llvm::cl::list<ParsedSourceLocation>
427FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
428 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
429
430//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000431// ObjC Rewriter Options
432//===----------------------------------------------------------------------===//
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000433
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000434static llvm::cl::opt<bool>
435SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
436 llvm::cl::desc("Silence ObjC rewriting warnings"));
437
438//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +0000439// Warning Options
440//===----------------------------------------------------------------------===//
441
442// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
443// driver has stripped off -Wa,foo etc. The driver has also translated -W to
444// -Wextra, so we don't need to worry about it.
445static llvm::cl::list<std::string>
446OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
447
448static llvm::cl::opt<bool> OptPedantic("pedantic");
449static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
450static llvm::cl::opt<bool> OptNoWarnings("w");
451
452//===----------------------------------------------------------------------===//
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000453// Dump Build Information
Chris Lattner75a97cb2009-04-17 21:05:01 +0000454//===----------------------------------------------------------------------===//
455
Daniel Dunbar227b2382009-11-09 22:45:57 +0000456static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000457 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000458 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000459 std::string ErrorInfo;
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000460 llvm::raw_ostream *OS =
461 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000462 if (!ErrorInfo.empty()) {
463 llvm::errs() << "error opening -dump-build-information file '"
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000464 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000465 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000466 return;
467 }
468
Daniel Dunbaraea36412009-11-11 09:38:24 +0000469 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000470 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000471 (*OS) << argv[i] << ' ';
472 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000474 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000475 DiagnosticClient *Logger =
476 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000477 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000478}
479
Chris Lattner75a97cb2009-04-17 21:05:01 +0000480//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000481// Main driver
482//===----------------------------------------------------------------------===//
483
Daniel Dunbare29709f2009-11-09 20:55:08 +0000484static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
485 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000486 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000487 bool Binary,
488 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000489 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000490 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000491 if (!CompOpts.getOutputFile().empty())
492 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000493 else if (InFile == "-") {
494 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000495 } else if (Extension) {
496 llvm::sys::Path Path(InFile);
497 Path.eraseSuffix();
498 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000499 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000500 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000501 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000502 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000503
Chris Lattner92bcc272009-08-23 02:59:41 +0000504 std::string Error;
505 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000506 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000507 if (!Error.empty()) {
508 // FIXME: Don't fail this way.
509 llvm::errs() << "ERROR: " << Error << "\n";
510 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner92bcc272009-08-23 02:59:41 +0000513 if (OutFile != "-")
514 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000515
516 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000517}
518
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000519/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000520/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000521static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000522 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000523 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000524
525 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
526 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
527 RequestedSourceLocation Requested;
528 Requested.File = File;
529 Requested.Line = FixItAtLocations[i].Line;
530 Requested.Column = FixItAtLocations[i].Column;
531 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000532 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000533 } else {
534 llvm::errs() << "FIX-IT could not find file \""
535 << FixItAtLocations[i].FileName << "\"\n";
536 }
537 }
538
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000539 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000540}
541
Daniel Dunbare29709f2009-11-09 20:55:08 +0000542static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
543 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000544 const std::string &InFile,
545 ProgActions PA,
546 llvm::OwningPtr<llvm::raw_ostream> &OS,
547 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000548 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000549 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000551 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000552
553 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000554 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000555 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Douglas Gregoree75c052009-05-21 20:55:50 +0000557 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000558 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000559 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000560
Eli Friedman66d6f042009-05-18 22:20:00 +0000561 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000562 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000563
Eli Friedman66d6f042009-05-18 22:20:00 +0000564 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000565 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000566
Anders Carlsson78762eb2009-09-24 18:54:49 +0000567 case DumpRecordLayouts:
568 return CreateRecordLayoutDumper();
569
Eli Friedman66d6f042009-05-18 22:20:00 +0000570 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000571 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000572
573 case EmitAssembly:
574 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000575 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000576 case EmitLLVMOnly: {
577 BackendAction Act;
578 if (ProgAction == EmitAssembly) {
579 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000580 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000581 } else if (ProgAction == EmitLLVM) {
582 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000583 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000584 } else if (ProgAction == EmitLLVMOnly) {
585 Act = Backend_EmitNothing;
586 } else {
587 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000588 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000589 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000590
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000591 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000592 CompOpts.getCompileOpts(), InFile, OS.get(),
593 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000594 }
595
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000596 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000597 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000598 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
599 PP.getLangOptions(), SilenceRewriteMacroWarning);
600
601 case RewriteBlocks:
602 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
603 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000604
605 case ParseSyntaxOnly:
606 return new ASTConsumer();
607
608 case PrintDeclContext:
609 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000610 }
611}
612
Daniel Dunbar975790e2009-11-12 02:53:20 +0000613/// ReadPCHFile - Load a PCH file from disk, and initialize the preprocessor for
614/// reading from the PCH file.
615///
616/// \return The AST source, or null on failure.
617static ExternalASTSource *ReadPCHFile(llvm::StringRef Path,
618 const CompilerInvocation &CompOpts,
619 Preprocessor &PP,
620 ASTContext &Context) {
621 // If the user specified -isysroot, it will be used for relocatable PCH files.
622 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
623 if (isysrootPCH[0] == '\0')
624 isysrootPCH = 0;
625
626 llvm::OwningPtr<PCHReader> Reader;
627 Reader.reset(new PCHReader(PP, &Context, isysrootPCH));
628
629 switch (Reader->ReadPCH(Path)) {
630 case PCHReader::Success:
631 // Set the predefines buffer as suggested by the PCH reader. Typically, the
632 // predefines buffer will be empty.
633 PP.setPredefines(Reader->getSuggestedPredefines());
634 return Reader.take();
635
636 case PCHReader::Failure:
637 // Unrecoverable failure: don't even try to process the input file.
638 break;
639
640 case PCHReader::IgnorePCH:
641 // No suitable PCH file could be found. Return an error.
642 break;
643 }
644
645 return 0;
646}
647
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000648/// ProcessInputFile - Process a single input file with the specified state.
649///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000650static void ProcessInputFile(const CompilerInvocation &CompOpts,
651 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000652 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000653 llvm::OwningPtr<llvm::raw_ostream> OS;
654 llvm::OwningPtr<ASTConsumer> Consumer;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000655 FixItRewriter *FixItRewrite = 0;
656 bool CompleteTranslationUnit = true;
657 llvm::sys::Path OutPath;
658
659 switch (PA) {
660 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000661 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000662 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000663 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000664 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000665 return;
666 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000667 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000668
669 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000670 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000671 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000672 break;
673
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000674 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000675 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000676 CompOpts.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000677 break;
678
Daniel Dunbarf7973292009-11-11 08:13:32 +0000679 case GeneratePCH: {
680 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
681 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000682 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
683 RelocatablePCH.setValue(false);
684 }
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Daniel Dunbare29709f2009-11-09 20:55:08 +0000686 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000687 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000688 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000689 else
690 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000691 CompleteTranslationUnit = false;
692 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000693 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000694
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000695 // Do any necessary set up for non-consumer actions.
696 case DumpRawTokens:
697 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000698 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000699 case ParseNoop:
700 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000702 case GeneratePTH:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000703 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000704 // FIXME: Don't fail this way.
705 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000706 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000707 ::exit(1);
708 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000709 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000710 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000711
Chris Lattnercc7dea82009-04-27 22:02:30 +0000712 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000713 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000714 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000715 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000716 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000717 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000718 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000719
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000720 // Check if we want a fix-it rewriter.
Daniel Dunbarbfbeadb2009-11-12 06:48:24 +0000721 if (FixItAll || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000722 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000723 PP.getSourceManager(),
724 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000725 if (!FixItAtLocations.empty() &&
726 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000727 // All of the fix-it locations were bad. Don't fix anything.
728 delete FixItRewrite;
729 FixItRewrite = 0;
730 }
731 }
732
733 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000734 llvm::OwningPtr<ExternalASTSource> Source;
735 const std::string &ImplicitPCHInclude =
736 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000737 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000738 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
739 PP.getSourceManager(),
740 PP.getTargetInfo(),
741 PP.getIdentifierTable(),
742 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000743 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000744 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000745 /* size_reserve = */0));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000746
747 if (!ImplicitPCHInclude.empty()) {
748 Source.reset(ReadPCHFile(ImplicitPCHInclude, CompOpts, PP,
749 *ContextOwner));
750 if (!Source)
751 return;
752
753 // Attach the PCH reader to the AST context as an external AST source, so
754 // that declarations will be deserialized from the PCH file as needed.
755 ContextOwner->setExternalSource(Source);
756 } else {
757 // Initialize builtin info when not using PCH.
758 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
759 PP.getLangOptions().NoBuiltin);
760 }
761
762 // Initialize the main file entry. This needs to be delayed until after PCH
763 // has loaded.
764 if (InitializeSourceManager(PP, InFile))
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000765 return;
766
Douglas Gregor81b747b2009-09-17 21:32:03 +0000767 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
768 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000769
Douglas Gregorb657f112009-09-22 21:11:38 +0000770 if (!CodeCompletionAt.FileName.empty()) {
771 // Tell the source manager to chop off the given file at a specific
772 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000773 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000774 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
775 // Truncate the named file at the given line/column.
776 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
777 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000778
Douglas Gregorb657f112009-09-22 21:11:38 +0000779 // Set up the creation routine for code-completion.
780 CreateCodeCompleter = BuildPrintingCodeCompleter;
781 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000782 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000783 << CodeCompletionAt.FileName;
784 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000785 }
786
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000787 // Run the AST consumer action.
Mike Stump1eb44332009-09-09 15:08:12 +0000788 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000789 CompleteTranslationUnit,
790 CreateCodeCompleter, CreateCodeCompleterData);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000791 } else {
792 // Initialize builtin info.
793 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
794 PP.getLangOptions().NoBuiltin);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000795
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000796 // Initialize the main file entry. This needs to be delayed until after PCH
797 // has loaded.
798 if (InitializeSourceManager(PP, InFile))
799 return;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000800
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000801 // Run the preprocessor actions.
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000802 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000803 switch (PA) {
804 default:
805 assert(0 && "unexpected program action");
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000806
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000807 case DumpRawTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000808 SourceManager &SM = PP.getSourceManager();
809 // Start lexing the specified input file.
810 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
811 RawLex.SetKeepWhitespaceMode(true);
812
813 Token RawTok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000814 RawLex.LexFromRawLexer(RawTok);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000815 while (RawTok.isNot(tok::eof)) {
816 PP.DumpToken(RawTok, true);
817 fprintf(stderr, "\n");
818 RawLex.LexFromRawLexer(RawTok);
819 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000820 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000821 }
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000822
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000823 case DumpTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000824 Token Tok;
825 // Start preprocessing the specified input file.
826 PP.EnterMainSourceFile();
827 do {
828 PP.Lex(Tok);
829 PP.DumpToken(Tok, true);
830 fprintf(stderr, "\n");
831 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000832 break;
833 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000834
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000835 case GeneratePTH:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000836 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000837 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000838
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000839 case ParseNoop:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000840 ParseFile(PP, new MinimalAction(PP));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000841 break;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000842
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000843 case ParsePrintCallbacks:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000844 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000845 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000846
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000847 case PrintPreprocessedInput:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000848 DoPrintPreprocessedInput(PP, OS.get(),
849 CompOpts.getPreprocessorOutputOpts());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000850 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000851
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000852 case RewriteMacros:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000853 RewriteMacrosInInput(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000854 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000855
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000856 case RewriteTest:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000857 DoRewriteTest(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000858 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000859
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000860 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000861 Token Tok;
862 // Start parsing the specified input file.
863 PP.EnterMainSourceFile();
864 do {
865 PP.Lex(Tok);
866 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000867 break;
868 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000869 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000870 }
871
Chris Lattner1aee61a2009-04-27 21:25:27 +0000872 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +0000873 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000874
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000875 // Release the consumer and the AST, in that order since the consumer may
876 // perform actions in its destructor which require the context.
877 if (DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000878 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000879 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000880 } else {
881 Consumer.reset();
882 ContextOwner.reset();
883 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000884
Daniel Dunbar879c3ea2008-10-27 22:03:52 +0000885 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000886 if (CheckDiagnostics(PP))
887 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000888
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000890 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 PP.PrintStats();
892 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000893 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000894 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 fprintf(stderr, "\n");
896 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000897
Eli Friedman66d6f042009-05-18 22:20:00 +0000898 // Always delete the output stream because we don't want to leak file
899 // handles. Also, we don't want to try to erase an open file.
900 OS.reset();
901
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000902 // If we had errors, try to erase the output file.
903 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000904 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000905}
906
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000907/// ProcessInputFile - Process a single AST input file with the specified state.
908///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000909static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
910 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000911 Diagnostic &Diags, FileManager &FileMgr,
912 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000913 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000914 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000915 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000916 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000917 return;
918 }
919
920 Preprocessor &PP = AST->getPreprocessor();
921
922 llvm::OwningPtr<llvm::raw_ostream> OS;
923 llvm::sys::Path OutPath;
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000924 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000925 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000926 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000927 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000928 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000929 return;
930 }
931
Daniel Dunbara674bf42009-09-21 03:03:56 +0000932 // Set the main file ID to an empty file.
933 //
934 // FIXME: We probably shouldn't need this, but for now this is the simplest
935 // way to reuse the logic in ParseAST.
936 const char *EmptyStr = "";
937 llvm::MemoryBuffer *SB =
938 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
939 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000940
Daniel Dunbara674bf42009-09-21 03:03:56 +0000941 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000942 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +0000943 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000944 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000945
946 // Release the consumer and the AST, in that order since the consumer may
947 // perform actions in its destructor which require the context.
948 if (DisableFree) {
949 Consumer.take();
950 AST.take();
951 } else {
952 Consumer.reset();
953 AST.reset();
954 }
955
956 // Always delete the output stream because we don't want to leak file
957 // handles. Also, we don't want to try to erase an open file.
958 OS.reset();
959
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000960 // If we had errors, try to erase the output file.
961 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000962 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000963}
964
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000965static void LLVMErrorHandler(void *UserData, const std::string &Message) {
966 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
967
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000968 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000969
970 // We cannot recover from llvm errors.
971 exit(1);
972}
973
Daniel Dunbar227b2382009-11-09 22:45:57 +0000974static LangKind GetLanguage() {
975 // If -x was given, that's the language.
976 if (BaseLang != langkind_unspecified)
977 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000978
Daniel Dunbar227b2382009-11-09 22:45:57 +0000979 // Otherwise guess it from the input filenames;
980 LangKind LK = langkind_unspecified;
981 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
982 llvm::StringRef Name(InputFilenames[i]);
983 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
984 .Case("ast", langkind_ast)
985 .Case("c", langkind_c)
986 .Cases("S", "s", langkind_asm_cpp)
987 .Case("i", langkind_c_cpp)
988 .Case("ii", langkind_cxx_cpp)
989 .Case("m", langkind_objc)
990 .Case("mi", langkind_objc_cpp)
991 .Cases("mm", "M", langkind_objcxx)
992 .Case("mii", langkind_objcxx_cpp)
993 .Case("C", langkind_cxx)
994 .Cases("C", "cc", "cp", langkind_cxx)
995 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
996 .Case("cl", langkind_ocl)
997 .Default(langkind_c);
998
999 if (LK != langkind_unspecified && ThisKind != LK) {
1000 llvm::errs() << "error: cannot have multiple input files of distinct "
1001 << "language kinds without -x\n";
1002 exit(1);
1003 }
1004
1005 LK = ThisKind;
1006 }
1007
1008 return LK;
1009}
1010
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001011static void FinalizeCompileOptions(CompileOptions &Opts,
1012 const LangOptions &Lang) {
1013 if (Lang.NoBuiltin)
1014 Opts.SimplifyLibCalls = 0;
1015 if (Lang.CPlusPlus)
1016 Opts.NoCommon = 1;
1017
1018 // Handle -ftime-report.
1019 Opts.TimePasses = TimeReport;
1020}
1021
Daniel Dunbar227b2382009-11-09 22:45:57 +00001022static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001023 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001024 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001025 TargetInfo &Target,
1026 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001027 Opts.getDiagnosticOpts() = DiagOpts;
1028
1029 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001030
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001031 // Initialize backend options, which may also be used to key some language
1032 // options.
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001033 InitializeCompileOptions(Opts.getCompileOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001034
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001035 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001036 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001037 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1038 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001039 if (LK != langkind_ast)
1040 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001041 Opts.getCompileOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001042
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001043 // Initialize the static analyzer options.
1044 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
1045
Daniel Dunbar0e0bae82009-11-11 21:43:12 +00001046 // Initialize the dependency output options (-M...).
1047 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
1048
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001049 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001050 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1051 GetBuiltinIncludePath(Argv0),
1052 Verbose,
1053 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001054
1055 // Initialize the other preprocessor options.
1056 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001057
Daniel Dunbar29cf7462009-11-11 10:07:44 +00001058 // Initialize the preprocessed output options.
1059 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
1060
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001061 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001062 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001063}
1064
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001065static Diagnostic *CreateDiagnosticEngine(const DiagnosticOptions &Opts,
1066 int argc, char **argv) {
1067 // Create the diagnostic client for reporting errors or for
1068 // implementing -verify.
1069 llvm::OwningPtr<DiagnosticClient> DiagClient;
1070 if (VerifyDiagnostics) {
1071 // When checking diagnostics, just buffer them up.
1072 DiagClient.reset(new TextDiagnosticBuffer());
1073 } else {
1074 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
1075 }
1076
Daniel Dunbar11e729d2009-11-12 07:28:21 +00001077 if (!Opts.DumpBuildInformation.empty())
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001078 SetUpBuildDumpLog(Opts, argc, argv, DiagClient);
1079
1080 // Configure our handling of diagnostics.
1081 Diagnostic *Diags = new Diagnostic(DiagClient.take());
1082 if (ProcessWarningOptions(*Diags, OptWarnings, OptPedantic, OptPedanticErrors,
1083 OptNoWarnings))
1084 return 0;
1085
1086 // Set an error handler, so that any LLVM backend diagnostics go through our
1087 // error handler.
1088 llvm::llvm_install_error_handler(LLVMErrorHandler,
1089 static_cast<void*>(Diags));
1090
1091 return Diags;
1092}
1093
Reid Spencer5f016e22007-07-11 17:01:13 +00001094int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001096 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001097 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001098
Daniel Dunbar4d861512009-09-03 04:54:12 +00001099 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001100 llvm::InitializeAllTargets();
1101 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001102
1103 llvm::cl::ParseCommandLineOptions(argc, argv,
1104 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001106 if (VerifyDiagnostics && InputFilenames.size() > 1) {
1107 fprintf(stderr, "-verify only works on single input files.\n");
1108 return 1;
1109 }
1110
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 Dunbar00e5b8d2009-11-12 06:48:31 +00001123 // Construct the diagnostic engine first, so that we can build a diagnostic
1124 // client to use for any errors during option handling.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001125 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001126 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001127 llvm::OwningPtr<Diagnostic>
1128 Diags(CreateDiagnosticEngine(DiagOpts, argc, argv));
1129 if (!Diags)
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001130 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001131
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001132 // FIXME: Hack to make sure we release the diagnostic client, the engine
1133 // should (optionally?) take ownership of it.
1134 llvm::OwningPtr<DiagnosticClient> DiagClient(Diags->getClient());
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001135
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001136 // Initialize base triple. If a -triple option has been specified, use
1137 // that triple. Otherwise, default to the host triple.
1138 llvm::Triple Triple(TargetTriple);
1139 if (Triple.getTriple().empty())
1140 Triple = llvm::Triple(llvm::sys::getHostTriple());
1141
Chris Lattner11215192008-03-14 06:12:05 +00001142 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001143 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001144 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Chris Lattner11215192008-03-14 06:12:05 +00001146 if (Target == 0) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001147 Diags->Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001148 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001149 }
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Daniel Dunbar73b79592009-09-14 00:02:12 +00001151 // Set the target ABI if specified.
1152 if (!TargetABI.empty()) {
1153 if (!Target->setABI(TargetABI)) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001154 Diags->Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001155 return 1;
1156 }
1157 }
1158
Daniel Dunbard4270232009-01-20 23:17:32 +00001159 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001160 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Daniel Dunbar227b2382009-11-09 22:45:57 +00001162 // Infer the input language.
1163 //
1164 // FIXME: We should move .ast inputs to taking a separate path, they are
1165 // really quite different.
1166 LangKind LK = GetLanguage();
1167
1168 // Now that we have initialized the diagnostics engine and the target, finish
1169 // setting up the compiler invocation.
1170 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001171 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001172
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001173 // Create the source manager.
1174 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner2c78b872009-04-14 23:22:57 +00001176 // Create a file manager object to provide access to and cache the filesystem.
1177 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001178
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001180 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001182 // AST inputs are handled specially.
1183 if (LK == langkind_ast) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001184 ProcessASTInputFile(CompOpts, InFile, ProgAction, *Diags, FileMgr,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001185 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001186 continue;
1187 }
1188
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001189 // Reset the ID tables if we are reusing the SourceManager.
1190 if (i)
1191 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Chris Lattnerf63aea32009-03-04 21:40:56 +00001193 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001194 llvm::OwningPtr<Preprocessor>
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001195 PP(CreatePreprocessor(*Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001196 CompOpts.getPreprocessorOpts(),
Daniel Dunbar961c76e2009-11-11 21:44:42 +00001197 CompOpts.getHeaderSearchOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001198 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001199 *Target, SourceMgr, FileMgr));
1200
Chris Lattnerf63aea32009-03-04 21:40:56 +00001201 // Process the source file.
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001202 Diags->getClient()->BeginSourceFile(CompOpts.getLangOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001203 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001204 Diags->getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 }
Chris Lattner11215192008-03-14 06:12:05 +00001206
Daniel Dunbar9253e492009-11-10 00:46:12 +00001207 if (CompOpts.getDiagnosticOpts().ShowCarets)
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001208 if (unsigned NumDiagnostics = Diags->getNumDiagnostics())
Mike Stumpfc0fed32009-04-28 01:19:10 +00001209 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1210 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 FileMgr.PrintStats();
1214 fprintf(stderr, "\n");
1215 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001216
1217 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Daniel Dunbar276373d2008-10-27 22:10:13 +00001219 // If verifying diagnostics and we reached here, all is well.
1220 if (VerifyDiagnostics)
1221 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001223 // Managed static deconstruction. Useful for making things like
1224 // -time-passes usable.
1225 llvm::llvm_shutdown();
1226
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001227 return (Diags->getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228}