blob: 11a11bd930a73a1bb313dc7373ea569c1d5c54ae [file] [log] [blame]
Chris Lattner60d39622008-08-17 01:35:29 +00001//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
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// This implements support for bulk buffered stream output.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Support/raw_ostream.h"
Chris Lattner42f77ab2008-08-23 20:34:06 +000015#include "llvm/Support/Format.h"
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +000016#include "llvm/System/Program.h"
Torok Edwine8ebb0f2009-06-04 07:09:50 +000017#include "llvm/System/Process.h"
Chris Lattner097af7f2008-08-23 19:23:10 +000018#include "llvm/ADT/SmallVector.h"
Chris Lattner969a46a2008-08-22 15:45:00 +000019#include "llvm/Config/config.h"
Daniel Dunbarb372c112009-03-17 21:15:18 +000020#include "llvm/Support/Compiler.h"
Daniel Dunbar579fb872009-07-15 08:11:46 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattner07f51f72008-08-17 04:13:37 +000022#include <ostream>
Chris Lattner60d39622008-08-17 01:35:29 +000023
Chris Lattner969a46a2008-08-22 15:45:00 +000024#if defined(HAVE_UNISTD_H)
25# include <unistd.h>
26#endif
27#if defined(HAVE_FCNTL_H)
28# include <fcntl.h>
29#endif
Argyrios Kyrtzidisb68dc362008-08-17 09:25:21 +000030
31#if defined(_MSC_VER)
Chris Lattner60d39622008-08-17 01:35:29 +000032#include <io.h>
Cedric Veneta3f343f2008-08-24 11:56:40 +000033#include <fcntl.h>
Owen Andersoncb371882008-08-21 00:14:44 +000034#ifndef STDIN_FILENO
35# define STDIN_FILENO 0
36#endif
37#ifndef STDOUT_FILENO
38# define STDOUT_FILENO 1
39#endif
40#ifndef STDERR_FILENO
41# define STDERR_FILENO 2
42#endif
Chris Lattner60d39622008-08-17 01:35:29 +000043#endif
44
Chris Lattner969a46a2008-08-22 15:45:00 +000045using namespace llvm;
46
Dan Gohmane87b2ab2009-07-15 23:25:33 +000047raw_ostream::~raw_ostream() {
Dan Gohman9a312542009-07-27 20:49:44 +000048 // raw_ostream's subclasses should take care to flush the buffer
49 // in their destructors.
50 assert(OutBufCur == OutBufStart &&
51 "raw_ostream destructor called with non-empty buffer!");
52
Dan Gohmane87b2ab2009-07-15 23:25:33 +000053 delete [] OutBufStart;
54
55 // If there are any pending errors, report them now. Clients wishing
56 // to avoid llvm_report_error calls should check for errors with
57 // has_error() and clear the error flag with clear_error() before
58 // destructing raw_ostream objects which may have errors.
59 if (Error)
60 llvm_report_error("IO failure on output stream.");
61}
Chris Lattner969a46a2008-08-22 15:45:00 +000062
Chris Lattner60d39622008-08-17 01:35:29 +000063// An out of line virtual method to provide a home for the class vtable.
64void raw_ostream::handle() {}
65
Owen Anderson66b17ba2008-08-21 20:58:52 +000066raw_ostream &raw_ostream::operator<<(unsigned long N) {
67 // Zero is a special case.
68 if (N == 0)
69 return *this << '0';
70
71 char NumberBuffer[20];
72 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
73 char *CurPtr = EndPtr;
74
75 while (N) {
76 *--CurPtr = '0' + char(N % 10);
77 N /= 10;
78 }
79 return write(CurPtr, EndPtr-CurPtr);
80}
81
82raw_ostream &raw_ostream::operator<<(long N) {
83 if (N < 0) {
Daniel Dunbarde75d7f2009-03-16 22:00:17 +000084 *this << '-';
Owen Anderson66b17ba2008-08-21 20:58:52 +000085 N = -N;
86 }
87
88 return this->operator<<(static_cast<unsigned long>(N));
89}
90
91raw_ostream &raw_ostream::operator<<(unsigned long long N) {
Daniel Dunbar78a3dd82009-07-29 06:45:14 +000092 // Output using 32-bit div/mod when possible.
93 if (N == static_cast<unsigned long>(N))
94 return this->operator<<(static_cast<unsigned long>(N));
95
Owen Anderson66b17ba2008-08-21 20:58:52 +000096 char NumberBuffer[20];
97 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
98 char *CurPtr = EndPtr;
99
100 while (N) {
101 *--CurPtr = '0' + char(N % 10);
102 N /= 10;
103 }
104 return write(CurPtr, EndPtr-CurPtr);
105}
106
107raw_ostream &raw_ostream::operator<<(long long N) {
108 if (N < 0) {
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000109 *this << '-';
Owen Anderson66b17ba2008-08-21 20:58:52 +0000110 N = -N;
111 }
112
113 return this->operator<<(static_cast<unsigned long long>(N));
114}
115
Daniel Dunbar48018e02009-07-30 18:21:23 +0000116raw_ostream &raw_ostream::write_hex(unsigned long long N) {
Daniel Dunbarb451a0c2009-03-16 22:08:44 +0000117 // Zero is a special case.
118 if (N == 0)
119 return *this << '0';
120
121 char NumberBuffer[20];
122 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
123 char *CurPtr = EndPtr;
124
125 while (N) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000126 uintptr_t x = N % 16;
Daniel Dunbarb451a0c2009-03-16 22:08:44 +0000127 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
128 N /= 16;
129 }
130
131 return write(CurPtr, EndPtr-CurPtr);
Chris Lattner944fac72008-08-23 22:23:09 +0000132}
133
Daniel Dunbar48018e02009-07-30 18:21:23 +0000134raw_ostream &raw_ostream::operator<<(const void *P) {
135 *this << '0' << 'x';
136
137 return write_hex((uintptr_t) P);
138}
139
Daniel Dunbarcf2a2c62009-03-16 22:55:06 +0000140void raw_ostream::flush_nonempty() {
141 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000142 write_impl(OutBufStart, OutBufCur - OutBufStart);
Daniel Dunbarcf2a2c62009-03-16 22:55:06 +0000143 OutBufCur = OutBufStart;
144}
145
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000146raw_ostream &raw_ostream::write(unsigned char C) {
Daniel Dunbar262541b2009-03-17 01:36:56 +0000147 // Group exceptional cases into a single branch.
148 if (OutBufCur >= OutBufEnd) {
149 if (Unbuffered) {
150 write_impl(reinterpret_cast<char*>(&C), 1);
151 return *this;
152 }
153
154 if (!OutBufStart)
155 SetBufferSize();
156 else
157 flush_nonempty();
Daniel Dunbard17d74b2009-03-17 01:13:35 +0000158 }
159
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000160 *OutBufCur++ = C;
Daniel Dunbarb451a0c2009-03-16 22:08:44 +0000161 return *this;
Daniel Dunbarde75d7f2009-03-16 22:00:17 +0000162}
Chris Lattner944fac72008-08-23 22:23:09 +0000163
Dan Gohmanad60f662009-07-16 15:24:40 +0000164raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
Daniel Dunbar262541b2009-03-17 01:36:56 +0000165 // Group exceptional cases into a single branch.
Daniel Dunbarb372c112009-03-17 21:15:18 +0000166 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
Dan Gohman33e49ef2009-08-13 15:44:52 +0000167 if (BUILTIN_EXPECT(!OutBufStart, false)) {
168 if (Unbuffered) {
169 write_impl(Ptr, Size);
170 return *this;
171 }
172 // Set up a buffer and start over.
Daniel Dunbar262541b2009-03-17 01:36:56 +0000173 SetBufferSize();
Dan Gohman33e49ef2009-08-13 15:44:52 +0000174 return write(Ptr, Size);
175 }
176 // Write out the data in buffer-sized blocks until the remainder
177 // fits within the buffer.
178 do {
179 size_t NumBytes = OutBufEnd - OutBufCur;
180 copy_to_buffer(Ptr, NumBytes);
Daniel Dunbar262541b2009-03-17 01:36:56 +0000181 flush_nonempty();
Dan Gohman33e49ef2009-08-13 15:44:52 +0000182 Ptr += NumBytes;
183 Size -= NumBytes;
184 } while (OutBufCur+Size > OutBufEnd);
Daniel Dunbar262541b2009-03-17 01:36:56 +0000185 }
Dan Gohman33e49ef2009-08-13 15:44:52 +0000186
187 copy_to_buffer(Ptr, Size);
188
189 return *this;
190}
191
192void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
Owen Anderson66b17ba2008-08-21 20:58:52 +0000193 // Handle short strings specially, memcpy isn't very good at very short
194 // strings.
195 switch (Size) {
196 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
197 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
198 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
199 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
200 case 0: break;
201 default:
Dan Gohman33e49ef2009-08-13 15:44:52 +0000202 memcpy(OutBufCur, Ptr, Size);
Owen Anderson66b17ba2008-08-21 20:58:52 +0000203 break;
204 }
Daniel Dunbare77e4342009-03-10 16:21:55 +0000205
Dan Gohman33e49ef2009-08-13 15:44:52 +0000206 OutBufCur += Size;
Owen Anderson66b17ba2008-08-21 20:58:52 +0000207}
208
Chris Lattner097af7f2008-08-23 19:23:10 +0000209// Formatted output.
210raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
Daniel Dunbar262541b2009-03-17 01:36:56 +0000211 // If we have more than a few bytes left in our output buffer, try
212 // formatting directly onto its end.
213 //
214 // FIXME: This test is a bit silly, since if we don't have enough
215 // space in the buffer we will have to flush the formatted output
216 // anyway. We should just flush upfront in such cases, and use the
217 // whole buffer as our scratch pad. Note, however, that this case is
218 // also necessary for correctness on unbuffered streams.
Dan Gohmanad60f662009-07-16 15:24:40 +0000219 size_t NextBufferSize = 127;
Chris Lattner097af7f2008-08-23 19:23:10 +0000220 if (OutBufEnd-OutBufCur > 3) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000221 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
222 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
Chris Lattner097af7f2008-08-23 19:23:10 +0000223
224 // Common case is that we have plenty of space.
225 if (BytesUsed < BufferBytesLeft) {
226 OutBufCur += BytesUsed;
227 return *this;
228 }
229
230 // Otherwise, we overflowed and the return value tells us the size to try
231 // again with.
232 NextBufferSize = BytesUsed;
233 }
234
235 // If we got here, we didn't have enough space in the output buffer for the
236 // string. Try printing into a SmallVector that is resized to have enough
237 // space. Iterate until we win.
238 SmallVector<char, 128> V;
239
240 while (1) {
241 V.resize(NextBufferSize);
242
243 // Try formatting into the SmallVector.
Dan Gohmanad60f662009-07-16 15:24:40 +0000244 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
Chris Lattner097af7f2008-08-23 19:23:10 +0000245
246 // If BytesUsed fit into the vector, we win.
Chris Lattnerf61ca1e2008-10-26 19:20:47 +0000247 if (BytesUsed <= NextBufferSize)
Chris Lattner097af7f2008-08-23 19:23:10 +0000248 return write(&V[0], BytesUsed);
249
250 // Otherwise, try again with a new size.
251 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
252 NextBufferSize = BytesUsed;
253 }
254}
255
256//===----------------------------------------------------------------------===//
257// Formatted Output
258//===----------------------------------------------------------------------===//
259
260// Out of line virtual method.
261void format_object_base::home() {
262}
263
Chris Lattner60d39622008-08-17 01:35:29 +0000264//===----------------------------------------------------------------------===//
265// raw_fd_ostream
266//===----------------------------------------------------------------------===//
267
Daniel Dunbar48534b32008-10-21 19:53:10 +0000268/// raw_fd_ostream - Open the specified file for writing. If an error
269/// occurs, information about the error is put into ErrorInfo, and the
270/// stream should be immediately destroyed; the string will be empty
271/// if no error occurred.
Dan Gohmana1bdced2009-07-15 17:29:42 +0000272raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
Ted Kremenekd75ba1c2008-12-04 22:51:11 +0000273 std::string &ErrorInfo) : pos(0) {
Daniel Dunbar48534b32008-10-21 19:53:10 +0000274 ErrorInfo.clear();
275
Chris Lattnerc52b1282008-08-17 03:53:23 +0000276 // Handle "-" as stdout.
277 if (Filename[0] == '-' && Filename[1] == 0) {
278 FD = STDOUT_FILENO;
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +0000279 // If user requested binary then put stdout into binary mode if
280 // possible.
281 if (Binary)
282 sys::Program::ChangeStdoutToBinary();
Chris Lattnerc52b1282008-08-17 03:53:23 +0000283 ShouldClose = false;
284 return;
285 }
286
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +0000287 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
288#ifdef O_BINARY
289 if (Binary)
290 Flags |= O_BINARY;
291#endif
Dan Gohmana1bdced2009-07-15 17:29:42 +0000292 if (!Force)
293 Flags |= O_EXCL;
Dan Gohman9f79d3e2009-07-15 16:39:40 +0000294 FD = open(Filename, Flags, 0664);
Chris Lattner60d39622008-08-17 01:35:29 +0000295 if (FD < 0) {
296 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
297 ShouldClose = false;
298 } else {
299 ShouldClose = true;
300 }
301}
302
303raw_fd_ostream::~raw_fd_ostream() {
Ted Kremenek43d1f022008-10-23 23:49:09 +0000304 if (FD >= 0) {
305 flush();
306 if (ShouldClose)
Dan Gohmand3a974f2009-07-15 16:43:01 +0000307 if (::close(FD) != 0)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000308 error_detected();
Ted Kremenek43d1f022008-10-23 23:49:09 +0000309 }
Chris Lattner60d39622008-08-17 01:35:29 +0000310}
311
Dan Gohmanad60f662009-07-16 15:24:40 +0000312void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
Ted Kremenek43d1f022008-10-23 23:49:09 +0000313 assert (FD >= 0 && "File already closed.");
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000314 pos += Size;
Daniel Dunbar579fb872009-07-15 08:11:46 +0000315 if (::write(FD, Ptr, Size) != (ssize_t) Size)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000316 error_detected();
Chris Lattner60d39622008-08-17 01:35:29 +0000317}
318
Ted Kremenek43d1f022008-10-23 23:49:09 +0000319void raw_fd_ostream::close() {
320 assert (ShouldClose);
321 ShouldClose = false;
322 flush();
Dan Gohmand3a974f2009-07-15 16:43:01 +0000323 if (::close(FD) != 0)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000324 error_detected();
Ted Kremenek43d1f022008-10-23 23:49:09 +0000325 FD = -1;
326}
327
Ted Kremenek9c278862009-01-26 21:42:04 +0000328uint64_t raw_fd_ostream::seek(uint64_t off) {
329 flush();
Daniel Dunbar579fb872009-07-15 08:11:46 +0000330 pos = ::lseek(FD, off, SEEK_SET);
Dan Gohmand3a974f2009-07-15 16:43:01 +0000331 if (pos != off)
Dan Gohmane87b2ab2009-07-15 23:25:33 +0000332 error_detected();
Ted Kremenek9c278862009-01-26 21:42:04 +0000333 return pos;
334}
335
Torok Edwine8ebb0f2009-06-04 07:09:50 +0000336raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
337 bool bg) {
338 if (sys::Process::ColorNeedsFlush())
339 flush();
340 const char *colorcode =
341 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
342 : sys::Process::OutputColor(colors, bold, bg);
343 if (colorcode) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000344 size_t len = strlen(colorcode);
Torok Edwine8ebb0f2009-06-04 07:09:50 +0000345 write(colorcode, len);
346 // don't account colors towards output characters
347 pos -= len;
348 }
349 return *this;
350}
351
352raw_ostream &raw_fd_ostream::resetColor() {
353 if (sys::Process::ColorNeedsFlush())
354 flush();
355 const char *colorcode = sys::Process::ResetColor();
356 if (colorcode) {
Dan Gohmanad60f662009-07-16 15:24:40 +0000357 size_t len = strlen(colorcode);
Torok Edwine8ebb0f2009-06-04 07:09:50 +0000358 write(colorcode, len);
359 // don't account colors towards output characters
360 pos -= len;
361 }
362 return *this;
363}
364
Chris Lattner07f51f72008-08-17 04:13:37 +0000365//===----------------------------------------------------------------------===//
366// raw_stdout/err_ostream
367//===----------------------------------------------------------------------===//
Chris Lattner60d39622008-08-17 01:35:29 +0000368
369raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
Daniel Dunbare77e4342009-03-10 16:21:55 +0000370raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
371 true) {}
Chris Lattner60d39622008-08-17 01:35:29 +0000372
373// An out of line virtual method to provide a home for the class vtable.
374void raw_stdout_ostream::handle() {}
375void raw_stderr_ostream::handle() {}
Chris Lattner07f51f72008-08-17 04:13:37 +0000376
377/// outs() - This returns a reference to a raw_ostream for standard output.
378/// Use it like: outs() << "foo" << "bar";
Owen Andersoncb371882008-08-21 00:14:44 +0000379raw_ostream &llvm::outs() {
Chris Lattner07f51f72008-08-17 04:13:37 +0000380 static raw_stdout_ostream S;
381 return S;
382}
383
384/// errs() - This returns a reference to a raw_ostream for standard error.
385/// Use it like: errs() << "foo" << "bar";
Owen Andersoncb371882008-08-21 00:14:44 +0000386raw_ostream &llvm::errs() {
Chris Lattner07f51f72008-08-17 04:13:37 +0000387 static raw_stderr_ostream S;
388 return S;
389}
390
Daniel Dunbar34ccf032009-07-16 21:17:53 +0000391/// nulls() - This returns a reference to a raw_ostream which discards output.
392raw_ostream &llvm::nulls() {
393 static raw_null_ostream S;
394 return S;
395}
396
Chris Lattner07f51f72008-08-17 04:13:37 +0000397//===----------------------------------------------------------------------===//
398// raw_os_ostream
399//===----------------------------------------------------------------------===//
400
Chris Lattner944fac72008-08-23 22:23:09 +0000401raw_os_ostream::~raw_os_ostream() {
402 flush();
403}
404
Dan Gohmanad60f662009-07-16 15:24:40 +0000405void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000406 OS.write(Ptr, Size);
Chris Lattner07f51f72008-08-17 04:13:37 +0000407}
Chris Lattner78a28122008-08-23 22:43:04 +0000408
Douglas Gregor8f7be472009-04-20 07:34:17 +0000409uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
410
411uint64_t raw_os_ostream::tell() {
412 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
413}
414
Chris Lattner78a28122008-08-23 22:43:04 +0000415//===----------------------------------------------------------------------===//
416// raw_string_ostream
417//===----------------------------------------------------------------------===//
418
419raw_string_ostream::~raw_string_ostream() {
420 flush();
421}
422
Dan Gohmanad60f662009-07-16 15:24:40 +0000423void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000424 OS.append(Ptr, Size);
Chris Lattner78a28122008-08-23 22:43:04 +0000425}
426
427//===----------------------------------------------------------------------===//
428// raw_svector_ostream
429//===----------------------------------------------------------------------===//
430
431raw_svector_ostream::~raw_svector_ostream() {
432 flush();
433}
434
Dan Gohmanad60f662009-07-16 15:24:40 +0000435void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbar89a66a92009-03-16 23:29:31 +0000436 OS.append(Ptr, Ptr + Size);
Chris Lattner78a28122008-08-23 22:43:04 +0000437}
438
Douglas Gregor8f7be472009-04-20 07:34:17 +0000439uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
440
441uint64_t raw_svector_ostream::tell() {
442 return OS.size() + GetNumBytesInBuffer();
443}
Daniel Dunbar34ccf032009-07-16 21:17:53 +0000444
445//===----------------------------------------------------------------------===//
446// raw_null_ostream
447//===----------------------------------------------------------------------===//
448
Dan Gohmanf78c8352009-07-27 21:46:02 +0000449raw_null_ostream::~raw_null_ostream() {
450#ifndef NDEBUG
451 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
452 // with raw_null_ostream, but it's better to have raw_null_ostream follow
453 // the rules than to change the rules just for raw_null_ostream.
454 flush();
455#endif
456}
457
Daniel Dunbar34ccf032009-07-16 21:17:53 +0000458void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
459}
460
461uint64_t raw_null_ostream::current_pos() {
462 return 0;
463}