LLVM API Documentation

raw_ostream.cpp
Go to the documentation of this file.
00001 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements support for bulk buffered stream output.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Support/raw_ostream.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SmallVector.h"
00017 #include "llvm/ADT/StringExtras.h"
00018 #include "llvm/Config/config.h"
00019 #include "llvm/Support/Compiler.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include "llvm/Support/FileSystem.h"
00022 #include "llvm/Support/Format.h"
00023 #include "llvm/Support/MathExtras.h"
00024 #include "llvm/Support/Process.h"
00025 #include "llvm/Support/Program.h"
00026 #include <cctype>
00027 #include <cerrno>
00028 #include <sys/stat.h>
00029 #include <system_error>
00030 
00031 // <fcntl.h> may provide O_BINARY.
00032 #if defined(HAVE_FCNTL_H)
00033 # include <fcntl.h>
00034 #endif
00035 
00036 #if defined(HAVE_UNISTD_H)
00037 # include <unistd.h>
00038 #endif
00039 #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
00040 #  include <sys/uio.h>
00041 #endif
00042 
00043 #if defined(__CYGWIN__)
00044 #include <io.h>
00045 #endif
00046 
00047 #if defined(_MSC_VER)
00048 #include <io.h>
00049 #ifndef STDIN_FILENO
00050 # define STDIN_FILENO 0
00051 #endif
00052 #ifndef STDOUT_FILENO
00053 # define STDOUT_FILENO 1
00054 #endif
00055 #ifndef STDERR_FILENO
00056 # define STDERR_FILENO 2
00057 #endif
00058 #endif
00059 
00060 using namespace llvm;
00061 
00062 raw_ostream::~raw_ostream() {
00063   // raw_ostream's subclasses should take care to flush the buffer
00064   // in their destructors.
00065   assert(OutBufCur == OutBufStart &&
00066          "raw_ostream destructor called with non-empty buffer!");
00067 
00068   if (BufferMode == InternalBuffer)
00069     delete [] OutBufStart;
00070 }
00071 
00072 // An out of line virtual method to provide a home for the class vtable.
00073 void raw_ostream::handle() {}
00074 
00075 size_t raw_ostream::preferred_buffer_size() const {
00076   // BUFSIZ is intended to be a reasonable default.
00077   return BUFSIZ;
00078 }
00079 
00080 void raw_ostream::SetBuffered() {
00081   // Ask the subclass to determine an appropriate buffer size.
00082   if (size_t Size = preferred_buffer_size())
00083     SetBufferSize(Size);
00084   else
00085     // It may return 0, meaning this stream should be unbuffered.
00086     SetUnbuffered();
00087 }
00088 
00089 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
00090                                    BufferKind Mode) {
00091   assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
00092           (Mode != Unbuffered && BufferStart && Size != 0)) &&
00093          "stream must be unbuffered or have at least one byte");
00094   // Make sure the current buffer is free of content (we can't flush here; the
00095   // child buffer management logic will be in write_impl).
00096   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
00097 
00098   if (BufferMode == InternalBuffer)
00099     delete [] OutBufStart;
00100   OutBufStart = BufferStart;
00101   OutBufEnd = OutBufStart+Size;
00102   OutBufCur = OutBufStart;
00103   BufferMode = Mode;
00104 
00105   assert(OutBufStart <= OutBufEnd && "Invalid size!");
00106 }
00107 
00108 raw_ostream &raw_ostream::operator<<(unsigned long N) {
00109   // Zero is a special case.
00110   if (N == 0)
00111     return *this << '0';
00112 
00113   char NumberBuffer[20];
00114   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00115   char *CurPtr = EndPtr;
00116 
00117   while (N) {
00118     *--CurPtr = '0' + char(N % 10);
00119     N /= 10;
00120   }
00121   return write(CurPtr, EndPtr-CurPtr);
00122 }
00123 
00124 raw_ostream &raw_ostream::operator<<(long N) {
00125   if (N <  0) {
00126     *this << '-';
00127     // Avoid undefined behavior on LONG_MIN with a cast.
00128     N = -(unsigned long)N;
00129   }
00130 
00131   return this->operator<<(static_cast<unsigned long>(N));
00132 }
00133 
00134 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
00135   // Output using 32-bit div/mod when possible.
00136   if (N == static_cast<unsigned long>(N))
00137     return this->operator<<(static_cast<unsigned long>(N));
00138 
00139   char NumberBuffer[20];
00140   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00141   char *CurPtr = EndPtr;
00142 
00143   while (N) {
00144     *--CurPtr = '0' + char(N % 10);
00145     N /= 10;
00146   }
00147   return write(CurPtr, EndPtr-CurPtr);
00148 }
00149 
00150 raw_ostream &raw_ostream::operator<<(long long N) {
00151   if (N < 0) {
00152     *this << '-';
00153     // Avoid undefined behavior on INT64_MIN with a cast.
00154     N = -(unsigned long long)N;
00155   }
00156 
00157   return this->operator<<(static_cast<unsigned long long>(N));
00158 }
00159 
00160 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
00161   // Zero is a special case.
00162   if (N == 0)
00163     return *this << '0';
00164 
00165   char NumberBuffer[20];
00166   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00167   char *CurPtr = EndPtr;
00168 
00169   while (N) {
00170     uintptr_t x = N % 16;
00171     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
00172     N /= 16;
00173   }
00174 
00175   return write(CurPtr, EndPtr-CurPtr);
00176 }
00177 
00178 raw_ostream &raw_ostream::write_escaped(StringRef Str,
00179                                         bool UseHexEscapes) {
00180   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00181     unsigned char c = Str[i];
00182 
00183     switch (c) {
00184     case '\\':
00185       *this << '\\' << '\\';
00186       break;
00187     case '\t':
00188       *this << '\\' << 't';
00189       break;
00190     case '\n':
00191       *this << '\\' << 'n';
00192       break;
00193     case '"':
00194       *this << '\\' << '"';
00195       break;
00196     default:
00197       if (std::isprint(c)) {
00198         *this << c;
00199         break;
00200       }
00201 
00202       // Write out the escaped representation.
00203       if (UseHexEscapes) {
00204         *this << '\\' << 'x';
00205         *this << hexdigit((c >> 4 & 0xF));
00206         *this << hexdigit((c >> 0) & 0xF);
00207       } else {
00208         // Always use a full 3-character octal escape.
00209         *this << '\\';
00210         *this << char('0' + ((c >> 6) & 7));
00211         *this << char('0' + ((c >> 3) & 7));
00212         *this << char('0' + ((c >> 0) & 7));
00213       }
00214     }
00215   }
00216 
00217   return *this;
00218 }
00219 
00220 raw_ostream &raw_ostream::operator<<(const void *P) {
00221   *this << '0' << 'x';
00222 
00223   return write_hex((uintptr_t) P);
00224 }
00225 
00226 raw_ostream &raw_ostream::operator<<(double N) {
00227 #ifdef _WIN32
00228   // On MSVCRT and compatible, output of %e is incompatible to Posix
00229   // by default. Number of exponent digits should be at least 2. "%+03d"
00230   // FIXME: Implement our formatter to here or Support/Format.h!
00231 #if __cplusplus >= 201103L && defined(__MINGW32__)
00232   // FIXME: It should be generic to C++11.
00233   if (N == 0.0 && std::signbit(N))
00234     return *this << "-0.000000e+00";
00235 #else
00236   int fpcl = _fpclass(N);
00237 
00238   // negative zero
00239   if (fpcl == _FPCLASS_NZ)
00240     return *this << "-0.000000e+00";
00241 #endif
00242 
00243   char buf[16];
00244   unsigned len;
00245   len = snprintf(buf, sizeof(buf), "%e", N);
00246   if (len <= sizeof(buf) - 2) {
00247     if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
00248       int cs = buf[len - 4];
00249       if (cs == '+' || cs == '-') {
00250         int c1 = buf[len - 2];
00251         int c0 = buf[len - 1];
00252         if (isdigit(static_cast<unsigned char>(c1)) &&
00253             isdigit(static_cast<unsigned char>(c0))) {
00254           // Trim leading '0': "...e+012" -> "...e+12\0"
00255           buf[len - 3] = c1;
00256           buf[len - 2] = c0;
00257           buf[--len] = 0;
00258         }
00259       }
00260     }
00261     return this->operator<<(buf);
00262   }
00263 #endif
00264   return this->operator<<(format("%e", N));
00265 }
00266 
00267 
00268 
00269 void raw_ostream::flush_nonempty() {
00270   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
00271   size_t Length = OutBufCur - OutBufStart;
00272   OutBufCur = OutBufStart;
00273   write_impl(OutBufStart, Length);
00274 }
00275 
00276 raw_ostream &raw_ostream::write(unsigned char C) {
00277   // Group exceptional cases into a single branch.
00278   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
00279     if (LLVM_UNLIKELY(!OutBufStart)) {
00280       if (BufferMode == Unbuffered) {
00281         write_impl(reinterpret_cast<char*>(&C), 1);
00282         return *this;
00283       }
00284       // Set up a buffer and start over.
00285       SetBuffered();
00286       return write(C);
00287     }
00288 
00289     flush_nonempty();
00290   }
00291 
00292   *OutBufCur++ = C;
00293   return *this;
00294 }
00295 
00296 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
00297   // Group exceptional cases into a single branch.
00298   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
00299     if (LLVM_UNLIKELY(!OutBufStart)) {
00300       if (BufferMode == Unbuffered) {
00301         write_impl(Ptr, Size);
00302         return *this;
00303       }
00304       // Set up a buffer and start over.
00305       SetBuffered();
00306       return write(Ptr, Size);
00307     }
00308 
00309     size_t NumBytes = OutBufEnd - OutBufCur;
00310 
00311     // If the buffer is empty at this point we have a string that is larger
00312     // than the buffer. Directly write the chunk that is a multiple of the
00313     // preferred buffer size and put the remainder in the buffer.
00314     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
00315       assert(NumBytes != 0 && "undefined behavior");
00316       size_t BytesToWrite = Size - (Size % NumBytes);
00317       write_impl(Ptr, BytesToWrite);
00318       size_t BytesRemaining = Size - BytesToWrite;
00319       if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
00320         // Too much left over to copy into our buffer.
00321         return write(Ptr + BytesToWrite, BytesRemaining);
00322       }
00323       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
00324       return *this;
00325     }
00326 
00327     // We don't have enough space in the buffer to fit the string in. Insert as
00328     // much as possible, flush and start over with the remainder.
00329     copy_to_buffer(Ptr, NumBytes);
00330     flush_nonempty();
00331     return write(Ptr + NumBytes, Size - NumBytes);
00332   }
00333 
00334   copy_to_buffer(Ptr, Size);
00335 
00336   return *this;
00337 }
00338 
00339 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
00340   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
00341 
00342   // Handle short strings specially, memcpy isn't very good at very short
00343   // strings.
00344   switch (Size) {
00345   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
00346   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
00347   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
00348   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
00349   case 0: break;
00350   default:
00351     memcpy(OutBufCur, Ptr, Size);
00352     break;
00353   }
00354 
00355   OutBufCur += Size;
00356 }
00357 
00358 // Formatted output.
00359 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
00360   // If we have more than a few bytes left in our output buffer, try
00361   // formatting directly onto its end.
00362   size_t NextBufferSize = 127;
00363   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
00364   if (BufferBytesLeft > 3) {
00365     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
00366 
00367     // Common case is that we have plenty of space.
00368     if (BytesUsed <= BufferBytesLeft) {
00369       OutBufCur += BytesUsed;
00370       return *this;
00371     }
00372 
00373     // Otherwise, we overflowed and the return value tells us the size to try
00374     // again with.
00375     NextBufferSize = BytesUsed;
00376   }
00377 
00378   // If we got here, we didn't have enough space in the output buffer for the
00379   // string.  Try printing into a SmallVector that is resized to have enough
00380   // space.  Iterate until we win.
00381   SmallVector<char, 128> V;
00382 
00383   while (1) {
00384     V.resize(NextBufferSize);
00385 
00386     // Try formatting into the SmallVector.
00387     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
00388 
00389     // If BytesUsed fit into the vector, we win.
00390     if (BytesUsed <= NextBufferSize)
00391       return write(V.data(), BytesUsed);
00392 
00393     // Otherwise, try again with a new size.
00394     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
00395     NextBufferSize = BytesUsed;
00396   }
00397 }
00398 
00399 raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
00400   unsigned Len = FS.Str.size(); 
00401   int PadAmount = FS.Width - Len;
00402   if (FS.RightJustify && (PadAmount > 0))
00403     this->indent(PadAmount);
00404   this->operator<<(FS.Str);
00405   if (!FS.RightJustify && (PadAmount > 0))
00406     this->indent(PadAmount);
00407   return *this;
00408 }
00409 
00410 raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
00411   if (FN.Hex) {
00412     unsigned Nibbles = (64 - countLeadingZeros(FN.HexValue)+3)/4;
00413     unsigned Width = (FN.Width > Nibbles+2) ? FN.Width : Nibbles+2;
00414         
00415     char NumberBuffer[20] = "0x0000000000000000";
00416     char *EndPtr = NumberBuffer+Width;
00417     char *CurPtr = EndPtr;
00418     const char A = FN.Upper ? 'A' : 'a';
00419     unsigned long long N = FN.HexValue;
00420     while (N) {
00421       uintptr_t x = N % 16;
00422       *--CurPtr = (x < 10 ? '0' + x : A + x - 10);
00423       N /= 16;
00424     }
00425 
00426     return write(NumberBuffer, Width);
00427   } else {
00428     // Zero is a special case.
00429     if (FN.DecValue == 0) {
00430       this->indent(FN.Width-1);
00431       return *this << '0';
00432     }
00433     char NumberBuffer[32];
00434     char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00435     char *CurPtr = EndPtr;
00436     bool Neg = (FN.DecValue < 0);
00437     uint64_t N = Neg ? -static_cast<uint64_t>(FN.DecValue) : FN.DecValue;
00438     while (N) {
00439       *--CurPtr = '0' + char(N % 10);
00440       N /= 10;
00441     }
00442     int Len = EndPtr - CurPtr;
00443     int Pad = FN.Width - Len;
00444     if (Neg) 
00445       --Pad;
00446     if (Pad > 0)
00447       this->indent(Pad);
00448     if (Neg)
00449       *this << '-';
00450     return write(CurPtr, Len);
00451   }
00452 }
00453 
00454 
00455 /// indent - Insert 'NumSpaces' spaces.
00456 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
00457   static const char Spaces[] = "                                "
00458                                "                                "
00459                                "                ";
00460 
00461   // Usually the indentation is small, handle it with a fastpath.
00462   if (NumSpaces < array_lengthof(Spaces))
00463     return write(Spaces, NumSpaces);
00464 
00465   while (NumSpaces) {
00466     unsigned NumToWrite = std::min(NumSpaces,
00467                                    (unsigned)array_lengthof(Spaces)-1);
00468     write(Spaces, NumToWrite);
00469     NumSpaces -= NumToWrite;
00470   }
00471   return *this;
00472 }
00473 
00474 
00475 //===----------------------------------------------------------------------===//
00476 //  Formatted Output
00477 //===----------------------------------------------------------------------===//
00478 
00479 // Out of line virtual method.
00480 void format_object_base::home() {
00481 }
00482 
00483 //===----------------------------------------------------------------------===//
00484 //  raw_fd_ostream
00485 //===----------------------------------------------------------------------===//
00486 
00487 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
00488                                sys::fs::OpenFlags Flags)
00489     : Error(false), UseAtomicWrites(false), pos(0) {
00490   EC = std::error_code();
00491   // Handle "-" as stdout. Note that when we do this, we consider ourself
00492   // the owner of stdout. This means that we can do things like close the
00493   // file descriptor when we're done and set the "binary" flag globally.
00494   if (Filename == "-") {
00495     FD = STDOUT_FILENO;
00496     // If user requested binary then put stdout into binary mode if
00497     // possible.
00498     if (!(Flags & sys::fs::F_Text))
00499       sys::ChangeStdoutToBinary();
00500     // Close stdout when we're done, to detect any output errors.
00501     ShouldClose = true;
00502     return;
00503   }
00504 
00505   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
00506 
00507   if (EC) {
00508     ShouldClose = false;
00509     return;
00510   }
00511 
00512   // Ok, we successfully opened the file, so it'll need to be closed.
00513   ShouldClose = true;
00514 }
00515 
00516 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
00517 /// ShouldClose is true, this closes the file when the stream is destroyed.
00518 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
00519   : raw_ostream(unbuffered), FD(fd),
00520     ShouldClose(shouldClose), Error(false), UseAtomicWrites(false) {
00521 #ifdef O_BINARY
00522   // Setting STDOUT to binary mode is necessary in Win32
00523   // to avoid undesirable linefeed conversion.
00524   // Don't touch STDERR, or w*printf() (in assert()) would barf wide chars.
00525   if (fd == STDOUT_FILENO)
00526     setmode(fd, O_BINARY);
00527 #endif
00528 
00529   // Get the starting position.
00530   off_t loc = ::lseek(FD, 0, SEEK_CUR);
00531   if (loc == (off_t)-1)
00532     pos = 0;
00533   else
00534     pos = static_cast<uint64_t>(loc);
00535 }
00536 
00537 raw_fd_ostream::~raw_fd_ostream() {
00538   if (FD >= 0) {
00539     flush();
00540     if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
00541       error_detected();
00542   }
00543 
00544 #ifdef __MINGW32__
00545   // On mingw, global dtors should not call exit().
00546   // report_fatal_error() invokes exit(). We know report_fatal_error()
00547   // might not write messages to stderr when any errors were detected
00548   // on FD == 2.
00549   if (FD == 2) return;
00550 #endif
00551 
00552   // If there are any pending errors, report them now. Clients wishing
00553   // to avoid report_fatal_error calls should check for errors with
00554   // has_error() and clear the error flag with clear_error() before
00555   // destructing raw_ostream objects which may have errors.
00556   if (has_error())
00557     report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
00558 }
00559 
00560 
00561 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
00562   assert(FD >= 0 && "File already closed.");
00563   pos += Size;
00564 
00565   do {
00566     ssize_t ret;
00567 
00568     // Check whether we should attempt to use atomic writes.
00569     if (LLVM_LIKELY(!UseAtomicWrites)) {
00570       ret = ::write(FD, Ptr, Size);
00571     } else {
00572       // Use ::writev() where available.
00573 #if defined(HAVE_WRITEV)
00574       const void *Addr = static_cast<const void *>(Ptr);
00575       struct iovec IOV = {const_cast<void *>(Addr), Size };
00576       ret = ::writev(FD, &IOV, 1);
00577 #else
00578       ret = ::write(FD, Ptr, Size);
00579 #endif
00580     }
00581 
00582     if (ret < 0) {
00583       // If it's a recoverable error, swallow it and retry the write.
00584       //
00585       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
00586       // raw_ostream isn't designed to do non-blocking I/O. However, some
00587       // programs, such as old versions of bjam, have mistakenly used
00588       // O_NONBLOCK. For compatibility, emulate blocking semantics by
00589       // spinning until the write succeeds. If you don't want spinning,
00590       // don't use O_NONBLOCK file descriptors with raw_ostream.
00591       if (errno == EINTR || errno == EAGAIN
00592 #ifdef EWOULDBLOCK
00593           || errno == EWOULDBLOCK
00594 #endif
00595           )
00596         continue;
00597 
00598       // Otherwise it's a non-recoverable error. Note it and quit.
00599       error_detected();
00600       break;
00601     }
00602 
00603     // The write may have written some or all of the data. Update the
00604     // size and buffer pointer to reflect the remainder that needs
00605     // to be written. If there are no bytes left, we're done.
00606     Ptr += ret;
00607     Size -= ret;
00608   } while (Size > 0);
00609 }
00610 
00611 void raw_fd_ostream::close() {
00612   assert(ShouldClose);
00613   ShouldClose = false;
00614   flush();
00615   if (sys::Process::SafelyCloseFileDescriptor(FD))
00616     error_detected();
00617   FD = -1;
00618 }
00619 
00620 uint64_t raw_fd_ostream::seek(uint64_t off) {
00621   flush();
00622   pos = ::lseek(FD, off, SEEK_SET);
00623   if (pos != off)
00624     error_detected();
00625   return pos;
00626 }
00627 
00628 size_t raw_fd_ostream::preferred_buffer_size() const {
00629 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
00630   // Windows and Minix have no st_blksize.
00631   assert(FD >= 0 && "File not yet open!");
00632   struct stat statbuf;
00633   if (fstat(FD, &statbuf) != 0)
00634     return 0;
00635 
00636   // If this is a terminal, don't use buffering. Line buffering
00637   // would be a more traditional thing to do, but it's not worth
00638   // the complexity.
00639   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
00640     return 0;
00641   // Return the preferred block size.
00642   return statbuf.st_blksize;
00643 #else
00644   return raw_ostream::preferred_buffer_size();
00645 #endif
00646 }
00647 
00648 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
00649                                          bool bg) {
00650   if (sys::Process::ColorNeedsFlush())
00651     flush();
00652   const char *colorcode =
00653     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
00654     : sys::Process::OutputColor(colors, bold, bg);
00655   if (colorcode) {
00656     size_t len = strlen(colorcode);
00657     write(colorcode, len);
00658     // don't account colors towards output characters
00659     pos -= len;
00660   }
00661   return *this;
00662 }
00663 
00664 raw_ostream &raw_fd_ostream::resetColor() {
00665   if (sys::Process::ColorNeedsFlush())
00666     flush();
00667   const char *colorcode = sys::Process::ResetColor();
00668   if (colorcode) {
00669     size_t len = strlen(colorcode);
00670     write(colorcode, len);
00671     // don't account colors towards output characters
00672     pos -= len;
00673   }
00674   return *this;
00675 }
00676 
00677 raw_ostream &raw_fd_ostream::reverseColor() {
00678   if (sys::Process::ColorNeedsFlush())
00679     flush();
00680   const char *colorcode = sys::Process::OutputReverse();
00681   if (colorcode) {
00682     size_t len = strlen(colorcode);
00683     write(colorcode, len);
00684     // don't account colors towards output characters
00685     pos -= len;
00686   }
00687   return *this;
00688 }
00689 
00690 bool raw_fd_ostream::is_displayed() const {
00691   return sys::Process::FileDescriptorIsDisplayed(FD);
00692 }
00693 
00694 bool raw_fd_ostream::has_colors() const {
00695   return sys::Process::FileDescriptorHasColors(FD);
00696 }
00697 
00698 //===----------------------------------------------------------------------===//
00699 //  outs(), errs(), nulls()
00700 //===----------------------------------------------------------------------===//
00701 
00702 /// outs() - This returns a reference to a raw_ostream for standard output.
00703 /// Use it like: outs() << "foo" << "bar";
00704 raw_ostream &llvm::outs() {
00705   // Set buffer settings to model stdout behavior.
00706   // Delete the file descriptor when the program exits, forcing error
00707   // detection. If you don't want this behavior, don't use outs().
00708   static raw_fd_ostream S(STDOUT_FILENO, true);
00709   return S;
00710 }
00711 
00712 /// errs() - This returns a reference to a raw_ostream for standard error.
00713 /// Use it like: errs() << "foo" << "bar";
00714 raw_ostream &llvm::errs() {
00715   // Set standard error to be unbuffered by default.
00716   static raw_fd_ostream S(STDERR_FILENO, false, true);
00717   return S;
00718 }
00719 
00720 /// nulls() - This returns a reference to a raw_ostream which discards output.
00721 raw_ostream &llvm::nulls() {
00722   static raw_null_ostream S;
00723   return S;
00724 }
00725 
00726 
00727 //===----------------------------------------------------------------------===//
00728 //  raw_string_ostream
00729 //===----------------------------------------------------------------------===//
00730 
00731 raw_string_ostream::~raw_string_ostream() {
00732   flush();
00733 }
00734 
00735 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
00736   OS.append(Ptr, Size);
00737 }
00738 
00739 //===----------------------------------------------------------------------===//
00740 //  raw_svector_ostream
00741 //===----------------------------------------------------------------------===//
00742 
00743 // The raw_svector_ostream implementation uses the SmallVector itself as the
00744 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
00745 // always pointing past the end of the vector, but within the vector
00746 // capacity. This allows raw_ostream to write directly into the correct place,
00747 // and we only need to set the vector size when the data is flushed.
00748 
00749 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
00750   // Set up the initial external buffer. We make sure that the buffer has at
00751   // least 128 bytes free; raw_ostream itself only requires 64, but we want to
00752   // make sure that we don't grow the buffer unnecessarily on destruction (when
00753   // the data is flushed). See the FIXME below.
00754   OS.reserve(OS.size() + 128);
00755   SetBuffer(OS.end(), OS.capacity() - OS.size());
00756 }
00757 
00758 raw_svector_ostream::~raw_svector_ostream() {
00759   // FIXME: Prevent resizing during this flush().
00760   flush();
00761 }
00762 
00763 /// resync - This is called when the SmallVector we're appending to is changed
00764 /// outside of the raw_svector_ostream's control.  It is only safe to do this
00765 /// if the raw_svector_ostream has previously been flushed.
00766 void raw_svector_ostream::resync() {
00767   assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
00768 
00769   if (OS.capacity() - OS.size() < 64)
00770     OS.reserve(OS.capacity() * 2);
00771   SetBuffer(OS.end(), OS.capacity() - OS.size());
00772 }
00773 
00774 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
00775   if (Ptr == OS.end()) {
00776     // Grow the buffer to include the scratch area without copying.
00777     size_t NewSize = OS.size() + Size;
00778     assert(NewSize <= OS.capacity() && "Invalid write_impl() call!");
00779     OS.set_size(NewSize);
00780   } else {
00781     assert(!GetNumBytesInBuffer());
00782     OS.append(Ptr, Ptr + Size);
00783   }
00784 
00785   OS.reserve(OS.size() + 64);
00786   SetBuffer(OS.end(), OS.capacity() - OS.size());
00787 }
00788 
00789 uint64_t raw_svector_ostream::current_pos() const {
00790    return OS.size();
00791 }
00792 
00793 StringRef raw_svector_ostream::str() {
00794   flush();
00795   return StringRef(OS.begin(), OS.size());
00796 }
00797 
00798 //===----------------------------------------------------------------------===//
00799 //  raw_null_ostream
00800 //===----------------------------------------------------------------------===//
00801 
00802 raw_null_ostream::~raw_null_ostream() {
00803 #ifndef NDEBUG
00804   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
00805   // with raw_null_ostream, but it's better to have raw_null_ostream follow
00806   // the rules than to change the rules just for raw_null_ostream.
00807   flush();
00808 #endif
00809 }
00810 
00811 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
00812 }
00813 
00814 uint64_t raw_null_ostream::current_pos() const {
00815   return 0;
00816 }