When standard output is a terminal, set outs() to be unbuffered, to
[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   SetBufferSize(preferred_buffer_size());
76 }
77
78 void raw_ostream::SetBufferSize(size_t Size) {
79   assert(Size >= 64 &&
80          "Buffer size must be somewhat large for invariants to hold");
81   flush();
82
83   delete [] OutBufStart;
84   OutBufStart = new char[Size];
85   OutBufEnd = OutBufStart+Size;
86   OutBufCur = OutBufStart;
87   Unbuffered = false;
88 }
89
90 void raw_ostream::SetUnbuffered() {
91   flush();
92
93   delete [] OutBufStart;
94   OutBufStart = OutBufEnd = OutBufCur = 0;
95   Unbuffered = true;
96 }
97
98 raw_ostream &raw_ostream::operator<<(unsigned long N) {
99   // Zero is a special case.
100   if (N == 0)
101     return *this << '0';
102   
103   char NumberBuffer[20];
104   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
105   char *CurPtr = EndPtr;
106   
107   while (N) {
108     *--CurPtr = '0' + char(N % 10);
109     N /= 10;
110   }
111   return write(CurPtr, EndPtr-CurPtr);
112 }
113
114 raw_ostream &raw_ostream::operator<<(long N) {
115   if (N <  0) {
116     *this << '-';
117     N = -N;
118   }
119   
120   return this->operator<<(static_cast<unsigned long>(N));
121 }
122
123 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
124   // Output using 32-bit div/mod when possible.
125   if (N == static_cast<unsigned long>(N))
126     return this->operator<<(static_cast<unsigned long>(N));
127
128   char NumberBuffer[20];
129   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
130   char *CurPtr = EndPtr;
131   
132   while (N) {
133     *--CurPtr = '0' + char(N % 10);
134     N /= 10;
135   }
136   return write(CurPtr, EndPtr-CurPtr);
137 }
138
139 raw_ostream &raw_ostream::operator<<(long long N) {
140   if (N <  0) {
141     *this << '-';
142     N = -N;
143   }
144   
145   return this->operator<<(static_cast<unsigned long long>(N));
146 }
147
148 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
149   // Zero is a special case.
150   if (N == 0)
151     return *this << '0';
152
153   char NumberBuffer[20];
154   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
155   char *CurPtr = EndPtr;
156
157   while (N) {
158     uintptr_t x = N % 16;
159     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
160     N /= 16;
161   }
162
163   return write(CurPtr, EndPtr-CurPtr);
164 }
165
166 raw_ostream &raw_ostream::operator<<(const void *P) {
167   *this << '0' << 'x';
168
169   return write_hex((uintptr_t) P);
170 }
171
172 void raw_ostream::flush_nonempty() {
173   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
174   write_impl(OutBufStart, OutBufCur - OutBufStart);
175   OutBufCur = OutBufStart;    
176 }
177
178 raw_ostream &raw_ostream::write(unsigned char C) {
179   // Group exceptional cases into a single branch.
180   if (OutBufCur >= OutBufEnd) {
181     if (Unbuffered) {
182       write_impl(reinterpret_cast<char*>(&C), 1);
183       return *this;
184     }
185     
186     if (!OutBufStart)
187       SetBuffered();
188     else
189       flush_nonempty();
190   }
191
192   *OutBufCur++ = C;
193   return *this;
194 }
195
196 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
197   // Group exceptional cases into a single branch.
198   if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
199     if (BUILTIN_EXPECT(!OutBufStart, false)) {
200       if (Unbuffered) {
201         write_impl(Ptr, Size);
202         return *this;
203       }
204       // Set up a buffer and start over.
205       SetBuffered();
206       return write(Ptr, Size);
207     }
208     // Write out the data in buffer-sized blocks until the remainder
209     // fits within the buffer.
210     do {
211       size_t NumBytes = OutBufEnd - OutBufCur;
212       copy_to_buffer(Ptr, NumBytes);
213       flush_nonempty();
214       Ptr += NumBytes;
215       Size -= NumBytes;
216     } while (OutBufCur+Size > OutBufEnd);
217   }
218
219   copy_to_buffer(Ptr, Size);
220
221   return *this;
222 }
223
224 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
225   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
226
227   // Handle short strings specially, memcpy isn't very good at very short
228   // strings.
229   switch (Size) {
230   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
231   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
232   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
233   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
234   case 0: break;
235   default:
236     memcpy(OutBufCur, Ptr, Size);
237     break;
238   }
239
240   OutBufCur += Size;
241 }
242
243 // Formatted output.
244 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
245   // If we have more than a few bytes left in our output buffer, try
246   // formatting directly onto its end.
247   //
248   // FIXME: This test is a bit silly, since if we don't have enough
249   // space in the buffer we will have to flush the formatted output
250   // anyway. We should just flush upfront in such cases, and use the
251   // whole buffer as our scratch pad. Note, however, that this case is
252   // also necessary for correctness on unbuffered streams.
253   size_t NextBufferSize = 127;
254   if (OutBufEnd-OutBufCur > 3) {
255     size_t BufferBytesLeft = OutBufEnd-OutBufCur;
256     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
257     
258     // Common case is that we have plenty of space.
259     if (BytesUsed < BufferBytesLeft) {
260       OutBufCur += BytesUsed;
261       return *this;
262     }
263     
264     // Otherwise, we overflowed and the return value tells us the size to try
265     // again with.
266     NextBufferSize = BytesUsed;
267   }
268   
269   // If we got here, we didn't have enough space in the output buffer for the
270   // string.  Try printing into a SmallVector that is resized to have enough
271   // space.  Iterate until we win.
272   SmallVector<char, 128> V;
273   
274   while (1) {
275     V.resize(NextBufferSize);
276     
277     // Try formatting into the SmallVector.
278     size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
279     
280     // If BytesUsed fit into the vector, we win.
281     if (BytesUsed <= NextBufferSize)
282       return write(&V[0], BytesUsed);
283     
284     // Otherwise, try again with a new size.
285     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
286     NextBufferSize = BytesUsed;
287   }
288 }
289
290 //===----------------------------------------------------------------------===//
291 //  Formatted Output
292 //===----------------------------------------------------------------------===//
293
294 // Out of line virtual method.
295 void format_object_base::home() {
296 }
297
298 //===----------------------------------------------------------------------===//
299 //  raw_fd_ostream
300 //===----------------------------------------------------------------------===//
301
302 /// raw_fd_ostream - Open the specified file for writing. If an error
303 /// occurs, information about the error is put into ErrorInfo, and the
304 /// stream should be immediately destroyed; the string will be empty
305 /// if no error occurred.
306 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
307                                std::string &ErrorInfo) : pos(0) {
308   ErrorInfo.clear();
309
310   // Handle "-" as stdout.
311   if (Filename[0] == '-' && Filename[1] == 0) {
312     FD = STDOUT_FILENO;
313     // If user requested binary then put stdout into binary mode if
314     // possible.
315     if (Binary)
316       sys::Program::ChangeStdoutToBinary();
317     ShouldClose = false;
318     // Mimic stdout by defaulting to unbuffered if the output device
319     // is a terminal.
320     if (sys::Process::StandardOutIsDisplayed())
321       SetUnbuffered();
322     return;
323   }
324   
325   int Flags = O_WRONLY|O_CREAT|O_TRUNC;
326 #ifdef O_BINARY
327   if (Binary)
328     Flags |= O_BINARY;
329 #endif
330   if (!Force)
331     Flags |= O_EXCL;
332   FD = open(Filename, Flags, 0664);
333   if (FD < 0) {
334     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
335     ShouldClose = false;
336   } else {
337     ShouldClose = true;
338   }
339 }
340
341 raw_fd_ostream::~raw_fd_ostream() {
342   if (FD >= 0) {
343     flush();
344     if (ShouldClose)
345       if (::close(FD) != 0)
346         error_detected();
347   }
348 }
349
350 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
351   assert (FD >= 0 && "File already closed.");
352   pos += Size;
353   if (::write(FD, Ptr, Size) != (ssize_t) Size)
354     error_detected();
355 }
356
357 void raw_fd_ostream::close() {
358   assert (ShouldClose);
359   ShouldClose = false;
360   flush();
361   if (::close(FD) != 0)
362     error_detected();
363   FD = -1;
364 }
365
366 uint64_t raw_fd_ostream::seek(uint64_t off) {
367   flush();
368   pos = ::lseek(FD, off, SEEK_SET);
369   if (pos != off)
370     error_detected();
371   return pos;  
372 }
373
374 size_t raw_fd_ostream::preferred_buffer_size() {
375 #if !defined(_MSC_VER) // Windows reportedly doesn't have st_blksize.
376   assert(FD >= 0 && "File not yet open!");
377   struct stat statbuf;
378   if (fstat(FD, &statbuf) == 0)
379     return statbuf.st_blksize;
380   error_detected();
381 #endif
382   return raw_ostream::preferred_buffer_size();
383 }
384
385 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
386                                          bool bg) {
387   if (sys::Process::ColorNeedsFlush())
388     flush();
389   const char *colorcode =
390     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
391     : sys::Process::OutputColor(colors, bold, bg);
392   if (colorcode) {
393     size_t len = strlen(colorcode);
394     write(colorcode, len);
395     // don't account colors towards output characters
396     pos -= len;
397   }
398   return *this;
399 }
400
401 raw_ostream &raw_fd_ostream::resetColor() {
402   if (sys::Process::ColorNeedsFlush())
403     flush();
404   const char *colorcode = sys::Process::ResetColor();
405   if (colorcode) {
406     size_t len = strlen(colorcode);
407     write(colorcode, len);
408     // don't account colors towards output characters
409     pos -= len;
410   }
411   return *this;
412 }
413
414 //===----------------------------------------------------------------------===//
415 //  raw_stdout/err_ostream
416 //===----------------------------------------------------------------------===//
417
418 // Set buffer settings to model stdout and stderr behavior.
419 // raw_ostream doesn't support line buffering, so set standard output to be
420 // unbuffered when the output device is a terminal. Set standard error to
421 // be unbuffered.
422 raw_stdout_ostream::raw_stdout_ostream()
423   : raw_fd_ostream(STDOUT_FILENO, false,
424                    sys::Process::StandardOutIsDisplayed()) {}
425 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false, 
426                                                         true) {}
427
428 // An out of line virtual method to provide a home for the class vtable.
429 void raw_stdout_ostream::handle() {}
430 void raw_stderr_ostream::handle() {}
431
432 /// outs() - This returns a reference to a raw_ostream for standard output.
433 /// Use it like: outs() << "foo" << "bar";
434 raw_ostream &llvm::outs() {
435   static raw_stdout_ostream S;
436   return S;
437 }
438
439 /// errs() - This returns a reference to a raw_ostream for standard error.
440 /// Use it like: errs() << "foo" << "bar";
441 raw_ostream &llvm::errs() {
442   static raw_stderr_ostream S;
443   return S;
444 }
445
446 /// nulls() - This returns a reference to a raw_ostream which discards output.
447 raw_ostream &llvm::nulls() {
448   static raw_null_ostream S;
449   return S;
450 }
451
452 //===----------------------------------------------------------------------===//
453 //  raw_os_ostream
454 //===----------------------------------------------------------------------===//
455
456 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
457   OS.write(Ptr, Size);
458 }
459
460 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
461
462 uint64_t raw_os_ostream::tell() { 
463   return (uint64_t)OS.tellp() + GetNumBytesInBuffer(); 
464 }
465
466 //===----------------------------------------------------------------------===//
467 //  raw_string_ostream
468 //===----------------------------------------------------------------------===//
469
470 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
471   OS.append(Ptr, Size);
472 }
473
474 //===----------------------------------------------------------------------===//
475 //  raw_svector_ostream
476 //===----------------------------------------------------------------------===//
477
478 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
479   OS.append(Ptr, Ptr + Size);
480 }
481
482 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
483
484 uint64_t raw_svector_ostream::tell() { 
485   return OS.size() + GetNumBytesInBuffer(); 
486 }
487
488 //===----------------------------------------------------------------------===//
489 //  raw_null_ostream
490 //===----------------------------------------------------------------------===//
491
492 raw_null_ostream::~raw_null_ostream() {
493 #ifndef NDEBUG
494   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
495   // with raw_null_ostream, but it's better to have raw_null_ostream follow
496   // the rules than to change the rules just for raw_null_ostream.
497   flush();
498 #endif
499 }
500
501 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
502 }
503
504 uint64_t raw_null_ostream::current_pos() {
505   return 0;
506 }