blob: 1abc8ed8683d50cc2a0e87ddc8d10a668d6d6cf4 [file] [log] [blame]
Chris Lattner84b94f72008-08-17 01:35:29 +00001//===--- 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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
Chris Lattner22b52c92008-08-23 19:23:10 +000016#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/StringExtras.h"
Chris Lattnerd564f292008-08-22 15:45:00 +000018#include "llvm/Config/config.h"
Daniel Dunbar437b8a52009-03-17 21:15:18 +000019#include "llvm/Support/Compiler.h"
Daniel Dunbardcb50b92009-07-15 08:11:46 +000020#include "llvm/Support/ErrorHandling.h"
Rafael Espindola6d354812013-07-16 19:44:17 +000021#include "llvm/Support/FileSystem.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Support/Format.h"
Zachary Turner11db2642016-11-11 23:57:40 +000023#include "llvm/Support/FormatVariadic.h"
Nick Kledzike6480372014-09-25 20:30:58 +000024#include "llvm/Support/MathExtras.h"
Zachary Turner733be512016-10-11 19:24:45 +000025#include "llvm/Support/NativeFormatting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Support/Process.h"
27#include "llvm/Support/Program.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000028#include <algorithm>
Benjamin Krameref14f802010-01-29 15:19:06 +000029#include <cctype>
Benjamin Kramerce84a252010-05-05 15:17:47 +000030#include <cerrno>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include <cstdio>
32#include <iterator>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000033#include <sys/stat.h>
Zachary Turner733be512016-10-11 19:24:45 +000034#include <system_error>
Chris Lattner84b94f72008-08-17 01:35:29 +000035
NAKAMURA Takumi212c80a2013-07-17 02:21:10 +000036// <fcntl.h> may provide O_BINARY.
37#if defined(HAVE_FCNTL_H)
38# include <fcntl.h>
39#endif
40
Chris Lattnerd564f292008-08-22 15:45:00 +000041#if defined(HAVE_UNISTD_H)
42# include <unistd.h>
43#endif
Daniel Dunbar4fed8872011-02-03 03:32:32 +000044#if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
45# include <sys/uio.h>
46#endif
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000047
NAKAMURA Takumife84f392010-10-19 01:21:55 +000048#if defined(__CYGWIN__)
49#include <io.h>
50#endif
51
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000052#if defined(_MSC_VER)
Chris Lattner84b94f72008-08-17 01:35:29 +000053#include <io.h>
Owen Anderson93719642008-08-21 00:14:44 +000054#ifndef STDIN_FILENO
55# define STDIN_FILENO 0
56#endif
57#ifndef STDOUT_FILENO
58# define STDOUT_FILENO 1
59#endif
60#ifndef STDERR_FILENO
61# define STDERR_FILENO 2
62#endif
Chris Lattner84b94f72008-08-17 01:35:29 +000063#endif
64
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +000065#ifdef LLVM_ON_WIN32
66#include "Windows/WindowsSupport.h"
67#endif
68
Chris Lattnerd564f292008-08-22 15:45:00 +000069using namespace llvm;
70
Dan Gohman58fcef92009-07-15 23:25:33 +000071raw_ostream::~raw_ostream() {
Dan Gohman1b763292009-07-27 20:49:44 +000072 // raw_ostream's subclasses should take care to flush the buffer
73 // in their destructors.
74 assert(OutBufCur == OutBufStart &&
75 "raw_ostream destructor called with non-empty buffer!");
76
Daniel Dunbar317a6cd2009-08-18 23:42:36 +000077 if (BufferMode == InternalBuffer)
78 delete [] OutBufStart;
Dan Gohman58fcef92009-07-15 23:25:33 +000079}
Chris Lattnerd564f292008-08-22 15:45:00 +000080
Chris Lattner84b94f72008-08-17 01:35:29 +000081// An out of line virtual method to provide a home for the class vtable.
82void raw_ostream::handle() {}
83
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +000084size_t raw_ostream::preferred_buffer_size() const {
Dan Gohman84487b92009-08-13 17:27:29 +000085 // BUFSIZ is intended to be a reasonable default.
86 return BUFSIZ;
87}
88
89void raw_ostream::SetBuffered() {
90 // Ask the subclass to determine an appropriate buffer size.
Dan Gohman17710222009-08-15 02:05:19 +000091 if (size_t Size = preferred_buffer_size())
92 SetBufferSize(Size);
93 else
94 // It may return 0, meaning this stream should be unbuffered.
95 SetUnbuffered();
Dan Gohman84487b92009-08-13 17:27:29 +000096}
97
Dan Gohmanb452d4e2010-03-24 19:38:02 +000098void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
Nick Lewycky7bfd86d2011-08-28 03:30:02 +000099 BufferKind Mode) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000100 assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
101 (Mode != Unbuffered && BufferStart && Size != 0)) &&
Daniel Dunbar316b4a02009-09-15 20:31:46 +0000102 "stream must be unbuffered or have at least one byte");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000103 // Make sure the current buffer is free of content (we can't flush here; the
104 // child buffer management logic will be in write_impl).
105 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
Dan Gohman54401d42009-08-13 15:58:55 +0000106
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000107 if (BufferMode == InternalBuffer)
108 delete [] OutBufStart;
109 OutBufStart = BufferStart;
Dan Gohman54401d42009-08-13 15:58:55 +0000110 OutBufEnd = OutBufStart+Size;
111 OutBufCur = OutBufStart;
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000112 BufferMode = Mode;
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000113
114 assert(OutBufStart <= OutBufEnd && "Invalid size!");
Dan Gohman54401d42009-08-13 15:58:55 +0000115}
116
Owen Andersond2850532008-08-21 20:58:52 +0000117raw_ostream &raw_ostream::operator<<(unsigned long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000118 write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000119 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000120}
121
122raw_ostream &raw_ostream::operator<<(long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000123 write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000124 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000125}
126
127raw_ostream &raw_ostream::operator<<(unsigned long long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000128 write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000129 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000130}
131
132raw_ostream &raw_ostream::operator<<(long long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000133 write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000134 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000135}
136
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000137raw_ostream &raw_ostream::write_hex(unsigned long long N) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000138 llvm::write_hex(*this, N, HexPrintStyle::Lower);
Zachary Turner733be512016-10-11 19:24:45 +0000139 return *this;
Chris Lattner0c19df42008-08-23 22:23:09 +0000140}
141
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000142raw_ostream &raw_ostream::write_escaped(StringRef Str,
143 bool UseHexEscapes) {
Craig Topper775fb732016-02-04 06:51:41 +0000144 for (unsigned char c : Str) {
Daniel Dunbar4108c432009-10-17 20:43:08 +0000145 switch (c) {
146 case '\\':
147 *this << '\\' << '\\';
148 break;
149 case '\t':
150 *this << '\\' << 't';
151 break;
152 case '\n':
153 *this << '\\' << 'n';
154 break;
155 case '"':
156 *this << '\\' << '"';
157 break;
158 default:
159 if (std::isprint(c)) {
160 *this << c;
161 break;
162 }
163
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000164 // Write out the escaped representation.
165 if (UseHexEscapes) {
166 *this << '\\' << 'x';
167 *this << hexdigit((c >> 4 & 0xF));
168 *this << hexdigit((c >> 0) & 0xF);
169 } else {
170 // Always use a full 3-character octal escape.
171 *this << '\\';
172 *this << char('0' + ((c >> 6) & 7));
173 *this << char('0' + ((c >> 3) & 7));
174 *this << char('0' + ((c >> 0) & 7));
175 }
Daniel Dunbar4108c432009-10-17 20:43:08 +0000176 }
177 }
178
179 return *this;
180}
181
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000182raw_ostream &raw_ostream::operator<<(const void *P) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000183 llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
Zachary Turner733be512016-10-11 19:24:45 +0000184 return *this;
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000185}
186
Chris Lattner06fa1762009-08-24 03:52:50 +0000187raw_ostream &raw_ostream::operator<<(double N) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000188 llvm::write_double(*this, N, FloatStyle::Exponent);
Zachary Turner733be512016-10-11 19:24:45 +0000189 return *this;
Chris Lattner06fa1762009-08-24 03:52:50 +0000190}
191
Daniel Dunbard24535f2009-03-16 22:55:06 +0000192void raw_ostream::flush_nonempty() {
193 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000194 size_t Length = OutBufCur - OutBufStart;
195 OutBufCur = OutBufStart;
196 write_impl(OutBufStart, Length);
Daniel Dunbard24535f2009-03-16 22:55:06 +0000197}
198
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000199raw_ostream &raw_ostream::write(unsigned char C) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000200 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000201 if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
202 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000203 if (BufferMode == Unbuffered) {
Dan Gohman23f90c12009-08-18 20:09:59 +0000204 write_impl(reinterpret_cast<char*>(&C), 1);
205 return *this;
206 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000207 // Set up a buffer and start over.
208 SetBuffered();
209 return write(C);
Dan Gohman23f90c12009-08-18 20:09:59 +0000210 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000211
212 flush_nonempty();
Daniel Dunbar2d603da2009-03-17 01:13:35 +0000213 }
214
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000215 *OutBufCur++ = C;
Daniel Dunbar87862182009-03-16 22:08:44 +0000216 return *this;
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000217}
Chris Lattner0c19df42008-08-23 22:23:09 +0000218
Dan Gohmanf199ad62009-07-16 15:24:40 +0000219raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000220 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000221 if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
222 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000223 if (BufferMode == Unbuffered) {
Dan Gohman52022c22009-08-13 15:44:52 +0000224 write_impl(Ptr, Size);
225 return *this;
226 }
227 // Set up a buffer and start over.
Dan Gohman84487b92009-08-13 17:27:29 +0000228 SetBuffered();
Dan Gohman52022c22009-08-13 15:44:52 +0000229 return write(Ptr, Size);
230 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000231
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000232 size_t NumBytes = OutBufEnd - OutBufCur;
233
Benjamin Krameracf08422011-03-04 18:18:16 +0000234 // If the buffer is empty at this point we have a string that is larger
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000235 // than the buffer. Directly write the chunk that is a multiple of the
236 // preferred buffer size and put the remainder in the buffer.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000237 if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
Michael Ilseman5be22a12014-12-12 21:48:03 +0000238 assert(NumBytes != 0 && "undefined behavior");
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000239 size_t BytesToWrite = Size - (Size % NumBytes);
240 write_impl(Ptr, BytesToWrite);
Matt Beaumont-Gaya182be82013-03-12 23:55:24 +0000241 size_t BytesRemaining = Size - BytesToWrite;
242 if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
243 // Too much left over to copy into our buffer.
244 return write(Ptr + BytesToWrite, BytesRemaining);
245 }
246 copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
Benjamin Krameracf08422011-03-04 18:18:16 +0000247 return *this;
248 }
249
250 // We don't have enough space in the buffer to fit the string in. Insert as
251 // much as possible, flush and start over with the remainder.
Benjamin Krameracf08422011-03-04 18:18:16 +0000252 copy_to_buffer(Ptr, NumBytes);
253 flush_nonempty();
254 return write(Ptr + NumBytes, Size - NumBytes);
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000255 }
Dan Gohman52022c22009-08-13 15:44:52 +0000256
257 copy_to_buffer(Ptr, Size);
258
259 return *this;
260}
261
262void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
Dan Gohmanc04a00a2009-08-13 20:32:03 +0000263 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
Dan Gohman98205552009-08-13 18:38:15 +0000264
Owen Andersond2850532008-08-21 20:58:52 +0000265 // Handle short strings specially, memcpy isn't very good at very short
266 // strings.
267 switch (Size) {
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000268 case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
269 case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
270 case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
271 case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
Owen Andersond2850532008-08-21 20:58:52 +0000272 case 0: break;
273 default:
Dan Gohman52022c22009-08-13 15:44:52 +0000274 memcpy(OutBufCur, Ptr, Size);
Owen Andersond2850532008-08-21 20:58:52 +0000275 break;
276 }
Daniel Dunbar3da6a702009-03-10 16:21:55 +0000277
Dan Gohman52022c22009-08-13 15:44:52 +0000278 OutBufCur += Size;
Owen Andersond2850532008-08-21 20:58:52 +0000279}
280
Chris Lattner22b52c92008-08-23 19:23:10 +0000281// Formatted output.
282raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000283 // If we have more than a few bytes left in our output buffer, try
284 // formatting directly onto its end.
Dan Gohmanf199ad62009-07-16 15:24:40 +0000285 size_t NextBufferSize = 127;
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000286 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
287 if (BufferBytesLeft > 3) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000288 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000289
Chris Lattner22b52c92008-08-23 19:23:10 +0000290 // Common case is that we have plenty of space.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000291 if (BytesUsed <= BufferBytesLeft) {
Chris Lattner22b52c92008-08-23 19:23:10 +0000292 OutBufCur += BytesUsed;
293 return *this;
294 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000295
Chris Lattner22b52c92008-08-23 19:23:10 +0000296 // Otherwise, we overflowed and the return value tells us the size to try
297 // again with.
298 NextBufferSize = BytesUsed;
299 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000300
Chris Lattner22b52c92008-08-23 19:23:10 +0000301 // If we got here, we didn't have enough space in the output buffer for the
302 // string. Try printing into a SmallVector that is resized to have enough
303 // space. Iterate until we win.
304 SmallVector<char, 128> V;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000305
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000306 while (true) {
Chris Lattner22b52c92008-08-23 19:23:10 +0000307 V.resize(NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000308
Chris Lattner22b52c92008-08-23 19:23:10 +0000309 // Try formatting into the SmallVector.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000310 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000311
Chris Lattner22b52c92008-08-23 19:23:10 +0000312 // If BytesUsed fit into the vector, we win.
Chris Lattner2bfc72e2008-10-26 19:20:47 +0000313 if (BytesUsed <= NextBufferSize)
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000314 return write(V.data(), BytesUsed);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000315
Chris Lattner22b52c92008-08-23 19:23:10 +0000316 // Otherwise, try again with a new size.
317 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
318 NextBufferSize = BytesUsed;
319 }
320}
321
Zachary Turner11db2642016-11-11 23:57:40 +0000322raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
323 SmallString<128> S;
324 Obj.format(*this);
325 return *this;
326}
327
Nick Kledzike6480372014-09-25 20:30:58 +0000328raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
329 unsigned Len = FS.Str.size();
330 int PadAmount = FS.Width - Len;
331 if (FS.RightJustify && (PadAmount > 0))
332 this->indent(PadAmount);
333 this->operator<<(FS.Str);
334 if (!FS.RightJustify && (PadAmount > 0))
335 this->indent(PadAmount);
336 return *this;
337}
338
339raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
340 if (FN.Hex) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000341 HexPrintStyle Style;
342 if (FN.Upper && FN.HexPrefix)
343 Style = HexPrintStyle::PrefixUpper;
344 else if (FN.Upper && !FN.HexPrefix)
345 Style = HexPrintStyle::Upper;
346 else if (!FN.Upper && FN.HexPrefix)
347 Style = HexPrintStyle::PrefixLower;
348 else
349 Style = HexPrintStyle::Lower;
350 llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
Nick Kledzike6480372014-09-25 20:30:58 +0000351 } else {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000352 llvm::SmallString<16> Buffer;
353 llvm::raw_svector_ostream Stream(Buffer);
Zachary Turner11db2642016-11-11 23:57:40 +0000354 llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
Zachary Turner5b2243e2016-10-29 00:27:22 +0000355 if (Buffer.size() < FN.Width)
356 indent(FN.Width - Buffer.size());
357 (*this) << Buffer;
Nick Kledzike6480372014-09-25 20:30:58 +0000358 }
Zachary Turner733be512016-10-11 19:24:45 +0000359 return *this;
Nick Kledzike6480372014-09-25 20:30:58 +0000360}
361
Zachary Turner4a86af02016-11-10 20:16:45 +0000362raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
363 if (FB.Bytes.empty())
364 return *this;
365
Greg Claytonbde0a162016-11-09 00:15:54 +0000366 size_t LineIndex = 0;
Zachary Turner4a86af02016-11-10 20:16:45 +0000367 auto Bytes = FB.Bytes;
368 const size_t Size = Bytes.size();
369 HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
370 uint64_t OffsetWidth = 0;
371 if (FB.FirstByteOffset.hasValue()) {
372 // Figure out how many nibbles are needed to print the largest offset
373 // represented by this data set, so that we can align the offset field
374 // to the right width.
375 size_t Lines = Size / FB.NumPerLine;
376 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
377 unsigned Power = 0;
378 if (MaxOffset > 0)
379 Power = llvm::Log2_64_Ceil(MaxOffset);
Zachary Turner805d43a2016-11-10 20:35:21 +0000380 OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
Zachary Turner4a86af02016-11-10 20:16:45 +0000381 }
382
383 // The width of a block of data including all spaces for group separators.
384 unsigned NumByteGroups =
385 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
386 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
387
388 while (!Bytes.empty()) {
389 indent(FB.IndentLevel);
390
Greg Claytonbde0a162016-11-09 00:15:54 +0000391 if (FB.FirstByteOffset.hasValue()) {
392 uint64_t Offset = FB.FirstByteOffset.getValue();
Zachary Turner4a86af02016-11-10 20:16:45 +0000393 llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
Greg Claytonbde0a162016-11-09 00:15:54 +0000394 *this << ": ";
395 }
Zachary Turner4a86af02016-11-10 20:16:45 +0000396
397 auto Line = Bytes.take_front(FB.NumPerLine);
398
399 size_t CharsPrinted = 0;
400 // Print the hex bytes for this line in groups
401 for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
402 if (I && (I % FB.ByteGroupSize) == 0) {
403 ++CharsPrinted;
Greg Claytonbde0a162016-11-09 00:15:54 +0000404 *this << " ";
Zachary Turner4a86af02016-11-10 20:16:45 +0000405 }
406 llvm::write_hex(*this, Line[I], HPS, 2);
Greg Claytonbde0a162016-11-09 00:15:54 +0000407 }
Zachary Turner4a86af02016-11-10 20:16:45 +0000408
Greg Claytonbde0a162016-11-09 00:15:54 +0000409 if (FB.ASCII) {
410 // Print any spaces needed for any bytes that we didn't print on this
411 // line so that the ASCII bytes are correctly aligned.
Zachary Turner4a86af02016-11-10 20:16:45 +0000412 assert(BlockCharWidth >= CharsPrinted);
413 indent(BlockCharWidth - CharsPrinted + 2);
414 *this << "|";
415
Greg Claytonbde0a162016-11-09 00:15:54 +0000416 // Print the ASCII char values for each byte on this line
Zachary Turner4a86af02016-11-10 20:16:45 +0000417 for (uint8_t Byte : Line) {
418 if (isprint(Byte))
419 *this << static_cast<char>(Byte);
Greg Claytonbde0a162016-11-09 00:15:54 +0000420 else
421 *this << '.';
422 }
423 *this << '|';
424 }
Zachary Turner4a86af02016-11-10 20:16:45 +0000425
426 Bytes = Bytes.drop_front(Line.size());
427 LineIndex += Line.size();
Greg Claytonbde0a162016-11-09 00:15:54 +0000428 if (LineIndex < Size)
429 *this << '\n';
430 }
431 return *this;
432}
433
Chris Lattnere6db2c32009-08-22 23:10:29 +0000434/// indent - Insert 'NumSpaces' spaces.
435raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
Dan Gohmanf88f52e2009-08-24 04:13:01 +0000436 static const char Spaces[] = " "
437 " "
438 " ";
Chris Lattnere6db2c32009-08-22 23:10:29 +0000439
440 // Usually the indentation is small, handle it with a fastpath.
Dan Gohmanc9fa0512009-08-24 04:43:38 +0000441 if (NumSpaces < array_lengthof(Spaces))
Chris Lattnere6db2c32009-08-22 23:10:29 +0000442 return write(Spaces, NumSpaces);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000443
Chris Lattnere6db2c32009-08-22 23:10:29 +0000444 while (NumSpaces) {
Dan Gohmanc9fa0512009-08-24 04:43:38 +0000445 unsigned NumToWrite = std::min(NumSpaces,
446 (unsigned)array_lengthof(Spaces)-1);
Chris Lattnere6db2c32009-08-22 23:10:29 +0000447 write(Spaces, NumToWrite);
448 NumSpaces -= NumToWrite;
449 }
450 return *this;
451}
452
Chris Lattner22b52c92008-08-23 19:23:10 +0000453//===----------------------------------------------------------------------===//
454// Formatted Output
455//===----------------------------------------------------------------------===//
456
457// Out of line virtual method.
458void format_object_base::home() {
459}
460
Chris Lattner84b94f72008-08-17 01:35:29 +0000461//===----------------------------------------------------------------------===//
462// raw_fd_ostream
463//===----------------------------------------------------------------------===//
464
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000465static int getFD(StringRef Filename, std::error_code &EC,
466 sys::fs::OpenFlags Flags) {
Dan Gohmanc825cee2010-08-18 22:26:19 +0000467 // Handle "-" as stdout. Note that when we do this, we consider ourself
Yaron Keren80745c52017-03-31 12:08:45 +0000468 // the owner of stdout and may set the "binary" flag globally based on Flags.
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000469 if (Filename == "-") {
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000470 EC = std::error_code();
Daniel Dunbared90e702008-11-13 05:01:07 +0000471 // If user requested binary then put stdout into binary mode if
472 // possible.
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000473 if (!(Flags & sys::fs::F_Text))
Rafael Espindolacb2eca02013-06-12 20:58:35 +0000474 sys::ChangeStdoutToBinary();
Yaron Keren9d27c472017-03-30 19:30:51 +0000475 return STDOUT_FILENO;
Chris Lattnerd5bc0682008-08-17 03:53:23 +0000476 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000477
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000478 int FD;
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000479 EC = sys::fs::openFileForWrite(Filename, FD, Flags);
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000480 if (EC)
481 return -1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000482
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000483 return FD;
Chris Lattner84b94f72008-08-17 01:35:29 +0000484}
485
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000486raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
487 sys::fs::OpenFlags Flags)
488 : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
489
Rafael Espindola62e6ec02015-04-09 16:59:07 +0000490/// FD is the file descriptor that this writes to. If ShouldClose is true, this
491/// closes the file when the stream is destroyed.
Francois Picheta3037c32010-10-14 20:30:58 +0000492raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
Rafael Espindola37b70152015-04-14 15:00:34 +0000493 : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
Rafael Espindola3f210fc2015-12-16 22:59:06 +0000494 Error(false) {
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000495 if (FD < 0 ) {
496 ShouldClose = false;
497 return;
498 }
Yaron Keren9d27c472017-03-30 19:30:51 +0000499 // We do not want to close STDOUT as there may have been several uses of it
500 // such as the case: llc %s -o=- -pass-remarks-output=- -filetype=asm
501 // which cause multiple closes of STDOUT_FILENO and/or use-after-close of it.
502 // Using dup() in getFD doesn't work as we end up with original STDOUT_FILENO
503 // open anyhow.
504 if (FD <= STDERR_FILENO)
505 ShouldClose = false;
Michael J. Spencerb7479902011-01-17 15:53:12 +0000506
507 // Get the starting position.
508 off_t loc = ::lseek(FD, 0, SEEK_CUR);
Rafael Espindolaa9b84ab2015-04-13 11:09:48 +0000509#ifdef LLVM_ON_WIN32
510 // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
511 sys::fs::file_status Status;
512 std::error_code EC = status(FD, Status);
513 SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
514#else
Rafael Espindola74d2f612015-04-10 18:15:51 +0000515 SupportsSeeking = loc != (off_t)-1;
Rafael Espindolaa9b84ab2015-04-13 11:09:48 +0000516#endif
Rafael Espindola74d2f612015-04-10 18:15:51 +0000517 if (!SupportsSeeking)
Michael J. Spencerb7479902011-01-17 15:53:12 +0000518 pos = 0;
519 else
520 pos = static_cast<uint64_t>(loc);
Francois Picheta3037c32010-10-14 20:30:58 +0000521}
522
Chris Lattner84b94f72008-08-17 01:35:29 +0000523raw_fd_ostream::~raw_fd_ostream() {
Dan Gohman38adfdd2010-08-20 16:34:20 +0000524 if (FD >= 0) {
525 flush();
David Majnemer51c2afc2014-10-07 05:48:40 +0000526 if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
527 error_detected();
Dan Gohman38adfdd2010-08-20 16:34:20 +0000528 }
529
NAKAMURA Takumi76e68ea2011-03-16 02:53:39 +0000530#ifdef __MINGW32__
531 // On mingw, global dtors should not call exit().
532 // report_fatal_error() invokes exit(). We know report_fatal_error()
533 // might not write messages to stderr when any errors were detected
534 // on FD == 2.
535 if (FD == 2) return;
536#endif
537
Dan Gohman38adfdd2010-08-20 16:34:20 +0000538 // If there are any pending errors, report them now. Clients wishing
539 // to avoid report_fatal_error calls should check for errors with
540 // has_error() and clear the error flag with clear_error() before
541 // destructing raw_ostream objects which may have errors.
542 if (has_error())
Chad Rosier7ce810c2013-03-27 18:30:00 +0000543 report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
Chris Lattnerce3b2c32010-08-17 23:11:56 +0000544}
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000545
Dan Gohmanf199ad62009-07-16 15:24:40 +0000546void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000547 assert(FD >= 0 && "File already closed.");
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000548 pos += Size;
Dan Gohmanef969f32010-05-06 01:27:36 +0000549
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000550#ifndef LLVM_ON_WIN32
551 bool ShouldWriteInChunks = false;
552#else
553 // Writing a large size of output to Windows console returns ENOMEM. It seems
554 // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
555 // the latter has a size limit (66000 bytes or less, depending on heap usage).
Reid Kleckner5fb7a582016-01-11 23:33:03 +0000556 bool ShouldWriteInChunks = !!::_isatty(FD) && !RunningWindows8OrGreater();
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000557#endif
558
Benjamin Kramerce84a252010-05-05 15:17:47 +0000559 do {
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000560 size_t ChunkSize = Size;
561 if (ChunkSize > 32767 && ShouldWriteInChunks)
562 ChunkSize = 32767;
563
564 ssize_t ret = ::write(FD, Ptr, ChunkSize);
Dan Gohmanef969f32010-05-06 01:27:36 +0000565
566 if (ret < 0) {
567 // If it's a recoverable error, swallow it and retry the write.
Dan Gohmandea53102010-05-18 15:25:14 +0000568 //
569 // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
570 // raw_ostream isn't designed to do non-blocking I/O. However, some
571 // programs, such as old versions of bjam, have mistakenly used
572 // O_NONBLOCK. For compatibility, emulate blocking semantics by
573 // spinning until the write succeeds. If you don't want spinning,
574 // don't use O_NONBLOCK file descriptors with raw_ostream.
Dan Gohmand3511162010-05-06 02:06:20 +0000575 if (errno == EINTR || errno == EAGAIN
576#ifdef EWOULDBLOCK
577 || errno == EWOULDBLOCK
578#endif
579 )
Dan Gohmanef969f32010-05-06 01:27:36 +0000580 continue;
581
582 // Otherwise it's a non-recoverable error. Note it and quit.
583 error_detected();
584 break;
585 }
586
587 // The write may have written some or all of the data. Update the
588 // size and buffer pointer to reflect the remainder that needs
589 // to be written. If there are no bytes left, we're done.
590 Ptr += ret;
591 Size -= ret;
592 } while (Size > 0);
Chris Lattner84b94f72008-08-17 01:35:29 +0000593}
594
Dan Gohman44790e72010-08-18 01:34:52 +0000595void raw_fd_ostream::close() {
596 assert(ShouldClose);
597 ShouldClose = false;
598 flush();
David Majnemer51c2afc2014-10-07 05:48:40 +0000599 if (sys::Process::SafelyCloseFileDescriptor(FD))
600 error_detected();
Dan Gohman44790e72010-08-18 01:34:52 +0000601 FD = -1;
602}
603
Ted Kremeneka2669922009-01-26 21:42:04 +0000604uint64_t raw_fd_ostream::seek(uint64_t off) {
Yaron Keren7cf7f802016-02-23 07:17:58 +0000605 assert(SupportsSeeking && "Stream does not support seeking!");
Ted Kremeneka2669922009-01-26 21:42:04 +0000606 flush();
Peter Collingbourne8db7e5e2016-12-09 05:20:43 +0000607#ifdef LLVM_ON_WIN32
608 pos = ::_lseeki64(FD, off, SEEK_SET);
609#elif defined(HAVE_LSEEK64)
610 pos = ::lseek64(FD, off, SEEK_SET);
611#else
Peter Collingbournef74fcdd2016-12-09 05:04:30 +0000612 pos = ::lseek(FD, off, SEEK_SET);
Peter Collingbourne8db7e5e2016-12-09 05:20:43 +0000613#endif
Rafael Espindola642a2212015-04-14 22:54:16 +0000614 if (pos == (uint64_t)-1)
Dan Gohman58fcef92009-07-15 23:25:33 +0000615 error_detected();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000616 return pos;
Ted Kremeneka2669922009-01-26 21:42:04 +0000617}
618
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000619void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
620 uint64_t Offset) {
Rafael Espindola37b70152015-04-14 15:00:34 +0000621 uint64_t Pos = tell();
622 seek(Offset);
623 write(Ptr, Size);
624 seek(Pos);
625}
626
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000627size_t raw_fd_ostream::preferred_buffer_size() const {
Chris Lattnerca97c922010-07-07 15:52:27 +0000628#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
Chris Lattnerc86cdc72010-04-09 20:45:04 +0000629 // Windows and Minix have no st_blksize.
Dan Gohman84487b92009-08-13 17:27:29 +0000630 assert(FD >= 0 && "File not yet open!");
631 struct stat statbuf;
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000632 if (fstat(FD, &statbuf) != 0)
633 return 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000634
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000635 // If this is a terminal, don't use buffering. Line buffering
636 // would be a more traditional thing to do, but it's not worth
637 // the complexity.
638 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
639 return 0;
640 // Return the preferred block size.
641 return statbuf.st_blksize;
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000642#else
Dan Gohman84487b92009-08-13 17:27:29 +0000643 return raw_ostream::preferred_buffer_size();
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000644#endif
Dan Gohman84487b92009-08-13 17:27:29 +0000645}
646
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000647raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
648 bool bg) {
649 if (sys::Process::ColorNeedsFlush())
650 flush();
651 const char *colorcode =
652 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
653 : sys::Process::OutputColor(colors, bold, bg);
654 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000655 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000656 write(colorcode, len);
657 // don't account colors towards output characters
658 pos -= len;
659 }
660 return *this;
661}
662
663raw_ostream &raw_fd_ostream::resetColor() {
664 if (sys::Process::ColorNeedsFlush())
665 flush();
666 const char *colorcode = sys::Process::ResetColor();
667 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000668 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000669 write(colorcode, len);
670 // don't account colors towards output characters
671 pos -= len;
672 }
673 return *this;
674}
675
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000676raw_ostream &raw_fd_ostream::reverseColor() {
677 if (sys::Process::ColorNeedsFlush())
678 flush();
679 const char *colorcode = sys::Process::OutputReverse();
680 if (colorcode) {
681 size_t len = strlen(colorcode);
682 write(colorcode, len);
683 // don't account colors towards output characters
684 pos -= len;
685 }
686 return *this;
687}
688
Dan Gohmane5929232009-09-11 20:46:33 +0000689bool raw_fd_ostream::is_displayed() const {
690 return sys::Process::FileDescriptorIsDisplayed(FD);
691}
692
Daniel Dunbar04b45832012-07-20 18:29:41 +0000693bool raw_fd_ostream::has_colors() const {
694 return sys::Process::FileDescriptorHasColors(FD);
695}
696
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000697//===----------------------------------------------------------------------===//
Dan Gohmane9a46912010-08-20 16:44:56 +0000698// outs(), errs(), nulls()
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000699//===----------------------------------------------------------------------===//
Chris Lattner84b94f72008-08-17 01:35:29 +0000700
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000701/// outs() - This returns a reference to a raw_ostream for standard output.
702/// Use it like: outs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000703raw_ostream &llvm::outs() {
Justin Lebarc75d5662016-02-19 00:18:46 +0000704 // Set buffer settings to model stdout behavior. Delete the file descriptor
705 // when the program exits, forcing error detection. This means that if you
706 // ever call outs(), you can't open another raw_fd_ostream on stdout, as we'll
707 // close stdout twice and print an error the second time.
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000708 std::error_code EC;
709 static raw_fd_ostream S("-", EC, sys::fs::F_None);
710 assert(!EC);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000711 return S;
712}
713
714/// errs() - This returns a reference to a raw_ostream for standard error.
715/// Use it like: errs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000716raw_ostream &llvm::errs() {
Dan Gohman443f2d62010-08-20 16:39:41 +0000717 // Set standard error to be unbuffered by default.
718 static raw_fd_ostream S(STDERR_FILENO, false, true);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000719 return S;
720}
721
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000722/// nulls() - This returns a reference to a raw_ostream which discards output.
723raw_ostream &llvm::nulls() {
724 static raw_null_ostream S;
725 return S;
726}
727
Chris Lattner205af962008-08-23 22:43:04 +0000728//===----------------------------------------------------------------------===//
729// raw_string_ostream
730//===----------------------------------------------------------------------===//
731
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000732raw_string_ostream::~raw_string_ostream() {
733 flush();
734}
735
Dan Gohmanf199ad62009-07-16 15:24:40 +0000736void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000737 OS.append(Ptr, Size);
Chris Lattner205af962008-08-23 22:43:04 +0000738}
739
740//===----------------------------------------------------------------------===//
741// raw_svector_ostream
742//===----------------------------------------------------------------------===//
743
Yaron Keren3d1173b2015-08-13 06:19:52 +0000744uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000745
Yaron Keren3d1173b2015-08-13 06:19:52 +0000746void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
747 OS.append(Ptr, Ptr + Size);
Nick Lewyckye2f6fb52015-08-13 18:10:19 +0000748}
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000749
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000750void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
751 uint64_t Offset) {
Yaron Keren3d1173b2015-08-13 06:19:52 +0000752 memcpy(OS.data() + Offset, Ptr, Size);
Daniel Dunbare813cba2009-08-19 18:40:58 +0000753}
754
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000755//===----------------------------------------------------------------------===//
756// raw_null_ostream
757//===----------------------------------------------------------------------===//
758
Dan Gohman4b66b472009-07-27 21:46:02 +0000759raw_null_ostream::~raw_null_ostream() {
760#ifndef NDEBUG
761 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
762 // with raw_null_ostream, but it's better to have raw_null_ostream follow
763 // the rules than to change the rules just for raw_null_ostream.
764 flush();
765#endif
766}
767
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000768void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
769}
770
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000771uint64_t raw_null_ostream::current_pos() const {
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000772 return 0;
773}
Rafael Espindola37b70152015-04-14 15:00:34 +0000774
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000775void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
776 uint64_t Offset) {}