blob: 939766351d169d7accbf69f061847488a9c90b9a [file] [log] [blame]
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001//===--- CompilerInstance.cpp ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorf18d0d82010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar12ce6942009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbar5eb81002009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000025#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000026#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000027#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000029#include "clang/Sema/CodeCompleteConsumer.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000030#include "llvm/LLVMContext.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000031#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000033#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000034#include "llvm/Support/Timer.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000035#include "llvm/System/Host.h"
Daniel Dunbara9204832009-11-13 10:37:48 +000036#include "llvm/System/Path.h"
Douglas Gregor2b4074f2009-12-01 05:55:20 +000037#include "llvm/System/Program.h"
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +000038#include "llvm/System/Signals.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000039using namespace clang;
40
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000041CompilerInstance::CompilerInstance()
Sebastian Redlffaab3e2010-07-30 00:29:29 +000042 : Invocation(new CompilerInvocation()) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000043}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000044
45CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000046}
47
48void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
49 LLVMContext.reset(Value);
Daniel Dunbar2a79e162009-11-13 03:51:44 +000050}
Daniel Dunbar16b74492009-11-13 04:12:06 +000051
Daniel Dunbar6228ca02010-01-30 21:47:07 +000052void CompilerInstance::setInvocation(CompilerInvocation *Value) {
53 Invocation.reset(Value);
54}
55
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000056void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000057 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000058}
59
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000060void CompilerInstance::setTarget(TargetInfo *Value) {
61 Target.reset(Value);
62}
63
64void CompilerInstance::setFileManager(FileManager *Value) {
65 FileMgr.reset(Value);
66}
67
68void CompilerInstance::setSourceManager(SourceManager *Value) {
69 SourceMgr.reset(Value);
70}
71
72void CompilerInstance::setPreprocessor(Preprocessor *Value) {
73 PP.reset(Value);
74}
75
76void CompilerInstance::setASTContext(ASTContext *Value) {
77 Context.reset(Value);
78}
79
Douglas Gregorf18d0d82010-08-12 23:31:19 +000080void CompilerInstance::setSema(Sema *S) {
81 TheSema.reset(S);
82}
83
Daniel Dunbar12ce6942009-11-14 02:47:17 +000084void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
85 Consumer.reset(Value);
86}
87
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000088void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
89 CompletionConsumer.reset(Value);
90}
91
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000092// Diagnostics
Douglas Gregord93256e2010-01-28 06:00:51 +000093namespace {
94 class BinaryDiagnosticSerializer : public DiagnosticClient {
95 llvm::raw_ostream &OS;
96 SourceManager *SourceMgr;
97 public:
98 explicit BinaryDiagnosticSerializer(llvm::raw_ostream &OS)
99 : OS(OS), SourceMgr(0) { }
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000100
Douglas Gregord93256e2010-01-28 06:00:51 +0000101 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
102 const DiagnosticInfo &Info);
103 };
104}
105
106void BinaryDiagnosticSerializer::HandleDiagnostic(Diagnostic::Level DiagLevel,
107 const DiagnosticInfo &Info) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000108 StoredDiagnostic(DiagLevel, Info).Serialize(OS);
Douglas Gregord93256e2010-01-28 06:00:51 +0000109}
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000110
111static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000112 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000113 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000114 std::string ErrorInfo;
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000115 llvm::OwningPtr<llvm::raw_ostream> OS(
116 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000117 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000118 Diags.Report(diag::err_fe_unable_to_open_logfile)
119 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000120 return;
121 }
122
Daniel Dunbardd63b282009-12-11 23:04:35 +0000123 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000124 for (unsigned i = 0; i != argc; ++i)
125 (*OS) << argv[i] << ' ';
126 (*OS) << '\n';
127
128 // Chain in a diagnostic client which will log the diagnostics.
129 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000130 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000131 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000132}
133
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000134void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv) {
Douglas Gregor28019772010-04-05 23:52:57 +0000135 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000136}
137
Douglas Gregor28019772010-04-05 23:52:57 +0000138llvm::IntrusiveRefCntPtr<Diagnostic>
139CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000140 int Argc, const char* const *Argv) {
Douglas Gregor28019772010-04-05 23:52:57 +0000141 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic());
Daniel Dunbar221c7212009-11-14 07:53:24 +0000142
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000143 // Create the diagnostic client for reporting errors or for
144 // implementing -verify.
Douglas Gregord93256e2010-01-28 06:00:51 +0000145 llvm::OwningPtr<DiagnosticClient> DiagClient;
146 if (Opts.BinaryOutput) {
147 if (llvm::sys::Program::ChangeStderrToBinary()) {
148 // We weren't able to set standard error to binary, which is a
149 // bit of a problem. So, just create a text diagnostic printer
150 // to complain about this problem, and pretend that the user
151 // didn't try to use binary output.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000152 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Douglas Gregord93256e2010-01-28 06:00:51 +0000153 Diags->Report(diag::err_fe_stderr_binary);
Douglas Gregor28019772010-04-05 23:52:57 +0000154 return Diags;
Douglas Gregord93256e2010-01-28 06:00:51 +0000155 } else {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000156 Diags->setClient(new BinaryDiagnosticSerializer(llvm::errs()));
Douglas Gregord93256e2010-01-28 06:00:51 +0000157 }
158 } else {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000159 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Douglas Gregord93256e2010-01-28 06:00:51 +0000160 }
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000161
162 // Chain in -verify checker, if requested.
163 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000164 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000165
166 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000167 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000168
169 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000170 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000171
Douglas Gregor28019772010-04-05 23:52:57 +0000172 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000173}
174
175// File Manager
176
Daniel Dunbar16b74492009-11-13 04:12:06 +0000177void CompilerInstance::createFileManager() {
178 FileMgr.reset(new FileManager());
179}
180
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000181// Source Manager
182
Daniel Dunbar16b74492009-11-13 04:12:06 +0000183void CompilerInstance::createSourceManager() {
Douglas Gregorf715ca12010-03-16 00:06:06 +0000184 SourceMgr.reset(new SourceManager(getDiagnostics()));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000185}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000186
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000187// Preprocessor
188
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000189void CompilerInstance::createPreprocessor() {
190 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
191 getPreprocessorOpts(), getHeaderSearchOpts(),
192 getDependencyOutputOpts(), getTarget(),
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000193 getFrontendOpts(), getSourceManager(),
194 getFileManager()));
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000195}
196
197Preprocessor *
198CompilerInstance::createPreprocessor(Diagnostic &Diags,
199 const LangOptions &LangInfo,
200 const PreprocessorOptions &PPOpts,
201 const HeaderSearchOptions &HSOpts,
202 const DependencyOutputOptions &DepOpts,
203 const TargetInfo &Target,
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000204 const FrontendOptions &FEOpts,
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000205 SourceManager &SourceMgr,
206 FileManager &FileMgr) {
207 // Create a PTH manager if we are using some form of a token cache.
208 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000209 if (!PPOpts.TokenCache.empty())
210 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000211
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000212 // Create the Preprocessor.
213 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
214 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
215 SourceMgr, *HeaderInfo, PTHMgr,
216 /*OwnsHeaderSearch=*/true);
217
218 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
219 // That argument is used as the IdentifierInfoLookup argument to
220 // IdentifierTable's ctor.
221 if (PTHMgr) {
222 PTHMgr->setPreprocessor(PP);
223 PP->setPTHManager(PTHMgr);
224 }
225
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000226 if (PPOpts.DetailedRecord)
227 PP->createPreprocessingRecord();
228
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000229 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000230
231 // Handle generating dependencies, if requested.
232 if (!DepOpts.OutputFile.empty())
233 AttachDependencyFileGen(*PP, DepOpts);
234
235 return PP;
236}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000237
238// ASTContext
239
240void CompilerInstance::createASTContext() {
241 Preprocessor &PP = getPreprocessor();
242 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
243 getTarget(), PP.getIdentifierTable(),
244 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000245 /*size_reserve=*/ 0));
246}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000247
248// ExternalASTSource
249
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000250void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000251 bool DisablePCHValidation,
252 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000253 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000254 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000255 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000256 DisablePCHValidation,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000257 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000258 DeserializationListener,
259 Preamble));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000260 getASTContext().setExternalSource(Source);
261}
262
263ExternalASTSource *
264CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
265 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000266 bool DisablePCHValidation,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000267 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000268 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000269 void *DeserializationListener,
270 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000271 llvm::OwningPtr<ASTReader> Reader;
272 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000273 Sysroot.empty() ? 0 : Sysroot.c_str(),
274 DisablePCHValidation));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000275
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000276 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000277 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000278 switch (Reader->ReadAST(Path,
279 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000280 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000281 // Set the predefines buffer as suggested by the PCH reader. Typically, the
282 // predefines buffer will be empty.
283 PP.setPredefines(Reader->getSuggestedPredefines());
284 return Reader.take();
285
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000286 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000287 // Unrecoverable failure: don't even try to process the input file.
288 break;
289
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000290 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000291 // No suitable PCH file could be found. Return an error.
292 break;
293 }
294
295 return 0;
296}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000297
298// Code Completion
299
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000300static bool EnableCodeCompletion(Preprocessor &PP,
301 const std::string &Filename,
302 unsigned Line,
303 unsigned Column) {
304 // Tell the source manager to chop off the given file at a specific
305 // line and column.
306 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
307 if (!Entry) {
308 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
309 << Filename;
310 return true;
311 }
312
313 // Truncate the named file at the given line/column.
314 PP.SetCodeCompletionPoint(Entry, Line, Column);
315 return false;
316}
317
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000318void CompilerInstance::createCodeCompletionConsumer() {
319 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000320 if (!CompletionConsumer) {
321 CompletionConsumer.reset(
322 createCodeCompletionConsumer(getPreprocessor(),
323 Loc.FileName, Loc.Line, Loc.Column,
324 getFrontendOpts().DebugCodeCompletionPrinter,
325 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000326 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000327 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000328 llvm::outs()));
329 if (!CompletionConsumer)
330 return;
331 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
332 Loc.Line, Loc.Column)) {
333 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000334 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000335 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000336
337 if (CompletionConsumer->isOutputBinary() &&
338 llvm::sys::Program::ChangeStdoutToBinary()) {
339 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
340 CompletionConsumer.reset();
341 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000342}
343
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000344void CompilerInstance::createFrontendTimer() {
345 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
346}
347
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000348CodeCompleteConsumer *
349CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
350 const std::string &Filename,
351 unsigned Line,
352 unsigned Column,
353 bool UseDebugPrinter,
354 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000355 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000356 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000357 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000358 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000359 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000360
361 // Set up the creation routine for code-completion.
362 if (UseDebugPrinter)
Douglas Gregor8071e422010-08-15 06:18:01 +0000363 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
364 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000365 else
Douglas Gregor8071e422010-08-15 06:18:01 +0000366 return new CIndexCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
367 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000368}
Daniel Dunbara9204832009-11-13 10:37:48 +0000369
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000370void CompilerInstance::createSema(bool CompleteTranslationUnit,
371 CodeCompleteConsumer *CompletionConsumer) {
372 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
373 CompleteTranslationUnit, CompletionConsumer));
374}
375
Daniel Dunbara9204832009-11-13 10:37:48 +0000376// Output Files
377
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000378void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
379 assert(OutFile.OS && "Attempt to add empty stream to output list!");
380 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000381}
382
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000383void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000384 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000385 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000386 delete it->OS;
387 if (!it->TempFilename.empty()) {
388 llvm::sys::Path TempPath(it->TempFilename);
389 if (EraseFiles)
390 TempPath.eraseFromDisk();
391 else {
392 std::string Error;
393 if (TempPath.renamePathOnDisk(llvm::sys::Path(it->Filename), &Error)) {
394 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
395 << it->TempFilename << it->Filename << Error;
396 TempPath.eraseFromDisk();
397 }
398 }
399 } else if (!it->Filename.empty() && EraseFiles)
400 llvm::sys::Path(it->Filename).eraseFromDisk();
401
Daniel Dunbara9204832009-11-13 10:37:48 +0000402 }
403 OutputFiles.clear();
404}
405
Daniel Dunbarf482d592009-11-13 18:32:08 +0000406llvm::raw_fd_ostream *
407CompilerInstance::createDefaultOutputFile(bool Binary,
408 llvm::StringRef InFile,
409 llvm::StringRef Extension) {
410 return createOutputFile(getFrontendOpts().OutputFile, Binary,
411 InFile, Extension);
412}
413
414llvm::raw_fd_ostream *
415CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
416 bool Binary,
417 llvm::StringRef InFile,
418 llvm::StringRef Extension) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000419 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000420 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
421 InFile, Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000422 &OutputPathName,
423 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000424 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000425 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
426 << OutputPath << Error;
427 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000428 }
429
430 // Add the output file -- but don't try to remove "-", since this means we are
431 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000432 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
433 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000434
435 return OS;
436}
437
438llvm::raw_fd_ostream *
439CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
440 std::string &Error,
441 bool Binary,
442 llvm::StringRef InFile,
443 llvm::StringRef Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000444 std::string *ResultPathName,
445 std::string *TempPathName) {
446 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000447 if (!OutputPath.empty()) {
448 OutFile = OutputPath;
449 } else if (InFile == "-") {
450 OutFile = "-";
451 } else if (!Extension.empty()) {
452 llvm::sys::Path Path(InFile);
453 Path.eraseSuffix();
454 Path.appendSuffix(Extension);
455 OutFile = Path.str();
456 } else {
457 OutFile = "-";
458 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000459
460 if (OutFile != "-") {
461 llvm::sys::Path OutPath(OutFile);
462 // Only create the temporary if we can actually write to OutPath, otherwise
463 // we want to fail early.
464 if (!OutPath.exists() ||
465 (OutPath.isRegularFile() && OutPath.canWrite())) {
466 // Create a temporary file.
467 llvm::sys::Path TempPath(OutFile);
468 if (!TempPath.createTemporaryFileOnDisk())
469 TempFile = TempPath.str();
470 }
471 }
472
473 std::string OSFile = OutFile;
474 if (!TempFile.empty())
475 OSFile = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000476
Daniel Dunbarfc971022009-11-20 22:32:38 +0000477 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000478 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000479 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
480 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000481 return 0;
482
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000483 // Make sure the out stream file gets removed if we crash.
484 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
485
Daniel Dunbarf482d592009-11-13 18:32:08 +0000486 if (ResultPathName)
487 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000488 if (TempPathName)
489 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000490
Daniel Dunbarfc971022009-11-20 22:32:38 +0000491 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000492}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000493
494// Initialization Utilities
495
496bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
497 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
498 getSourceManager(), getFrontendOpts());
499}
500
501bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
502 Diagnostic &Diags,
503 FileManager &FileMgr,
504 SourceManager &SourceMgr,
505 const FrontendOptions &Opts) {
506 // Figure out where to get and map in the main file.
Daniel Dunbar27585952010-03-19 19:44:04 +0000507 if (InputFile != "-") {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000508 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohmanf155dfa2010-08-27 15:44:11 +0000509 if (File) SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000510 if (SourceMgr.getMainFileID().isInvalid()) {
511 Diags.Report(diag::err_fe_error_reading) << InputFile;
512 return false;
513 }
514 } else {
515 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Dan Gohman6f118972010-05-27 17:33:40 +0000516 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000517 if (SourceMgr.getMainFileID().isInvalid()) {
518 Diags.Report(diag::err_fe_error_reading_stdin);
519 return false;
520 }
521 }
522
523 return true;
524}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000525
526// High-Level Operations
527
528bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
529 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
530 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
531 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
532
533 // FIXME: Take this as an argument, once all the APIs we used have moved to
534 // taking it as an input instead of hard-coding llvm::errs.
535 llvm::raw_ostream &OS = llvm::errs();
536
537 // Create the target instance.
538 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
539 if (!hasTarget())
540 return false;
541
542 // Inform the target of the language options.
543 //
544 // FIXME: We shouldn't need to do this, the target should be immutable once
545 // created. This complexity should be lifted elsewhere.
546 getTarget().setForcedLangOptions(getLangOpts());
547
548 // Validate/process some options.
549 if (getHeaderSearchOpts().Verbose)
550 OS << "clang -cc1 version " CLANG_VERSION_STRING
551 << " based upon " << PACKAGE_STRING
552 << " hosted on " << llvm::sys::getHostTriple() << "\n";
553
554 if (getFrontendOpts().ShowTimers)
555 createFrontendTimer();
556
Douglas Gregor95dd5582010-03-30 17:33:59 +0000557 if (getFrontendOpts().ShowStats)
558 llvm::EnableStatistics();
559
Daniel Dunbar0397af22010-01-13 00:48:06 +0000560 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
561 const std::string &InFile = getFrontendOpts().Inputs[i].second;
562
Daniel Dunbar20560482010-06-07 23:23:50 +0000563 // Reset the ID tables if we are reusing the SourceManager.
564 if (hasSourceManager())
565 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000566
Daniel Dunbard3598a62010-06-07 23:23:06 +0000567 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000568 Act.Execute();
569 Act.EndSourceFile();
570 }
571 }
572
Chris Lattner53eee7b2010-04-07 18:47:42 +0000573 if (getDiagnosticOpts().ShowCarets) {
574 unsigned NumWarnings = getDiagnostics().getNumWarnings();
Douglas Gregor1864f2e2010-04-14 22:19:45 +0000575 unsigned NumErrors = getDiagnostics().getNumErrors() -
576 getDiagnostics().getNumErrorsSuppressed();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000577
578 if (NumWarnings)
579 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
580 if (NumWarnings && NumErrors)
581 OS << " and ";
582 if (NumErrors)
583 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
584 if (NumWarnings || NumErrors)
585 OS << " generated.\n";
586 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000587
Daniel Dunbar20560482010-06-07 23:23:50 +0000588 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000589 getFileManager().PrintStats();
590 OS << "\n";
591 }
592
593 // Return the appropriate status when verifying diagnostics.
594 //
595 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
596 // this.
597 if (getDiagnosticOpts().VerifyDiagnostics)
598 return !static_cast<VerifyDiagnosticsClient&>(
599 getDiagnosticClient()).HadErrors();
600
601 return !getDiagnostics().getNumErrors();
602}
603
604