blob: 212a1cf9f246c0736b7f92fa154dd67d07b5bd1e [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,
112 unsigned argc, char **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
134void CompilerInstance::createDiagnostics(int Argc, char **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,
140 int Argc, char **Argv) {
141 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;
254 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000255 DisablePCHValidation,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000256 getPreprocessor(), getASTContext(),
257 DeserializationListener));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000258 getASTContext().setExternalSource(Source);
259}
260
261ExternalASTSource *
262CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
263 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000264 bool DisablePCHValidation,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000265 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000266 ASTContext &Context,
267 void *DeserializationListener) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000268 llvm::OwningPtr<ASTReader> Reader;
269 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000270 Sysroot.empty() ? 0 : Sysroot.c_str(),
271 DisablePCHValidation));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000272
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000273 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000274 static_cast<ASTDeserializationListener *>(DeserializationListener));
275 switch (Reader->ReadAST(Path)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000276 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000277 // Set the predefines buffer as suggested by the PCH reader. Typically, the
278 // predefines buffer will be empty.
279 PP.setPredefines(Reader->getSuggestedPredefines());
280 return Reader.take();
281
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000282 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000283 // Unrecoverable failure: don't even try to process the input file.
284 break;
285
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000286 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000287 // No suitable PCH file could be found. Return an error.
288 break;
289 }
290
291 return 0;
292}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000293
294// Code Completion
295
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000296static bool EnableCodeCompletion(Preprocessor &PP,
297 const std::string &Filename,
298 unsigned Line,
299 unsigned Column) {
300 // Tell the source manager to chop off the given file at a specific
301 // line and column.
302 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
303 if (!Entry) {
304 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
305 << Filename;
306 return true;
307 }
308
309 // Truncate the named file at the given line/column.
310 PP.SetCodeCompletionPoint(Entry, Line, Column);
311 return false;
312}
313
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000314void CompilerInstance::createCodeCompletionConsumer() {
315 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000316 if (!CompletionConsumer) {
317 CompletionConsumer.reset(
318 createCodeCompletionConsumer(getPreprocessor(),
319 Loc.FileName, Loc.Line, Loc.Column,
320 getFrontendOpts().DebugCodeCompletionPrinter,
321 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000322 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000324 llvm::outs()));
325 if (!CompletionConsumer)
326 return;
327 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
328 Loc.Line, Loc.Column)) {
329 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000330 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000331 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000332
333 if (CompletionConsumer->isOutputBinary() &&
334 llvm::sys::Program::ChangeStdoutToBinary()) {
335 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
336 CompletionConsumer.reset();
337 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000338}
339
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000340void CompilerInstance::createFrontendTimer() {
341 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
342}
343
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000344CodeCompleteConsumer *
345CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
346 const std::string &Filename,
347 unsigned Line,
348 unsigned Column,
349 bool UseDebugPrinter,
350 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000351 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000352 bool ShowGlobals,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000353 llvm::raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000354 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000355 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000356
357 // Set up the creation routine for code-completion.
358 if (UseDebugPrinter)
Douglas Gregor8071e422010-08-15 06:18:01 +0000359 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
360 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000361 else
Douglas Gregor8071e422010-08-15 06:18:01 +0000362 return new CIndexCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
363 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000364}
Daniel Dunbara9204832009-11-13 10:37:48 +0000365
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000366void CompilerInstance::createSema(bool CompleteTranslationUnit,
367 CodeCompleteConsumer *CompletionConsumer) {
368 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
369 CompleteTranslationUnit, CompletionConsumer));
370}
371
Daniel Dunbara9204832009-11-13 10:37:48 +0000372// Output Files
373
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000374void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
375 assert(OutFile.OS && "Attempt to add empty stream to output list!");
376 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000377}
378
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000379void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000380 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000381 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000382 delete it->OS;
383 if (!it->TempFilename.empty()) {
384 llvm::sys::Path TempPath(it->TempFilename);
385 if (EraseFiles)
386 TempPath.eraseFromDisk();
387 else {
388 std::string Error;
389 if (TempPath.renamePathOnDisk(llvm::sys::Path(it->Filename), &Error)) {
390 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
391 << it->TempFilename << it->Filename << Error;
392 TempPath.eraseFromDisk();
393 }
394 }
395 } else if (!it->Filename.empty() && EraseFiles)
396 llvm::sys::Path(it->Filename).eraseFromDisk();
397
Daniel Dunbara9204832009-11-13 10:37:48 +0000398 }
399 OutputFiles.clear();
400}
401
Daniel Dunbarf482d592009-11-13 18:32:08 +0000402llvm::raw_fd_ostream *
403CompilerInstance::createDefaultOutputFile(bool Binary,
404 llvm::StringRef InFile,
405 llvm::StringRef Extension) {
406 return createOutputFile(getFrontendOpts().OutputFile, Binary,
407 InFile, Extension);
408}
409
410llvm::raw_fd_ostream *
411CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
412 bool Binary,
413 llvm::StringRef InFile,
414 llvm::StringRef Extension) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000415 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000416 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
417 InFile, Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000418 &OutputPathName,
419 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000420 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000421 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
422 << OutputPath << Error;
423 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000424 }
425
426 // Add the output file -- but don't try to remove "-", since this means we are
427 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000428 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
429 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000430
431 return OS;
432}
433
434llvm::raw_fd_ostream *
435CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
436 std::string &Error,
437 bool Binary,
438 llvm::StringRef InFile,
439 llvm::StringRef Extension,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000440 std::string *ResultPathName,
441 std::string *TempPathName) {
442 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000443 if (!OutputPath.empty()) {
444 OutFile = OutputPath;
445 } else if (InFile == "-") {
446 OutFile = "-";
447 } else if (!Extension.empty()) {
448 llvm::sys::Path Path(InFile);
449 Path.eraseSuffix();
450 Path.appendSuffix(Extension);
451 OutFile = Path.str();
452 } else {
453 OutFile = "-";
454 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000455
456 if (OutFile != "-") {
457 llvm::sys::Path OutPath(OutFile);
458 // Only create the temporary if we can actually write to OutPath, otherwise
459 // we want to fail early.
460 if (!OutPath.exists() ||
461 (OutPath.isRegularFile() && OutPath.canWrite())) {
462 // Create a temporary file.
463 llvm::sys::Path TempPath(OutFile);
464 if (!TempPath.createTemporaryFileOnDisk())
465 TempFile = TempPath.str();
466 }
467 }
468
469 std::string OSFile = OutFile;
470 if (!TempFile.empty())
471 OSFile = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000472
Daniel Dunbarfc971022009-11-20 22:32:38 +0000473 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000474 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000475 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
476 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000477 return 0;
478
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000479 // Make sure the out stream file gets removed if we crash.
480 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
481
Daniel Dunbarf482d592009-11-13 18:32:08 +0000482 if (ResultPathName)
483 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000484 if (TempPathName)
485 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000486
Daniel Dunbarfc971022009-11-20 22:32:38 +0000487 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000488}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000489
490// Initialization Utilities
491
492bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
493 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
494 getSourceManager(), getFrontendOpts());
495}
496
497bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
498 Diagnostic &Diags,
499 FileManager &FileMgr,
500 SourceManager &SourceMgr,
501 const FrontendOptions &Opts) {
502 // Figure out where to get and map in the main file.
Daniel Dunbar27585952010-03-19 19:44:04 +0000503 if (InputFile != "-") {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000504 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohmanf155dfa2010-08-27 15:44:11 +0000505 if (File) SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000506 if (SourceMgr.getMainFileID().isInvalid()) {
507 Diags.Report(diag::err_fe_error_reading) << InputFile;
508 return false;
509 }
510 } else {
511 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Dan Gohman6f118972010-05-27 17:33:40 +0000512 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000513 if (SourceMgr.getMainFileID().isInvalid()) {
514 Diags.Report(diag::err_fe_error_reading_stdin);
515 return false;
516 }
517 }
518
519 return true;
520}
Daniel Dunbar0397af22010-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 Gregor95dd5582010-03-30 17:33:59 +0000553 if (getFrontendOpts().ShowStats)
554 llvm::EnableStatistics();
555
Daniel Dunbar0397af22010-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 Dunbar20560482010-06-07 23:23:50 +0000559 // Reset the ID tables if we are reusing the SourceManager.
560 if (hasSourceManager())
561 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000562
Daniel Dunbard3598a62010-06-07 23:23:06 +0000563 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000564 Act.Execute();
565 Act.EndSourceFile();
566 }
567 }
568
Chris Lattner53eee7b2010-04-07 18:47:42 +0000569 if (getDiagnosticOpts().ShowCarets) {
570 unsigned NumWarnings = getDiagnostics().getNumWarnings();
Douglas Gregor1864f2e2010-04-14 22:19:45 +0000571 unsigned NumErrors = getDiagnostics().getNumErrors() -
572 getDiagnostics().getNumErrorsSuppressed();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000573
574 if (NumWarnings)
575 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
576 if (NumWarnings && NumErrors)
577 OS << " and ";
578 if (NumErrors)
579 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
580 if (NumWarnings || NumErrors)
581 OS << " generated.\n";
582 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000583
Daniel Dunbar20560482010-06-07 23:23:50 +0000584 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000585 getFileManager().PrintStats();
586 OS << "\n";
587 }
588
589 // Return the appropriate status when verifying diagnostics.
590 //
591 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
592 // this.
593 if (getDiagnosticOpts().VerifyDiagnostics)
594 return !static_cast<VerifyDiagnosticsClient&>(
595 getDiagnosticClient()).HadErrors();
596
597 return !getDiagnostics().getNumErrors();
598}
599
600