Speed up raw_ostream::<<(unsigned long long) for 32-bit systems by doing most
[oota-llvm.git] / lib / Support / raw_ostream.cpp
1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements support for bulk buffered stream output.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/System/Program.h"
17 #include "llvm/System/Process.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include <ostream>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25
26 #if defined(HAVE_UNISTD_H)
27 # include <unistd.h>
28 #endif
29 #if defined(HAVE_FCNTL_H)
30 # include <fcntl.h>
31 #endif
32
33 #if defined(_MSC_VER)
34 #include <io.h>
35 #include <fcntl.h>
36 #ifndef STDIN_FILENO
37 # define STDIN_FILENO 0
38 #endif
39 #ifndef STDOUT_FILENO
40 # define STDOUT_FILENO 1
41 #endif
42 #ifndef STDERR_FILENO
43 # define STDERR_FILENO 2
44 #endif
45 #endif
46
47 using namespace llvm;
48
49 raw_ostream::~raw_ostream() {
50   // raw_ostream's subclasses should take care to flush the buffer
51   // in their destructors.
52   assert(OutBufCur == OutBufStart &&
53          "raw_ostream destructor called with non-empty buffer!");
54
55   delete [] OutBufStart;
56
57   // If there are any pending errors, report them now. Clients wishing
58   // to avoid llvm_report_error calls should check for errors with
59   // has_error() and clear the error flag with clear_error() before
60   // destructing raw_ostream objects which may have errors.
61   if (Error)
62     llvm_report_error("IO failure on output stream.");
63 }
64
65 // An out of line virtual method to provide a home for the class vtable.
66 void raw_ostream::handle() {}
67
68 size_t raw_ostream::preferred_buffer_size() {
69   // BUFSIZ is intended to be a reasonable default.
70   return BUFSIZ;
71 }
72
73 void raw_ostream::SetBuffered() {
74   // Ask the subclass to determine an appropriate buffer size.
75   if (size_t Size = preferred_buffer_size())
76     SetBufferSize(Size);
77   else
78     // It may return 0, meaning this stream should be unbuffered.
79     SetUnbuffered();
80 }
81
82 void raw_ostream::SetBufferSize(size_t Size) {
83   assert(Size >= 64 &&
84          "Buffer size must be somewhat large for invariants to hold");
85   flush();
86
87   delete [] OutBufStart;
88   OutBufStart = new char[Size];
89   OutBufEnd = OutBufStart+Size;
90   OutBufCur = OutBufStart;
91   Unbuffered = false;
92 }
93
94 void raw_ostream::SetUnbuffered() {
95   flush();
96
97   delete [] OutBufStart;
98   OutBufStart = OutBufEnd = OutBufCur = 0;
99   Unbuffered = true;
100 }
101
102 raw_ostream &raw_ostream::operator<<(unsigned long N) {
103   // Zero is a special case.
104   if (N == 0)
105     return *this << '0';
106   
107   char NumberBuffer[20];
108   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
109   char *CurPtr = EndPtr;
110   
111   while (N) {
112     *--CurPtr = '0' + char(N % 10);
113     N /= 10;
114   }
115   return write(CurPtr, EndPtr-CurPtr);
116 }
117
118 raw_ostream &raw_ostream::operator<<(long N) {
119   if (N <  0) {
120     *this << '-';
121     N = -N;
122   }
123   
124   return this->operator<<(static_cast<unsigned long>(N));
125 }
126
127 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
128   // Handle simple case when value fits in long already.
129   if (N == static_cast<unsigned long>(N))
130     return this->operator<<(static_cast<unsigned long>(N));
131
132   // Otherwise divide into at two or three 10**9 chunks and write out using
133   // long div/mod, this is substantially faster on a 32-bit system.
134   unsigned long Top = 0, Mid = 0, Bot = N % 1000000000;
135   N /= 1000000000;
136   if (N > 1000000000) {
137     Mid = N % 1000000000;
138     Top = N / 1000000000;
139   } else
140     Mid = N;
141
142   if (Top)
143     this->operator<<(static_cast<unsigned long>(Top));
144   this->operator<<(static_cast<unsigned long>(Mid));
145   return this->operator<<(static_cast<unsigned long>(Bot));
146 }
147
148 raw_ostream &raw_ostream::operator<<(long long N) {
149   if (N <  0) {
150     *this << '-';
151     N = -N;
152   }
153   
154   return this->operator<<(static_cast<unsigned long long>(N));
155 }
156
157 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
158   // Zero is a special case.
159   if (N == 0)
160     return *this << '0';
161
162   char NumberBuffer[20];
163   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
164   char *CurPtr = EndPtr;
165
166   while (N) {
167     uintptr_t x = N % 16;
168     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
169     N /= 16;
170   }
171
172   return write(CurPtr, EndPtr-CurPtr);
173 }
174
175 raw_ostream &raw_ostream::operator<<(const void *P) {
176   *this << '0' << 'x';
177
178   return write_hex((uintptr_t) P);
179 }
180
181 void raw_ostream::flush_nonempty() {
182   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
183   write_impl(OutBufStart, OutBufCur - OutBufStart);
184   OutBufCur = OutBufStart;    
185 }
186
187 raw_ostream &raw_ostream::write(unsigned char C) {
188   // Group exceptional cases into a single branch.
189   if (OutBufCur >= OutBufEnd) {
190     if (Unbuffered) {
191       write_impl(reinterpret_cast<char*>(&C), 1);
192       return *this;
193     }
194     
195     if (OutBufStart)
196       flush_nonempty();
197     else {
198       SetBuffered();
199       // It's possible for the underlying stream to decline
200       // buffering, so check this condition again.
201       if (Unbuffered) {
202         write_impl(reinterpret_cast<char*>(&C), 1);
203         return *this;
204       }
205     }
206   }
207
208   *OutBufCur++ = C;
209   return *this;
210 }
211
212 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
213   // Group exceptional cases into a single branch.
214   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
215     if (BUILTIN_EXPECT(!OutBufStart, false)) {
216       if (Unbuffered) {
217         write_impl(Ptr, Size);
218         return *this;
219       }
220       // Set up a buffer and start over.
221       SetBuffered();
222       return write(Ptr, Size);
223     }
224     // Write out the data in buffer-sized blocks until the remainder
225     // fits within the buffer.
226     do {
227       size_t NumBytes = OutBufEnd - OutBufCur;
228       copy_to_buffer(Ptr, NumBytes);
229       flush_nonempty();
230       Ptr += NumBytes;
231       Size -= NumBytes;
232     } while (OutBufCur+Size > OutBufEnd);
233   }
234
235   copy_to_buffer(Ptr, Size);
236
237   return *this;
238 }
239
240 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
241   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
242
243   // Handle short strings specially, memcpy isn't very good at very short
244   // strings.
245   switch (Size) {
246   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
247   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
248   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
249   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
250   case 0: break;
251   default:
252     memcpy(OutBufCur, Ptr, Size);
253     break;
254   }
255
256   OutBufCur += Size;
257 }
258
259 // Formatted output.
260 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
261   // If we have more than a few bytes left in our output buffer, try
262   // formatting directly onto its end.
263   //
264   // FIXME: This test is a bit silly, since if we don't have enough
265   // space in the buffer we will have to flush the formatted output
266   // anyway. We should just flush upfront in such cases, and use the
267   // whole buffer as our scratch pad. Note, however, that this case is
268   // also necessary for correctness on unbuffered streams.
269   size_t NextBufferSize = 127;
270   if (OutBufEnd-OutBufCur > 3) {
271     size_t BufferBytesLeft = OutBufEnd-OutBufCur;
272     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
273     
274     // Common case is that we have plenty of space.
275     if (BytesUsed < BufferBytesLeft) {
276       OutBufCur += BytesUsed;
277       return *this;
278     }
279     
280     // Otherwise, we overflowed and the return value tells us the size to try
281     // again with.
282     NextBufferSize = BytesUsed;
283   }
284   
285   // If we got here, we didn't have enough space in the output buffer for the
286   // string.  Try printing into a SmallVector that is resized to have enough
287   // space.  Iterate until we win.
288   SmallVector<char, 128> V;
289   
290   while (1) {
291     V.resize(NextBufferSize);
292     
293     // Try formatting into the SmallVector.
294     size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
295     
296     // If BytesUsed fit into the vector, we win.
297     if (BytesUsed <= NextBufferSize)
298       return write(&V[0], BytesUsed);
299     
300     // Otherwise, try again with a new size.
301     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
302     NextBufferSize = BytesUsed;
303   }
304 }
305
306 //===----------------------------------------------------------------------===//
307 //  Formatted Output
308 //===----------------------------------------------------------------------===//
309
310 // Out of line virtual method.
311 void format_object_base::home() {
312 }
313
314 //===----------------------------------------------------------------------===//
315 //  raw_fd_ostream
316 //===----------------------------------------------------------------------===//
317
318 /// raw_fd_ostream - Open the specified file for writing. If an error
319 /// occurs, information about the error is put into ErrorInfo, and the
320 /// stream should be immediately destroyed; the string will be empty
321 /// if no error occurred.
322 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
323                                std::string &ErrorInfo) : pos(0) {
324   ErrorInfo.clear();
325
326   // Handle "-" as stdout.
327   if (Filename[0] == '-' && Filename[1] == 0) {
328     FD = STDOUT_FILENO;
329     // If user requested binary then put stdout into binary mode if
330     // possible.
331     if (Binary)
332       sys::Program::ChangeStdoutToBinary();
333     ShouldClose = false;
334     return;
335   }
336   
337   int Flags = O_WRONLY|O_CREAT|O_TRUNC;
338 #ifdef O_BINARY
339   if (Binary)
340     Flags |= O_BINARY;
341 #endif
342   if (!Force)
343     Flags |= O_EXCL;
344   FD = open(Filename, Flags, 0664);
345   if (FD < 0) {
346     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
347     ShouldClose = false;
348   } else {
349     ShouldClose = true;
350   }
351 }
352
353 raw_fd_ostream::~raw_fd_ostream() {
354   if (FD >= 0) {
355     flush();
356     if (ShouldClose)
357       if (::close(FD) != 0)
358         error_detected();
359   }
360 }
361
362 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
363   assert (FD >= 0 && "File already closed.");
364   pos += Size;
365   if (::write(FD, Ptr, Size) != (ssize_t) Size)
366     error_detected();
367 }
368
369 void raw_fd_ostream::close() {
370   assert (ShouldClose);
371   ShouldClose = false;
372   flush();
373   if (::close(FD) != 0)
374     error_detected();
375   FD = -1;
376 }
377
378 uint64_t raw_fd_ostream::seek(uint64_t off) {
379   flush();
380   pos = ::lseek(FD, off, SEEK_SET);
381   if (pos != off)
382     error_detected();
383   return pos;  
384 }
385
386 size_t raw_fd_ostream::preferred_buffer_size() {
387 #if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
388   assert(FD >= 0 && "File not yet open!");
389   struct stat statbuf;
390   if (fstat(FD, &statbuf) == 0) {
391     // If this is a terminal, don't use buffering. Line buffering
392     // would be a more traditional thing to do, but it's not worth
393     // the complexity.
394     if (S_ISCHR(statbuf.st_mode) && isatty(FD))
395       return 0;
396     // Return the preferred block size.
397     return statbuf.st_blksize;
398   }
399   error_detected();
400 #endif
401   return raw_ostream::preferred_buffer_size();
402 }
403
404 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
405                                          bool bg) {
406   if (sys::Process::ColorNeedsFlush())
407     flush();
408   const char *colorcode =
409     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
410     : sys::Process::OutputColor(colors, bold, bg);
411   if (colorcode) {
412     size_t len = strlen(colorcode);
413     write(colorcode, len);
414     // don't account colors towards output characters
415     pos -= len;
416   }
417   return *this;
418 }
419
420 raw_ostream &raw_fd_ostream::resetColor() {
421   if (sys::Process::ColorNeedsFlush())
422     flush();
423   const char *colorcode = sys::Process::ResetColor();
424   if (colorcode) {
425     size_t len = strlen(colorcode);
426     write(colorcode, len);
427     // don't account colors towards output characters
428     pos -= len;
429   }
430   return *this;
431 }
432
433 //===----------------------------------------------------------------------===//
434 //  raw_stdout/err_ostream
435 //===----------------------------------------------------------------------===//
436
437 // Set buffer settings to model stdout and stderr behavior.
438 // Set standard error to be unbuffered by default.
439 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
440 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
441                                                         true) {}
442
443 // An out of line virtual method to provide a home for the class vtable.
444 void raw_stdout_ostream::handle() {}
445 void raw_stderr_ostream::handle() {}
446
447 /// outs() - This returns a reference to a raw_ostream for standard output.
448 /// Use it like: outs() << "foo" << "bar";
449 raw_ostream &llvm::outs() {
450   static raw_stdout_ostream S;
451   return S;
452 }
453
454 /// errs() - This returns a reference to a raw_ostream for standard error.
455 /// Use it like: errs() << "foo" << "bar";
456 raw_ostream &llvm::errs() {
457   static raw_stderr_ostream S;
458   return S;
459 }
460
461 /// nulls() - This returns a reference to a raw_ostream which discards output.
462 raw_ostream &llvm::nulls() {
463   static raw_null_ostream S;
464   return S;
465 }
466
467 //===----------------------------------------------------------------------===//
468 //  raw_os_ostream
469 //===----------------------------------------------------------------------===//
470
471 raw_os_ostream::~raw_os_ostream() {
472   flush();
473 }
474
475 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
476   OS.write(Ptr, Size);
477 }
478
479 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
480
481 uint64_t raw_os_ostream::tell() { 
482   return (uint64_t)OS.tellp() + GetNumBytesInBuffer(); 
483 }
484
485 //===----------------------------------------------------------------------===//
486 //  raw_string_ostream
487 //===----------------------------------------------------------------------===//
488
489 raw_string_ostream::~raw_string_ostream() {
490   flush();
491 }
492
493 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
494   OS.append(Ptr, Size);
495 }
496
497 //===----------------------------------------------------------------------===//
498 //  raw_svector_ostream
499 //===----------------------------------------------------------------------===//
500
501 raw_svector_ostream::~raw_svector_ostream() {
502   flush();
503 }
504
505 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
506   OS.append(Ptr, Ptr + Size);
507 }
508
509 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
510
511 uint64_t raw_svector_ostream::tell() { 
512   return OS.size() + GetNumBytesInBuffer(); 
513 }
514
515 //===----------------------------------------------------------------------===//
516 //  raw_null_ostream
517 //===----------------------------------------------------------------------===//
518
519 raw_null_ostream::~raw_null_ostream() {
520 #ifndef NDEBUG
521   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
522   // with raw_null_ostream, but it's better to have raw_null_ostream follow
523   // the rules than to change the rules just for raw_null_ostream.
524   flush();
525 #endif
526 }
527
528 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
529 }
530
531 uint64_t raw_null_ostream::current_pos() {
532   return 0;
533 }