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 = format("%e", N).snprint(buf, sizeof(buf));
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 PrefixChars = FN.HexPrefix ? 2 : 0;
00414     unsigned Width = std::max(FN.Width, Nibbles + PrefixChars);
00415 
00416     char NumberBuffer[20] = "0x0000000000000000";
00417     if (!FN.HexPrefix)
00418       NumberBuffer[1] = '0';
00419     char *EndPtr = NumberBuffer+Width;
00420     char *CurPtr = EndPtr;
00421     const char A = FN.Upper ? 'A' : 'a';
00422     unsigned long long N = FN.HexValue;
00423     while (N) {
00424       uintptr_t x = N % 16;
00425       *--CurPtr = (x < 10 ? '0' + x : A + x - 10);
00426       N /= 16;
00427     }
00428 
00429     return write(NumberBuffer, Width);
00430   } else {
00431     // Zero is a special case.
00432     if (FN.DecValue == 0) {
00433       this->indent(FN.Width-1);
00434       return *this << '0';
00435     }
00436     char NumberBuffer[32];
00437     char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
00438     char *CurPtr = EndPtr;
00439     bool Neg = (FN.DecValue < 0);
00440     uint64_t N = Neg ? -static_cast<uint64_t>(FN.DecValue) : FN.DecValue;
00441     while (N) {
00442       *--CurPtr = '0' + char(N % 10);
00443       N /= 10;
00444     }
00445     int Len = EndPtr - CurPtr;
00446     int Pad = FN.Width - Len;
00447     if (Neg) 
00448       --Pad;
00449     if (Pad > 0)
00450       this->indent(Pad);
00451     if (Neg)
00452       *this << '-';
00453     return write(CurPtr, Len);
00454   }
00455 }
00456 
00457 
00458 /// indent - Insert 'NumSpaces' spaces.
00459 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
00460   static const char Spaces[] = "                                "
00461                                "                                "
00462                                "                ";
00463 
00464   // Usually the indentation is small, handle it with a fastpath.
00465   if (NumSpaces < array_lengthof(Spaces))
00466     return write(Spaces, NumSpaces);
00467 
00468   while (NumSpaces) {
00469     unsigned NumToWrite = std::min(NumSpaces,
00470                                    (unsigned)array_lengthof(Spaces)-1);
00471     write(Spaces, NumToWrite);
00472     NumSpaces -= NumToWrite;
00473   }
00474   return *this;
00475 }
00476 
00477 
00478 //===----------------------------------------------------------------------===//
00479 //  Formatted Output
00480 //===----------------------------------------------------------------------===//
00481 
00482 // Out of line virtual method.
00483 void format_object_base::home() {
00484 }
00485 
00486 //===----------------------------------------------------------------------===//
00487 //  raw_fd_ostream
00488 //===----------------------------------------------------------------------===//
00489 
00490 raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
00491                                sys::fs::OpenFlags Flags)
00492     : Error(false), UseAtomicWrites(false), pos(0) {
00493   EC = std::error_code();
00494   // Handle "-" as stdout. Note that when we do this, we consider ourself
00495   // the owner of stdout. This means that we can do things like close the
00496   // file descriptor when we're done and set the "binary" flag globally.
00497   if (Filename == "-") {
00498     FD = STDOUT_FILENO;
00499     // If user requested binary then put stdout into binary mode if
00500     // possible.
00501     if (!(Flags & sys::fs::F_Text))
00502       sys::ChangeStdoutToBinary();
00503     // Close stdout when we're done, to detect any output errors.
00504     ShouldClose = true;
00505     return;
00506   }
00507 
00508   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
00509 
00510   if (EC) {
00511     ShouldClose = false;
00512     return;
00513   }
00514 
00515   // Ok, we successfully opened the file, so it'll need to be closed.
00516   ShouldClose = true;
00517 }
00518 
00519 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
00520 /// ShouldClose is true, this closes the file when the stream is destroyed.
00521 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
00522   : raw_ostream(unbuffered), FD(fd),
00523     ShouldClose(shouldClose), Error(false), UseAtomicWrites(false) {
00524 #ifdef O_BINARY
00525   // Setting STDOUT to binary mode is necessary in Win32
00526   // to avoid undesirable linefeed conversion.
00527   // Don't touch STDERR, or w*printf() (in assert()) would barf wide chars.
00528   if (fd == STDOUT_FILENO)
00529     setmode(fd, O_BINARY);
00530 #endif
00531 
00532   // Get the starting position.
00533   off_t loc = ::lseek(FD, 0, SEEK_CUR);
00534   if (loc == (off_t)-1)
00535     pos = 0;
00536   else
00537     pos = static_cast<uint64_t>(loc);
00538 }
00539 
00540 raw_fd_ostream::~raw_fd_ostream() {
00541   if (FD >= 0) {
00542     flush();
00543     if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
00544       error_detected();
00545   }
00546 
00547 #ifdef __MINGW32__
00548   // On mingw, global dtors should not call exit().
00549   // report_fatal_error() invokes exit(). We know report_fatal_error()
00550   // might not write messages to stderr when any errors were detected
00551   // on FD == 2.
00552   if (FD == 2) return;
00553 #endif
00554 
00555   // If there are any pending errors, report them now. Clients wishing
00556   // to avoid report_fatal_error calls should check for errors with
00557   // has_error() and clear the error flag with clear_error() before
00558   // destructing raw_ostream objects which may have errors.
00559   if (has_error())
00560     report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
00561 }
00562 
00563 
00564 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
00565   assert(FD >= 0 && "File already closed.");
00566   pos += Size;
00567 
00568   do {
00569     ssize_t ret;
00570 
00571     // Check whether we should attempt to use atomic writes.
00572     if (LLVM_LIKELY(!UseAtomicWrites)) {
00573       ret = ::write(FD, Ptr, Size);
00574     } else {
00575       // Use ::writev() where available.
00576 #if defined(HAVE_WRITEV)
00577       const void *Addr = static_cast<const void *>(Ptr);
00578       struct iovec IOV = {const_cast<void *>(Addr), Size };
00579       ret = ::writev(FD, &IOV, 1);
00580 #else
00581       ret = ::write(FD, Ptr, Size);
00582 #endif
00583     }
00584 
00585     if (ret < 0) {
00586       // If it's a recoverable error, swallow it and retry the write.
00587       //
00588       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
00589       // raw_ostream isn't designed to do non-blocking I/O. However, some
00590       // programs, such as old versions of bjam, have mistakenly used
00591       // O_NONBLOCK. For compatibility, emulate blocking semantics by
00592       // spinning until the write succeeds. If you don't want spinning,
00593       // don't use O_NONBLOCK file descriptors with raw_ostream.
00594       if (errno == EINTR || errno == EAGAIN
00595 #ifdef EWOULDBLOCK
00596           || errno == EWOULDBLOCK
00597 #endif
00598           )
00599         continue;
00600 
00601       // Otherwise it's a non-recoverable error. Note it and quit.
00602       error_detected();
00603       break;
00604     }
00605 
00606     // The write may have written some or all of the data. Update the
00607     // size and buffer pointer to reflect the remainder that needs
00608     // to be written. If there are no bytes left, we're done.
00609     Ptr += ret;
00610     Size -= ret;
00611   } while (Size > 0);
00612 }
00613 
00614 void raw_fd_ostream::close() {
00615   assert(ShouldClose);
00616   ShouldClose = false;
00617   flush();
00618   if (sys::Process::SafelyCloseFileDescriptor(FD))
00619     error_detected();
00620   FD = -1;
00621 }
00622 
00623 uint64_t raw_fd_ostream::seek(uint64_t off) {
00624   flush();
00625   pos = ::lseek(FD, off, SEEK_SET);
00626   if (pos != off)
00627     error_detected();
00628   return pos;
00629 }
00630 
00631 size_t raw_fd_ostream::preferred_buffer_size() const {
00632 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
00633   // Windows and Minix have no st_blksize.
00634   assert(FD >= 0 && "File not yet open!");
00635   struct stat statbuf;
00636   if (fstat(FD, &statbuf) != 0)
00637     return 0;
00638 
00639   // If this is a terminal, don't use buffering. Line buffering
00640   // would be a more traditional thing to do, but it's not worth
00641   // the complexity.
00642   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
00643     return 0;
00644   // Return the preferred block size.
00645   return statbuf.st_blksize;
00646 #else
00647   return raw_ostream::preferred_buffer_size();
00648 #endif
00649 }
00650 
00651 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
00652                                          bool bg) {
00653   if (sys::Process::ColorNeedsFlush())
00654     flush();
00655   const char *colorcode =
00656     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
00657     : sys::Process::OutputColor(colors, bold, bg);
00658   if (colorcode) {
00659     size_t len = strlen(colorcode);
00660     write(colorcode, len);
00661     // don't account colors towards output characters
00662     pos -= len;
00663   }
00664   return *this;
00665 }
00666 
00667 raw_ostream &raw_fd_ostream::resetColor() {
00668   if (sys::Process::ColorNeedsFlush())
00669     flush();
00670   const char *colorcode = sys::Process::ResetColor();
00671   if (colorcode) {
00672     size_t len = strlen(colorcode);
00673     write(colorcode, len);
00674     // don't account colors towards output characters
00675     pos -= len;
00676   }
00677   return *this;
00678 }
00679 
00680 raw_ostream &raw_fd_ostream::reverseColor() {
00681   if (sys::Process::ColorNeedsFlush())
00682     flush();
00683   const char *colorcode = sys::Process::OutputReverse();
00684   if (colorcode) {
00685     size_t len = strlen(colorcode);
00686     write(colorcode, len);
00687     // don't account colors towards output characters
00688     pos -= len;
00689   }
00690   return *this;
00691 }
00692 
00693 bool raw_fd_ostream::is_displayed() const {
00694   return sys::Process::FileDescriptorIsDisplayed(FD);
00695 }
00696 
00697 bool raw_fd_ostream::has_colors() const {
00698   return sys::Process::FileDescriptorHasColors(FD);
00699 }
00700 
00701 //===----------------------------------------------------------------------===//
00702 //  outs(), errs(), nulls()
00703 //===----------------------------------------------------------------------===//
00704 
00705 /// outs() - This returns a reference to a raw_ostream for standard output.
00706 /// Use it like: outs() << "foo" << "bar";
00707 raw_ostream &llvm::outs() {
00708   // Set buffer settings to model stdout behavior.
00709   // Delete the file descriptor when the program exits, forcing error
00710   // detection. If you don't want this behavior, don't use outs().
00711   static raw_fd_ostream S(STDOUT_FILENO, true);
00712   return S;
00713 }
00714 
00715 /// errs() - This returns a reference to a raw_ostream for standard error.
00716 /// Use it like: errs() << "foo" << "bar";
00717 raw_ostream &llvm::errs() {
00718   // Set standard error to be unbuffered by default.
00719   static raw_fd_ostream S(STDERR_FILENO, false, true);
00720   return S;
00721 }
00722 
00723 /// nulls() - This returns a reference to a raw_ostream which discards output.
00724 raw_ostream &llvm::nulls() {
00725   static raw_null_ostream S;
00726   return S;
00727 }
00728 
00729 
00730 //===----------------------------------------------------------------------===//
00731 //  raw_string_ostream
00732 //===----------------------------------------------------------------------===//
00733 
00734 raw_string_ostream::~raw_string_ostream() {
00735   flush();
00736 }
00737 
00738 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
00739   OS.append(Ptr, Size);
00740 }
00741 
00742 //===----------------------------------------------------------------------===//
00743 //  raw_svector_ostream
00744 //===----------------------------------------------------------------------===//
00745 
00746 // The raw_svector_ostream implementation uses the SmallVector itself as the
00747 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
00748 // always pointing past the end of the vector, but within the vector
00749 // capacity. This allows raw_ostream to write directly into the correct place,
00750 // and we only need to set the vector size when the data is flushed.
00751 
00752 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
00753   // Set up the initial external buffer. We make sure that the buffer has at
00754   // least 128 bytes free; raw_ostream itself only requires 64, but we want to
00755   // make sure that we don't grow the buffer unnecessarily on destruction (when
00756   // the data is flushed). See the FIXME below.
00757   OS.reserve(OS.size() + 128);
00758   SetBuffer(OS.end(), OS.capacity() - OS.size());
00759 }
00760 
00761 raw_svector_ostream::~raw_svector_ostream() {
00762   // FIXME: Prevent resizing during this flush().
00763   flush();
00764 }
00765 
00766 /// resync - This is called when the SmallVector we're appending to is changed
00767 /// outside of the raw_svector_ostream's control.  It is only safe to do this
00768 /// if the raw_svector_ostream has previously been flushed.
00769 void raw_svector_ostream::resync() {
00770   assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
00771 
00772   if (OS.capacity() - OS.size() < 64)
00773     OS.reserve(OS.capacity() * 2);
00774   SetBuffer(OS.end(), OS.capacity() - OS.size());
00775 }
00776 
00777 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
00778   if (Ptr == OS.end()) {
00779     // Grow the buffer to include the scratch area without copying.
00780     size_t NewSize = OS.size() + Size;
00781     assert(NewSize <= OS.capacity() && "Invalid write_impl() call!");
00782     OS.set_size(NewSize);
00783   } else {
00784     assert(!GetNumBytesInBuffer());
00785     OS.append(Ptr, Ptr + Size);
00786   }
00787 
00788   OS.reserve(OS.size() + 64);
00789   SetBuffer(OS.end(), OS.capacity() - OS.size());
00790 }
00791 
00792 uint64_t raw_svector_ostream::current_pos() const {
00793    return OS.size();
00794 }
00795 
00796 StringRef raw_svector_ostream::str() {
00797   flush();
00798   return StringRef(OS.begin(), OS.size());
00799 }
00800 
00801 //===----------------------------------------------------------------------===//
00802 //  raw_null_ostream
00803 //===----------------------------------------------------------------------===//
00804 
00805 raw_null_ostream::~raw_null_ostream() {
00806 #ifndef NDEBUG
00807   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
00808   // with raw_null_ostream, but it's better to have raw_null_ostream follow
00809   // the rules than to change the rules just for raw_null_ostream.
00810   flush();
00811 #endif
00812 }
00813 
00814 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
00815 }
00816 
00817 uint64_t raw_null_ostream::current_pos() const {
00818   return 0;
00819 }