blob: 2f544a8742e5d9de793a6872cc8df795d274f915 [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//===----------------------------------------------------------------------===//
Daniel Dunbaraa576142009-11-12 15:23:20 +000079// Code Completion Options
Reid Spencer5f016e22007-07-11 17:01:13 +000080//===----------------------------------------------------------------------===//
81
Daniel Dunbaraa576142009-11-12 15:23:20 +000082enum CodeCompletionPrinter {
83 CCP_Debug,
84 CCP_CIndex
85};
86
87static llvm::cl::opt<ParsedSourceLocation>
88CodeCompletionAt("code-completion-at",
89 llvm::cl::value_desc("file:line:column"),
90 llvm::cl::desc("Dump code-completion information at a location"));
91
92static llvm::cl::opt<CodeCompletionPrinter>
93CodeCompletionPrinter("code-completion-printer",
94 llvm::cl::desc("Choose output type:"),
95 llvm::cl::init(CCP_Debug),
96 llvm::cl::values(
97 clEnumValN(CCP_Debug, "debug",
98 "Debug code-completion results"),
99 clEnumValN(CCP_CIndex, "cindex",
100 "Code-completion results for the CIndex library"),
101 clEnumValEnd));
Chris Lattner47099742009-02-18 01:51:21 +0000102
Reid Spencer5f016e22007-07-11 17:01:13 +0000103static llvm::cl::opt<bool>
Daniel Dunbaraa576142009-11-12 15:23:20 +0000104CodeCompletionWantsMacros("code-completion-macros",
105 llvm::cl::desc("Include macros in code-completion results"));
106
107/// \brief Buld a new code-completion consumer that prints the results of
108/// code completion to standard output.
109static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
110 switch (CodeCompletionPrinter.getValue()) {
111 case CCP_Debug:
112 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
113 llvm::outs());
114
115 case CCP_CIndex:
116 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
117 llvm::outs());
118 };
119
120 return 0;
121}
122
123//===----------------------------------------------------------------------===//
124// Frontend Actions
125//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000126
127enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000128 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000129 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000130 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000131 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +0000132 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000133 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000135 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000136 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000137 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000138 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000139 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000140 ASTDump, // Parse ASTs and dump them.
141 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000142 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000143 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 ParsePrintCallbacks, // Parse and print each callback.
145 ParseSyntaxOnly, // Parse and perform semantic analysis.
146 ParseNoop, // Parse with noop callbacks.
147 RunPreprocessorOnly, // Just lex, no output.
148 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000149 DumpTokens, // Dump out preprocessed tokens.
150 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000151 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000152 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000153 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000154 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000155};
156
Mike Stump1eb44332009-09-09 15:08:12 +0000157static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000158ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
159 llvm::cl::init(ParseSyntaxOnly),
160 llvm::cl::values(
161 clEnumValN(RunPreprocessorOnly, "Eonly",
162 "Just run preprocessor, no output (for timings)"),
163 clEnumValN(PrintPreprocessedInput, "E",
164 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000165 clEnumValN(DumpRawTokens, "dump-raw-tokens",
166 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000167 clEnumValN(RunAnalysis, "analyze",
168 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000169 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 "Run preprocessor, dump internal rep of tokens"),
171 clEnumValN(ParseNoop, "parse-noop",
172 "Run parser with noop callbacks (for timings)"),
173 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
174 "Run parser and perform semantic analysis"),
175 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
176 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000177 clEnumValN(EmitHTML, "emit-html",
178 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000179 clEnumValN(ASTPrint, "ast-print",
180 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000181 clEnumValN(ASTPrintXML, "ast-print-xml",
182 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000183 clEnumValN(ASTDump, "ast-dump",
184 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000185 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000186 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000187 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000188 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000189 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
190 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000191 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000192 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000193 clEnumValN(GeneratePCH, "emit-pch",
194 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000195 clEnumValN(EmitAssembly, "S",
196 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000198 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000199 clEnumValN(EmitBC, "emit-llvm-bc",
200 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000201 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
202 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000203 clEnumValN(RewriteTest, "rewrite-test",
204 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000205 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000206 "Rewrite ObjC into C (code rewriter example)"),
207 clEnumValN(RewriteMacros, "rewrite-macros",
208 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000209 clEnumValN(RewriteBlocks, "rewrite-blocks",
210 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 clEnumValEnd));
212
Daniel Dunbaraa576142009-11-12 15:23:20 +0000213//===----------------------------------------------------------------------===//
214// Frontend Options
215//===----------------------------------------------------------------------===//
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000216
Daniel Dunbaraa576142009-11-12 15:23:20 +0000217static llvm::cl::list<ParsedSourceLocation>
218FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
219 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000220
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000221static llvm::cl::opt<bool>
Daniel Dunbaraa576142009-11-12 15:23:20 +0000222Verbose("v", llvm::cl::desc("Enable verbose output"));
223
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000224//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000225// Language Options
226//===----------------------------------------------------------------------===//
227
Reid Spencer5f016e22007-07-11 17:01:13 +0000228static llvm::cl::opt<LangKind>
229BaseLang("x", llvm::cl::desc("Base language to compile"),
230 llvm::cl::init(langkind_unspecified),
231 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000232 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 clEnumValN(langkind_cxx, "c++", "C++"),
234 clEnumValN(langkind_objc, "objective-c", "Objective C"),
235 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000236 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000238 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
239 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000241 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
243 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000244 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000246 clEnumValN(langkind_c, "c-header",
247 "C header"),
248 clEnumValN(langkind_objc, "objective-c-header",
249 "Objective-C header"),
250 clEnumValN(langkind_cxx, "c++-header",
251 "C++ header"),
252 clEnumValN(langkind_objcxx, "objective-c++-header",
253 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000254 clEnumValN(langkind_ast, "ast",
255 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 clEnumValEnd));
257
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000258static llvm::cl::opt<std::string>
259TargetTriple("triple",
260 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
261
Daniel Dunbar56749082009-11-11 07:26:12 +0000262static llvm::cl::opt<std::string>
263TargetABI("target-abi",
264 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000265
266//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000267// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000268//===----------------------------------------------------------------------===//
269
Douglas Gregore1d918e2009-04-10 23:10:45 +0000270static bool InitializeSourceManager(Preprocessor &PP,
Daniel Dunbar26266882009-11-12 23:52:32 +0000271 const FrontendOptions &FEOpts,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000272 const std::string &InFile) {
273 // Figure out where to get and map in the main file.
274 SourceManager &SourceMgr = PP.getSourceManager();
275 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000276
Daniel Dunbar26266882009-11-12 23:52:32 +0000277 if (FEOpts.EmptyInputOnly) {
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000278 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000279 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000280 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
281 SourceMgr.createMainFileIDForMemBuffer(SB);
282 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000283 const FileEntry *File = FileMgr.getFile(InFile);
284 if (File) SourceMgr.createMainFileID(File, SourceLocation());
285 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000286 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000287 return true;
288 }
289 } else {
290 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000291 SourceMgr.createMainFileIDForMemBuffer(SB);
292 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000293 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000294 return true;
295 }
296 }
297
298 return false;
299}
300
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000301//===----------------------------------------------------------------------===//
302// Preprocessor construction
303//===----------------------------------------------------------------------===//
Chris Lattner5f9eae52008-03-01 08:07:28 +0000304
Daniel Dunbar750156a2009-11-07 04:19:57 +0000305std::string GetBuiltinIncludePath(const char *Argv0) {
306 llvm::sys::Path P =
307 llvm::sys::Path::GetMainExecutable(Argv0,
308 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000309
Daniel Dunbar750156a2009-11-07 04:19:57 +0000310 if (!P.isEmpty()) {
311 P.eraseComponent(); // Remove /clang from foo/bin/clang
312 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000313
Daniel Dunbar750156a2009-11-07 04:19:57 +0000314 // Get foo/lib/clang/<version>/include
315 P.appendComponent("lib");
316 P.appendComponent("clang");
317 P.appendComponent(CLANG_VERSION_STRING);
318 P.appendComponent("include");
319 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000320
Daniel Dunbar750156a2009-11-07 04:19:57 +0000321 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000322}
323
Daniel Dunbar90b18272009-11-04 23:56:25 +0000324static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000325CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000326 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000327 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000328 const DependencyOutputOptions &DepOpts,
329 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000330 FileManager &FileMgr) {
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000331 // Create a PTH manager if we are using some form of a token cache.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000332 PTHManager *PTHMgr = 0;
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000333 if (!PPOpts.getTokenCache().empty())
334 PTHMgr = PTHManager::Create(PPOpts.getTokenCache(), Diags);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000335
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000336 // FIXME: Don't fail like this.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000337 if (Diags.hasErrorOccurred())
338 exit(1);
339
340 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000341 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000342 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000343 SourceMgr, *HeaderInfo, PTHMgr,
344 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000345
346 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
347 // That argument is used as the IdentifierInfoLookup argument to
348 // IdentifierTable's ctor.
349 if (PTHMgr) {
350 PTHMgr->setPreprocessor(PP);
351 PP->setPTHManager(PTHMgr);
352 }
353
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000354 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000355
Daniel Dunbarca11f612009-11-11 21:44:00 +0000356 // Handle generating dependencies, if requested.
357 if (!DepOpts.OutputFile.empty())
358 AttachDependencyFileGen(*PP, DepOpts);
359
Daniel Dunbar90b18272009-11-04 23:56:25 +0000360 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000361}
Reid Spencer5f016e22007-07-11 17:01:13 +0000362
Reid Spencer5f016e22007-07-11 17:01:13 +0000363//===----------------------------------------------------------------------===//
364// Basic Parser driver
365//===----------------------------------------------------------------------===//
366
Chris Lattner51574ea2008-04-19 23:25:44 +0000367static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000369 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // Parsing the specified input file.
372 P.ParseTranslationUnit();
373 delete PA;
374}
375
376//===----------------------------------------------------------------------===//
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000377// Dump Build Information
Chris Lattner75a97cb2009-04-17 21:05:01 +0000378//===----------------------------------------------------------------------===//
379
Daniel Dunbar227b2382009-11-09 22:45:57 +0000380static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000381 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000382 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000383 std::string ErrorInfo;
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000384 llvm::raw_ostream *OS =
385 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000386 if (!ErrorInfo.empty()) {
387 llvm::errs() << "error opening -dump-build-information file '"
Daniel Dunbar11e729d2009-11-12 07:28:21 +0000388 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000389 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000390 return;
391 }
392
Daniel Dunbaraea36412009-11-11 09:38:24 +0000393 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000394 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000395 (*OS) << argv[i] << ' ';
396 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000398 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000399 DiagnosticClient *Logger =
400 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000401 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000402}
403
Chris Lattner75a97cb2009-04-17 21:05:01 +0000404//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000405// Main driver
406//===----------------------------------------------------------------------===//
407
Daniel Dunbaraa576142009-11-12 15:23:20 +0000408/// ClangFrontendTimer - The front-end activities should charge time to it with
409/// TimeRegion. The -ftime-report option controls whether this will do
410/// anything.
411llvm::Timer *ClangFrontendTimer = 0;
412
Daniel Dunbare29709f2009-11-09 20:55:08 +0000413static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
414 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000415 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000416 bool Binary,
417 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000418 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000419 std::string OutFile;
Daniel Dunbar26266882009-11-12 23:52:32 +0000420 if (!CompOpts.getFrontendOpts().OutputFile.empty())
421 OutFile = CompOpts.getFrontendOpts().OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +0000422 else if (InFile == "-") {
423 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000424 } else if (Extension) {
425 llvm::sys::Path Path(InFile);
426 Path.eraseSuffix();
427 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000428 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000429 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000430 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000431 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000432
Chris Lattner92bcc272009-08-23 02:59:41 +0000433 std::string Error;
434 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000435 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000436 if (!Error.empty()) {
437 // FIXME: Don't fail this way.
438 llvm::errs() << "ERROR: " << Error << "\n";
439 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner92bcc272009-08-23 02:59:41 +0000442 if (OutFile != "-")
443 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000444
445 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000446}
447
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000448/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000449/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000450static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000451 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000452 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000453
454 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
455 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
456 RequestedSourceLocation Requested;
457 Requested.File = File;
458 Requested.Line = FixItAtLocations[i].Line;
459 Requested.Column = FixItAtLocations[i].Column;
460 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000461 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000462 } else {
463 llvm::errs() << "FIX-IT could not find file \""
464 << FixItAtLocations[i].FileName << "\"\n";
465 }
466 }
467
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000468 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000469}
470
Daniel Dunbare29709f2009-11-09 20:55:08 +0000471static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
472 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000473 const std::string &InFile,
474 ProgActions PA,
475 llvm::OwningPtr<llvm::raw_ostream> &OS,
476 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000477 llvm::LLVMContext& Context) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000478 const FrontendOptions &FEOpts = CompOpts.getFrontendOpts();
479
Ted Kremenek85888962008-10-21 00:54:44 +0000480 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000482 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000483
484 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000485 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000486 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Douglas Gregoree75c052009-05-21 20:55:50 +0000488 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000489 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000490 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000491
Eli Friedman66d6f042009-05-18 22:20:00 +0000492 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000493 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000494
Eli Friedman66d6f042009-05-18 22:20:00 +0000495 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000496 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000497
Anders Carlsson78762eb2009-09-24 18:54:49 +0000498 case DumpRecordLayouts:
499 return CreateRecordLayoutDumper();
500
Eli Friedman66d6f042009-05-18 22:20:00 +0000501 case InheritanceView:
Daniel Dunbar26266882009-11-12 23:52:32 +0000502 return CreateInheritanceViewer(FEOpts.ViewClassInheritance);
Eli Friedman66d6f042009-05-18 22:20:00 +0000503
504 case EmitAssembly:
505 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000506 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000507 case EmitLLVMOnly: {
508 BackendAction Act;
509 if (ProgAction == EmitAssembly) {
510 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000511 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000512 } else if (ProgAction == EmitLLVM) {
513 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000514 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000515 } else if (ProgAction == EmitLLVMOnly) {
516 Act = Backend_EmitNothing;
517 } else {
518 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000519 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000520 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000521
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000522 // Fix-its can change semantics, disallow with any IRgen action.
Daniel Dunbar26266882009-11-12 23:52:32 +0000523 if (FEOpts.FixItAll || !FixItAtLocations.empty()) {
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000524 PP.getDiagnostics().Report(diag::err_fe_no_fixit_and_codegen);
525 return 0;
526 }
527
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000528 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000529 CompOpts.getCodeGenOpts(), InFile, OS.get(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000530 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000531 }
532
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000533 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000534 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000535 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Daniel Dunbar69079432009-11-12 07:28:44 +0000536 PP.getLangOptions(),
537 CompOpts.getDiagnosticOpts().NoRewriteMacros);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000538
539 case RewriteBlocks:
540 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
541 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000542
543 case ParseSyntaxOnly:
544 return new ASTConsumer();
545
546 case PrintDeclContext:
547 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000548 }
549}
550
Daniel Dunbar975790e2009-11-12 02:53:20 +0000551/// ReadPCHFile - Load a PCH file from disk, and initialize the preprocessor for
552/// reading from the PCH file.
553///
554/// \return The AST source, or null on failure.
555static ExternalASTSource *ReadPCHFile(llvm::StringRef Path,
556 const CompilerInvocation &CompOpts,
557 Preprocessor &PP,
558 ASTContext &Context) {
559 // If the user specified -isysroot, it will be used for relocatable PCH files.
560 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
561 if (isysrootPCH[0] == '\0')
562 isysrootPCH = 0;
563
564 llvm::OwningPtr<PCHReader> Reader;
565 Reader.reset(new PCHReader(PP, &Context, isysrootPCH));
566
567 switch (Reader->ReadPCH(Path)) {
568 case PCHReader::Success:
569 // Set the predefines buffer as suggested by the PCH reader. Typically, the
570 // predefines buffer will be empty.
571 PP.setPredefines(Reader->getSuggestedPredefines());
572 return Reader.take();
573
574 case PCHReader::Failure:
575 // Unrecoverable failure: don't even try to process the input file.
576 break;
577
578 case PCHReader::IgnorePCH:
579 // No suitable PCH file could be found. Return an error.
580 break;
581 }
582
583 return 0;
584}
585
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000586/// ProcessInputFile - Process a single input file with the specified state.
587///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000588static void ProcessInputFile(const CompilerInvocation &CompOpts,
589 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000590 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000591 const FrontendOptions &FEOpts = CompOpts.getFrontendOpts();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000592 llvm::OwningPtr<llvm::raw_ostream> OS;
593 llvm::OwningPtr<ASTConsumer> Consumer;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000594 FixItRewriter *FixItRewrite = 0;
595 bool CompleteTranslationUnit = true;
596 llvm::sys::Path OutPath;
597
598 switch (PA) {
599 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000600 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000601 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000602 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000603 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000604 return;
605 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000606 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000607
608 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000609 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000610 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000611 break;
612
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000613 case RunAnalysis:
Daniel Dunbar26266882009-11-12 23:52:32 +0000614 Consumer.reset(CreateAnalysisConsumer(PP, FEOpts.OutputFile,
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000615 CompOpts.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000616 break;
617
Daniel Dunbarf7973292009-11-11 08:13:32 +0000618 case GeneratePCH: {
619 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
Daniel Dunbar26266882009-11-12 23:52:32 +0000620 bool Relocatable = FEOpts.RelocatablePCH;
621 if (Relocatable && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000622 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
Daniel Dunbar26266882009-11-12 23:52:32 +0000623 Relocatable = false;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Daniel Dunbare29709f2009-11-09 20:55:08 +0000626 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar26266882009-11-12 23:52:32 +0000627 if (Relocatable)
Daniel Dunbarf7973292009-11-11 08:13:32 +0000628 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000629 else
630 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000631 CompleteTranslationUnit = false;
632 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000633 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000634
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000635 // Do any necessary set up for non-consumer actions.
636 case DumpRawTokens:
637 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000638 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000639 case ParseNoop:
640 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000642 case GeneratePTH:
Daniel Dunbar26266882009-11-12 23:52:32 +0000643 if (FEOpts.OutputFile.empty() || FEOpts.OutputFile == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000644 // FIXME: Don't fail this way.
645 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000646 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000647 ::exit(1);
648 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000649 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000650 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000651
Chris Lattnercc7dea82009-04-27 22:02:30 +0000652 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000653 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000654 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000655 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000656 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000657 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000658 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000659
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000660 // Check if we want a fix-it rewriter.
Daniel Dunbar26266882009-11-12 23:52:32 +0000661 if (FEOpts.FixItAll || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000662 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000663 PP.getSourceManager(),
664 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000665 if (!FixItAtLocations.empty() &&
666 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000667 // All of the fix-it locations were bad. Don't fix anything.
668 delete FixItRewrite;
669 FixItRewrite = 0;
670 }
671 }
672
673 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000674 llvm::OwningPtr<ExternalASTSource> Source;
675 const std::string &ImplicitPCHInclude =
676 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000677 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000678 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
679 PP.getSourceManager(),
680 PP.getTargetInfo(),
681 PP.getIdentifierTable(),
682 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000683 PP.getBuiltinInfo(),
Daniel Dunbar26266882009-11-12 23:52:32 +0000684 /* FreeMemory = */ !FEOpts.DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000685 /* size_reserve = */0));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000686
687 if (!ImplicitPCHInclude.empty()) {
688 Source.reset(ReadPCHFile(ImplicitPCHInclude, CompOpts, PP,
689 *ContextOwner));
690 if (!Source)
691 return;
692
693 // Attach the PCH reader to the AST context as an external AST source, so
694 // that declarations will be deserialized from the PCH file as needed.
695 ContextOwner->setExternalSource(Source);
696 } else {
697 // Initialize builtin info when not using PCH.
698 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
699 PP.getLangOptions().NoBuiltin);
700 }
701
702 // Initialize the main file entry. This needs to be delayed until after PCH
703 // has loaded.
Daniel Dunbar26266882009-11-12 23:52:32 +0000704 if (InitializeSourceManager(PP, CompOpts.getFrontendOpts(), InFile))
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000705 return;
706
Douglas Gregor81b747b2009-09-17 21:32:03 +0000707 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
708 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000709
Douglas Gregorb657f112009-09-22 21:11:38 +0000710 if (!CodeCompletionAt.FileName.empty()) {
711 // Tell the source manager to chop off the given file at a specific
712 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000713 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000714 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
715 // Truncate the named file at the given line/column.
716 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
717 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000718
Douglas Gregorb657f112009-09-22 21:11:38 +0000719 // Set up the creation routine for code-completion.
720 CreateCodeCompleter = BuildPrintingCodeCompleter;
721 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000722 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000723 << CodeCompletionAt.FileName;
724 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000725 }
726
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000727 // Run the AST consumer action.
Daniel Dunbar26266882009-11-12 23:52:32 +0000728 ParseAST(PP, Consumer.get(), *ContextOwner.get(), FEOpts.ShowStats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000729 CompleteTranslationUnit,
730 CreateCodeCompleter, CreateCodeCompleterData);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000731 } else {
732 // Initialize builtin info.
733 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
734 PP.getLangOptions().NoBuiltin);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000735
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000736 // Initialize the main file entry. This needs to be delayed until after PCH
737 // has loaded.
Daniel Dunbar26266882009-11-12 23:52:32 +0000738 if (InitializeSourceManager(PP, CompOpts.getFrontendOpts(), InFile))
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000739 return;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000740
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000741 // Run the preprocessor actions.
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000742 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000743 switch (PA) {
744 default:
745 assert(0 && "unexpected program action");
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000746
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000747 case DumpRawTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000748 SourceManager &SM = PP.getSourceManager();
749 // Start lexing the specified input file.
750 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
751 RawLex.SetKeepWhitespaceMode(true);
752
753 Token RawTok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000754 RawLex.LexFromRawLexer(RawTok);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000755 while (RawTok.isNot(tok::eof)) {
756 PP.DumpToken(RawTok, true);
757 fprintf(stderr, "\n");
758 RawLex.LexFromRawLexer(RawTok);
759 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000760 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000761 }
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000762
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000763 case DumpTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000764 Token Tok;
765 // Start preprocessing the specified input file.
766 PP.EnterMainSourceFile();
767 do {
768 PP.Lex(Tok);
769 PP.DumpToken(Tok, true);
770 fprintf(stderr, "\n");
771 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000772 break;
773 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000774
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000775 case GeneratePTH:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000776 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000777 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000778
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000779 case ParseNoop:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000780 ParseFile(PP, new MinimalAction(PP));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000781 break;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000782
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000783 case ParsePrintCallbacks:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000784 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000785 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000786
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000787 case PrintPreprocessedInput:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000788 DoPrintPreprocessedInput(PP, OS.get(),
789 CompOpts.getPreprocessorOutputOpts());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000790 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000791
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000792 case RewriteMacros:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000793 RewriteMacrosInInput(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000794 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000795
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000796 case RewriteTest:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000797 DoRewriteTest(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000798 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000799
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000800 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000801 Token Tok;
802 // Start parsing the specified input file.
803 PP.EnterMainSourceFile();
804 do {
805 PP.Lex(Tok);
806 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000807 break;
808 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000809 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000810 }
811
Chris Lattner1aee61a2009-04-27 21:25:27 +0000812 if (FixItRewrite)
Daniel Dunbar26266882009-11-12 23:52:32 +0000813 FixItRewrite->WriteFixedFile(InFile, FEOpts.OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000814
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000815 // Release the consumer and the AST, in that order since the consumer may
816 // perform actions in its destructor which require the context.
Daniel Dunbar26266882009-11-12 23:52:32 +0000817 if (FEOpts.DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000818 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000819 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000820 } else {
821 Consumer.reset();
822 ContextOwner.reset();
823 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000824
Daniel Dunbar26266882009-11-12 23:52:32 +0000825 if (CompOpts.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000826 if (CheckDiagnostics(PP))
827 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000828
Daniel Dunbar26266882009-11-12 23:52:32 +0000829 if (FEOpts.ShowStats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000830 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 PP.PrintStats();
832 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000833 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000834 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 fprintf(stderr, "\n");
836 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000837
Eli Friedman66d6f042009-05-18 22:20:00 +0000838 // Always delete the output stream because we don't want to leak file
839 // handles. Also, we don't want to try to erase an open file.
840 OS.reset();
841
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000842 // If we had errors, try to erase the output file.
843 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000844 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000845}
846
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000847/// ProcessInputFile - Process a single AST input file with the specified state.
848///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000849static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
850 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000851 Diagnostic &Diags, FileManager &FileMgr,
852 llvm::LLVMContext& Context) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000853 const FrontendOptions &FEOpts = CompOpts.getFrontendOpts();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000854 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000855 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000856 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000857 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000858 return;
859 }
860
861 Preprocessor &PP = AST->getPreprocessor();
862
863 llvm::OwningPtr<llvm::raw_ostream> OS;
864 llvm::sys::Path OutPath;
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000865 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000866 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000867 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000868 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000869 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000870 return;
871 }
872
Daniel Dunbara674bf42009-09-21 03:03:56 +0000873 // Set the main file ID to an empty file.
874 //
875 // FIXME: We probably shouldn't need this, but for now this is the simplest
876 // way to reuse the logic in ParseAST.
877 const char *EmptyStr = "";
878 llvm::MemoryBuffer *SB =
879 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
880 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000881
Daniel Dunbara674bf42009-09-21 03:03:56 +0000882 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000883 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbar26266882009-11-12 23:52:32 +0000884 ParseAST(PP, Consumer.get(), AST->getASTContext(), FEOpts.ShowStats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000885 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000886
887 // Release the consumer and the AST, in that order since the consumer may
888 // perform actions in its destructor which require the context.
Daniel Dunbar26266882009-11-12 23:52:32 +0000889 if (FEOpts.DisableFree) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000890 Consumer.take();
891 AST.take();
892 } else {
893 Consumer.reset();
894 AST.reset();
895 }
896
897 // Always delete the output stream because we don't want to leak file
898 // handles. Also, we don't want to try to erase an open file.
899 OS.reset();
900
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000901 // If we had errors, try to erase the output file.
902 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000903 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000904}
905
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000906static void LLVMErrorHandler(void *UserData, const std::string &Message) {
907 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
908
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000909 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000910
911 // We cannot recover from llvm errors.
912 exit(1);
913}
914
Daniel Dunbar26266882009-11-12 23:52:32 +0000915static LangKind GetLanguage(const std::vector<std::string> &Inputs) {
Daniel Dunbar227b2382009-11-09 22:45:57 +0000916 // If -x was given, that's the language.
917 if (BaseLang != langkind_unspecified)
918 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000919
Daniel Dunbar227b2382009-11-09 22:45:57 +0000920 // Otherwise guess it from the input filenames;
921 LangKind LK = langkind_unspecified;
Daniel Dunbar26266882009-11-12 23:52:32 +0000922 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
923 llvm::StringRef Name(Inputs[i]);
Daniel Dunbar227b2382009-11-09 22:45:57 +0000924 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
925 .Case("ast", langkind_ast)
926 .Case("c", langkind_c)
927 .Cases("S", "s", langkind_asm_cpp)
928 .Case("i", langkind_c_cpp)
929 .Case("ii", langkind_cxx_cpp)
930 .Case("m", langkind_objc)
931 .Case("mi", langkind_objc_cpp)
932 .Cases("mm", "M", langkind_objcxx)
933 .Case("mii", langkind_objcxx_cpp)
934 .Case("C", langkind_cxx)
935 .Cases("C", "cc", "cp", langkind_cxx)
936 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
937 .Case("cl", langkind_ocl)
938 .Default(langkind_c);
939
940 if (LK != langkind_unspecified && ThisKind != LK) {
941 llvm::errs() << "error: cannot have multiple input files of distinct "
942 << "language kinds without -x\n";
943 exit(1);
944 }
945
946 LK = ThisKind;
947 }
948
949 return LK;
950}
951
Daniel Dunbar227b2382009-11-09 22:45:57 +0000952static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000953 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +0000954 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000955 TargetInfo &Target,
Daniel Dunbar26266882009-11-12 23:52:32 +0000956 bool &IsAST) {
Daniel Dunbar227b2382009-11-09 22:45:57 +0000957 Opts.getDiagnosticOpts() = DiagOpts;
958
Daniel Dunbar26266882009-11-12 23:52:32 +0000959 // Initialize frontend options.
960 InitializeFrontendOptions(Opts.getFrontendOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000961
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000962 // Initialize backend options, which may also be used to key some language
963 // options.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000964 InitializeCodeGenOptions(Opts.getCodeGenOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000965
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000966 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000967 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000968 // FIXME: These aren't used during operations on ASTs. Split onto a separate
969 // code path to make this obvious.
Daniel Dunbar26266882009-11-12 23:52:32 +0000970 LangKind LK = GetLanguage(Opts.getFrontendOpts().InputFilenames);
971 IsAST = LK == langkind_ast;
972 if (!IsAST)
Daniel Dunbar56749082009-11-11 07:26:12 +0000973 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000974 Opts.getCodeGenOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000975
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000976 // Initialize the static analyzer options.
977 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
978
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000979 // Initialize the dependency output options (-M...).
980 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
981
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000982 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000983 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
984 GetBuiltinIncludePath(Argv0),
985 Verbose,
986 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000987
988 // Initialize the other preprocessor options.
989 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000990
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000991 // Initialize the preprocessed output options.
992 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
993
Daniel Dunbar26266882009-11-12 23:52:32 +0000994 // Finalize some code generation options which are derived from other places.
995 if (Opts.getLangOpts().NoBuiltin)
996 Opts.getCodeGenOpts().SimplifyLibCalls = 0;
997 if (Opts.getLangOpts().CPlusPlus)
998 Opts.getCodeGenOpts().NoCommon = 1;
999 Opts.getCodeGenOpts().TimePasses = Opts.getFrontendOpts().ShowTimers;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001000}
1001
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001002static Diagnostic *CreateDiagnosticEngine(const DiagnosticOptions &Opts,
1003 int argc, char **argv) {
1004 // Create the diagnostic client for reporting errors or for
1005 // implementing -verify.
1006 llvm::OwningPtr<DiagnosticClient> DiagClient;
Daniel Dunbar26266882009-11-12 23:52:32 +00001007 if (Opts.VerifyDiagnostics) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001008 // When checking diagnostics, just buffer them up.
1009 DiagClient.reset(new TextDiagnosticBuffer());
1010 } else {
1011 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
1012 }
1013
Daniel Dunbar11e729d2009-11-12 07:28:21 +00001014 if (!Opts.DumpBuildInformation.empty())
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001015 SetUpBuildDumpLog(Opts, argc, argv, DiagClient);
1016
1017 // Configure our handling of diagnostics.
1018 Diagnostic *Diags = new Diagnostic(DiagClient.take());
Daniel Dunbar69079432009-11-12 07:28:44 +00001019 if (ProcessWarningOptions(*Diags, Opts))
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001020 return 0;
1021
1022 // Set an error handler, so that any LLVM backend diagnostics go through our
1023 // error handler.
1024 llvm::llvm_install_error_handler(LLVMErrorHandler,
1025 static_cast<void*>(Diags));
1026
1027 return Diags;
1028}
1029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001032 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001033 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001034
Daniel Dunbar4d861512009-09-03 04:54:12 +00001035 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001036 llvm::InitializeAllTargets();
1037 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001038
1039 llvm::cl::ParseCommandLineOptions(argc, argv,
1040 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001042 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001043 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1044 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001045 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001047 // Construct the diagnostic engine first, so that we can build a diagnostic
1048 // client to use for any errors during option handling.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001049 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001050 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001051 llvm::OwningPtr<Diagnostic>
1052 Diags(CreateDiagnosticEngine(DiagOpts, argc, argv));
1053 if (!Diags)
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001054 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001055
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001056 // FIXME: Hack to make sure we release the diagnostic client, the engine
1057 // should (optionally?) take ownership of it.
1058 llvm::OwningPtr<DiagnosticClient> DiagClient(Diags->getClient());
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001059
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001060 // Initialize base triple. If a -triple option has been specified, use
1061 // that triple. Otherwise, default to the host triple.
1062 llvm::Triple Triple(TargetTriple);
1063 if (Triple.getTriple().empty())
1064 Triple = llvm::Triple(llvm::sys::getHostTriple());
1065
Chris Lattner11215192008-03-14 06:12:05 +00001066 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001067 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001068 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Chris Lattner11215192008-03-14 06:12:05 +00001069 if (Target == 0) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001070 Diags->Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001071 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001072 }
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Daniel Dunbar73b79592009-09-14 00:02:12 +00001074 // Set the target ABI if specified.
Daniel Dunbaraa576142009-11-12 15:23:20 +00001075 if (!TargetABI.empty() &&!Target->setABI(TargetABI)) {
1076 Diags->Report(diag::err_fe_unknown_target_abi) << TargetABI;
1077 return 1;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001078 }
1079
Daniel Dunbar26266882009-11-12 23:52:32 +00001080 // Now that we have initialized the diagnostics engine and the target, finish
1081 // setting up the compiler invocation.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001082 //
1083 // FIXME: We should move .ast inputs to taking a separate path, they are
1084 // really quite different.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001085 CompilerInvocation CompOpts;
Daniel Dunbar26266882009-11-12 23:52:32 +00001086 bool IsAST;
1087 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, IsAST);
1088
1089 // Validate some options.
1090 if (CompOpts.getFrontendOpts().ShowTimers)
1091 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
1092
1093 if (CompOpts.getDiagnosticOpts().VerifyDiagnostics &&
1094 CompOpts.getFrontendOpts().InputFilenames.size() > 1) {
1095 fprintf(stderr, "-verify only works on single input files.\n");
1096 return 1;
1097 }
1098
1099 // C++ visualization?
1100 if (!CompOpts.getFrontendOpts().ViewClassInheritance.empty())
1101 ProgAction = InheritanceView;
Daniel Dunbar227b2382009-11-09 22:45:57 +00001102
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001103 // Create the source manager.
1104 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Chris Lattner2c78b872009-04-14 23:22:57 +00001106 // Create a file manager object to provide access to and cache the filesystem.
1107 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001108
Daniel Dunbar26266882009-11-12 23:52:32 +00001109 for (unsigned i = 0, e = CompOpts.getFrontendOpts().InputFilenames.size();
1110 i != e; ++i) {
1111 const std::string &InFile = CompOpts.getFrontendOpts().InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001113 // AST inputs are handled specially.
Daniel Dunbar26266882009-11-12 23:52:32 +00001114 if (IsAST) {
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001115 ProcessASTInputFile(CompOpts, InFile, ProgAction, *Diags, FileMgr,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001116 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001117 continue;
1118 }
1119
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001120 // Reset the ID tables if we are reusing the SourceManager.
1121 if (i)
1122 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattnerf63aea32009-03-04 21:40:56 +00001124 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001125 llvm::OwningPtr<Preprocessor>
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001126 PP(CreatePreprocessor(*Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001127 CompOpts.getPreprocessorOpts(),
Daniel Dunbar961c76e2009-11-11 21:44:42 +00001128 CompOpts.getHeaderSearchOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001129 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001130 *Target, SourceMgr, FileMgr));
1131
Chris Lattnerf63aea32009-03-04 21:40:56 +00001132 // Process the source file.
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001133 Diags->getClient()->BeginSourceFile(CompOpts.getLangOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001134 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001135 Diags->getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 }
Chris Lattner11215192008-03-14 06:12:05 +00001137
Daniel Dunbar9253e492009-11-10 00:46:12 +00001138 if (CompOpts.getDiagnosticOpts().ShowCarets)
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001139 if (unsigned NumDiagnostics = Diags->getNumDiagnostics())
Mike Stumpfc0fed32009-04-28 01:19:10 +00001140 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1141 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Daniel Dunbar26266882009-11-12 23:52:32 +00001143 if (CompOpts.getFrontendOpts().ShowStats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 FileMgr.PrintStats();
1145 fprintf(stderr, "\n");
1146 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001147
1148 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Daniel Dunbar276373d2008-10-27 22:10:13 +00001150 // If verifying diagnostics and we reached here, all is well.
Daniel Dunbar26266882009-11-12 23:52:32 +00001151 if (CompOpts.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001152 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001154 // Managed static deconstruction. Useful for making things like
1155 // -time-passes usable.
1156 llvm::llvm_shutdown();
1157
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +00001158 return (Diags->getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001159}