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 void raw_ostream::SetBufferSize(size_t Size) {
68 "Buffer size must be somewhat large for invariants to hold");
71 delete [] OutBufStart;
72 OutBufStart = new char[Size];
73 OutBufEnd = OutBufStart+Size;
74 OutBufCur = OutBufStart;
78 void raw_ostream::SetUnbuffered() {
81 delete [] OutBufStart;
82 OutBufStart = OutBufEnd = OutBufCur = 0;
86 raw_ostream &raw_ostream::operator<<(unsigned long N) {
87 // Zero is a special case.
91 char NumberBuffer[20];
92 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
93 char *CurPtr = EndPtr;
96 *--CurPtr = '0' + char(N % 10);
99 return write(CurPtr, EndPtr-CurPtr);
102 raw_ostream &raw_ostream::operator<<(long N) {
108 return this->operator<<(static_cast<unsigned long>(N));
111 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
112 // Output using 32-bit div/mod when possible.
113 if (N == static_cast<unsigned long>(N))
114 return this->operator<<(static_cast<unsigned long>(N));
116 char NumberBuffer[20];
117 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
118 char *CurPtr = EndPtr;
121 *--CurPtr = '0' + char(N % 10);
124 return write(CurPtr, EndPtr-CurPtr);
127 raw_ostream &raw_ostream::operator<<(long long N) {
133 return this->operator<<(static_cast<unsigned long long>(N));
136 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
137 // Zero is a special case.
141 char NumberBuffer[20];
142 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
143 char *CurPtr = EndPtr;
146 uintptr_t x = N % 16;
147 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
151 return write(CurPtr, EndPtr-CurPtr);
154 raw_ostream &raw_ostream::operator<<(const void *P) {
157 return write_hex((uintptr_t) P);
160 void raw_ostream::flush_nonempty() {
161 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
162 write_impl(OutBufStart, OutBufCur - OutBufStart);
163 OutBufCur = OutBufStart;
166 raw_ostream &raw_ostream::write(unsigned char C) {
167 // Group exceptional cases into a single branch.
168 if (OutBufCur >= OutBufEnd) {
170 write_impl(reinterpret_cast<char*>(&C), 1);
184 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
185 // Group exceptional cases into a single branch.
186 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
187 if (BUILTIN_EXPECT(!OutBufStart, false)) {
189 write_impl(Ptr, Size);
192 // Set up a buffer and start over.
194 return write(Ptr, Size);
196 // Write out the data in buffer-sized blocks until the remainder
197 // fits within the buffer.
199 size_t NumBytes = OutBufEnd - OutBufCur;
200 copy_to_buffer(Ptr, NumBytes);
204 } while (OutBufCur+Size > OutBufEnd);
207 copy_to_buffer(Ptr, Size);
212 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
213 // Handle short strings specially, memcpy isn't very good at very short
216 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
217 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
218 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
219 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
222 memcpy(OutBufCur, Ptr, Size);
230 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
231 // If we have more than a few bytes left in our output buffer, try
232 // formatting directly onto its end.
234 // FIXME: This test is a bit silly, since if we don't have enough
235 // space in the buffer we will have to flush the formatted output
236 // anyway. We should just flush upfront in such cases, and use the
237 // whole buffer as our scratch pad. Note, however, that this case is
238 // also necessary for correctness on unbuffered streams.
239 size_t NextBufferSize = 127;
240 if (OutBufEnd-OutBufCur > 3) {
241 size_t BufferBytesLeft = OutBufEnd-OutBufCur;
242 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
244 // Common case is that we have plenty of space.
245 if (BytesUsed < BufferBytesLeft) {
246 OutBufCur += BytesUsed;
250 // Otherwise, we overflowed and the return value tells us the size to try
252 NextBufferSize = BytesUsed;
255 // If we got here, we didn't have enough space in the output buffer for the
256 // string. Try printing into a SmallVector that is resized to have enough
257 // space. Iterate until we win.
258 SmallVector<char, 128> V;
261 V.resize(NextBufferSize);
263 // Try formatting into the SmallVector.
264 size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
266 // If BytesUsed fit into the vector, we win.
267 if (BytesUsed <= NextBufferSize)
268 return write(&V[0], BytesUsed);
270 // Otherwise, try again with a new size.
271 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
272 NextBufferSize = BytesUsed;
276 //===----------------------------------------------------------------------===//
278 //===----------------------------------------------------------------------===//
280 // Out of line virtual method.
281 void format_object_base::home() {
284 //===----------------------------------------------------------------------===//
286 //===----------------------------------------------------------------------===//
288 /// raw_fd_ostream - Open the specified file for writing. If an error
289 /// occurs, information about the error is put into ErrorInfo, and the
290 /// stream should be immediately destroyed; the string will be empty
291 /// if no error occurred.
292 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
293 std::string &ErrorInfo) : pos(0) {
296 // Handle "-" as stdout.
297 if (Filename[0] == '-' && Filename[1] == 0) {
299 // If user requested binary then put stdout into binary mode if
302 sys::Program::ChangeStdoutToBinary();
307 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
314 FD = open(Filename, Flags, 0664);
316 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
323 raw_fd_ostream::~raw_fd_ostream() {
327 if (::close(FD) != 0)
332 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
333 assert (FD >= 0 && "File already closed.");
335 if (::write(FD, Ptr, Size) != (ssize_t) Size)
339 void raw_fd_ostream::close() {
340 assert (ShouldClose);
343 if (::close(FD) != 0)
348 uint64_t raw_fd_ostream::seek(uint64_t off) {
350 pos = ::lseek(FD, off, SEEK_SET);
356 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
358 if (sys::Process::ColorNeedsFlush())
360 const char *colorcode =
361 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
362 : sys::Process::OutputColor(colors, bold, bg);
364 size_t len = strlen(colorcode);
365 write(colorcode, len);
366 // don't account colors towards output characters
372 raw_ostream &raw_fd_ostream::resetColor() {
373 if (sys::Process::ColorNeedsFlush())
375 const char *colorcode = sys::Process::ResetColor();
377 size_t len = strlen(colorcode);
378 write(colorcode, len);
379 // don't account colors towards output characters
385 //===----------------------------------------------------------------------===//
386 // raw_stdout/err_ostream
387 //===----------------------------------------------------------------------===//
389 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
390 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
393 // An out of line virtual method to provide a home for the class vtable.
394 void raw_stdout_ostream::handle() {}
395 void raw_stderr_ostream::handle() {}
397 /// outs() - This returns a reference to a raw_ostream for standard output.
398 /// Use it like: outs() << "foo" << "bar";
399 raw_ostream &llvm::outs() {
400 static raw_stdout_ostream S;
404 /// errs() - This returns a reference to a raw_ostream for standard error.
405 /// Use it like: errs() << "foo" << "bar";
406 raw_ostream &llvm::errs() {
407 static raw_stderr_ostream S;
411 /// nulls() - This returns a reference to a raw_ostream which discards output.
412 raw_ostream &llvm::nulls() {
413 static raw_null_ostream S;
417 //===----------------------------------------------------------------------===//
419 //===----------------------------------------------------------------------===//
421 raw_os_ostream::~raw_os_ostream() {
425 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
429 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
431 uint64_t raw_os_ostream::tell() {
432 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
435 //===----------------------------------------------------------------------===//
436 // raw_string_ostream
437 //===----------------------------------------------------------------------===//
439 raw_string_ostream::~raw_string_ostream() {
443 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
444 OS.append(Ptr, Size);
447 //===----------------------------------------------------------------------===//
448 // raw_svector_ostream
449 //===----------------------------------------------------------------------===//
451 raw_svector_ostream::~raw_svector_ostream() {
455 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
456 OS.append(Ptr, Ptr + Size);
459 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
461 uint64_t raw_svector_ostream::tell() {
462 return OS.size() + GetNumBytesInBuffer();
465 //===----------------------------------------------------------------------===//
467 //===----------------------------------------------------------------------===//
469 raw_null_ostream::~raw_null_ostream() {
471 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
472 // with raw_null_ostream, but it's better to have raw_null_ostream follow
473 // the rules than to change the rules just for raw_null_ostream.
478 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
481 uint64_t raw_null_ostream::current_pos() {