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