Set raw_os_ostream, raw_string_ostream, and raw_svector_ostream to be
[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   // Handle short strings specially, memcpy isn't very good at very short
226   // strings.
227   switch (Size) {
228   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
229   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
230   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
231   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
232   case 0: break;
233   default:
234     memcpy(OutBufCur, Ptr, Size);
235     break;
236   }
237
238   OutBufCur += Size;
239 }
240
241 // Formatted output.
242 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
243   // If we have more than a few bytes left in our output buffer, try
244   // formatting directly onto its end.
245   //
246   // FIXME: This test is a bit silly, since if we don't have enough
247   // space in the buffer we will have to flush the formatted output
248   // anyway. We should just flush upfront in such cases, and use the
249   // whole buffer as our scratch pad. Note, however, that this case is
250   // also necessary for correctness on unbuffered streams.
251   size_t NextBufferSize = 127;
252   if (OutBufEnd-OutBufCur > 3) {
253     size_t BufferBytesLeft = OutBufEnd-OutBufCur;
254     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
255     
256     // Common case is that we have plenty of space.
257     if (BytesUsed < BufferBytesLeft) {
258       OutBufCur += BytesUsed;
259       return *this;
260     }
261     
262     // Otherwise, we overflowed and the return value tells us the size to try
263     // again with.
264     NextBufferSize = BytesUsed;
265   }
266   
267   // If we got here, we didn't have enough space in the output buffer for the
268   // string.  Try printing into a SmallVector that is resized to have enough
269   // space.  Iterate until we win.
270   SmallVector<char, 128> V;
271   
272   while (1) {
273     V.resize(NextBufferSize);
274     
275     // Try formatting into the SmallVector.
276     size_t BytesUsed = Fmt.print(&V[0], NextBufferSize);
277     
278     // If BytesUsed fit into the vector, we win.
279     if (BytesUsed <= NextBufferSize)
280       return write(&V[0], BytesUsed);
281     
282     // Otherwise, try again with a new size.
283     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
284     NextBufferSize = BytesUsed;
285   }
286 }
287
288 //===----------------------------------------------------------------------===//
289 //  Formatted Output
290 //===----------------------------------------------------------------------===//
291
292 // Out of line virtual method.
293 void format_object_base::home() {
294 }
295
296 //===----------------------------------------------------------------------===//
297 //  raw_fd_ostream
298 //===----------------------------------------------------------------------===//
299
300 /// raw_fd_ostream - Open the specified file for writing. If an error
301 /// occurs, information about the error is put into ErrorInfo, and the
302 /// stream should be immediately destroyed; the string will be empty
303 /// if no error occurred.
304 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
305                                std::string &ErrorInfo) : pos(0) {
306   ErrorInfo.clear();
307
308   // Handle "-" as stdout.
309   if (Filename[0] == '-' && Filename[1] == 0) {
310     FD = STDOUT_FILENO;
311     // If user requested binary then put stdout into binary mode if
312     // possible.
313     if (Binary)
314       sys::Program::ChangeStdoutToBinary();
315     ShouldClose = false;
316     return;
317   }
318   
319   int Flags = O_WRONLY|O_CREAT|O_TRUNC;
320 #ifdef O_BINARY
321   if (Binary)
322     Flags |= O_BINARY;
323 #endif
324   if (!Force)
325     Flags |= O_EXCL;
326   FD = open(Filename, Flags, 0664);
327   if (FD < 0) {
328     ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
329     ShouldClose = false;
330   } else {
331     ShouldClose = true;
332   }
333 }
334
335 raw_fd_ostream::~raw_fd_ostream() {
336   if (FD >= 0) {
337     flush();
338     if (ShouldClose)
339       if (::close(FD) != 0)
340         error_detected();
341   }
342 }
343
344 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
345   assert (FD >= 0 && "File already closed.");
346   pos += Size;
347   if (::write(FD, Ptr, Size) != (ssize_t) Size)
348     error_detected();
349 }
350
351 void raw_fd_ostream::close() {
352   assert (ShouldClose);
353   ShouldClose = false;
354   flush();
355   if (::close(FD) != 0)
356     error_detected();
357   FD = -1;
358 }
359
360 uint64_t raw_fd_ostream::seek(uint64_t off) {
361   flush();
362   pos = ::lseek(FD, off, SEEK_SET);
363   if (pos != off)
364     error_detected();
365   return pos;  
366 }
367
368 size_t raw_fd_ostream::preferred_buffer_size() {
369 #if !defined(_MSC_VER) // Windows reportedly doesn't have st_blksize.
370   assert(FD >= 0 && "File not yet open!");
371   struct stat statbuf;
372   if (fstat(FD, &statbuf) == 0)
373     return statbuf.st_blksize;
374   error_detected();
375 #endif
376   return raw_ostream::preferred_buffer_size();
377 }
378
379 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
380                                          bool bg) {
381   if (sys::Process::ColorNeedsFlush())
382     flush();
383   const char *colorcode =
384     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
385     : sys::Process::OutputColor(colors, bold, bg);
386   if (colorcode) {
387     size_t len = strlen(colorcode);
388     write(colorcode, len);
389     // don't account colors towards output characters
390     pos -= len;
391   }
392   return *this;
393 }
394
395 raw_ostream &raw_fd_ostream::resetColor() {
396   if (sys::Process::ColorNeedsFlush())
397     flush();
398   const char *colorcode = sys::Process::ResetColor();
399   if (colorcode) {
400     size_t len = strlen(colorcode);
401     write(colorcode, len);
402     // don't account colors towards output characters
403     pos -= len;
404   }
405   return *this;
406 }
407
408 //===----------------------------------------------------------------------===//
409 //  raw_stdout/err_ostream
410 //===----------------------------------------------------------------------===//
411
412 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
413 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false, 
414                                                         true) {}
415
416 // An out of line virtual method to provide a home for the class vtable.
417 void raw_stdout_ostream::handle() {}
418 void raw_stderr_ostream::handle() {}
419
420 /// outs() - This returns a reference to a raw_ostream for standard output.
421 /// Use it like: outs() << "foo" << "bar";
422 raw_ostream &llvm::outs() {
423   static raw_stdout_ostream S;
424   return S;
425 }
426
427 /// errs() - This returns a reference to a raw_ostream for standard error.
428 /// Use it like: errs() << "foo" << "bar";
429 raw_ostream &llvm::errs() {
430   static raw_stderr_ostream S;
431   return S;
432 }
433
434 /// nulls() - This returns a reference to a raw_ostream which discards output.
435 raw_ostream &llvm::nulls() {
436   static raw_null_ostream S;
437   return S;
438 }
439
440 //===----------------------------------------------------------------------===//
441 //  raw_os_ostream
442 //===----------------------------------------------------------------------===//
443
444 void raw_os_ostream::write_impl(const char *Ptr, size_t Size) {
445   OS.write(Ptr, Size);
446 }
447
448 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
449
450 uint64_t raw_os_ostream::tell() { 
451   return (uint64_t)OS.tellp() + GetNumBytesInBuffer(); 
452 }
453
454 //===----------------------------------------------------------------------===//
455 //  raw_string_ostream
456 //===----------------------------------------------------------------------===//
457
458 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
459   OS.append(Ptr, Size);
460 }
461
462 //===----------------------------------------------------------------------===//
463 //  raw_svector_ostream
464 //===----------------------------------------------------------------------===//
465
466 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
467   OS.append(Ptr, Ptr + Size);
468 }
469
470 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
471
472 uint64_t raw_svector_ostream::tell() { 
473   return OS.size() + GetNumBytesInBuffer(); 
474 }
475
476 //===----------------------------------------------------------------------===//
477 //  raw_null_ostream
478 //===----------------------------------------------------------------------===//
479
480 raw_null_ostream::~raw_null_ostream() {
481 #ifndef NDEBUG
482   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
483   // with raw_null_ostream, but it's better to have raw_null_ostream follow
484   // the rules than to change the rules just for raw_null_ostream.
485   flush();
486 #endif
487 }
488
489 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
490 }
491
492 uint64_t raw_null_ostream::current_pos() {
493   return 0;
494 }