blob: 92aed39b5c34fc32cbced5812656b9e227cd391a [file] [log] [blame]
Daniel Dunbar636404a2009-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 Gregor0e93f012010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar56d9c292009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbardf3e30c2009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar546a6762009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000025#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbar50ec0da2009-11-14 03:24:39 +000026#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000027#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000029#include "clang/Sema/CodeCompleteConsumer.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000030#include "llvm/LLVMContext.h"
Michael J. Spencerf6efe582011-01-10 02:34:13 +000031#include "llvm/Support/FileSystem.h"
Daniel Dunbar409e8902009-11-14 07:53:04 +000032#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregor171b7802010-03-30 17:33:59 +000034#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +000035#include "llvm/Support/Timer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000036#include "llvm/Support/Host.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/Program.h"
39#include "llvm/Support/Signals.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000040#include "llvm/Support/system_error.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000041using namespace clang;
42
Daniel Dunbare922d9b2010-02-16 01:54:47 +000043CompilerInstance::CompilerInstance()
Sebastian Redl07a89a82010-07-30 00:29:29 +000044 : Invocation(new CompilerInvocation()) {
Daniel Dunbar68242252010-01-30 21:47:07 +000045}
Daniel Dunbar636404a2009-11-13 03:51:44 +000046
47CompilerInstance::~CompilerInstance() {
Daniel Dunbare922d9b2010-02-16 01:54:47 +000048}
49
50void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
51 LLVMContext.reset(Value);
Daniel Dunbar636404a2009-11-13 03:51:44 +000052}
Daniel Dunbar546a6762009-11-13 04:12:06 +000053
Daniel Dunbar68242252010-01-30 21:47:07 +000054void CompilerInstance::setInvocation(CompilerInvocation *Value) {
55 Invocation.reset(Value);
56}
57
Daniel Dunbare01dc862009-11-14 01:20:40 +000058void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor7f95d262010-04-05 23:52:57 +000059 Diagnostics = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000060}
61
Daniel Dunbare01dc862009-11-14 01:20:40 +000062void CompilerInstance::setTarget(TargetInfo *Value) {
63 Target.reset(Value);
64}
65
66void CompilerInstance::setFileManager(FileManager *Value) {
67 FileMgr.reset(Value);
68}
69
70void CompilerInstance::setSourceManager(SourceManager *Value) {
71 SourceMgr.reset(Value);
72}
73
74void CompilerInstance::setPreprocessor(Preprocessor *Value) {
75 PP.reset(Value);
76}
77
78void CompilerInstance::setASTContext(ASTContext *Value) {
79 Context.reset(Value);
80}
81
Douglas Gregor0e93f012010-08-12 23:31:19 +000082void CompilerInstance::setSema(Sema *S) {
83 TheSema.reset(S);
84}
85
Daniel Dunbar56d9c292009-11-14 02:47:17 +000086void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
87 Consumer.reset(Value);
88}
89
Daniel Dunbare01dc862009-11-14 01:20:40 +000090void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
91 CompletionConsumer.reset(Value);
92}
93
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000094// Diagnostics
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000095static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann89c31492010-10-11 09:13:46 +000096 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +000097 Diagnostic &Diags) {
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000098 std::string ErrorInfo;
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +000099 llvm::OwningPtr<llvm::raw_ostream> OS(
100 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000101 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000102 Diags.Report(diag::err_fe_unable_to_open_logfile)
103 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000104 return;
105 }
106
Daniel Dunbar520d1e62009-12-11 23:04:35 +0000107 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000108 for (unsigned i = 0; i != argc; ++i)
109 (*OS) << argv[i] << ' ';
110 (*OS) << '\n';
111
112 // Chain in a diagnostic client which will log the diagnostics.
113 DiagnosticClient *Logger =
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +0000114 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000115 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000116}
117
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000118void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
119 DiagnosticClient *Client) {
120 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000121}
122
Douglas Gregor7f95d262010-04-05 23:52:57 +0000123llvm::IntrusiveRefCntPtr<Diagnostic>
124CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000125 int Argc, const char* const *Argv,
126 DiagnosticClient *Client) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000127 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
128 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000129
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000130 // Create the diagnostic client for reporting errors or for
131 // implementing -verify.
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000132 if (Client)
133 Diags->setClient(Client);
134 else
135 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbar50ec0da2009-11-14 03:24:39 +0000136
137 // Chain in -verify checker, if requested.
138 if (Opts.VerifyDiagnostics)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000139 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000140
141 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000142 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000143
144 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam9ff84d92010-03-17 09:36:02 +0000145 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000146
Douglas Gregor7f95d262010-04-05 23:52:57 +0000147 return Diags;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000148}
149
150// File Manager
151
Daniel Dunbar546a6762009-11-13 04:12:06 +0000152void CompilerInstance::createFileManager() {
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000153 FileMgr.reset(new FileManager(getFileSystemOpts()));
Daniel Dunbar546a6762009-11-13 04:12:06 +0000154}
155
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000156// Source Manager
157
Chris Lattner5159f612010-11-23 08:35:12 +0000158void CompilerInstance::createSourceManager(FileManager &FileMgr) {
159 SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr));
Daniel Dunbar546a6762009-11-13 04:12:06 +0000160}
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000161
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000162// Preprocessor
163
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000164void CompilerInstance::createPreprocessor() {
165 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
166 getPreprocessorOpts(), getHeaderSearchOpts(),
167 getDependencyOutputOpts(), getTarget(),
Chris Lattner5159f612010-11-23 08:35:12 +0000168 getFrontendOpts(), getSourceManager(),
169 getFileManager()));
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000170}
171
172Preprocessor *
173CompilerInstance::createPreprocessor(Diagnostic &Diags,
174 const LangOptions &LangInfo,
175 const PreprocessorOptions &PPOpts,
176 const HeaderSearchOptions &HSOpts,
177 const DependencyOutputOptions &DepOpts,
178 const TargetInfo &Target,
Fariborz Jahanian3f7b8b22010-01-13 18:51:17 +0000179 const FrontendOptions &FEOpts,
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000180 SourceManager &SourceMgr,
181 FileManager &FileMgr) {
182 // Create a PTH manager if we are using some form of a token cache.
183 PTHManager *PTHMgr = 0;
Daniel Dunbard6ea9022009-11-17 05:52:41 +0000184 if (!PPOpts.TokenCache.empty())
Chris Lattner7219a5d2010-11-23 09:01:31 +0000185 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000186
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000187 // Create the Preprocessor.
Chris Lattner5159f612010-11-23 08:35:12 +0000188 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000189 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
190 SourceMgr, *HeaderInfo, PTHMgr,
191 /*OwnsHeaderSearch=*/true);
192
193 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
194 // That argument is used as the IdentifierInfoLookup argument to
195 // IdentifierTable's ctor.
196 if (PTHMgr) {
197 PTHMgr->setPreprocessor(PP);
198 PP->setPTHManager(PTHMgr);
199 }
200
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000201 if (PPOpts.DetailedRecord)
202 PP->createPreprocessingRecord();
203
Chris Lattner5159f612010-11-23 08:35:12 +0000204 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000205
206 // Handle generating dependencies, if requested.
207 if (!DepOpts.OutputFile.empty())
208 AttachDependencyFileGen(*PP, DepOpts);
209
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000210 // Handle generating header include information, if requested.
211 if (DepOpts.ShowHeaderIncludes)
212 AttachHeaderIncludeGen(*PP);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000213 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
214 llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
215 if (OutputPath == "-")
216 OutputPath = "";
217 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath);
218 }
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000219
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000220 return PP;
221}
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000222
223// ASTContext
224
225void CompilerInstance::createASTContext() {
226 Preprocessor &PP = getPreprocessor();
227 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
228 getTarget(), PP.getIdentifierTable(),
229 PP.getSelectorTable(), PP.getBuiltinInfo(),
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000230 /*size_reserve=*/ 0));
231}
Daniel Dunbar599313e2009-11-13 08:21:10 +0000232
233// ExternalASTSource
234
Douglas Gregorce3a8292010-07-27 00:27:13 +0000235void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000236 bool DisablePCHValidation,
237 void *DeserializationListener){
Daniel Dunbar599313e2009-11-13 08:21:10 +0000238 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl009e7f22010-10-05 16:15:19 +0000239 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000240 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000241 DisablePCHValidation,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000242 getPreprocessor(), getASTContext(),
Sebastian Redl009e7f22010-10-05 16:15:19 +0000243 DeserializationListener,
244 Preamble));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000245 getASTContext().setExternalSource(Source);
246}
247
248ExternalASTSource *
249CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
250 const std::string &Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000251 bool DisablePCHValidation,
Daniel Dunbar599313e2009-11-13 08:21:10 +0000252 Preprocessor &PP,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000253 ASTContext &Context,
Sebastian Redl009e7f22010-10-05 16:15:19 +0000254 void *DeserializationListener,
255 bool Preamble) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000256 llvm::OwningPtr<ASTReader> Reader;
257 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000258 Sysroot.empty() ? 0 : Sysroot.c_str(),
259 DisablePCHValidation));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000260
Sebastian Redl07a89a82010-07-30 00:29:29 +0000261 Reader->setDeserializationListener(
Sebastian Redl3e31c722010-08-18 23:56:56 +0000262 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl009e7f22010-10-05 16:15:19 +0000263 switch (Reader->ReadAST(Path,
264 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000265 case ASTReader::Success:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000266 // Set the predefines buffer as suggested by the PCH reader. Typically, the
267 // predefines buffer will be empty.
268 PP.setPredefines(Reader->getSuggestedPredefines());
269 return Reader.take();
270
Sebastian Redl2c499f62010-08-18 23:56:43 +0000271 case ASTReader::Failure:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000272 // Unrecoverable failure: don't even try to process the input file.
273 break;
274
Sebastian Redl2c499f62010-08-18 23:56:43 +0000275 case ASTReader::IgnorePCH:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000276 // No suitable PCH file could be found. Return an error.
277 break;
278 }
279
280 return 0;
281}
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000282
283// Code Completion
284
Douglas Gregor8e984da2010-08-04 16:47:14 +0000285static bool EnableCodeCompletion(Preprocessor &PP,
286 const std::string &Filename,
287 unsigned Line,
288 unsigned Column) {
289 // Tell the source manager to chop off the given file at a specific
290 // line and column.
Chris Lattner5159f612010-11-23 08:35:12 +0000291 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000292 if (!Entry) {
293 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
294 << Filename;
295 return true;
296 }
297
298 // Truncate the named file at the given line/column.
299 PP.SetCodeCompletionPoint(Entry, Line, Column);
300 return false;
301}
302
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000303void CompilerInstance::createCodeCompletionConsumer() {
304 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000305 if (!CompletionConsumer) {
306 CompletionConsumer.reset(
307 createCodeCompletionConsumer(getPreprocessor(),
308 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000309 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000310 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +0000311 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000312 llvm::outs()));
313 if (!CompletionConsumer)
314 return;
315 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
316 Loc.Line, Loc.Column)) {
317 CompletionConsumer.reset();
Douglas Gregor00a0cf72010-03-16 06:04:47 +0000318 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000319 }
Douglas Gregorf09935f2009-12-01 05:55:20 +0000320
321 if (CompletionConsumer->isOutputBinary() &&
322 llvm::sys::Program::ChangeStdoutToBinary()) {
323 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
324 CompletionConsumer.reset();
325 }
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000326}
327
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000328void CompilerInstance::createFrontendTimer() {
329 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
330}
331
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000332CodeCompleteConsumer *
333CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
334 const std::string &Filename,
335 unsigned Line,
336 unsigned Column,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000337 bool ShowMacros,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000338 bool ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000339 bool ShowGlobals,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000340 llvm::raw_ostream &OS) {
Douglas Gregor8e984da2010-08-04 16:47:14 +0000341 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000342 return 0;
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000343
344 // Set up the creation routine for code-completion.
Douglas Gregorb9ab0ed2010-10-11 22:12:15 +0000345 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000346 ShowGlobals, OS);
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000347}
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000348
Douglas Gregor0e93f012010-08-12 23:31:19 +0000349void CompilerInstance::createSema(bool CompleteTranslationUnit,
350 CodeCompleteConsumer *CompletionConsumer) {
351 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
352 CompleteTranslationUnit, CompletionConsumer));
353}
354
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000355// Output Files
356
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000357void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
358 assert(OutFile.OS && "Attempt to add empty stream to output list!");
359 OutputFiles.push_back(OutFile);
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000360}
361
Kovarththanan Rajaratnam1c558cd2010-03-06 12:07:48 +0000362void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000363 for (std::list<OutputFile>::iterator
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000364 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000365 delete it->OS;
366 if (!it->TempFilename.empty()) {
367 llvm::sys::Path TempPath(it->TempFilename);
368 if (EraseFiles)
369 TempPath.eraseFromDisk();
370 else {
371 std::string Error;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000372 llvm::sys::Path NewOutFile(it->Filename);
373 // If '-working-directory' was passed, the output filename should be
374 // relative to that.
375 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
376 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000377 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
378 << it->TempFilename << it->Filename << Error;
379 TempPath.eraseFromDisk();
380 }
381 }
382 } else if (!it->Filename.empty() && EraseFiles)
383 llvm::sys::Path(it->Filename).eraseFromDisk();
384
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000385 }
386 OutputFiles.clear();
387}
388
Daniel Dunbar420b0f12009-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,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000394 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000395}
396
397llvm::raw_fd_ostream *
398CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000399 bool Binary, bool RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000400 llvm::StringRef InFile,
401 llvm::StringRef Extension) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000402 std::string Error, OutputPathName, TempPathName;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000403 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000404 RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000405 InFile, Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000406 &OutputPathName,
407 &TempPathName);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000408 if (!OS) {
Daniel Dunbar75546992009-12-03 09:13:30 +0000409 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
410 << OutputPath << Error;
411 return 0;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000412 }
413
414 // Add the output file -- but don't try to remove "-", since this means we are
415 // using stdin.
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000416 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
417 TempPathName, OS));
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000418
419 return OS;
420}
421
422llvm::raw_fd_ostream *
423CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
424 std::string &Error,
425 bool Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000426 bool RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000427 llvm::StringRef InFile,
428 llvm::StringRef Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000429 std::string *ResultPathName,
430 std::string *TempPathName) {
431 std::string OutFile, TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000432 if (!OutputPath.empty()) {
433 OutFile = OutputPath;
434 } else if (InFile == "-") {
435 OutFile = "-";
436 } else if (!Extension.empty()) {
437 llvm::sys::Path Path(InFile);
438 Path.eraseSuffix();
439 Path.appendSuffix(Extension);
440 OutFile = Path.str();
441 } else {
442 OutFile = "-";
443 }
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000444
445 if (OutFile != "-") {
446 llvm::sys::Path OutPath(OutFile);
447 // Only create the temporary if we can actually write to OutPath, otherwise
448 // we want to fail early.
Michael J. Spencerf6efe582011-01-10 02:34:13 +0000449 bool Exists;
450 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000451 (OutPath.isRegularFile() && OutPath.canWrite())) {
452 // Create a temporary file.
453 llvm::sys::Path TempPath(OutFile);
454 if (!TempPath.createTemporaryFileOnDisk())
455 TempFile = TempPath.str();
456 }
457 }
458
459 std::string OSFile = OutFile;
460 if (!TempFile.empty())
461 OSFile = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000462
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000463 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000464 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000465 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
466 if (!Error.empty())
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000467 return 0;
468
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000469 // Make sure the out stream file gets removed if we crash.
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000470 if (RemoveFileOnSignal)
471 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000472
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000473 if (ResultPathName)
474 *ResultPathName = OutFile;
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000475 if (TempPathName)
476 *TempPathName = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000477
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000478 return OS.take();
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000479}
Daniel Dunbar409e8902009-11-14 07:53:04 +0000480
481// Initialization Utilities
482
483bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
484 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
485 getSourceManager(), getFrontendOpts());
486}
487
488bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
489 Diagnostic &Diags,
490 FileManager &FileMgr,
491 SourceManager &SourceMgr,
492 const FrontendOptions &Opts) {
Douglas Gregor936a5b42010-11-30 05:23:00 +0000493 // Figure out where to get and map in the main file, unless it's already
494 // been created (e.g., by a precompiled preamble).
495 if (!SourceMgr.getMainFileID().isInvalid()) {
496 // Do nothing: the main file has already been set.
497 } else if (InputFile != "-") {
Chris Lattner5159f612010-11-23 08:35:12 +0000498 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman52765212010-10-26 21:13:51 +0000499 if (!File) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000500 Diags.Report(diag::err_fe_error_reading) << InputFile;
501 return false;
502 }
Dan Gohman52765212010-10-26 21:13:51 +0000503 SourceMgr.createMainFileID(File);
Daniel Dunbar409e8902009-11-14 07:53:04 +0000504 } else {
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000505 llvm::OwningPtr<llvm::MemoryBuffer> SB;
506 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000507 // FIXME: Give ec.message() in this diag.
Daniel Dunbar409e8902009-11-14 07:53:04 +0000508 Diags.Report(diag::err_fe_error_reading_stdin);
509 return false;
510 }
Dan Gohman2f76cd72010-10-26 23:21:25 +0000511 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner5159f612010-11-23 08:35:12 +0000512 SB->getBufferSize(), 0);
Dan Gohman2f76cd72010-10-26 23:21:25 +0000513 SourceMgr.createMainFileID(File);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000514 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbar409e8902009-11-14 07:53:04 +0000515 }
516
Dan Gohman52765212010-10-26 21:13:51 +0000517 assert(!SourceMgr.getMainFileID().isInvalid() &&
518 "Couldn't establish MainFileID!");
Daniel Dunbar409e8902009-11-14 07:53:04 +0000519 return true;
520}
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000521
522// High-Level Operations
523
524bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
525 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
526 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
527 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
528
529 // FIXME: Take this as an argument, once all the APIs we used have moved to
530 // taking it as an input instead of hard-coding llvm::errs.
531 llvm::raw_ostream &OS = llvm::errs();
532
533 // Create the target instance.
534 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
535 if (!hasTarget())
536 return false;
537
538 // Inform the target of the language options.
539 //
540 // FIXME: We shouldn't need to do this, the target should be immutable once
541 // created. This complexity should be lifted elsewhere.
542 getTarget().setForcedLangOptions(getLangOpts());
543
544 // Validate/process some options.
545 if (getHeaderSearchOpts().Verbose)
546 OS << "clang -cc1 version " CLANG_VERSION_STRING
547 << " based upon " << PACKAGE_STRING
548 << " hosted on " << llvm::sys::getHostTriple() << "\n";
549
550 if (getFrontendOpts().ShowTimers)
551 createFrontendTimer();
552
Douglas Gregor171b7802010-03-30 17:33:59 +0000553 if (getFrontendOpts().ShowStats)
554 llvm::EnableStatistics();
555
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000556 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
557 const std::string &InFile = getFrontendOpts().Inputs[i].second;
558
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000559 // Reset the ID tables if we are reusing the SourceManager.
560 if (hasSourceManager())
561 getSourceManager().clearIDTables();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000562
Daniel Dunbar86546382010-06-07 23:23:06 +0000563 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000564 Act.Execute();
565 Act.EndSourceFile();
566 }
567 }
568
Chris Lattner198cb4d2010-04-07 18:47:42 +0000569 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000570 // We can have multiple diagnostics sharing one diagnostic client.
571 // Get the total number of warnings/errors from the client.
572 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
573 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner198cb4d2010-04-07 18:47:42 +0000574
575 if (NumWarnings)
576 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
577 if (NumWarnings && NumErrors)
578 OS << " and ";
579 if (NumErrors)
580 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
581 if (NumWarnings || NumErrors)
582 OS << " generated.\n";
583 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000584
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000585 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000586 getFileManager().PrintStats();
587 OS << "\n";
588 }
589
Argyrios Kyrtzidisbc467932010-11-18 21:13:57 +0000590 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000591}
592
593