1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements support for bulk buffered stream output.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/System/Program.h"
17 #include "llvm/System/Process.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
24 #if defined(HAVE_UNISTD_H)
27 #if defined(HAVE_FCNTL_H)
35 # define STDIN_FILENO 0
38 # define STDOUT_FILENO 1
41 # define STDERR_FILENO 2
47 raw_ostream::~raw_ostream() {
48 // 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!");
53 delete [] OutBufStart;
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.
60 llvm_report_error("IO failure on output stream.");
63 // An out of line virtual method to provide a home for the class vtable.
64 void raw_ostream::handle() {}
66 raw_ostream &raw_ostream::operator<<(unsigned long N) {
67 // Zero is a special case.
71 char NumberBuffer[20];
72 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
73 char *CurPtr = EndPtr;
76 *--CurPtr = '0' + char(N % 10);
79 return write(CurPtr, EndPtr-CurPtr);
82 raw_ostream &raw_ostream::operator<<(long N) {
88 return this->operator<<(static_cast<unsigned long>(N));
91 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
92 // 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));
96 char NumberBuffer[20];
97 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
98 char *CurPtr = EndPtr;
101 *--CurPtr = '0' + char(N % 10);
104 return write(CurPtr, EndPtr-CurPtr);
107 raw_ostream &raw_ostream::operator<<(long long N) {
113 return this->operator<<(static_cast<unsigned long long>(N));
116 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
117 // Zero is a special case.
121 char NumberBuffer[20];
122 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
123 char *CurPtr = EndPtr;
126 uintptr_t x = N % 16;
127 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
131 return write(CurPtr, EndPtr-CurPtr);
134 raw_ostream &raw_ostream::operator<<(const void *P) {
137 return write_hex((uintptr_t) P);
140 void raw_ostream::flush_nonempty() {
141 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
142 write_impl(OutBufStart, OutBufCur - OutBufStart);
143 OutBufCur = OutBufStart;
146 raw_ostream &raw_ostream::write(unsigned char C) {
147 // Group exceptional cases into a single branch.
148 if (OutBufCur >= OutBufEnd) {
150 write_impl(reinterpret_cast<char*>(&C), 1);
164 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
165 // Group exceptional cases into a single branch.
166 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
167 if (BUILTIN_EXPECT(!OutBufStart, false)) {
169 write_impl(Ptr, Size);
172 // Set up a buffer and start over.
174 return write(Ptr, Size);
176 // Write out the data in buffer-sized blocks until the remainder
177 // fits within the buffer.
179 size_t NumBytes = OutBufEnd - OutBufCur;
180 copy_to_buffer(Ptr, NumBytes);
184 } while (OutBufCur+Size > OutBufEnd);
187 copy_to_buffer(Ptr, Size);
192 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
193 // Handle short strings specially, memcpy isn't very good at very short
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
202 memcpy(OutBufCur, Ptr, Size);
210 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
211 // If we have more than a few bytes left in our output buffer, try
212 // formatting directly onto its end.
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.
219 size_t NextBufferSize = 127;
220 if (OutBufEnd-OutBufCur > 3) {
221 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
222 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
224 // Common case is that we have plenty of space.
225 if (BytesUsed < BufferBytesLeft) {
226 OutBufCur += BytesUsed;
230 // Otherwise, we overflowed and the return value tells us the size to try
232 NextBufferSize = BytesUsed;
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;
241 V.resize(NextBufferSize);
243 // Try formatting into the SmallVector.
244 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
246 // If BytesUsed fit into the vector, we win.
247 if (BytesUsed <= NextBufferSize)
248 return write(&V[0], BytesUsed);
250 // Otherwise, try again with a new size.
251 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
252 NextBufferSize = BytesUsed;
256 //===----------------------------------------------------------------------===//
258 //===----------------------------------------------------------------------===//
260 // Out of line virtual method.
261 void format_object_base::home() {
264 //===----------------------------------------------------------------------===//
266 //===----------------------------------------------------------------------===//
268 /// 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.
272 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
273 std::string &ErrorInfo) : pos(0) {
276 // Handle "-" as stdout.
277 if (Filename[0] == '-' && Filename[1] == 0) {
279 // If user requested binary then put stdout into binary mode if
282 sys::Program::ChangeStdoutToBinary();
287 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
294 FD = open(Filename, Flags, 0664);
296 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
303 raw_fd_ostream::~raw_fd_ostream() {
307 if (::close(FD) != 0)
312 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
313 assert (FD >= 0 && "File already closed.");
315 if (::write(FD, Ptr, Size) != (ssize_t) Size)
319 void raw_fd_ostream::close() {
320 assert (ShouldClose);
323 if (::close(FD) != 0)
328 uint64_t raw_fd_ostream::seek(uint64_t off) {
330 pos = ::lseek(FD, off, SEEK_SET);
336 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
338 if (sys::Process::ColorNeedsFlush())
340 const char *colorcode =
341 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
342 : sys::Process::OutputColor(colors, bold, bg);
344 size_t len = strlen(colorcode);
345 write(colorcode, len);
346 // don't account colors towards output characters
352 raw_ostream &raw_fd_ostream::resetColor() {
353 if (sys::Process::ColorNeedsFlush())
355 const char *colorcode = sys::Process::ResetColor();
357 size_t len = strlen(colorcode);
358 write(colorcode, len);
359 // don't account colors towards output characters
365 //===----------------------------------------------------------------------===//
366 // raw_stdout/err_ostream
367 //===----------------------------------------------------------------------===//
369 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
370 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
373 // An out of line virtual method to provide a home for the class vtable.
374 void raw_stdout_ostream::handle() {}
375 void raw_stderr_ostream::handle() {}
377 /// outs() - This returns a reference to a raw_ostream for standard output.
378 /// Use it like: outs() << "foo" << "bar";
379 raw_ostream &llvm::outs() {
380 static raw_stdout_ostream S;
384 /// errs() - This returns a reference to a raw_ostream for standard error.
385 /// Use it like: errs() << "foo" << "bar";
386 raw_ostream &llvm::errs() {
387 static raw_stderr_ostream S;
391 /// nulls() - This returns a reference to a raw_ostream which discards output.
392 raw_ostream &llvm::nulls() {
393 static raw_null_ostream S;
397 //===----------------------------------------------------------------------===//
399 //===----------------------------------------------------------------------===//
401 raw_os_ostream::~raw_os_ostream() {
405 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
409 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
411 uint64_t raw_os_ostream::tell() {
412 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
415 //===----------------------------------------------------------------------===//
416 // raw_string_ostream
417 //===----------------------------------------------------------------------===//
419 raw_string_ostream::~raw_string_ostream() {
423 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
424 OS.append(Ptr, Size);
427 //===----------------------------------------------------------------------===//
428 // raw_svector_ostream
429 //===----------------------------------------------------------------------===//
431 raw_svector_ostream::~raw_svector_ostream() {
435 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
436 OS.append(Ptr, Ptr + Size);
439 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
441 uint64_t raw_svector_ostream::tell() {
442 return OS.size() + GetNumBytesInBuffer();
445 //===----------------------------------------------------------------------===//
447 //===----------------------------------------------------------------------===//
449 raw_null_ostream::~raw_null_ostream() {
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.
458 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
461 uint64_t raw_null_ostream::current_pos() {