Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Support/raw_ostream.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This implements support for bulk buffered stream output.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "llvm/Support/raw_ostream.h"
14
#include "llvm/ADT/STLExtras.h"
15
#include "llvm/ADT/SmallVector.h"
16
#include "llvm/ADT/StringExtras.h"
17
#include "llvm/Config/config.h"
18
#include "llvm/Support/Compiler.h"
19
#include "llvm/Support/ErrorHandling.h"
20
#include "llvm/Support/FileSystem.h"
21
#include "llvm/Support/Format.h"
22
#include "llvm/Support/FormatVariadic.h"
23
#include "llvm/Support/MathExtras.h"
24
#include "llvm/Support/NativeFormatting.h"
25
#include "llvm/Support/Process.h"
26
#include "llvm/Support/Program.h"
27
#include <algorithm>
28
#include <cctype>
29
#include <cerrno>
30
#include <cstdio>
31
#include <iterator>
32
#include <sys/stat.h>
33
#include <system_error>
34
35
// <fcntl.h> may provide O_BINARY.
36
#if defined(HAVE_FCNTL_H)
37
# include <fcntl.h>
38
#endif
39
40
#if defined(HAVE_UNISTD_H)
41
# include <unistd.h>
42
#endif
43
44
#if defined(__CYGWIN__)
45
#include <io.h>
46
#endif
47
48
#if defined(_MSC_VER)
49
#include <io.h>
50
#ifndef STDIN_FILENO
51
# define STDIN_FILENO 0
52
#endif
53
#ifndef STDOUT_FILENO
54
# define STDOUT_FILENO 1
55
#endif
56
#ifndef STDERR_FILENO
57
# define STDERR_FILENO 2
58
#endif
59
#endif
60
61
#ifdef _WIN32
62
#include "llvm/Support/ConvertUTF.h"
63
#include "Windows/WindowsSupport.h"
64
#endif
65
66
using namespace llvm;
67
68
112M
raw_ostream::~raw_ostream() {
69
112M
  // raw_ostream's subclasses should take care to flush the buffer
70
112M
  // in their destructors.
71
112M
  assert(OutBufCur == OutBufStart &&
72
112M
         "raw_ostream destructor called with non-empty buffer!");
73
112M
74
112M
  if (BufferMode == InternalBuffer)
75
25.3M
    delete [] OutBufStart;
76
112M
}
77
78
24.5M
size_t raw_ostream::preferred_buffer_size() const {
79
24.5M
  // BUFSIZ is intended to be a reasonable default.
80
24.5M
  return BUFSIZ;
81
24.5M
}
82
83
24.6M
void raw_ostream::SetBuffered() {
84
24.6M
  // Ask the subclass to determine an appropriate buffer size.
85
24.6M
  if (size_t Size = preferred_buffer_size())
86
24.6M
    SetBufferSize(Size);
87
0
  else
88
0
    // It may return 0, meaning this stream should be unbuffered.
89
0
    SetUnbuffered();
90
24.6M
}
91
92
void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
93
113M
                                   BufferKind Mode) {
94
113M
  assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
95
113M
          (Mode != Unbuffered && BufferStart && Size != 0)) &&
96
113M
         "stream must be unbuffered or have at least one byte");
97
113M
  // Make sure the current buffer is free of content (we can't flush here; the
98
113M
  // child buffer management logic will be in write_impl).
99
113M
  assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
100
113M
101
113M
  if (BufferMode == InternalBuffer)
102
112M
    delete [] OutBufStart;
103
113M
  OutBufStart = BufferStart;
104
113M
  OutBufEnd = OutBufStart+Size;
105
113M
  OutBufCur = OutBufStart;
106
113M
  BufferMode = Mode;
107
113M
108
113M
  assert(OutBufStart <= OutBufEnd && "Invalid size!");
109
113M
}
110
111
48.8M
raw_ostream &raw_ostream::operator<<(unsigned long N) {
112
48.8M
  write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
113
48.8M
  return *this;
114
48.8M
}
115
116
15.5M
raw_ostream &raw_ostream::operator<<(long N) {
117
15.5M
  write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
118
15.5M
  return *this;
119
15.5M
}
120
121
21.1M
raw_ostream &raw_ostream::operator<<(unsigned long long N) {
122
21.1M
  write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
123
21.1M
  return *this;
124
21.1M
}
125
126
1.43M
raw_ostream &raw_ostream::operator<<(long long N) {
127
1.43M
  write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
128
1.43M
  return *this;
129
1.43M
}
130
131
498k
raw_ostream &raw_ostream::write_hex(unsigned long long N) {
132
498k
  llvm::write_hex(*this, N, HexPrintStyle::Lower);
133
498k
  return *this;
134
498k
}
135
136
42
raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) {
137
714
  for (int Idx = 0; Idx < 16; 
++Idx672
) {
138
672
    *this << format("%02" PRIX32, UUID[Idx]);
139
672
    if (Idx == 3 || 
Idx == 5630
||
Idx == 7588
||
Idx == 9546
)
140
168
      *this << "-";
141
672
  }
142
42
  return *this;
143
42
}
144
145
146
raw_ostream &raw_ostream::write_escaped(StringRef Str,
147
161k
                                        bool UseHexEscapes) {
148
1.89M
  for (unsigned char c : Str) {
149
1.89M
    switch (c) {
150
1.89M
    case '\\':
151
72
      *this << '\\' << '\\';
152
72
      break;
153
1.89M
    case '\t':
154
676
      *this << '\\' << 't';
155
676
      break;
156
1.89M
    case '\n':
157
500
      *this << '\\' << 'n';
158
500
      break;
159
1.89M
    case '"':
160
89
      *this << '\\' << '"';
161
89
      break;
162
1.89M
    default:
163
1.89M
      if (isPrint(c)) {
164
1.87M
        *this << c;
165
1.87M
        break;
166
1.87M
      }
167
17.2k
168
17.2k
      // Write out the escaped representation.
169
17.2k
      if (UseHexEscapes) {
170
189
        *this << '\\' << 'x';
171
189
        *this << hexdigit((c >> 4 & 0xF));
172
189
        *this << hexdigit((c >> 0) & 0xF);
173
17.0k
      } else {
174
17.0k
        // Always use a full 3-character octal escape.
175
17.0k
        *this << '\\';
176
17.0k
        *this << char('0' + ((c >> 6) & 7));
177
17.0k
        *this << char('0' + ((c >> 3) & 7));
178
17.0k
        *this << char('0' + ((c >> 0) & 7));
179
17.0k
      }
180
1.89M
    }
181
1.89M
  }
182
161k
183
161k
  return *this;
184
161k
}
185
186
41.3k
raw_ostream &raw_ostream::operator<<(const void *P) {
187
41.3k
  llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
188
41.3k
  return *this;
189
41.3k
}
190
191
28.6k
raw_ostream &raw_ostream::operator<<(double N) {
192
28.6k
  llvm::write_double(*this, N, FloatStyle::Exponent);
193
28.6k
  return *this;
194
28.6k
}
195
196
27.8M
void raw_ostream::flush_nonempty() {
197
27.8M
  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
198
27.8M
  size_t Length = OutBufCur - OutBufStart;
199
27.8M
  OutBufCur = OutBufStart;
200
27.8M
  write_impl(OutBufStart, Length);
201
27.8M
}
202
203
248M
raw_ostream &raw_ostream::write(unsigned char C) {
204
248M
  // Group exceptional cases into a single branch.
205
248M
  if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
206
243M
    if (LLVM_UNLIKELY(!OutBufStart)) {
207
243M
      if (BufferMode == Unbuffered) {
208
239M
        write_impl(reinterpret_cast<char*>(&C), 1);
209
239M
        return *this;
210
239M
      }
211
4.50M
      // Set up a buffer and start over.
212
4.50M
      SetBuffered();
213
4.50M
      return write(C);
214
4.50M
    }
215
79.9k
216
79.9k
    flush_nonempty();
217
79.9k
  }
218
248M
219
248M
  *OutBufCur++ = C;
220
4.81M
  return *this;
221
248M
}
222
223
748M
raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
224
748M
  // Group exceptional cases into a single branch.
225
748M
  if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
226
619M
    if (LLVM_UNLIKELY(!OutBufStart)) {
227
618M
      if (BufferMode == Unbuffered) {
228
597M
        write_impl(Ptr, Size);
229
597M
        return *this;
230
597M
      }
231
20.1M
      // Set up a buffer and start over.
232
20.1M
      SetBuffered();
233
20.1M
      return write(Ptr, Size);
234
20.1M
    }
235
1.02M
236
1.02M
    size_t NumBytes = OutBufEnd - OutBufCur;
237
1.02M
238
1.02M
    // If the buffer is empty at this point we have a string that is larger
239
1.02M
    // than the buffer. Directly write the chunk that is a multiple of the
240
1.02M
    // preferred buffer size and put the remainder in the buffer.
241
1.02M
    if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
242
9.94k
      assert(NumBytes != 0 && "undefined behavior");
243
9.94k
      size_t BytesToWrite = Size - (Size % NumBytes);
244
9.94k
      write_impl(Ptr, BytesToWrite);
245
9.94k
      size_t BytesRemaining = Size - BytesToWrite;
246
9.94k
      if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
247
0
        // Too much left over to copy into our buffer.
248
0
        return write(Ptr + BytesToWrite, BytesRemaining);
249
0
      }
250
9.94k
      copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
251
9.94k
      return *this;
252
9.94k
    }
253
1.02M
254
1.02M
    // We don't have enough space in the buffer to fit the string in. Insert as
255
1.02M
    // much as possible, flush and start over with the remainder.
256
1.02M
    copy_to_buffer(Ptr, NumBytes);
257
1.02M
    flush_nonempty();
258
1.02M
    return write(Ptr + NumBytes, Size - NumBytes);
259
1.02M
  }
260
129M
261
129M
  copy_to_buffer(Ptr, Size);
262
129M
263
129M
  return *this;
264
129M
}
265
266
130M
void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
267
130M
  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
268
130M
269
130M
  // Handle short strings specially, memcpy isn't very good at very short
270
130M
  // strings.
271
130M
  switch (Size) {
272
130M
  
case 4: OutBufCur[3] = Ptr[3]; 15.7M
LLVM_FALLTHROUGH15.7M
;
273
18.3M
  case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
274
65.0M
  case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
275
98.6M
  case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
276
101M
  case 0: break;
277
98.6M
  default:
278
29.8M
    memcpy(OutBufCur, Ptr, Size);
279
29.8M
    break;
280
130M
  }
281
130M
282
130M
  OutBufCur += Size;
283
130M
}
284
285
// Formatted output.
286
6.84M
raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
287
6.84M
  // If we have more than a few bytes left in our output buffer, try
288
6.84M
  // formatting directly onto its end.
289
6.84M
  size_t NextBufferSize = 127;
290
6.84M
  size_t BufferBytesLeft = OutBufEnd - OutBufCur;
291
6.84M
  if (BufferBytesLeft > 3) {
292
2.06M
    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
293
2.06M
294
2.06M
    // Common case is that we have plenty of space.
295
2.06M
    if (BytesUsed <= BufferBytesLeft) {
296
2.06M
      OutBufCur += BytesUsed;
297
2.06M
      return *this;
298
2.06M
    }
299
435
300
435
    // Otherwise, we overflowed and the return value tells us the size to try
301
435
    // again with.
302
435
    NextBufferSize = BytesUsed;
303
435
  }
304
6.84M
305
6.84M
  // If we got here, we didn't have enough space in the output buffer for the
306
6.84M
  // string.  Try printing into a SmallVector that is resized to have enough
307
6.84M
  // space.  Iterate until we win.
308
6.84M
  SmallVector<char, 128> V;
309
4.77M
310
4.77M
  while (true) {
311
4.77M
    V.resize(NextBufferSize);
312
4.77M
313
4.77M
    // Try formatting into the SmallVector.
314
4.77M
    size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
315
4.77M
316
4.77M
    // If BytesUsed fit into the vector, we win.
317
4.77M
    if (BytesUsed <= NextBufferSize)
318
4.77M
      return write(V.data(), BytesUsed);
319
87
320
87
    // Otherwise, try again with a new size.
321
87
    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
322
87
    NextBufferSize = BytesUsed;
323
87
  }
324
4.77M
}
325
326
113k
raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
327
113k
  SmallString<128> S;
328
113k
  Obj.format(*this);
329
113k
  return *this;
330
113k
}
331
332
337k
raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
333
337k
  if (FS.Str.size() >= FS.Width || 
FS.Justify == FormattedString::JustifyNone271k
) {
334
65.9k
    this->operator<<(FS.Str);
335
65.9k
    return *this;
336
65.9k
  }
337
271k
  const size_t Difference = FS.Width - FS.Str.size();
338
271k
  switch (FS.Justify) {
339
271k
  case FormattedString::JustifyLeft:
340
1.73k
    this->operator<<(FS.Str);
341
1.73k
    this->indent(Difference);
342
1.73k
    break;
343
271k
  case FormattedString::JustifyRight:
344
269k
    this->indent(Difference);
345
269k
    this->operator<<(FS.Str);
346
269k
    break;
347
271k
  case FormattedString::JustifyCenter: {
348
5
    int PadAmount = Difference / 2;
349
5
    this->indent(PadAmount);
350
5
    this->operator<<(FS.Str);
351
5
    this->indent(Difference - PadAmount);
352
5
    break;
353
271k
  }
354
271k
  default:
355
0
    llvm_unreachable("Bad Justification");
356
271k
  }
357
271k
  return *this;
358
271k
}
359
360
25.7M
raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
361
25.7M
  if (FN.Hex) {
362
3.01M
    HexPrintStyle Style;
363
3.01M
    if (FN.Upper && 
FN.HexPrefix2.53M
)
364
2.87k
      Style = HexPrintStyle::PrefixUpper;
365
3.01M
    else if (FN.Upper && 
!FN.HexPrefix2.53M
)
366
2.53M
      Style = HexPrintStyle::Upper;
367
475k
    else if (!FN.Upper && FN.HexPrefix)
368
66.3k
      Style = HexPrintStyle::PrefixLower;
369
409k
    else
370
409k
      Style = HexPrintStyle::Lower;
371
3.01M
    llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
372
22.7M
  } else {
373
22.7M
    llvm::SmallString<16> Buffer;
374
22.7M
    llvm::raw_svector_ostream Stream(Buffer);
375
22.7M
    llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
376
22.7M
    if (Buffer.size() < FN.Width)
377
16.6M
      indent(FN.Width - Buffer.size());
378
22.7M
    (*this) << Buffer;
379
22.7M
  }
380
25.7M
  return *this;
381
25.7M
}
382
383
5.18k
raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
384
5.18k
  if (FB.Bytes.empty())
385
80
    return *this;
386
5.10k
387
5.10k
  size_t LineIndex = 0;
388
5.10k
  auto Bytes = FB.Bytes;
389
5.10k
  const size_t Size = Bytes.size();
390
5.10k
  HexPrintStyle HPS = FB.Upper ? 
HexPrintStyle::Upper5.07k
:
HexPrintStyle::Lower34
;
391
5.10k
  uint64_t OffsetWidth = 0;
392
5.10k
  if (FB.FirstByteOffset.hasValue()) {
393
2.22k
    // Figure out how many nibbles are needed to print the largest offset
394
2.22k
    // represented by this data set, so that we can align the offset field
395
2.22k
    // to the right width.
396
2.22k
    size_t Lines = Size / FB.NumPerLine;
397
2.22k
    uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
398
2.22k
    unsigned Power = 0;
399
2.22k
    if (MaxOffset > 0)
400
1.58k
      Power = llvm::Log2_64_Ceil(MaxOffset);
401
2.22k
    OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
402
2.22k
  }
403
5.10k
404
5.10k
  // The width of a block of data including all spaces for group separators.
405
5.10k
  unsigned NumByteGroups =
406
5.10k
      alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
407
5.10k
  unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
408
5.10k
409
1.71M
  while (!Bytes.empty()) {
410
1.71M
    indent(FB.IndentLevel);
411
1.71M
412
1.71M
    if (FB.FirstByteOffset.hasValue()) {
413
1.70M
      uint64_t Offset = FB.FirstByteOffset.getValue();
414
1.70M
      llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
415
1.70M
      *this << ": ";
416
1.70M
    }
417
1.71M
418
1.71M
    auto Line = Bytes.take_front(FB.NumPerLine);
419
1.71M
420
1.71M
    size_t CharsPrinted = 0;
421
1.71M
    // Print the hex bytes for this line in groups
422
29.0M
    for (size_t I = 0; I < Line.size(); 
++I, CharsPrinted += 227.3M
) {
423
27.3M
      if (I && 
(I % FB.ByteGroupSize) == 025.6M
) {
424
5.14M
        ++CharsPrinted;
425
5.14M
        *this << " ";
426
5.14M
      }
427
27.3M
      llvm::write_hex(*this, Line[I], HPS, 2);
428
27.3M
    }
429
1.71M
430
1.71M
    if (FB.ASCII) {
431
1.70M
      // Print any spaces needed for any bytes that we didn't print on this
432
1.70M
      // line so that the ASCII bytes are correctly aligned.
433
1.70M
      assert(BlockCharWidth >= CharsPrinted);
434
1.70M
      indent(BlockCharWidth - CharsPrinted + 2);
435
1.70M
      *this << "|";
436
1.70M
437
1.70M
      // Print the ASCII char values for each byte on this line
438
27.3M
      for (uint8_t Byte : Line) {
439
27.3M
        if (isPrint(Byte))
440
35.2k
          *this << static_cast<char>(Byte);
441
27.2M
        else
442
27.2M
          *this << '.';
443
27.3M
      }
444
1.70M
      *this << '|';
445
1.70M
    }
446
1.71M
447
1.71M
    Bytes = Bytes.drop_front(Line.size());
448
1.71M
    LineIndex += Line.size();
449
1.71M
    if (LineIndex < Size)
450
1.70M
      *this << '\n';
451
1.71M
  }
452
5.10k
  return *this;
453
5.10k
}
454
455
template <char C>
456
54.4M
static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
457
54.4M
  static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
458
54.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
459
54.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
460
54.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
461
54.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
462
54.4M
463
54.4M
  // Usually the indentation is small, handle it with a fastpath.
464
54.4M
  if (NumChars < array_lengthof(Chars))
465
54.4M
    return OS.write(Chars, NumChars);
466
813
467
4.12M
  
while (813
NumChars) {
468
4.12M
    unsigned NumToWrite = std::min(NumChars,
469
4.12M
                                   (unsigned)array_lengthof(Chars)-1);
470
4.12M
    OS.write(Chars, NumToWrite);
471
4.12M
    NumChars -= NumToWrite;
472
4.12M
  }
473
813
  return OS;
474
813
}
raw_ostream.cpp:llvm::raw_ostream& write_padding<(char)32>(llvm::raw_ostream&, unsigned int)
Line
Count
Source
456
53.4M
static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
457
53.4M
  static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
458
53.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
459
53.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
460
53.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
461
53.4M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
462
53.4M
463
53.4M
  // Usually the indentation is small, handle it with a fastpath.
464
53.4M
  if (NumChars < array_lengthof(Chars))
465
53.4M
    return OS.write(Chars, NumChars);
466
0
467
0
  while (NumChars) {
468
0
    unsigned NumToWrite = std::min(NumChars,
469
0
                                   (unsigned)array_lengthof(Chars)-1);
470
0
    OS.write(Chars, NumToWrite);
471
0
    NumChars -= NumToWrite;
472
0
  }
473
0
  return OS;
474
0
}
raw_ostream.cpp:llvm::raw_ostream& write_padding<(char)0>(llvm::raw_ostream&, unsigned int)
Line
Count
Source
456
1.00M
static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
457
1.00M
  static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
458
1.00M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
459
1.00M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
460
1.00M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
461
1.00M
                               C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
462
1.00M
463
1.00M
  // Usually the indentation is small, handle it with a fastpath.
464
1.00M
  if (NumChars < array_lengthof(Chars))
465
1.00M
    return OS.write(Chars, NumChars);
466
813
467
4.12M
  
while (813
NumChars) {
468
4.12M
    unsigned NumToWrite = std::min(NumChars,
469
4.12M
                                   (unsigned)array_lengthof(Chars)-1);
470
4.12M
    OS.write(Chars, NumToWrite);
471
4.12M
    NumChars -= NumToWrite;
472
4.12M
  }
473
813
  return OS;
474
813
}
475
476
/// indent - Insert 'NumSpaces' spaces.
477
53.4M
raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
478
53.4M
  return write_padding<' '>(*this, NumSpaces);
479
53.4M
}
480
481
/// write_zeros - Insert 'NumZeros' nulls.
482
1.00M
raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) {
483
1.00M
  return write_padding<'\0'>(*this, NumZeros);
484
1.00M
}
485
486
0
void raw_ostream::anchor() {}
487
488
//===----------------------------------------------------------------------===//
489
//  Formatted Output
490
//===----------------------------------------------------------------------===//
491
492
// Out of line virtual method.
493
0
void format_object_base::home() {
494
0
}
495
496
//===----------------------------------------------------------------------===//
497
//  raw_fd_ostream
498
//===----------------------------------------------------------------------===//
499
500
static int getFD(StringRef Filename, std::error_code &EC,
501
                 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
502
88.2k
                 sys::fs::OpenFlags Flags) {
503
88.2k
  assert((Access & sys::fs::FA_Write) &&
504
88.2k
         "Cannot make a raw_ostream from a read-only descriptor!");
505
88.2k
506
88.2k
  // Handle "-" as stdout. Note that when we do this, we consider ourself
507
88.2k
  // the owner of stdout and may set the "binary" flag globally based on Flags.
508
88.2k
  if (Filename == "-") {
509
67.3k
    EC = std::error_code();
510
67.3k
    // If user requested binary then put stdout into binary mode if
511
67.3k
    // possible.
512
67.3k
    if (!(Flags & sys::fs::OF_Text))
513
34.9k
      sys::ChangeStdoutToBinary();
514
67.3k
    return STDOUT_FILENO;
515
67.3k
  }
516
20.9k
517
20.9k
  int FD;
518
20.9k
  if (Access & sys::fs::FA_Read)
519
158
    EC = sys::fs::openFileForReadWrite(Filename, FD, Disp, Flags);
520
20.7k
  else
521
20.7k
    EC = sys::fs::openFileForWrite(Filename, FD, Disp, Flags);
522
20.9k
  if (EC)
523
372
    return -1;
524
20.5k
525
20.5k
  return FD;
526
20.5k
}
527
528
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC)
529
    : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
530
14
                     sys::fs::OF_None) {}
Unexecuted instantiation: llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&)
llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&)
Line
Count
Source
530
14
                     sys::fs::OF_None) {}
531
532
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
533
                               sys::fs::CreationDisposition Disp)
534
23
    : raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
Unexecuted instantiation: llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::CreationDisposition)
llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::CreationDisposition)
Line
Count
Source
534
23
    : raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
535
536
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
537
                               sys::fs::FileAccess Access)
538
    : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, Access,
539
158
                     sys::fs::OF_None) {}
Unexecuted instantiation: llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::FileAccess)
llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::FileAccess)
Line
Count
Source
539
158
                     sys::fs::OF_None) {}
540
541
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
542
                               sys::fs::OpenFlags Flags)
543
    : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
544
88.0k
                     Flags) {}
Unexecuted instantiation: llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::OpenFlags)
llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::OpenFlags)
Line
Count
Source
544
88.0k
                     Flags) {}
545
546
raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
547
                               sys::fs::CreationDisposition Disp,
548
                               sys::fs::FileAccess Access,
549
                               sys::fs::OpenFlags Flags)
550
88.2k
    : raw_fd_ostream(getFD(Filename, EC, Disp, Access, Flags), true) {}
Unexecuted instantiation: llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::CreationDisposition, llvm::sys::fs::FileAccess, llvm::sys::fs::OpenFlags)
llvm::raw_fd_ostream::raw_fd_ostream(llvm::StringRef, std::__1::error_code&, llvm::sys::fs::CreationDisposition, llvm::sys::fs::FileAccess, llvm::sys::fs::OpenFlags)
Line
Count
Source
550
88.2k
    : raw_fd_ostream(getFD(Filename, EC, Disp, Access, Flags), true) {}
551
552
/// FD is the file descriptor that this writes to.  If ShouldClose is true, this
553
/// closes the file when the stream is destroyed.
554
raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
555
246k
    : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) {
556
246k
  if (FD < 0 ) {
557
372
    ShouldClose = false;
558
372
    return;
559
372
  }
560
246k
561
246k
  // Do not attempt to close stdout or stderr. We used to try to maintain the
562
246k
  // property that tools that support writing file to stdout should not also
563
246k
  // write informational output to stdout, but in practice we were never able to
564
246k
  // maintain this invariant. Many features have been added to LLVM and clang
565
246k
  // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so
566
246k
  // users must simply be aware that mixed output and remarks is a possibility.
567
246k
  if (FD <= STDERR_FILENO)
568
246k
    
ShouldClose = false204k
;
569
246k
570
#ifdef _WIN32
571
  // Check if this is a console device. This is not equivalent to isatty.
572
  IsWindowsConsole =
573
      ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
574
#endif
575
576
246k
  // Get the starting position.
577
246k
  off_t loc = ::lseek(FD, 0, SEEK_CUR);
578
#ifdef _WIN32
579
  // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
580
  sys::fs::file_status Status;
581
  std::error_code EC = status(FD, Status);
582
  SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
583
#else
584
  SupportsSeeking = loc != (off_t)-1;
585
246k
#endif
586
246k
  if (!SupportsSeeking)
587
201k
    pos = 0;
588
44.5k
  else
589
44.5k
    pos = static_cast<uint64_t>(loc);
590
246k
}
591
592
246k
raw_fd_ostream::~raw_fd_ostream() {
593
246k
  if (FD >= 0) {
594
242k
    flush();
595
242k
    if (ShouldClose) {
596
37.7k
      if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
597
0
        error_detected(EC);
598
37.7k
    }
599
242k
  }
600
246k
601
#ifdef __MINGW32__
602
  // On mingw, global dtors should not call exit().
603
  // report_fatal_error() invokes exit(). We know report_fatal_error()
604
  // might not write messages to stderr when any errors were detected
605
  // on FD == 2.
606
  if (FD == 2) return;
607
#endif
608
609
246k
  // If there are any pending errors, report them now. Clients wishing
610
246k
  // to avoid report_fatal_error calls should check for errors with
611
246k
  // has_error() and clear the error flag with clear_error() before
612
246k
  // destructing raw_ostream objects which may have errors.
613
246k
  if (has_error())
614
1
    report_fatal_error("IO failure on output stream: " + error().message(),
615
1
                       /*gen_crash_diag=*/false);
616
246k
}
617
618
#if defined(_WIN32)
619
// The most reliable way to print unicode in a Windows console is with
620
// WriteConsoleW. To use that, first transcode from UTF-8 to UTF-16. This
621
// assumes that LLVM programs always print valid UTF-8 to the console. The data
622
// might not be UTF-8 for two major reasons:
623
// 1. The program is printing binary (-filetype=obj -o -), in which case it
624
// would have been gibberish anyway.
625
// 2. The program is printing text in a semi-ascii compatible codepage like
626
// shift-jis or cp1252.
627
//
628
// Most LLVM programs don't produce non-ascii text unless they are quoting
629
// user source input. A well-behaved LLVM program should either validate that
630
// the input is UTF-8 or transcode from the local codepage to UTF-8 before
631
// quoting it. If they don't, this may mess up the encoding, but this is still
632
// probably the best compromise we can make.
633
static bool write_console_impl(int FD, StringRef Data) {
634
  SmallVector<wchar_t, 256> WideText;
635
636
  // Fall back to ::write if it wasn't valid UTF-8.
637
  if (auto EC = sys::windows::UTF8ToUTF16(Data, WideText))
638
    return false;
639
640
  // On Windows 7 and earlier, WriteConsoleW has a low maximum amount of data
641
  // that can be written to the console at a time.
642
  size_t MaxWriteSize = WideText.size();
643
  if (!RunningWindows8OrGreater())
644
    MaxWriteSize = 32767;
645
646
  size_t WCharsWritten = 0;
647
  do {
648
    size_t WCharsToWrite =
649
        std::min(MaxWriteSize, WideText.size() - WCharsWritten);
650
    DWORD ActuallyWritten;
651
    bool Success =
652
        ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
653
                        WCharsToWrite, &ActuallyWritten,
654
                        /*Reserved=*/nullptr);
655
656
    // The most likely reason for WriteConsoleW to fail is that FD no longer
657
    // points to a console. Fall back to ::write. If this isn't the first loop
658
    // iteration, something is truly wrong.
659
    if (!Success)
660
      return false;
661
662
    WCharsWritten += ActuallyWritten;
663
  } while (WCharsWritten != WideText.size());
664
  return true;
665
}
666
#endif
667
668
30.9M
void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
669
30.9M
  assert(FD >= 0 && "File already closed.");
670
30.9M
  pos += Size;
671
30.9M
672
#if defined(_WIN32)
673
  // If this is a Windows console device, try re-encoding from UTF-8 to UTF-16
674
  // and using WriteConsoleW. If that fails, fall back to plain write().
675
  if (IsWindowsConsole)
676
    if (write_console_impl(FD, StringRef(Ptr, Size)))
677
      return;
678
#endif
679
680
30.9M
  // The maximum write size is limited to INT32_MAX. A write
681
30.9M
  // greater than SSIZE_MAX is implementation-defined in POSIX,
682
30.9M
  // and Windows _write requires 32 bit input.
683
30.9M
  size_t MaxWriteSize = INT32_MAX;
684
30.9M
685
#if defined(__linux__)
686
  // It is observed that Linux returns EINVAL for a very large write (>2G).
687
  // Make it a reasonably small value.
688
  MaxWriteSize = 1024 * 1024 * 1024;
689
#endif
690
691
30.9M
  do {
692
30.9M
    size_t ChunkSize = std::min(Size, MaxWriteSize);
693
30.9M
    ssize_t ret = ::write(FD, Ptr, ChunkSize);
694
30.9M
695
30.9M
    if (ret < 0) {
696
11
      // If it's a recoverable error, swallow it and retry the write.
697
11
      //
698
11
      // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
699
11
      // raw_ostream isn't designed to do non-blocking I/O. However, some
700
11
      // programs, such as old versions of bjam, have mistakenly used
701
11
      // O_NONBLOCK. For compatibility, emulate blocking semantics by
702
11
      // spinning until the write succeeds. If you don't want spinning,
703
11
      // don't use O_NONBLOCK file descriptors with raw_ostream.
704
11
      if (errno == EINTR || errno == EAGAIN
705
11
#ifdef EWOULDBLOCK
706
11
          || errno == EWOULDBLOCK
707
11
#endif
708
11
          )
709
11
        
continue0
;
710
11
711
11
      // Otherwise it's a non-recoverable error. Note it and quit.
712
11
      error_detected(std::error_code(errno, std::generic_category()));
713
11
      break;
714
11
    }
715
30.9M
716
30.9M
    // The write may have written some or all of the data. Update the
717
30.9M
    // size and buffer pointer to reflect the remainder that needs
718
30.9M
    // to be written. If there are no bytes left, we're done.
719
30.9M
    Ptr += ret;
720
30.9M
    Size -= ret;
721
30.9M
  } while (Size > 0);
722
30.9M
}
723
724
2.88k
void raw_fd_ostream::close() {
725
2.88k
  assert(ShouldClose);
726
2.88k
  ShouldClose = false;
727
2.88k
  flush();
728
2.88k
  if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
729
0
    error_detected(EC);
730
2.88k
  FD = -1;
731
2.88k
}
732
733
15.5k
uint64_t raw_fd_ostream::seek(uint64_t off) {
734
15.5k
  assert(SupportsSeeking && "Stream does not support seeking!");
735
15.5k
  flush();
736
#ifdef _WIN32
737
  pos = ::_lseeki64(FD, off, SEEK_SET);
738
#elif defined(HAVE_LSEEK64)
739
  pos = ::lseek64(FD, off, SEEK_SET);
740
#else
741
  pos = ::lseek(FD, off, SEEK_SET);
742
15.5k
#endif
743
15.5k
  if (pos == (uint64_t)-1)
744
0
    error_detected(std::error_code(errno, std::generic_category()));
745
15.5k
  return pos;
746
15.5k
}
747
748
void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
749
7.51k
                                 uint64_t Offset) {
750
7.51k
  uint64_t Pos = tell();
751
7.51k
  seek(Offset);
752
7.51k
  write(Ptr, Size);
753
7.51k
  seek(Pos);
754
7.51k
}
755
756
107k
size_t raw_fd_ostream::preferred_buffer_size() const {
757
#if defined(_WIN32)
758
  // Disable buffering for console devices. Console output is re-encoded from
759
  // UTF-8 to UTF-16 on Windows, and buffering it would require us to split the
760
  // buffer on a valid UTF-8 codepoint boundary. Terminal buffering is disabled
761
  // below on most other OSs, so do the same thing on Windows and avoid that
762
  // complexity.
763
  if (IsWindowsConsole)
764
    return 0;
765
  return raw_ostream::preferred_buffer_size();
766
#elif !defined(__minix)
767
  // Minix has no st_blksize.
768
107k
  assert(FD >= 0 && "File not yet open!");
769
107k
  struct stat statbuf;
770
107k
  if (fstat(FD, &statbuf) != 0)
771
0
    return 0;
772
107k
773
107k
  // If this is a terminal, don't use buffering. Line buffering
774
107k
  // would be a more traditional thing to do, but it's not worth
775
107k
  // the complexity.
776
107k
  if (S_ISCHR(statbuf.st_mode) && 
isatty(FD)1.02k
)
777
0
    return 0;
778
107k
  // Return the preferred block size.
779
107k
  return statbuf.st_blksize;
780
#else
781
  return raw_ostream::preferred_buffer_size();
782
#endif
783
}
784
785
raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
786
796
                                         bool bg) {
787
796
  if (sys::Process::ColorNeedsFlush())
788
0
    flush();
789
796
  const char *colorcode =
790
796
    (colors == SAVEDCOLOR) ? 
sys::Process::OutputBold(bg)110
791
796
    : 
sys::Process::OutputColor(colors, bold, bg)686
;
792
796
  if (colorcode) {
793
796
    size_t len = strlen(colorcode);
794
796
    write(colorcode, len);
795
796
    // don't account colors towards output characters
796
796
    pos -= len;
797
796
  }
798
796
  return *this;
799
796
}
800
801
789
raw_ostream &raw_fd_ostream::resetColor() {
802
789
  if (sys::Process::ColorNeedsFlush())
803
0
    flush();
804
789
  const char *colorcode = sys::Process::ResetColor();
805
789
  if (colorcode) {
806
789
    size_t len = strlen(colorcode);
807
789
    write(colorcode, len);
808
789
    // don't account colors towards output characters
809
789
    pos -= len;
810
789
  }
811
789
  return *this;
812
789
}
813
814
0
raw_ostream &raw_fd_ostream::reverseColor() {
815
0
  if (sys::Process::ColorNeedsFlush())
816
0
    flush();
817
0
  const char *colorcode = sys::Process::OutputReverse();
818
0
  if (colorcode) {
819
0
    size_t len = strlen(colorcode);
820
0
    write(colorcode, len);
821
0
    // don't account colors towards output characters
822
0
    pos -= len;
823
0
  }
824
0
  return *this;
825
0
}
826
827
8.17k
bool raw_fd_ostream::is_displayed() const {
828
8.17k
  return sys::Process::FileDescriptorIsDisplayed(FD);
829
8.17k
}
830
831
918k
bool raw_fd_ostream::has_colors() const {
832
918k
  return sys::Process::FileDescriptorHasColors(FD);
833
918k
}
834
835
0
void raw_fd_ostream::anchor() {}
836
837
//===----------------------------------------------------------------------===//
838
//  outs(), errs(), nulls()
839
//===----------------------------------------------------------------------===//
840
841
/// outs() - This returns a reference to a raw_ostream for standard output.
842
/// Use it like: outs() << "foo" << "bar";
843
1.42M
raw_ostream &llvm::outs() {
844
1.42M
  // Set buffer settings to model stdout behavior.
845
1.42M
  std::error_code EC;
846
1.42M
  static raw_fd_ostream S("-", EC, sys::fs::F_None);
847
1.42M
  assert(!EC);
848
1.42M
  return S;
849
1.42M
}
850
851
/// errs() - This returns a reference to a raw_ostream for standard error.
852
/// Use it like: errs() << "foo" << "bar";
853
727k
raw_ostream &llvm::errs() {
854
727k
  // Set standard error to be unbuffered by default.
855
727k
  static raw_fd_ostream S(STDERR_FILENO, false, true);
856
727k
  return S;
857
727k
}
858
859
/// nulls() - This returns a reference to a raw_ostream which discards output.
860
1.67M
raw_ostream &llvm::nulls() {
861
1.67M
  static raw_null_ostream S;
862
1.67M
  return S;
863
1.67M
}
864
865
//===----------------------------------------------------------------------===//
866
//  raw_string_ostream
867
//===----------------------------------------------------------------------===//
868
869
7.03M
raw_string_ostream::~raw_string_ostream() {
870
7.03M
  flush();
871
7.03M
}
872
873
7.53M
void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
874
7.53M
  OS.append(Ptr, Size);
875
7.53M
}
876
877
//===----------------------------------------------------------------------===//
878
//  raw_svector_ostream
879
//===----------------------------------------------------------------------===//
880
881
10.6M
uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
882
883
806M
void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
884
806M
  OS.append(Ptr, Ptr + Size);
885
806M
}
886
887
void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
888
6.51k
                                      uint64_t Offset) {
889
6.51k
  memcpy(OS.data() + Offset, Ptr, Size);
890
6.51k
}
891
892
//===----------------------------------------------------------------------===//
893
//  raw_null_ostream
894
//===----------------------------------------------------------------------===//
895
896
1.38M
raw_null_ostream::~raw_null_ostream() {
897
#ifndef NDEBUG
898
  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
899
  // with raw_null_ostream, but it's better to have raw_null_ostream follow
900
  // the rules than to change the rules just for raw_null_ostream.
901
  flush();
902
#endif
903
}
904
905
8
void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
906
8
}
907
908
0
uint64_t raw_null_ostream::current_pos() const {
909
0
  return 0;
910
0
}
911
912
void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
913
0
                                   uint64_t Offset) {}
914
915
0
void raw_pwrite_stream::anchor() {}
916
917
0
void buffer_ostream::anchor() {}