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