blob: b930702ef407852f42fe99780071390017d67881 [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 Redl85728132010-08-17 20:43:28 +000028#include "clang/Serialization/PCHReader.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"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000038using namespace clang;
39
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000040CompilerInstance::CompilerInstance()
Sebastian Redlffaab3e2010-07-30 00:29:29 +000041 : Invocation(new CompilerInvocation()) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000042}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000043
44CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000045}
46
47void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
48 LLVMContext.reset(Value);
Daniel Dunbar2a79e162009-11-13 03:51:44 +000049}
Daniel Dunbar16b74492009-11-13 04:12:06 +000050
Daniel Dunbar6228ca02010-01-30 21:47:07 +000051void CompilerInstance::setInvocation(CompilerInvocation *Value) {
52 Invocation.reset(Value);
53}
54
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000055void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000056 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000057}
58
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000059void CompilerInstance::setTarget(TargetInfo *Value) {
60 Target.reset(Value);
61}
62
63void CompilerInstance::setFileManager(FileManager *Value) {
64 FileMgr.reset(Value);
65}
66
67void CompilerInstance::setSourceManager(SourceManager *Value) {
68 SourceMgr.reset(Value);
69}
70
71void CompilerInstance::setPreprocessor(Preprocessor *Value) {
72 PP.reset(Value);
73}
74
75void CompilerInstance::setASTContext(ASTContext *Value) {
76 Context.reset(Value);
77}
78
Douglas Gregorf18d0d82010-08-12 23:31:19 +000079void CompilerInstance::setSema(Sema *S) {
80 TheSema.reset(S);
81}
82
Daniel Dunbar12ce6942009-11-14 02:47:17 +000083void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
84 Consumer.reset(Value);
85}
86
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000087void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
88 CompletionConsumer.reset(Value);
89}
90
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000091// Diagnostics
Douglas Gregord93256e2010-01-28 06:00:51 +000092namespace {
93 class BinaryDiagnosticSerializer : public DiagnosticClient {
94 llvm::raw_ostream &OS;
95 SourceManager *SourceMgr;
96 public:
97 explicit BinaryDiagnosticSerializer(llvm::raw_ostream &OS)
98 : OS(OS), SourceMgr(0) { }
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +000099
Douglas Gregord93256e2010-01-28 06:00:51 +0000100 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
101 const DiagnosticInfo &Info);
102 };
103}
104
105void BinaryDiagnosticSerializer::HandleDiagnostic(Diagnostic::Level DiagLevel,
106 const DiagnosticInfo &Info) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000107 StoredDiagnostic(DiagLevel, Info).Serialize(OS);
Douglas Gregord93256e2010-01-28 06:00:51 +0000108}
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000109
110static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
111 unsigned argc, char **argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000112 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000113 std::string ErrorInfo;
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000114 llvm::OwningPtr<llvm::raw_ostream> OS(
115 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000116 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000117 Diags.Report(diag::err_fe_unable_to_open_logfile)
118 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000119 return;
120 }
121
Daniel Dunbardd63b282009-12-11 23:04:35 +0000122 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000123 for (unsigned i = 0; i != argc; ++i)
124 (*OS) << argv[i] << ' ';
125 (*OS) << '\n';
126
127 // Chain in a diagnostic client which will log the diagnostics.
128 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000129 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000130 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000131}
132
133void CompilerInstance::createDiagnostics(int Argc, char **Argv) {
Douglas Gregor28019772010-04-05 23:52:57 +0000134 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000135}
136
Douglas Gregor28019772010-04-05 23:52:57 +0000137llvm::IntrusiveRefCntPtr<Diagnostic>
138CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
139 int Argc, char **Argv) {
140 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic());
Daniel Dunbar221c7212009-11-14 07:53:24 +0000141
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000142 // Create the diagnostic client for reporting errors or for
143 // implementing -verify.
Douglas Gregord93256e2010-01-28 06:00:51 +0000144 llvm::OwningPtr<DiagnosticClient> DiagClient;
145 if (Opts.BinaryOutput) {
146 if (llvm::sys::Program::ChangeStderrToBinary()) {
147 // We weren't able to set standard error to binary, which is a
148 // bit of a problem. So, just create a text diagnostic printer
149 // to complain about this problem, and pretend that the user
150 // didn't try to use binary output.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000151 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Douglas Gregord93256e2010-01-28 06:00:51 +0000152 Diags->Report(diag::err_fe_stderr_binary);
Douglas Gregor28019772010-04-05 23:52:57 +0000153 return Diags;
Douglas Gregord93256e2010-01-28 06:00:51 +0000154 } else {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000155 Diags->setClient(new BinaryDiagnosticSerializer(llvm::errs()));
Douglas Gregord93256e2010-01-28 06:00:51 +0000156 }
157 } else {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000158 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Douglas Gregord93256e2010-01-28 06:00:51 +0000159 }
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000160
161 // Chain in -verify checker, if requested.
162 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000163 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000164
165 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000166 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000167
168 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000169 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000170
Douglas Gregor28019772010-04-05 23:52:57 +0000171 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000172}
173
174// File Manager
175
Daniel Dunbar16b74492009-11-13 04:12:06 +0000176void CompilerInstance::createFileManager() {
177 FileMgr.reset(new FileManager());
178}
179
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000180// Source Manager
181
Daniel Dunbar16b74492009-11-13 04:12:06 +0000182void CompilerInstance::createSourceManager() {
Douglas Gregorf715ca12010-03-16 00:06:06 +0000183 SourceMgr.reset(new SourceManager(getDiagnostics()));
Daniel Dunbar16b74492009-11-13 04:12:06 +0000184}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000185
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000186// Preprocessor
187
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000188void CompilerInstance::createPreprocessor() {
189 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
190 getPreprocessorOpts(), getHeaderSearchOpts(),
191 getDependencyOutputOpts(), getTarget(),
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000192 getFrontendOpts(), getSourceManager(),
193 getFileManager()));
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000194}
195
196Preprocessor *
197CompilerInstance::createPreprocessor(Diagnostic &Diags,
198 const LangOptions &LangInfo,
199 const PreprocessorOptions &PPOpts,
200 const HeaderSearchOptions &HSOpts,
201 const DependencyOutputOptions &DepOpts,
202 const TargetInfo &Target,
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000203 const FrontendOptions &FEOpts,
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000204 SourceManager &SourceMgr,
205 FileManager &FileMgr) {
206 // Create a PTH manager if we are using some form of a token cache.
207 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000208 if (!PPOpts.TokenCache.empty())
209 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000210
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000211 // Create the Preprocessor.
212 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
213 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
214 SourceMgr, *HeaderInfo, PTHMgr,
215 /*OwnsHeaderSearch=*/true);
216
217 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
218 // That argument is used as the IdentifierInfoLookup argument to
219 // IdentifierTable's ctor.
220 if (PTHMgr) {
221 PTHMgr->setPreprocessor(PP);
222 PP->setPTHManager(PTHMgr);
223 }
224
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000225 if (PPOpts.DetailedRecord)
226 PP->createPreprocessingRecord();
227
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000228 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000229
230 // Handle generating dependencies, if requested.
231 if (!DepOpts.OutputFile.empty())
232 AttachDependencyFileGen(*PP, DepOpts);
233
234 return PP;
235}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000236
237// ASTContext
238
239void CompilerInstance::createASTContext() {
240 Preprocessor &PP = getPreprocessor();
241 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
242 getTarget(), PP.getIdentifierTable(),
243 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000244 /*size_reserve=*/ 0));
245}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000246
247// ExternalASTSource
248
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000249void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000250 bool DisablePCHValidation,
251 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000252 llvm::OwningPtr<ExternalASTSource> Source;
253 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000254 DisablePCHValidation,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000255 getPreprocessor(), getASTContext(),
256 DeserializationListener));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000257 getASTContext().setExternalSource(Source);
258}
259
260ExternalASTSource *
261CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
262 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000263 bool DisablePCHValidation,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000264 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000265 ASTContext &Context,
266 void *DeserializationListener) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000267 llvm::OwningPtr<ASTReader> Reader;
268 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000269 Sysroot.empty() ? 0 : Sysroot.c_str(),
270 DisablePCHValidation));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000271
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000272 Reader->setDeserializationListener(
273 static_cast<PCHDeserializationListener *>(DeserializationListener));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000274 switch (Reader->ReadPCH(Path)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000275 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000276 // Set the predefines buffer as suggested by the PCH reader. Typically, the
277 // predefines buffer will be empty.
278 PP.setPredefines(Reader->getSuggestedPredefines());
279 return Reader.take();
280
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000281 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000282 // Unrecoverable failure: don't even try to process the input file.
283 break;
284
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000285 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000286 // No suitable PCH file could be found. Return an error.
287 break;
288 }
289
290 return 0;
291}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000292
293// Code Completion
294
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000295static bool EnableCodeCompletion(Preprocessor &PP,
296 const std::string &Filename,
297 unsigned Line,
298 unsigned Column) {
299 // Tell the source manager to chop off the given file at a specific
300 // line and column.
301 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
302 if (!Entry) {
303 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
304 << Filename;
305 return true;
306 }
307
308 // Truncate the named file at the given line/column.
309 PP.SetCodeCompletionPoint(Entry, Line, Column);
310 return false;
311}
312
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000313void CompilerInstance::createCodeCompletionConsumer() {
314 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000315 if (!CompletionConsumer) {
316 CompletionConsumer.reset(
317 createCodeCompletionConsumer(getPreprocessor(),
318 Loc.FileName, Loc.Line, Loc.Column,
319 getFrontendOpts().DebugCodeCompletionPrinter,
320 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000321 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000322 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000323 llvm::outs()));
324 if (!CompletionConsumer)
325 return;
326 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
327 Loc.Line, Loc.Column)) {
328 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000329 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000330 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000331
332 if (CompletionConsumer->isOutputBinary() &&
333 llvm::sys::Program::ChangeStdoutToBinary()) {
334 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
335 CompletionConsumer.reset();
336 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000337}
338
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000339void CompilerInstance::createFrontendTimer() {
340 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
341}
342
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000343CodeCompleteConsumer *
344CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
345 const std::string &Filename,
346 unsigned Line,
347 unsigned Column,
348 bool UseDebugPrinter,
349 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000350 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000351 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000352 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000353 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000354 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000355
356 // Set up the creation routine for code-completion.
357 if (UseDebugPrinter)
Douglas Gregor8071e422010-08-15 06:18:01 +0000358 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
359 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000360 else
Douglas Gregor8071e422010-08-15 06:18:01 +0000361 return new CIndexCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
362 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000363}
Daniel Dunbara9204832009-11-13 10:37:48 +0000364
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000365void CompilerInstance::createSema(bool CompleteTranslationUnit,
366 CodeCompleteConsumer *CompletionConsumer) {
367 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
368 CompleteTranslationUnit, CompletionConsumer));
369}
370
Daniel Dunbara9204832009-11-13 10:37:48 +0000371// Output Files
372
373void CompilerInstance::addOutputFile(llvm::StringRef Path,
374 llvm::raw_ostream *OS) {
375 assert(OS && "Attempt to add empty stream to output list!");
376 OutputFiles.push_back(std::make_pair(Path, OS));
377}
378
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000379void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Daniel Dunbara9204832009-11-13 10:37:48 +0000380 for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator
381 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
382 delete it->second;
383 if (EraseFiles && !it->first.empty())
384 llvm::sys::Path(it->first).eraseFromDisk();
385 }
386 OutputFiles.clear();
387}
388
Daniel Dunbarf482d592009-11-13 18:32:08 +0000389llvm::raw_fd_ostream *
390CompilerInstance::createDefaultOutputFile(bool Binary,
391 llvm::StringRef InFile,
392 llvm::StringRef Extension) {
393 return createOutputFile(getFrontendOpts().OutputFile, Binary,
394 InFile, Extension);
395}
396
397llvm::raw_fd_ostream *
398CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
399 bool Binary,
400 llvm::StringRef InFile,
401 llvm::StringRef Extension) {
402 std::string Error, OutputPathName;
403 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
404 InFile, Extension,
405 &OutputPathName);
406 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000407 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
408 << OutputPath << Error;
409 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000410 }
411
412 // Add the output file -- but don't try to remove "-", since this means we are
413 // using stdin.
414 addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS);
415
416 return OS;
417}
418
419llvm::raw_fd_ostream *
420CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
421 std::string &Error,
422 bool Binary,
423 llvm::StringRef InFile,
424 llvm::StringRef Extension,
425 std::string *ResultPathName) {
426 std::string OutFile;
427 if (!OutputPath.empty()) {
428 OutFile = OutputPath;
429 } else if (InFile == "-") {
430 OutFile = "-";
431 } else if (!Extension.empty()) {
432 llvm::sys::Path Path(InFile);
433 Path.eraseSuffix();
434 Path.appendSuffix(Extension);
435 OutFile = Path.str();
436 } else {
437 OutFile = "-";
438 }
439
Daniel Dunbarfc971022009-11-20 22:32:38 +0000440 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Daniel Dunbarf482d592009-11-13 18:32:08 +0000441 new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000442 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
443 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000444 return 0;
445
446 if (ResultPathName)
447 *ResultPathName = OutFile;
448
Daniel Dunbarfc971022009-11-20 22:32:38 +0000449 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000450}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000451
452// Initialization Utilities
453
454bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
455 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
456 getSourceManager(), getFrontendOpts());
457}
458
459bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
460 Diagnostic &Diags,
461 FileManager &FileMgr,
462 SourceManager &SourceMgr,
463 const FrontendOptions &Opts) {
464 // Figure out where to get and map in the main file.
Daniel Dunbar27585952010-03-19 19:44:04 +0000465 if (InputFile != "-") {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000466 const FileEntry *File = FileMgr.getFile(InputFile);
467 if (File) SourceMgr.createMainFileID(File, SourceLocation());
468 if (SourceMgr.getMainFileID().isInvalid()) {
469 Diags.Report(diag::err_fe_error_reading) << InputFile;
470 return false;
471 }
472 } else {
473 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Dan Gohman6f118972010-05-27 17:33:40 +0000474 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000475 if (SourceMgr.getMainFileID().isInvalid()) {
476 Diags.Report(diag::err_fe_error_reading_stdin);
477 return false;
478 }
479 }
480
481 return true;
482}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000483
484// High-Level Operations
485
486bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
487 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
488 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
489 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
490
491 // FIXME: Take this as an argument, once all the APIs we used have moved to
492 // taking it as an input instead of hard-coding llvm::errs.
493 llvm::raw_ostream &OS = llvm::errs();
494
495 // Create the target instance.
496 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
497 if (!hasTarget())
498 return false;
499
500 // Inform the target of the language options.
501 //
502 // FIXME: We shouldn't need to do this, the target should be immutable once
503 // created. This complexity should be lifted elsewhere.
504 getTarget().setForcedLangOptions(getLangOpts());
505
506 // Validate/process some options.
507 if (getHeaderSearchOpts().Verbose)
508 OS << "clang -cc1 version " CLANG_VERSION_STRING
509 << " based upon " << PACKAGE_STRING
510 << " hosted on " << llvm::sys::getHostTriple() << "\n";
511
512 if (getFrontendOpts().ShowTimers)
513 createFrontendTimer();
514
Douglas Gregor95dd5582010-03-30 17:33:59 +0000515 if (getFrontendOpts().ShowStats)
516 llvm::EnableStatistics();
517
Daniel Dunbar0397af22010-01-13 00:48:06 +0000518 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
519 const std::string &InFile = getFrontendOpts().Inputs[i].second;
520
Daniel Dunbar20560482010-06-07 23:23:50 +0000521 // Reset the ID tables if we are reusing the SourceManager.
522 if (hasSourceManager())
523 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000524
Daniel Dunbard3598a62010-06-07 23:23:06 +0000525 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000526 Act.Execute();
527 Act.EndSourceFile();
528 }
529 }
530
Chris Lattner53eee7b2010-04-07 18:47:42 +0000531 if (getDiagnosticOpts().ShowCarets) {
532 unsigned NumWarnings = getDiagnostics().getNumWarnings();
Douglas Gregor1864f2e2010-04-14 22:19:45 +0000533 unsigned NumErrors = getDiagnostics().getNumErrors() -
534 getDiagnostics().getNumErrorsSuppressed();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000535
536 if (NumWarnings)
537 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
538 if (NumWarnings && NumErrors)
539 OS << " and ";
540 if (NumErrors)
541 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
542 if (NumWarnings || NumErrors)
543 OS << " generated.\n";
544 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000545
Daniel Dunbar20560482010-06-07 23:23:50 +0000546 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000547 getFileManager().PrintStats();
548 OS << "\n";
549 }
550
551 // Return the appropriate status when verifying diagnostics.
552 //
553 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
554 // this.
555 if (getDiagnosticOpts().VerifyDiagnostics)
556 return !static_cast<VerifyDiagnosticsClient&>(
557 getDiagnosticClient()).HadErrors();
558
559 return !getDiagnostics().getNumErrors();
560}
561
562