Add Thumb2 lsr hooks.
[oota-llvm.git] / lib / Support / raw_ostream.cpp
index 8724801818c289822eb1de40df3129e3940a1dd9..dcd33673acd91bbcd6604e38c377ca16518e202d 100644 (file)
@@ -20,6 +20,8 @@
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <ostream>
+#include <sys/stat.h>
+#include <sys/types.h>
 
 #if defined(HAVE_UNISTD_H)
 # include <unistd.h>
 using namespace llvm;
 
 raw_ostream::~raw_ostream() {
+  // raw_ostream's subclasses should take care to flush the buffer
+  // in their destructors.
+  assert(OutBufCur == OutBufStart &&
+         "raw_ostream destructor called with non-empty buffer!");
+
   delete [] OutBufStart;
 
   // If there are any pending errors, report them now. Clients wishing
@@ -58,6 +65,36 @@ raw_ostream::~raw_ostream() {
 // An out of line virtual method to provide a home for the class vtable.
 void raw_ostream::handle() {}
 
+size_t raw_ostream::preferred_buffer_size() {
+  // BUFSIZ is intended to be a reasonable default.
+  return BUFSIZ;
+}
+
+void raw_ostream::SetBuffered() {
+  // Ask the subclass to determine an appropriate buffer size.
+  SetBufferSize(preferred_buffer_size());
+}
+
+void raw_ostream::SetBufferSize(size_t Size) {
+  assert(Size >= 64 &&
+         "Buffer size must be somewhat large for invariants to hold");
+  flush();
+
+  delete [] OutBufStart;
+  OutBufStart = new char[Size];
+  OutBufEnd = OutBufStart+Size;
+  OutBufCur = OutBufStart;
+  Unbuffered = false;
+}
+
+void raw_ostream::SetUnbuffered() {
+  flush();
+
+  delete [] OutBufStart;
+  OutBufStart = OutBufEnd = OutBufCur = 0;
+  Unbuffered = true;
+}
+
 raw_ostream &raw_ostream::operator<<(unsigned long N) {
   // Zero is a special case.
   if (N == 0)
@@ -84,10 +121,10 @@ raw_ostream &raw_ostream::operator<<(long N) {
 }
 
 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
-  // Zero is a special case.
-  if (N == 0)
-    return *this << '0';
-  
+  // Output using 32-bit div/mod when possible.
+  if (N == static_cast<unsigned long>(N))
+    return this->operator<<(static_cast<unsigned long>(N));
+
   char NumberBuffer[20];
   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
   char *CurPtr = EndPtr;
@@ -108,10 +145,7 @@ raw_ostream &raw_ostream::operator<<(long long N) {
   return this->operator<<(static_cast<unsigned long long>(N));
 }
 
-raw_ostream &raw_ostream::operator<<(const void *P) {
-  uintptr_t N = (uintptr_t) P;
-  *this << '0' << 'x';
-  
+raw_ostream &raw_ostream::write_hex(unsigned long long N) {
   // Zero is a special case.
   if (N == 0)
     return *this << '0';
@@ -121,7 +155,7 @@ raw_ostream &raw_ostream::operator<<(const void *P) {
   char *CurPtr = EndPtr;
 
   while (N) {
-    unsigned x = N % 16;
+    uintptr_t x = N % 16;
     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
     N /= 16;
   }
@@ -129,6 +163,12 @@ raw_ostream &raw_ostream::operator<<(const void *P) {
   return write(CurPtr, EndPtr-CurPtr);
 }
 
+raw_ostream &raw_ostream::operator<<(const void *P) {
+  *this << '0' << 'x';
+
+  return write_hex((uintptr_t) P);
+}
+
 void raw_ostream::flush_nonempty() {
   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
   write_impl(OutBufStart, OutBufCur - OutBufStart);
@@ -144,7 +184,7 @@ raw_ostream &raw_ostream::write(unsigned char C) {
     }
     
     if (!OutBufStart)
-      SetBufferSize();
+      SetBuffered();
     else
       flush_nonempty();
   }
@@ -153,20 +193,37 @@ raw_ostream &raw_ostream::write(unsigned char C) {
   return *this;
 }
 
-raw_ostream &raw_ostream::write(const char *Ptr, unsigned Size) {
+raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
   // Group exceptional cases into a single branch.
   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
-    if (Unbuffered) {
-      write_impl(Ptr, Size);
-      return *this;
+    if (BUILTIN_EXPECT(!OutBufStart, false)) {
+      if (Unbuffered) {
+        write_impl(Ptr, Size);
+        return *this;
+      }
+      // Set up a buffer and start over.
+      SetBuffered();
+      return write(Ptr, Size);
     }
-    
-    if (!OutBufStart)
-      SetBufferSize();
-    else
+    // Write out the data in buffer-sized blocks until the remainder
+    // fits within the buffer.
+    do {
+      size_t NumBytes = OutBufEnd - OutBufCur;
+      copy_to_buffer(Ptr, NumBytes);
       flush_nonempty();
+      Ptr += NumBytes;
+      Size -= NumBytes;
+    } while (OutBufCur+Size > OutBufEnd);
   }
-  
+
+  copy_to_buffer(Ptr, Size);
+
+  return *this;
+}
+
+void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
+  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
+
   // Handle short strings specially, memcpy isn't very good at very short
   // strings.
   switch (Size) {
@@ -176,21 +233,11 @@ raw_ostream &raw_ostream::write(const char *Ptr, unsigned Size) {
   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
   case 0: break;
   default:
-    // Normally the string to emit is shorter than the buffer.
-    if (Size <= unsigned(OutBufEnd-OutBufCur)) {
-      memcpy(OutBufCur, Ptr, Size);
-      break;
-    } 
-
-    // Otherwise we are emitting a string larger than our buffer. We
-    // know we already flushed, so just write it out directly.
-    write_impl(Ptr, Size);
-    Size = 0;
+    memcpy(OutBufCur, Ptr, Size);
     break;
   }
-  OutBufCur += Size;
 
-  return *this;
+  OutBufCur += Size;
 }
 
 // Formatted output.
@@ -203,10 +250,10 @@ raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
   // anyway. We should just flush upfront in such cases, and use the
   // whole buffer as our scratch pad. Note, however, that this case is
   // also necessary for correctness on unbuffered streams.
-  unsigned NextBufferSize = 127;
+  size_t NextBufferSize = 127;
   if (OutBufEnd-OutBufCur > 3) {
-    unsigned BufferBytesLeft = OutBufEnd-OutBufCur;
-    unsigned BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
+    size_t BufferBytesLeft = OutBufEnd-OutBufCur;
+    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
     
     // Common case is that we have plenty of space.
     if (BytesUsed < BufferBytesLeft) {
@@ -228,7 +275,7 @@ raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
     V.resize(NextBufferSize);
     
     // Try formatting into the SmallVector.
-    unsigned BytesUsed = Fmt.print(&V[0], NextBufferSize);
+    size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
     
     // If BytesUsed fit into the vector, we win.
     if (BytesUsed <= NextBufferSize)
@@ -268,6 +315,10 @@ raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
     if (Binary)
       sys::Program::ChangeStdoutToBinary();
     ShouldClose = false;
+    // Mimic stdout by defaulting to unbuffered if the output device
+    // is a terminal.
+    if (sys::Process::StandardOutIsDisplayed())
+      SetUnbuffered();
     return;
   }
   
@@ -296,7 +347,7 @@ raw_fd_ostream::~raw_fd_ostream() {
   }
 }
 
-void raw_fd_ostream::write_impl(const char *Ptr, unsigned Size) {
+void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
   assert (FD >= 0 && "File already closed.");
   pos += Size;
   if (::write(FD, Ptr, Size) != (ssize_t) Size)
@@ -320,6 +371,17 @@ uint64_t raw_fd_ostream::seek(uint64_t off) {
   return pos;  
 }
 
+size_t raw_fd_ostream::preferred_buffer_size() {
+#if !defined(_MSC_VER) // Windows reportedly doesn't have st_blksize.
+  assert(FD >= 0 && "File not yet open!");
+  struct stat statbuf;
+  if (fstat(FD, &statbuf) == 0)
+    return statbuf.st_blksize;
+  error_detected();
+#endif
+  return raw_ostream::preferred_buffer_size();
+}
+
 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
                                          bool bg) {
   if (sys::Process::ColorNeedsFlush())
@@ -328,7 +390,7 @@ raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
     : sys::Process::OutputColor(colors, bold, bg);
   if (colorcode) {
-    unsigned len = strlen(colorcode);
+    size_t len = strlen(colorcode);
     write(colorcode, len);
     // don't account colors towards output characters
     pos -= len;
@@ -341,7 +403,7 @@ raw_ostream &raw_fd_ostream::resetColor() {
     flush();
   const char *colorcode = sys::Process::ResetColor();
   if (colorcode) {
-    unsigned len = strlen(colorcode);
+    size_t len = strlen(colorcode);
     write(colorcode, len);
     // don't account colors towards output characters
     pos -= len;
@@ -353,7 +415,13 @@ raw_ostream &raw_fd_ostream::resetColor() {
 //  raw_stdout/err_ostream
 //===----------------------------------------------------------------------===//
 
-raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
+// Set buffer settings to model stdout and stderr behavior.
+// raw_ostream doesn't support line buffering, so set standard output to be
+// unbuffered when the output device is a terminal. Set standard error to
+// be unbuffered.
+raw_stdout_ostream::raw_stdout_ostream()
+  : raw_fd_ostream(STDOUT_FILENO, false,
+                   sys::Process::StandardOutIsDisplayed()) {}
 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false, 
                                                         true) {}
 
@@ -375,15 +443,17 @@ raw_ostream &llvm::errs() {
   return S;
 }
 
+/// nulls() - This returns a reference to a raw_ostream which discards output.
+raw_ostream &llvm::nulls() {
+  static raw_null_ostream S;
+  return S;
+}
+
 //===----------------------------------------------------------------------===//
 //  raw_os_ostream
 //===----------------------------------------------------------------------===//
 
-raw_os_ostream::~raw_os_ostream() {
-  flush();
-}
-
-void raw_os_ostream::write_impl(const char *Ptr, unsigned Size) {
+void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
   OS.write(Ptr, Size);
 }
 
@@ -397,11 +467,7 @@ uint64_t raw_os_ostream::tell() {
 //  raw_string_ostream
 //===----------------------------------------------------------------------===//
 
-raw_string_ostream::~raw_string_ostream() {
-  flush();
-}
-
-void raw_string_ostream::write_impl(const char *Ptr, unsigned Size) {
+void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
   OS.append(Ptr, Size);
 }
 
@@ -409,11 +475,7 @@ void raw_string_ostream::write_impl(const char *Ptr, unsigned Size) {
 //  raw_svector_ostream
 //===----------------------------------------------------------------------===//
 
-raw_svector_ostream::~raw_svector_ostream() {
-  flush();
-}
-
-void raw_svector_ostream::write_impl(const char *Ptr, unsigned Size) {
+void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
   OS.append(Ptr, Ptr + Size);
 }
 
@@ -422,3 +484,23 @@ uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
 uint64_t raw_svector_ostream::tell() { 
   return OS.size() + GetNumBytesInBuffer(); 
 }
+
+//===----------------------------------------------------------------------===//
+//  raw_null_ostream
+//===----------------------------------------------------------------------===//
+
+raw_null_ostream::~raw_null_ostream() {
+#ifndef NDEBUG
+  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
+  // with raw_null_ostream, but it's better to have raw_null_ostream follow
+  // the rules than to change the rules just for raw_null_ostream.
+  flush();
+#endif
+}
+
+void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
+}
+
+uint64_t raw_null_ostream::current_pos() {
+  return 0;
+}