blob: a1b731c9f27a7d8630952a4faaaea7585ce8f558 [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"
Daniel Dunbar775bee72009-11-11 10:07:22 +000021#include "clang/Analysis/PathDiagnostic.h"
22#include "clang/Basic/FileManager.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Basic/Version.h"
26#include "clang/CodeGen/ModuleBuilder.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000027#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000028#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000029#include "clang/Frontend/AnalysisConsumer.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000030#include "clang/Frontend/CommandLineSourceLoc.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000031#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000032#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbar0e0bae82009-11-11 21:43:12 +000033#include "clang/Frontend/DependencyOutputOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000034#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000035#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000036#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000037#include "clang/Frontend/PathDiagnosticClients.h"
38#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000039#include "clang/Frontend/PreprocessorOutputOptions.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000040#include "clang/Frontend/Utils.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000041#include "clang/Lex/HeaderSearch.h"
42#include "clang/Lex/LexDiagnostic.h"
43#include "clang/Parse/Parser.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000044#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000045#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000046#include "clang/Sema/SemaDiagnostic.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000047#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000048#include "llvm/ADT/OwningPtr.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000051#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000052#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000053#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000055#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000056#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000057#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000058#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000059#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000060#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000061#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000062#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000063#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000064#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000065# include <sys/types.h>
66#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000067
Reid Spencer5f016e22007-07-11 17:01:13 +000068using namespace clang;
69
70//===----------------------------------------------------------------------===//
Daniel Dunbaraa576142009-11-12 15:23:20 +000071// Frontend Actions
72//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000073
74enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000075 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000076 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000077 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000078 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000079 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000080 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000081 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000082 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +000083 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +000084 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000085 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +000086 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +000087 ASTDump, // Parse ASTs and dump them.
88 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +000089 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +000090 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +000091 ParsePrintCallbacks, // Parse and print each callback.
92 ParseSyntaxOnly, // Parse and perform semantic analysis.
93 ParseNoop, // Parse with noop callbacks.
94 RunPreprocessorOnly, // Just lex, no output.
95 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +000096 DumpTokens, // Dump out preprocessed tokens.
97 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +000098 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +000099 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000100 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000101 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000102};
103
Mike Stump1eb44332009-09-09 15:08:12 +0000104static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000105ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
106 llvm::cl::init(ParseSyntaxOnly),
107 llvm::cl::values(
108 clEnumValN(RunPreprocessorOnly, "Eonly",
109 "Just run preprocessor, no output (for timings)"),
110 clEnumValN(PrintPreprocessedInput, "E",
111 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000112 clEnumValN(DumpRawTokens, "dump-raw-tokens",
113 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000114 clEnumValN(RunAnalysis, "analyze",
115 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000116 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 "Run preprocessor, dump internal rep of tokens"),
118 clEnumValN(ParseNoop, "parse-noop",
119 "Run parser with noop callbacks (for timings)"),
120 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
121 "Run parser and perform semantic analysis"),
122 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
123 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000124 clEnumValN(EmitHTML, "emit-html",
125 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000126 clEnumValN(ASTPrint, "ast-print",
127 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000128 clEnumValN(ASTPrintXML, "ast-print-xml",
129 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000130 clEnumValN(ASTDump, "ast-dump",
131 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000132 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000133 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000134 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000135 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000136 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
137 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000138 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000139 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000140 clEnumValN(GeneratePCH, "emit-pch",
141 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000142 clEnumValN(EmitAssembly, "S",
143 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000145 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000146 clEnumValN(EmitBC, "emit-llvm-bc",
147 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000148 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
149 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000150 clEnumValN(RewriteTest, "rewrite-test",
151 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000152 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000153 "Rewrite ObjC into C (code rewriter example)"),
154 clEnumValN(RewriteMacros, "rewrite-macros",
155 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000156 clEnumValN(RewriteBlocks, "rewrite-blocks",
157 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 clEnumValEnd));
159
Daniel Dunbaraa576142009-11-12 15:23:20 +0000160//===----------------------------------------------------------------------===//
Daniel Dunbar914474c2009-11-13 01:02:10 +0000161// Utility Methods
Reid Spencer5f016e22007-07-11 17:01:13 +0000162//===----------------------------------------------------------------------===//
163
Douglas Gregore1d918e2009-04-10 23:10:45 +0000164static bool InitializeSourceManager(Preprocessor &PP,
Daniel Dunbar26266882009-11-12 23:52:32 +0000165 const FrontendOptions &FEOpts,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000166 const std::string &InFile) {
167 // Figure out where to get and map in the main file.
168 SourceManager &SourceMgr = PP.getSourceManager();
169 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000170
Daniel Dunbar26266882009-11-12 23:52:32 +0000171 if (FEOpts.EmptyInputOnly) {
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000172 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000173 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000174 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
175 SourceMgr.createMainFileIDForMemBuffer(SB);
176 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000177 const FileEntry *File = FileMgr.getFile(InFile);
178 if (File) SourceMgr.createMainFileID(File, SourceLocation());
179 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000180 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000181 return true;
182 }
183 } else {
184 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000185 SourceMgr.createMainFileIDForMemBuffer(SB);
186 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000187 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000188 return true;
189 }
190 }
191
192 return false;
193}
194
Daniel Dunbar750156a2009-11-07 04:19:57 +0000195std::string GetBuiltinIncludePath(const char *Argv0) {
196 llvm::sys::Path P =
197 llvm::sys::Path::GetMainExecutable(Argv0,
198 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000199
Daniel Dunbar750156a2009-11-07 04:19:57 +0000200 if (!P.isEmpty()) {
201 P.eraseComponent(); // Remove /clang from foo/bin/clang
202 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000203
Daniel Dunbar750156a2009-11-07 04:19:57 +0000204 // Get foo/lib/clang/<version>/include
205 P.appendComponent("lib");
206 P.appendComponent("clang");
207 P.appendComponent(CLANG_VERSION_STRING);
208 P.appendComponent("include");
209 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000210
Daniel Dunbar750156a2009-11-07 04:19:57 +0000211 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000212}
213
Daniel Dunbar914474c2009-11-13 01:02:10 +0000214/// \brief Buld a new code-completion consumer that prints the results of
215/// code completion to standard output.
216static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S,
217 void *UserData) {
218 const FrontendOptions &Opts = *(FrontendOptions*)UserData;
219 if (Opts.DebugCodeCompletionPrinter)
220 return new PrintingCodeCompleteConsumer(S, Opts.ShowMacrosInCodeCompletion,
221 llvm::outs());
222
223 return new CIndexCodeCompleteConsumer(S, Opts.ShowMacrosInCodeCompletion,
224 llvm::outs());
225}
226
Reid Spencer5f016e22007-07-11 17:01:13 +0000227//===----------------------------------------------------------------------===//
228// Basic Parser driver
229//===----------------------------------------------------------------------===//
230
Chris Lattner51574ea2008-04-19 23:25:44 +0000231static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000233 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 // Parsing the specified input file.
236 P.ParseTranslationUnit();
237 delete PA;
238}
239
240//===----------------------------------------------------------------------===//
241// Main driver
242//===----------------------------------------------------------------------===//
243
Daniel Dunbaraa576142009-11-12 15:23:20 +0000244/// ClangFrontendTimer - The front-end activities should charge time to it with
245/// TimeRegion. The -ftime-report option controls whether this will do
246/// anything.
247llvm::Timer *ClangFrontendTimer = 0;
248
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000249static llvm::raw_ostream *ComputeOutFile(const FrontendOptions &Opts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000250 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000251 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000252 bool Binary,
253 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000254 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000255 std::string OutFile;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000256 if (!Opts.OutputFile.empty())
257 OutFile = Opts.OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +0000258 else if (InFile == "-") {
259 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000260 } else if (Extension) {
261 llvm::sys::Path Path(InFile);
262 Path.eraseSuffix();
263 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000264 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000265 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000266 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000267 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000268
Chris Lattner92bcc272009-08-23 02:59:41 +0000269 std::string Error;
270 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000271 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000272 if (!Error.empty()) {
273 // FIXME: Don't fail this way.
274 llvm::errs() << "ERROR: " << Error << "\n";
275 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000276 }
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner92bcc272009-08-23 02:59:41 +0000278 if (OutFile != "-")
279 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000280
281 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000282}
283
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000284/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000285/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000286static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000287 FileManager &FileMgr,
288 const std::vector<ParsedSourceLocation> &Locs) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000289 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000290
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000291 for (unsigned i = 0, e = Locs.size(); i != e; ++i) {
292 if (const FileEntry *File = FileMgr.getFile(Locs[i].FileName)) {
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000293 RequestedSourceLocation Requested;
294 Requested.File = File;
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000295 Requested.Line = Locs[i].Line;
296 Requested.Column = Locs[i].Column;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000297 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000298 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000299 } else {
300 llvm::errs() << "FIX-IT could not find file \""
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000301 << Locs[i].FileName << "\"\n";
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000302 }
303 }
304
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000305 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000306}
307
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000308static ASTConsumer *CreateConsumerAction(CompilerInstance &CI,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000309 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000310 const std::string &InFile,
311 ProgActions PA,
312 llvm::OwningPtr<llvm::raw_ostream> &OS,
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000313 llvm::sys::Path &OutPath) {
314 const FrontendOptions &FEOpts = CI.getFrontendOpts();
Daniel Dunbar26266882009-11-12 23:52:32 +0000315
Ted Kremenek85888962008-10-21 00:54:44 +0000316 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000318 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000319
320 case ASTPrint:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000321 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000322 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Douglas Gregoree75c052009-05-21 20:55:50 +0000324 case ASTPrintXML:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000325 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "xml", false,
326 OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000327 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000328
Eli Friedman66d6f042009-05-18 22:20:00 +0000329 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000330 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000331
Eli Friedman66d6f042009-05-18 22:20:00 +0000332 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000333 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000334
Anders Carlsson78762eb2009-09-24 18:54:49 +0000335 case DumpRecordLayouts:
336 return CreateRecordLayoutDumper();
337
Eli Friedman66d6f042009-05-18 22:20:00 +0000338 case InheritanceView:
Daniel Dunbar26266882009-11-12 23:52:32 +0000339 return CreateInheritanceViewer(FEOpts.ViewClassInheritance);
Eli Friedman66d6f042009-05-18 22:20:00 +0000340
341 case EmitAssembly:
342 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000343 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000344 case EmitLLVMOnly: {
345 BackendAction Act;
346 if (ProgAction == EmitAssembly) {
347 Act = Backend_EmitAssembly;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000348 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "s", true,
349 OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000350 } else if (ProgAction == EmitLLVM) {
351 Act = Backend_EmitLL;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000352 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "ll", true,
353 OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000354 } else if (ProgAction == EmitLLVMOnly) {
355 Act = Backend_EmitNothing;
356 } else {
357 Act = Backend_EmitBC;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000358 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "bc", true,
359 OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000360 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000361
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000362 // Fix-its can change semantics, disallow with any IRgen action.
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000363 if (FEOpts.FixItAll || !FEOpts.FixItLocations.empty()) {
Daniel Dunbare0c4ff22009-11-12 15:42:53 +0000364 PP.getDiagnostics().Report(diag::err_fe_no_fixit_and_codegen);
365 return 0;
366 }
367
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000368 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000369 CI.getCodeGenOpts(), InFile, OS.get(),
370 CI.getLLVMContext());
Eli Friedman66d6f042009-05-18 22:20:00 +0000371 }
372
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000373 case RewriteObjC:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000374 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000375 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Daniel Dunbar69079432009-11-12 07:28:44 +0000376 PP.getLangOptions(),
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000377 CI.getDiagnosticOpts().NoRewriteMacros);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000378
379 case RewriteBlocks:
380 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
381 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000382
383 case ParseSyntaxOnly:
384 return new ASTConsumer();
385
386 case PrintDeclContext:
387 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000388 }
389}
390
Daniel Dunbar975790e2009-11-12 02:53:20 +0000391/// ReadPCHFile - Load a PCH file from disk, and initialize the preprocessor for
392/// reading from the PCH file.
393///
394/// \return The AST source, or null on failure.
395static ExternalASTSource *ReadPCHFile(llvm::StringRef Path,
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000396 const std::string Sysroot,
Daniel Dunbar975790e2009-11-12 02:53:20 +0000397 Preprocessor &PP,
398 ASTContext &Context) {
399 // If the user specified -isysroot, it will be used for relocatable PCH files.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000400 const char *isysrootPCH = Sysroot.c_str();
Daniel Dunbar975790e2009-11-12 02:53:20 +0000401 if (isysrootPCH[0] == '\0')
402 isysrootPCH = 0;
403
404 llvm::OwningPtr<PCHReader> Reader;
405 Reader.reset(new PCHReader(PP, &Context, isysrootPCH));
406
407 switch (Reader->ReadPCH(Path)) {
408 case PCHReader::Success:
409 // Set the predefines buffer as suggested by the PCH reader. Typically, the
410 // predefines buffer will be empty.
411 PP.setPredefines(Reader->getSuggestedPredefines());
412 return Reader.take();
413
414 case PCHReader::Failure:
415 // Unrecoverable failure: don't even try to process the input file.
416 break;
417
418 case PCHReader::IgnorePCH:
419 // No suitable PCH file could be found. Return an error.
420 break;
421 }
422
423 return 0;
424}
425
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000426/// ProcessInputFile - Process a single input file with the specified state.
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000427static void ProcessInputFile(CompilerInstance &CI, const std::string &InFile,
428 ProgActions PA) {
429 Preprocessor &PP = CI.getPreprocessor();
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000430 const FrontendOptions &FEOpts = CI.getFrontendOpts();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000431 llvm::OwningPtr<llvm::raw_ostream> OS;
432 llvm::OwningPtr<ASTConsumer> Consumer;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000433 FixItRewriter *FixItRewrite = 0;
434 bool CompleteTranslationUnit = true;
435 llvm::sys::Path OutPath;
436
437 switch (PA) {
438 default:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000439 Consumer.reset(CreateConsumerAction(CI, PP, InFile, PA, OS, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000440 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000441 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000442 return;
443 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000444 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000445
446 case EmitHTML:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000447 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000448 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000449 break;
450
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000451 case RunAnalysis:
Daniel Dunbar26266882009-11-12 23:52:32 +0000452 Consumer.reset(CreateAnalysisConsumer(PP, FEOpts.OutputFile,
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000453 CI.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000454 break;
455
Daniel Dunbarf7973292009-11-11 08:13:32 +0000456 case GeneratePCH: {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000457 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Daniel Dunbar26266882009-11-12 23:52:32 +0000458 bool Relocatable = FEOpts.RelocatablePCH;
459 if (Relocatable && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000460 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
Daniel Dunbar26266882009-11-12 23:52:32 +0000461 Relocatable = false;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000462 }
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000464 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Daniel Dunbar26266882009-11-12 23:52:32 +0000465 if (Relocatable)
Daniel Dunbarf7973292009-11-11 08:13:32 +0000466 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000467 else
468 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000469 CompleteTranslationUnit = false;
470 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000471 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000472
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000473 // Do any necessary set up for non-consumer actions.
474 case DumpRawTokens:
475 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000476 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000477 case ParseNoop:
478 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000480 case GeneratePTH:
Daniel Dunbar26266882009-11-12 23:52:32 +0000481 if (FEOpts.OutputFile.empty() || FEOpts.OutputFile == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000482 // FIXME: Don't fail this way.
483 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000484 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000485 ::exit(1);
486 }
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000487 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000488 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000489
Chris Lattnercc7dea82009-04-27 22:02:30 +0000490 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000491 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000492 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000493 case RewriteTest:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000494 OS.reset(ComputeOutFile(CI.getFrontendOpts(), InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000495 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000496 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000497
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000498 // Check if we want a fix-it rewriter.
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000499 if (FEOpts.FixItAll || !FEOpts.FixItLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000500 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000501 PP.getSourceManager(),
502 PP.getLangOptions());
Daniel Dunbarc86804b2009-11-12 23:52:56 +0000503 if (!FEOpts.FixItLocations.empty() &&
504 !AddFixItLocations(FixItRewrite, PP.getFileManager(),
505 FEOpts.FixItLocations)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000506 // All of the fix-it locations were bad. Don't fix anything.
507 delete FixItRewrite;
508 FixItRewrite = 0;
509 }
510 }
511
512 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000513 llvm::OwningPtr<ExternalASTSource> Source;
514 const std::string &ImplicitPCHInclude =
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000515 CI.getPreprocessorOpts().getImplicitPCHInclude();
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000516 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000517 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
518 PP.getSourceManager(),
519 PP.getTargetInfo(),
520 PP.getIdentifierTable(),
521 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000522 PP.getBuiltinInfo(),
Daniel Dunbar26266882009-11-12 23:52:32 +0000523 /* FreeMemory = */ !FEOpts.DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000524 /* size_reserve = */0));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000525
526 if (!ImplicitPCHInclude.empty()) {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000527 Source.reset(ReadPCHFile(ImplicitPCHInclude,
528 CI.getHeaderSearchOpts().Sysroot, PP,
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000529 *ContextOwner));
530 if (!Source)
531 return;
532
533 // Attach the PCH reader to the AST context as an external AST source, so
534 // that declarations will be deserialized from the PCH file as needed.
535 ContextOwner->setExternalSource(Source);
536 } else {
537 // Initialize builtin info when not using PCH.
538 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
539 PP.getLangOptions().NoBuiltin);
540 }
541
542 // Initialize the main file entry. This needs to be delayed until after PCH
543 // has loaded.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000544 if (InitializeSourceManager(PP, CI.getFrontendOpts(), InFile))
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000545 return;
546
Douglas Gregor81b747b2009-09-17 21:32:03 +0000547 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
Daniel Dunbar914474c2009-11-13 01:02:10 +0000548 void *CreateCodeCompleterData = (void*) &FEOpts;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000549
Daniel Dunbar914474c2009-11-13 01:02:10 +0000550 if (!FEOpts.CodeCompletionAt.FileName.empty()) {
Douglas Gregorb657f112009-09-22 21:11:38 +0000551 // Tell the source manager to chop off the given file at a specific
552 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000553 if (const FileEntry *Entry
Daniel Dunbar914474c2009-11-13 01:02:10 +0000554 = PP.getFileManager().getFile(FEOpts.CodeCompletionAt.FileName)) {
Douglas Gregorb657f112009-09-22 21:11:38 +0000555 // Truncate the named file at the given line/column.
Daniel Dunbar914474c2009-11-13 01:02:10 +0000556 PP.getSourceManager().truncateFileAt(Entry,
557 FEOpts.CodeCompletionAt.Line,
558 FEOpts.CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000559
Douglas Gregorb657f112009-09-22 21:11:38 +0000560 // Set up the creation routine for code-completion.
561 CreateCodeCompleter = BuildPrintingCodeCompleter;
562 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000563 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Daniel Dunbar914474c2009-11-13 01:02:10 +0000564 << FEOpts.CodeCompletionAt.FileName;
Douglas Gregorb657f112009-09-22 21:11:38 +0000565 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000566 }
567
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000568 // Run the AST consumer action.
Daniel Dunbar26266882009-11-12 23:52:32 +0000569 ParseAST(PP, Consumer.get(), *ContextOwner.get(), FEOpts.ShowStats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000570 CompleteTranslationUnit,
571 CreateCodeCompleter, CreateCodeCompleterData);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000572 } else {
573 // Initialize builtin info.
574 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
575 PP.getLangOptions().NoBuiltin);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000576
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000577 // Initialize the main file entry. This needs to be delayed until after PCH
578 // has loaded.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000579 if (InitializeSourceManager(PP, CI.getFrontendOpts(), InFile))
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000580 return;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000581
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000582 // Run the preprocessor actions.
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000583 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000584 switch (PA) {
585 default:
586 assert(0 && "unexpected program action");
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000587
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000588 case DumpRawTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000589 SourceManager &SM = PP.getSourceManager();
590 // Start lexing the specified input file.
591 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
592 RawLex.SetKeepWhitespaceMode(true);
593
594 Token RawTok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000595 RawLex.LexFromRawLexer(RawTok);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000596 while (RawTok.isNot(tok::eof)) {
597 PP.DumpToken(RawTok, true);
598 fprintf(stderr, "\n");
599 RawLex.LexFromRawLexer(RawTok);
600 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000601 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000602 }
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000603
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000604 case DumpTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000605 Token Tok;
606 // Start preprocessing the specified input file.
607 PP.EnterMainSourceFile();
608 do {
609 PP.Lex(Tok);
610 PP.DumpToken(Tok, true);
611 fprintf(stderr, "\n");
612 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000613 break;
614 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000615
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000616 case GeneratePTH:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000617 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000618 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000619
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000620 case ParseNoop:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000621 ParseFile(PP, new MinimalAction(PP));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000622 break;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000623
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000624 case ParsePrintCallbacks:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000625 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000626 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000627
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000628 case PrintPreprocessedInput:
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000629 DoPrintPreprocessedInput(PP, OS.get(), CI.getPreprocessorOutputOpts());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000630 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000631
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000632 case RewriteMacros:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000633 RewriteMacrosInInput(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000634 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000635
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000636 case RewriteTest:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000637 DoRewriteTest(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000638 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000639
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000640 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000641 Token Tok;
642 // Start parsing the specified input file.
643 PP.EnterMainSourceFile();
644 do {
645 PP.Lex(Tok);
646 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000647 break;
648 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000649 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000650 }
651
Chris Lattner1aee61a2009-04-27 21:25:27 +0000652 if (FixItRewrite)
Daniel Dunbar26266882009-11-12 23:52:32 +0000653 FixItRewrite->WriteFixedFile(InFile, FEOpts.OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000654
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000655 // Release the consumer and the AST, in that order since the consumer may
656 // perform actions in its destructor which require the context.
Daniel Dunbar26266882009-11-12 23:52:32 +0000657 if (FEOpts.DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000658 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000659 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000660 } else {
661 Consumer.reset();
662 ContextOwner.reset();
663 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000664
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000665 if (CI.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000666 if (CheckDiagnostics(PP))
667 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000668
Daniel Dunbar26266882009-11-12 23:52:32 +0000669 if (FEOpts.ShowStats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000670 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 PP.PrintStats();
672 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000673 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000674 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000675 fprintf(stderr, "\n");
676 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000677
Eli Friedman66d6f042009-05-18 22:20:00 +0000678 // Always delete the output stream because we don't want to leak file
679 // handles. Also, we don't want to try to erase an open file.
680 OS.reset();
681
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000682 // If we had errors, try to erase the output file.
683 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000684 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000685}
686
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000687/// ProcessASTInputFile - Process a single AST input file with the specified
688/// state.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000689static void ProcessASTInputFile(CompilerInstance &CI, const std::string &InFile,
Daniel Dunbar16b74492009-11-13 04:12:06 +0000690 ProgActions PA) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000691 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000692 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000693 if (!AST) {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000694 CI.getDiagnostics().Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000695 return;
696 }
697
698 Preprocessor &PP = AST->getPreprocessor();
699
700 llvm::OwningPtr<llvm::raw_ostream> OS;
701 llvm::sys::Path OutPath;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000702 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CI, PP, InFile, PA,
703 OS, OutPath));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000704 if (!Consumer.get()) {
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000705 CI.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000706 return;
707 }
708
Daniel Dunbara674bf42009-09-21 03:03:56 +0000709 // Set the main file ID to an empty file.
710 //
711 // FIXME: We probably shouldn't need this, but for now this is the simplest
712 // way to reuse the logic in ParseAST.
713 const char *EmptyStr = "";
714 llvm::MemoryBuffer *SB =
715 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
716 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000717
Daniel Dunbara674bf42009-09-21 03:03:56 +0000718 // Stream the input AST to the consumer.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000719 CI.getDiagnostics().getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000720 ParseAST(PP, Consumer.get(), AST->getASTContext(),
721 CI.getFrontendOpts().ShowStats);
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000722 CI.getDiagnostics().getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000723
724 // Release the consumer and the AST, in that order since the consumer may
725 // perform actions in its destructor which require the context.
Daniel Dunbar16b74492009-11-13 04:12:06 +0000726 if (CI.getFrontendOpts().DisableFree) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000727 Consumer.take();
728 AST.take();
729 } else {
730 Consumer.reset();
731 AST.reset();
732 }
733
734 // Always delete the output stream because we don't want to leak file
735 // handles. Also, we don't want to try to erase an open file.
736 OS.reset();
737
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000738 // If we had errors, try to erase the output file.
739 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000740 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000741}
742
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000743static void LLVMErrorHandler(void *UserData, const std::string &Message) {
744 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
745
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000746 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000747
748 // We cannot recover from llvm errors.
749 exit(1);
750}
751
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000752static TargetInfo *
753ConstructCompilerInvocation(CompilerInvocation &Opts, Diagnostic &Diags,
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000754 const char *Argv0, bool &IsAST) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000755 // Initialize frontend options.
756 InitializeFrontendOptions(Opts.getFrontendOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000757
Daniel Dunbarf819b252009-11-13 05:52:19 +0000758 // FIXME: The target information in frontend options should be split out into
759 // TargetOptions, and the target options in codegen options should move there
760 // as well. Then we could properly initialize in layering order.
761
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000762 // Initialize base triple. If a -triple option has been specified, use
763 // that triple. Otherwise, default to the host triple.
764 llvm::Triple Triple(Opts.getFrontendOpts().TargetTriple);
765 if (Triple.getTriple().empty())
766 Triple = llvm::Triple(llvm::sys::getHostTriple());
767
768 // Get information about the target being compiled for.
769 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple.getTriple());
770 if (!Target) {
771 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
772 return 0;
773 }
774
775 // Set the target ABI if specified.
776 if (!Opts.getFrontendOpts().TargetABI.empty() &&
777 !Target->setABI(Opts.getFrontendOpts().TargetABI)) {
778 Diags.Report(diag::err_fe_unknown_target_abi)
779 << Opts.getFrontendOpts().TargetABI;
780 return 0;
781 }
782
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000783 // Initialize backend options, which may also be used to key some language
784 // options.
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000785 InitializeCodeGenOptions(Opts.getCodeGenOpts(), *Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +0000786
Daniel Dunbarfbe2faf2009-11-13 02:06:12 +0000787 // Determine the input language, we currently require all files to match.
788 FrontendOptions::InputKind IK = Opts.getFrontendOpts().Inputs[0].first;
789 for (unsigned i = 1, e = Opts.getFrontendOpts().Inputs.size(); i != e; ++i) {
790 if (Opts.getFrontendOpts().Inputs[i].first != IK) {
791 llvm::errs() << "error: cannot have multiple input files of distinct "
792 << "language kinds without -x\n";
793 return 0;
794 }
795 }
796
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000797 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000798 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000799 // FIXME: These aren't used during operations on ASTs. Split onto a separate
800 // code path to make this obvious.
Daniel Dunbarfbe2faf2009-11-13 02:06:12 +0000801 IsAST = (IK == FrontendOptions::IK_AST);
Daniel Dunbar26266882009-11-12 23:52:32 +0000802 if (!IsAST)
Daniel Dunbarfbe2faf2009-11-13 02:06:12 +0000803 InitializeLangOptions(Opts.getLangOpts(), IK, *Target,
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000804 Opts.getCodeGenOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000805
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000806 // Initialize the static analyzer options.
807 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
808
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000809 // Initialize the dependency output options (-M...).
810 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
811
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000812 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000813 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
814 GetBuiltinIncludePath(Argv0),
Daniel Dunbarf7973292009-11-11 08:13:32 +0000815 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000816
817 // Initialize the other preprocessor options.
818 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000819
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000820 // Initialize the preprocessed output options.
821 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
822
Daniel Dunbar26266882009-11-12 23:52:32 +0000823 // Finalize some code generation options which are derived from other places.
824 if (Opts.getLangOpts().NoBuiltin)
825 Opts.getCodeGenOpts().SimplifyLibCalls = 0;
826 if (Opts.getLangOpts().CPlusPlus)
827 Opts.getCodeGenOpts().NoCommon = 1;
828 Opts.getCodeGenOpts().TimePasses = Opts.getFrontendOpts().ShowTimers;
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000829
830 return Target;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000831}
832
Reid Spencer5f016e22007-07-11 17:01:13 +0000833int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +0000835 llvm::PrettyStackTraceProgram X(argc, argv);
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000836 CompilerInstance Clang(&llvm::getGlobalContext(), false);
Daniel Dunbard6970812009-09-02 23:20:15 +0000837
Daniel Dunbar4d861512009-09-03 04:54:12 +0000838 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +0000839 llvm::InitializeAllTargets();
840 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +0000841
842 llvm::cl::ParseCommandLineOptions(argc, argv,
843 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Daniel Dunbar00e5b8d2009-11-12 06:48:31 +0000845 // Construct the diagnostic engine first, so that we can build a diagnostic
846 // client to use for any errors during option handling.
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000847 InitializeDiagnosticOptions(Clang.getDiagnosticOpts());
848 Clang.createDiagnostics(argc, argv);
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000849 if (!&Clang.getDiagnostics())
Sebastian Redl63a9e0f2009-03-06 17:41:35 +0000850 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +0000851
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000852 // Set an error handler, so that any LLVM backend diagnostics go through our
853 // error handler.
854 llvm::llvm_install_error_handler(LLVMErrorHandler,
855 static_cast<void*>(&Clang.getDiagnostics()));
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000856
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000857 // Now that we have initialized the diagnostics engine, create the target and
858 // the compiler invocation object.
Daniel Dunbar227b2382009-11-09 22:45:57 +0000859 //
860 // FIXME: We should move .ast inputs to taking a separate path, they are
861 // really quite different.
Daniel Dunbar26266882009-11-12 23:52:32 +0000862 bool IsAST;
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000863 Clang.setTarget(
864 ConstructCompilerInvocation(Clang.getInvocation(), Clang.getDiagnostics(),
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000865 argv[0], IsAST));
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000866 if (!&Clang.getTarget())
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000867 return 1;
Daniel Dunbar26266882009-11-12 23:52:32 +0000868
Daniel Dunbar21dac5e2009-11-13 01:02:19 +0000869 // Validate/process some options
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000870 if (Clang.getHeaderSearchOpts().Verbose)
Daniel Dunbar1417c742009-11-12 23:52:46 +0000871 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
872 << " based upon " << PACKAGE_STRING
873 << " hosted on " << llvm::sys::getHostTriple() << "\n";
874
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000875 if (Clang.getFrontendOpts().ShowTimers)
Daniel Dunbar26266882009-11-12 23:52:32 +0000876 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
877
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000878 if (Clang.getDiagnosticOpts().VerifyDiagnostics &&
879 Clang.getFrontendOpts().Inputs.size() > 1) {
Daniel Dunbar26266882009-11-12 23:52:32 +0000880 fprintf(stderr, "-verify only works on single input files.\n");
881 return 1;
882 }
883
884 // C++ visualization?
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000885 if (!Clang.getFrontendOpts().ViewClassInheritance.empty())
Daniel Dunbar26266882009-11-12 23:52:32 +0000886 ProgAction = InheritanceView;
Daniel Dunbar227b2382009-11-09 22:45:57 +0000887
Daniel Dunbar4cc1a252009-11-05 01:53:23 +0000888 // Create the source manager.
Daniel Dunbar16b74492009-11-13 04:12:06 +0000889 Clang.createSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Chris Lattner2c78b872009-04-14 23:22:57 +0000891 // Create a file manager object to provide access to and cache the filesystem.
Daniel Dunbar16b74492009-11-13 04:12:06 +0000892 Clang.createFileManager();
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000893
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000894 for (unsigned i = 0, e = Clang.getFrontendOpts().Inputs.size(); i != e; ++i) {
895 const std::string &InFile = Clang.getFrontendOpts().Inputs[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000897 // AST inputs are handled specially.
Daniel Dunbar26266882009-11-12 23:52:32 +0000898 if (IsAST) {
Daniel Dunbar16b74492009-11-13 04:12:06 +0000899 ProcessASTInputFile(Clang, InFile, ProgAction);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000900 continue;
901 }
902
Daniel Dunbar4cc1a252009-11-05 01:53:23 +0000903 // Reset the ID tables if we are reusing the SourceManager.
904 if (i)
Daniel Dunbar16b74492009-11-13 04:12:06 +0000905 Clang.getSourceManager().clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000907 // Create the preprocessor.
908 Clang.createPreprocessor();
Daniel Dunbar5814e652009-11-11 21:44:21 +0000909
Chris Lattnerf63aea32009-03-04 21:40:56 +0000910 // Process the source file.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000911 Clang.getDiagnostics().getClient()->BeginSourceFile(Clang.getLangOpts());
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000912 ProcessInputFile(Clang, InFile, ProgAction);
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000913 Clang.getDiagnostics().getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 }
Chris Lattner11215192008-03-14 06:12:05 +0000915
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000916 if (Clang.getDiagnosticOpts().ShowCarets)
917 if (unsigned NumDiagnostics = Clang.getDiagnostics().getNumDiagnostics())
Mike Stumpfc0fed32009-04-28 01:19:10 +0000918 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
919 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000921 if (Clang.getFrontendOpts().ShowStats) {
Daniel Dunbar16b74492009-11-13 04:12:06 +0000922 Clang.getFileManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 fprintf(stderr, "\n");
924 }
Chris Lattner75a97cb2009-04-17 21:05:01 +0000925
926 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Daniel Dunbar276373d2008-10-27 22:10:13 +0000928 // If verifying diagnostics and we reached here, all is well.
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000929 if (Clang.getDiagnosticOpts().VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000930 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Daniel Dunbar524b86f2008-10-28 00:38:08 +0000932 // Managed static deconstruction. Useful for making things like
933 // -time-passes usable.
934 llvm::llvm_shutdown();
935
Daniel Dunbar2a79e162009-11-13 03:51:44 +0000936 return (Clang.getDiagnostics().getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000937}