LLVM 22.0.0git
raw_ostream.h
Go to the documentation of this file.
1//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
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 file defines the raw_ostream class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_RAW_OSTREAM_H
14#define LLVM_SUPPORT_RAW_OSTREAM_H
15
17#include "llvm/ADT/StringRef.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23#include <cstring>
24#include <optional>
25#include <string>
26#include <string_view>
27#include <system_error>
28#include <type_traits>
29
30namespace llvm {
31
32class Duration;
33class formatv_object_base;
34class format_object_base;
35class FormattedString;
36class FormattedNumber;
37class FormattedBytes;
38template <class T> class [[nodiscard]] Expected;
39
40namespace sys {
41namespace fs {
42enum FileAccess : unsigned;
43enum OpenFlags : unsigned;
45class FileLocker;
46} // end namespace fs
47} // end namespace sys
48
49/// This class implements an extremely fast bulk output stream that can *only*
50/// output to a stream. It does not support seeking, reopening, rewinding, line
51/// buffered disciplines etc. It is a simple buffer that outputs
52/// a chunk at a time.
54public:
55 // Class kinds to support LLVM-style RTTI.
56 enum class OStreamKind {
57 OK_OStream,
58 OK_FDStream,
59 OK_SVecStream,
60 };
61
62private:
63 OStreamKind Kind;
64
65 /// The buffer is handled in such a way that the buffer is
66 /// uninitialized, unbuffered, or out of space when OutBufCur >=
67 /// OutBufEnd. Thus a single comparison suffices to determine if we
68 /// need to take the slow path to write a single character.
69 ///
70 /// The buffer is in one of three states:
71 /// 1. Unbuffered (BufferMode == Unbuffered)
72 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
73 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
74 /// OutBufEnd - OutBufStart >= 1).
75 ///
76 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
77 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
78 /// managed by the subclass.
79 ///
80 /// If a subclass installs an external buffer using SetBuffer then it can wait
81 /// for a \see write_impl() call to handle the data which has been put into
82 /// this buffer.
83 char *OutBufStart, *OutBufEnd, *OutBufCur;
84 bool ColorEnabled = false;
85
86 enum class BufferKind {
87 Unbuffered = 0,
88 InternalBuffer,
89 ExternalBuffer
90 } BufferMode;
91
92public:
93 // color order matches ANSI escape sequence, don't change
94 enum class Colors {
95 BLACK = 0,
96 RED,
97 GREEN,
98 YELLOW,
99 BLUE,
100 MAGENTA,
101 CYAN,
102 WHITE,
103 BRIGHT_BLACK,
104 BRIGHT_RED,
105 BRIGHT_GREEN,
106 BRIGHT_YELLOW,
107 BRIGHT_BLUE,
108 BRIGHT_MAGENTA,
109 BRIGHT_CYAN,
110 BRIGHT_WHITE,
111 SAVEDCOLOR,
112 RESET,
113 };
114
115 static constexpr Colors BLACK = Colors::BLACK;
116 static constexpr Colors RED = Colors::RED;
117 static constexpr Colors GREEN = Colors::GREEN;
118 static constexpr Colors YELLOW = Colors::YELLOW;
119 static constexpr Colors BLUE = Colors::BLUE;
120 static constexpr Colors MAGENTA = Colors::MAGENTA;
121 static constexpr Colors CYAN = Colors::CYAN;
122 static constexpr Colors WHITE = Colors::WHITE;
123 static constexpr Colors BRIGHT_BLACK = Colors::BRIGHT_BLACK;
124 static constexpr Colors BRIGHT_RED = Colors::BRIGHT_RED;
125 static constexpr Colors BRIGHT_GREEN = Colors::BRIGHT_GREEN;
126 static constexpr Colors BRIGHT_YELLOW = Colors::BRIGHT_YELLOW;
127 static constexpr Colors BRIGHT_BLUE = Colors::BRIGHT_BLUE;
128 static constexpr Colors BRIGHT_MAGENTA = Colors::BRIGHT_MAGENTA;
129 static constexpr Colors BRIGHT_CYAN = Colors::BRIGHT_CYAN;
130 static constexpr Colors BRIGHT_WHITE = Colors::BRIGHT_WHITE;
131 static constexpr Colors SAVEDCOLOR = Colors::SAVEDCOLOR;
132 static constexpr Colors RESET = Colors::RESET;
133
134 explicit raw_ostream(bool unbuffered = false,
135 OStreamKind K = OStreamKind::OK_OStream)
136 : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered
137 : BufferKind::InternalBuffer) {
138 // Start out ready to flush.
139 OutBufStart = OutBufEnd = OutBufCur = nullptr;
140 }
141
142 raw_ostream(const raw_ostream &) = delete;
143 void operator=(const raw_ostream &) = delete;
144
145 virtual ~raw_ostream();
146
147 /// tell - Return the current offset with the file.
148 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
149
150 OStreamKind get_kind() const { return Kind; }
151
152 //===--------------------------------------------------------------------===//
153 // Configuration Interface
154 //===--------------------------------------------------------------------===//
155
156 /// If possible, pre-allocate \p ExtraSize bytes for stream data.
157 /// i.e. it extends internal buffers to keep additional ExtraSize bytes.
158 /// So that the stream could keep at least tell() + ExtraSize bytes
159 /// without re-allocations. reserveExtraSpace() does not change
160 /// the size/data of the stream.
161 virtual void reserveExtraSpace(uint64_t ExtraSize) { (void)ExtraSize; }
162
163 /// Set the stream to be buffered, with an automatically determined buffer
164 /// size.
165 void SetBuffered();
166
167 /// Set the stream to be buffered, using the specified buffer size.
168 void SetBufferSize(size_t Size) {
169 flush();
170 SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer);
171 }
172
173 size_t GetBufferSize() const {
174 // If we're supposed to be buffered but haven't actually gotten around
175 // to allocating the buffer yet, return the value that would be used.
176 if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
177 return preferred_buffer_size();
178
179 // Otherwise just return the size of the allocated buffer.
180 return OutBufEnd - OutBufStart;
181 }
182
183 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
184 /// after every write. This routine will also flush the buffer immediately
185 /// when the stream is being set to unbuffered.
187 flush();
188 SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
189 }
190
191 size_t GetNumBytesInBuffer() const {
192 return OutBufCur - OutBufStart;
193 }
194
195 //===--------------------------------------------------------------------===//
196 // Data Output Interface
197 //===--------------------------------------------------------------------===//
198
199 void flush() {
200 if (OutBufCur != OutBufStart)
201 flush_nonempty();
202 }
203
205 if (OutBufCur >= OutBufEnd)
206 return write(C);
207 *OutBufCur++ = C;
208 return *this;
209 }
210
211 raw_ostream &operator<<(unsigned char C) {
212 if (OutBufCur >= OutBufEnd)
213 return write(C);
214 *OutBufCur++ = C;
215 return *this;
216 }
217
218 raw_ostream &operator<<(signed char C) {
219 if (OutBufCur >= OutBufEnd)
220 return write(C);
221 *OutBufCur++ = C;
222 return *this;
223 }
224
226 // Inline fast path, particularly for strings with a known length.
227 size_t Size = Str.size();
228
229 // Make sure we can use the fast path.
230 if (Size > (size_t)(OutBufEnd - OutBufCur))
231 return write(Str.data(), Size);
232
233 if (Size) {
234 memcpy(OutBufCur, Str.data(), Size);
235 OutBufCur += Size;
236 }
237 return *this;
238 }
239
240#if defined(__cpp_char8_t)
241 // When using `char8_t *` integers or pointers are written to the ostream
242 // instead of UTF-8 code as one might expect. This might lead to unexpected
243 // behavior, especially as `u8""` literals are of type `char8_t*` instead of
244 // type `char_t*` from C++20 onwards. Thus we disallow using them with
245 // raw_ostreams.
246 // If you have u8"" literals to stream, you can rewrite them as ordinary
247 // literals with escape sequences
248 // e.g. replace `u8"\u00a0"` by `"\xc2\xa0"`
249 // or use `reinterpret_cast`:
250 // e.g. replace `u8"\u00a0"` by `reinterpret_cast<const char *>(u8"\u00a0")`
251 raw_ostream &operator<<(const char8_t *Str) = delete;
252#endif
253
254 raw_ostream &operator<<(const char *Str) {
255 // Inline fast path, particularly for constant strings where a sufficiently
256 // smart compiler will simplify strlen.
257
258 return this->operator<<(StringRef(Str));
259 }
260
261 raw_ostream &operator<<(const std::string &Str) {
262 // Avoid the fast path, it would only increase code size for a marginal win.
263 return write(Str.data(), Str.length());
264 }
265
266 raw_ostream &operator<<(const std::string_view &Str) {
267 return write(Str.data(), Str.length());
268 }
269
271 return write(Str.data(), Str.size());
272 }
273
274 raw_ostream &operator<<(unsigned long N);
275 raw_ostream &operator<<(long N);
276 raw_ostream &operator<<(unsigned long long N);
277 raw_ostream &operator<<(long long N);
278 raw_ostream &operator<<(const void *P);
279
280 raw_ostream &operator<<(unsigned int N) {
281 return this->operator<<(static_cast<unsigned long>(N));
282 }
283
285 return this->operator<<(static_cast<long>(N));
286 }
287
288 raw_ostream &operator<<(double N);
289
290 /// Output \p N in hexadecimal, without any prefix or padding.
291 raw_ostream &write_hex(unsigned long long N);
292
293 // Change the foreground color of text.
294 raw_ostream &operator<<(Colors C);
295
296 /// Output a formatted UUID with dash separators.
297 using uuid_t = uint8_t[16];
298 raw_ostream &write_uuid(const uuid_t UUID);
299
300 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
301 /// satisfy llvm::isPrint into an escape sequence.
302 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
303
304 raw_ostream &write(unsigned char C);
305 raw_ostream &write(const char *Ptr, size_t Size);
306
307 // Formatted output, see the format() function in Support/Format.h.
309
310 // Formatted output, see the leftJustify() function in Support/Format.h.
312
313 // Formatted output, see the formatHex() function in Support/Format.h.
315
316 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
318
319 // Formatted output, see the format_bytes() function in Support/Format.h.
321
322 /// indent - Insert 'NumSpaces' spaces.
323 raw_ostream &indent(unsigned NumSpaces);
324
325 /// write_zeros - Insert 'NumZeros' nulls.
326 raw_ostream &write_zeros(unsigned NumZeros);
327
328 /// Changes the foreground color of text that will be output from this point
329 /// forward.
330 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
331 /// change only the bold attribute, and keep colors untouched
332 /// @param Bold bold/brighter text, default false
333 /// @param BG if true change the background, default: change foreground
334 /// @returns itself so it can be used within << invocations
335 virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false,
336 bool BG = false);
337
338 /// Resets the colors to terminal defaults. Call this when you are done
339 /// outputting colored text, or before program exit.
340 virtual raw_ostream &resetColor();
341
342 /// Reverses the foreground and background colors.
343 virtual raw_ostream &reverseColor();
344
345 /// This function determines if this stream is connected to a "tty" or
346 /// "console" window. That is, the output would be displayed to the user
347 /// rather than being put on a pipe or stored in a file.
348 virtual bool is_displayed() const { return false; }
349
350 /// This function determines if this stream is displayed and supports colors.
351 /// The result is unaffected by calls to enable_color().
352 virtual bool has_colors() const { return is_displayed(); }
353
354 // Enable or disable colors. Once enable_colors(false) is called,
355 // changeColor() has no effect until enable_colors(true) is called.
356 virtual void enable_colors(bool enable) { ColorEnabled = enable; }
357
358 bool colors_enabled() const { return ColorEnabled; }
359
360 //===--------------------------------------------------------------------===//
361 // Subclass Interface
362 //===--------------------------------------------------------------------===//
363
364private:
365 /// The is the piece of the class that is implemented by subclasses. This
366 /// writes the \p Size bytes starting at
367 /// \p Ptr to the underlying stream.
368 ///
369 /// This function is guaranteed to only be called at a point at which it is
370 /// safe for the subclass to install a new buffer via SetBuffer.
371 ///
372 /// \param Ptr The start of the data to be written. For buffered streams this
373 /// is guaranteed to be the start of the buffer.
374 ///
375 /// \param Size The number of bytes to be written.
376 ///
377 /// \invariant { Size > 0 }
378 virtual void write_impl(const char *Ptr, size_t Size) = 0;
379
380 /// Return the current position within the stream, not counting the bytes
381 /// currently in the buffer.
382 virtual uint64_t current_pos() const = 0;
383
384protected:
385 /// Use the provided buffer as the raw_ostream buffer. This is intended for
386 /// use only by subclasses which can arrange for the output to go directly
387 /// into the desired output buffer, instead of being copied on each flush.
388 void SetBuffer(char *BufferStart, size_t Size) {
389 SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
390 }
391
392 /// Return an efficient buffer size for the underlying output mechanism.
393 virtual size_t preferred_buffer_size() const;
394
395 /// Return the beginning of the current stream buffer, or 0 if the stream is
396 /// unbuffered.
397 const char *getBufferStart() const { return OutBufStart; }
398
399 //===--------------------------------------------------------------------===//
400 // Private Interface
401 //===--------------------------------------------------------------------===//
402private:
403 /// Install the given buffer and mode.
404 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
405
406 /// Flush the current buffer, which is known to be non-empty. This outputs the
407 /// currently buffered data and resets the buffer to empty.
408 void flush_nonempty();
409
410 /// Copy data into the buffer. Size must not be greater than the number of
411 /// unused bytes in the buffer.
412 void copy_to_buffer(const char *Ptr, size_t Size);
413
414 /// Compute whether colors should be used and do the necessary work such as
415 /// flushing. The result is affected by calls to enable_color().
416 bool prepare_colors();
417
418 virtual void anchor();
419};
420
421/// Call the appropriate insertion operator, given an rvalue reference to a
422/// raw_ostream object and return a stream of the same type as the argument.
423template <typename OStream, typename T>
424std::enable_if_t<!std::is_reference_v<OStream> &&
425 std::is_base_of_v<raw_ostream, OStream>,
426 OStream &&>
427operator<<(OStream &&OS, const T &Value) {
428 OS << Value;
429 return std::move(OS);
430}
431
432/// An abstract base class for streams implementations that also support a
433/// pwrite operation. This is useful for code that can mostly stream out data,
434/// but needs to patch in a header that needs to know the output size.
436 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
437 void anchor() override;
438
439public:
440 explicit raw_pwrite_stream(bool Unbuffered = false,
441 OStreamKind K = OStreamKind::OK_OStream)
442 : raw_ostream(Unbuffered, K) {}
443 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
444#ifndef NDEBUG
445 uint64_t Pos = tell();
446 // /dev/null always reports a pos of 0, so we cannot perform this check
447 // in that case.
448 if (Pos)
449 assert(Size + Offset <= Pos && "We don't support extending the stream");
450#endif
451 pwrite_impl(Ptr, Size, Offset);
452 }
453};
454
455//===----------------------------------------------------------------------===//
456// File Output Streams
457//===----------------------------------------------------------------------===//
458
459/// A raw_ostream that writes to a file descriptor.
460///
462 int FD;
463 bool ShouldClose;
464 bool SupportsSeeking = false;
465 bool IsRegularFile = false;
466 mutable std::optional<bool> HasColors;
467
468 /// Optional stream this stream is tied to. If this stream is written to, the
469 /// tied-to stream will be flushed first.
470 raw_ostream *TiedStream = nullptr;
471
472#ifdef _WIN32
473 /// True if this fd refers to a Windows console device. Mintty and other
474 /// terminal emulators are TTYs, but they are not consoles.
475 bool IsWindowsConsole = false;
476#endif
477
478 std::error_code EC;
479
480 uint64_t pos = 0;
481
482 /// See raw_ostream::write_impl.
483 void write_impl(const char *Ptr, size_t Size) override;
484
485 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
486
487 /// Return the current position within the stream, not counting the bytes
488 /// currently in the buffer.
489 uint64_t current_pos() const override { return pos; }
490
491 /// Determine an efficient buffer size.
492 size_t preferred_buffer_size() const override;
493
494 void anchor() override;
495
496protected:
497 /// Set the flag indicating that an output error has been encountered.
498 void error_detected(std::error_code EC) { this->EC = EC; }
499
500 /// Return the file descriptor.
501 int get_fd() const { return FD; }
502
503 // Update the file position by increasing \p Delta.
504 void inc_pos(uint64_t Delta) { pos += Delta; }
505
506public:
507 /// Open the specified file for writing. If an error occurs, information
508 /// about the error is put into EC, and the stream should be immediately
509 /// destroyed;
510 /// \p Flags allows optional flags to control how the file will be opened.
511 ///
512 /// As a special case, if Filename is "-", then the stream will use
513 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
514 /// descriptor.
515 raw_fd_ostream(StringRef Filename, std::error_code &EC);
516 raw_fd_ostream(StringRef Filename, std::error_code &EC,
518 raw_fd_ostream(StringRef Filename, std::error_code &EC,
520 raw_fd_ostream(StringRef Filename, std::error_code &EC,
521 sys::fs::OpenFlags Flags);
522 raw_fd_ostream(StringRef Filename, std::error_code &EC,
524 sys::fs::OpenFlags Flags);
525
526 /// FD is the file descriptor that this writes to. If ShouldClose is true,
527 /// this closes the file when the stream is destroyed. If FD is for stdout or
528 /// stderr, it will not be closed.
529 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false,
530 OStreamKind K = OStreamKind::OK_OStream);
531
532 ~raw_fd_ostream() override;
533
534 /// Manually flush the stream and close the file. Note that this does not call
535 /// fsync.
536 void close();
537
538 bool supportsSeeking() const { return SupportsSeeking; }
539
540 bool isRegularFile() const { return IsRegularFile; }
541
542 /// Flushes the stream and repositions the underlying file descriptor position
543 /// to the offset specified from the beginning of the file.
544 uint64_t seek(uint64_t off);
545
546 bool is_displayed() const override;
547
548 bool has_colors() const override;
549
550 /// Tie this stream to the specified stream. Replaces any existing tied-to
551 /// stream. Specifying a nullptr unties the stream. This is intended for to
552 /// tie errs() to outs(), so that outs() is flushed whenever something is
553 /// written to errs(), preventing weird and hard-to-test output when stderr
554 /// is redirected to stdout.
555 void tie(raw_ostream *TieTo) { TiedStream = TieTo; }
556
557 std::error_code error() const { return EC; }
558
559 /// Return the value of the flag in this raw_fd_ostream indicating whether an
560 /// output error has been encountered.
561 /// This doesn't implicitly flush any pending output. Also, it doesn't
562 /// guarantee to detect all errors unless the stream has been closed.
563 bool has_error() const { return bool(EC); }
564
565 /// Set the flag read by has_error() to false. If the error flag is set at the
566 /// time when this raw_ostream's destructor is called, report_fatal_error is
567 /// called to report the error. Use clear_error() after handling the error to
568 /// avoid this behavior.
569 ///
570 /// "Errors should never pass silently.
571 /// Unless explicitly silenced."
572 /// - from The Zen of Python, by Tim Peters
573 ///
574 void clear_error() { EC = std::error_code(); }
575
576 /// Locks the underlying file.
577 ///
578 /// @returns RAII object that releases the lock upon leaving the scope, if the
579 /// locking was successful. Otherwise returns corresponding
580 /// error code.
581 ///
582 /// The function blocks the current thread until the lock become available or
583 /// error occurs.
584 ///
585 /// Possible use of this function may be as follows:
586 ///
587 /// @code{.cpp}
588 /// if (auto L = stream.lock()) {
589 /// // ... do action that require file to be locked.
590 /// } else {
591 /// handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) {
592 /// // ... handle lock error.
593 /// });
594 /// }
595 /// @endcode
596 [[nodiscard]] Expected<sys::fs::FileLocker> lock();
597
598 /// Tries to lock the underlying file within the specified period.
599 ///
600 /// @returns RAII object that releases the lock upon leaving the scope, if the
601 /// locking was successful. Otherwise returns corresponding
602 /// error code.
603 ///
604 /// It is used as @ref lock.
606 tryLockFor(Duration const &Timeout);
607};
608
609/// This returns a reference to a raw_fd_ostream for standard output. Use it
610/// like: outs() << "foo" << "bar";
611LLVM_ABI raw_fd_ostream &outs();
612
613/// This returns a reference to a raw_ostream for standard error.
614/// Use it like: errs() << "foo" << "bar";
615/// By default, the stream is tied to stdout to ensure stdout is flushed before
616/// stderr is written, to ensure the error messages are written in their
617/// expected place.
618LLVM_ABI raw_fd_ostream &errs();
619
620/// This returns a reference to a raw_ostream which simply discards output.
621LLVM_ABI raw_ostream &nulls();
622
623//===----------------------------------------------------------------------===//
624// File Streams
625//===----------------------------------------------------------------------===//
626
627/// A raw_ostream of a file for reading/writing/seeking.
628///
630public:
631 /// Open the specified file for reading/writing/seeking. If an error occurs,
632 /// information about the error is put into EC, and the stream should be
633 /// immediately destroyed.
634 LLVM_ABI raw_fd_stream(StringRef Filename, std::error_code &EC);
635
636 LLVM_ABI raw_fd_stream(int fd, bool shouldClose);
637
638 /// This reads the \p Size bytes into a buffer pointed by \p Ptr.
639 ///
640 /// \param Ptr The start of the buffer to hold data to be read.
641 ///
642 /// \param Size The number of bytes to be read.
643 ///
644 /// On success, the number of bytes read is returned, and the file position is
645 /// advanced by this number. On error, -1 is returned, use error() to get the
646 /// error code.
647 LLVM_ABI ssize_t read(char *Ptr, size_t Size);
648
649 /// Check if \p OS is a pointer of type raw_fd_stream*.
650 LLVM_ABI static bool classof(const raw_ostream *OS);
651};
652
653//===----------------------------------------------------------------------===//
654// Output Stream Adaptors
655//===----------------------------------------------------------------------===//
656
657/// A raw_ostream that writes to an std::string. This is a simple adaptor
658/// class. This class does not encounter output errors.
659/// raw_string_ostream operates without a buffer, delegating all memory
660/// management to the std::string. Thus the std::string is always up-to-date,
661/// may be used directly and there is no need to call flush().
663 std::string &OS;
664
665 /// See raw_ostream::write_impl.
666 void write_impl(const char *Ptr, size_t Size) override;
667
668 /// Return the current position within the stream, not counting the bytes
669 /// currently in the buffer.
670 uint64_t current_pos() const override { return OS.size(); }
671
672public:
673 explicit raw_string_ostream(std::string &O) : OS(O) {
674 SetUnbuffered();
675 }
676
677 /// Returns the string's reference. In most cases it is better to simply use
678 /// the underlying std::string directly.
679 /// TODO: Consider removing this API.
680 std::string &str() { return OS; }
681
682 void reserveExtraSpace(uint64_t ExtraSize) override {
683 OS.reserve(tell() + ExtraSize);
684 }
685};
686
687/// A raw_ostream that writes to an SmallVector or SmallString. This is a
688/// simple adaptor class. This class does not encounter output errors.
689/// raw_svector_ostream operates without a buffer, delegating all memory
690/// management to the SmallString. Thus the SmallString is always up-to-date,
691/// may be used directly and there is no need to call flush().
694
695 /// See raw_ostream::write_impl.
696 void write_impl(const char *Ptr, size_t Size) override;
697
698 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
699
700 /// Return the current position within the stream.
701 uint64_t current_pos() const override;
702
703public:
704 /// Construct a new raw_svector_ostream.
705 ///
706 /// \param O The vector to write to; this should generally have at least 128
707 /// bytes free to avoid any extraneous memory overhead.
710 OS(O) {
711 // FIXME: here and in a few other places, set directly to unbuffered in the
712 // ctor.
713 SetUnbuffered();
714 }
715
716 ~raw_svector_ostream() override = default;
717
718 void flush() = delete;
719
720 /// Return a StringRef for the vector contents.
721 StringRef str() const { return StringRef(OS.data(), OS.size()); }
723
724 void reserveExtraSpace(uint64_t ExtraSize) override {
725 OS.reserve(tell() + ExtraSize);
726 }
727
728 static bool classof(const raw_ostream *OS);
729};
730
731/// A raw_ostream that discards all output.
733 /// See raw_ostream::write_impl.
734 void write_impl(const char *Ptr, size_t size) override;
735 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
736
737 /// Return the current position within the stream, not counting the bytes
738 /// currently in the buffer.
739 uint64_t current_pos() const override;
740
741public:
742 explicit raw_null_ostream() = default;
743 ~raw_null_ostream() override;
744};
745
749
750 void anchor() override;
751
752public:
754 ~buffer_ostream() override { OS << str(); }
755};
756
758 std::unique_ptr<raw_ostream> OS;
760
761 void anchor() override;
762
763public:
764 buffer_unique_ostream(std::unique_ptr<raw_ostream> OS)
765 : raw_svector_ostream(Buffer), OS(std::move(OS)) {
766 // Turn off buffering on OS, which we now own, to avoid allocating a buffer
767 // when the destructor writes only to be immediately flushed again.
768 this->OS->SetUnbuffered();
769 }
770 ~buffer_unique_ostream() override { *OS << str(); }
771};
772
773// Helper struct to add indentation to raw_ostream. Instead of
774// OS.indent(6) << "more stuff";
775// you can use
776// OS << indent(6) << "more stuff";
777// which has better ergonomics (and clang-formats better as well).
778//
779// If indentation is always in increments of a fixed value, you can use Scale
780// to set that value once. So indent(1, 2) will add 2 spaces and
781// indent(1,2) + 1 will add 4 spaces.
782struct indent {
783 // Indentation is represented as `NumIndents` steps of size `Scale` each.
784 unsigned NumIndents;
785 unsigned Scale;
786
787 explicit indent(unsigned NumIndents, unsigned Scale = 1)
789
790 // These arithmeric operators preserve scale.
791 void operator+=(unsigned N) { NumIndents += N; }
792 void operator-=(unsigned N) {
793 assert(NumIndents >= N && "Indentation underflow");
794 NumIndents -= N;
795 }
796 indent operator+(unsigned N) const { return indent(NumIndents + N, Scale); }
797 indent operator-(unsigned N) const {
798 assert(NumIndents >= N && "Indentation undeflow");
799 return indent(NumIndents - N, Scale);
800 }
801 indent &operator++() { // Prefix ++.
802 ++NumIndents;
803 return *this;
804 }
805 indent operator++(int) { // Postfix ++.
806 indent Old = *this;
807 ++NumIndents;
808 return Old;
809 }
810 indent &operator--() { // Prefix --.
811 assert(NumIndents >= 1);
812 --NumIndents;
813 return *this;
814 }
815 indent operator--(int) { // Postfix --.
816 indent Old = *this;
817 assert(NumIndents >= 1);
818 --NumIndents;
819 return Old;
820 }
821 indent &operator=(unsigned N) {
822 NumIndents = N;
823 return *this;
824 }
825};
826
827inline raw_ostream &operator<<(raw_ostream &OS, const indent &Indent) {
828 return OS.indent(Indent.NumIndents * Indent.Scale);
829}
830
831class Error;
832
833/// This helper creates an output stream and then passes it to \p Write.
834/// The stream created is based on the specified \p OutputFileName:
835/// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream
836/// for other names. For raw_fd_ostream instances, the stream writes to
837/// a temporary file. The final output file is atomically replaced with the
838/// temporary file after the \p Write function is finished.
839LLVM_ABI Error writeToOutput(StringRef OutputFileName,
840 std::function<Error(raw_ostream &)> Write);
841
842LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, std::nullopt_t);
843
844template <typename T, typename = decltype(std::declval<raw_ostream &>()
845 << std::declval<const T &>())>
846raw_ostream &operator<<(raw_ostream &OS, const std::optional<T> &O) {
847 if (O)
848 OS << *O;
849 else
850 OS << std::nullopt;
851 return OS;
852}
853
854} // end namespace llvm
855
856#endif // LLVM_SUPPORT_RAW_OSTREAM_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
raw_ostream & operator<<(raw_ostream &OS, const binary_le_impl< value_type > &BLE)
#define LLVM_ABI
Definition: Compiler.h:213
DXIL Resource Access
uint64_t Size
uint64_t Offset
Definition: ELF_riscv.cpp:478
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static void write(bool isBE, void *P, T V)
raw_pwrite_stream & OS
This file defines the SmallVector class.
std::pair< llvm::MachO::Target, std::string > UUID
Tagged union holding either a T or a Error.
Definition: Error.h:485
This is a helper class used for format_hex() and format_decimal().
Definition: Format.h:166
This is a helper class for left_justify, right_justify, and center_justify.
Definition: Format.h:131
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
buffer_ostream(raw_ostream &OS)
Definition: raw_ostream.h:753
~buffer_ostream() override
Definition: raw_ostream.h:754
buffer_unique_ostream(std::unique_ptr< raw_ostream > OS)
Definition: raw_ostream.h:764
This is a helper class used for handling formatted output.
Definition: Format.h:40
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:461
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
Definition: raw_ostream.h:563
std::error_code error() const
Definition: raw_ostream.h:557
void inc_pos(uint64_t Delta)
Definition: raw_ostream.h:504
void tie(raw_ostream *TieTo)
Tie this stream to the specified stream.
Definition: raw_ostream.h:555
bool supportsSeeking() const
Definition: raw_ostream.h:538
void clear_error()
Set the flag read by has_error() to false.
Definition: raw_ostream.h:574
bool isRegularFile() const
Definition: raw_ostream.h:540
int get_fd() const
Return the file descriptor.
Definition: raw_ostream.h:501
void error_detected(std::error_code EC)
Set the flag indicating that an output error has been encountered.
Definition: raw_ostream.h:498
A raw_ostream of a file for reading/writing/seeking.
Definition: raw_ostream.h:629
static LLVM_ABI bool classof(const raw_ostream *OS)
Check if OS is a pointer of type raw_fd_stream*.
LLVM_ABI ssize_t read(char *Ptr, size_t Size)
This reads the Size bytes into a buffer pointed by Ptr.
A raw_ostream that discards all output.
Definition: raw_ostream.h:732
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
raw_ostream & operator<<(unsigned char C)
Definition: raw_ostream.h:211
raw_ostream(bool unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
Definition: raw_ostream.h:134
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:148
raw_ostream & operator<<(const std::string_view &Str)
Definition: raw_ostream.h:266
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
Definition: raw_ostream.h:168
size_t GetBufferSize() const
Definition: raw_ostream.h:173
raw_ostream & operator<<(char C)
Definition: raw_ostream.h:204
void SetBuffer(char *BufferStart, size_t Size)
Use the provided buffer as the raw_ostream buffer.
Definition: raw_ostream.h:388
void SetUnbuffered()
Set the stream to be unbuffered.
Definition: raw_ostream.h:186
virtual bool is_displayed() const
This function determines if this stream is connected to a "tty" or "console" window.
Definition: raw_ostream.h:348
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
const char * getBufferStart() const
Return the beginning of the current stream buffer, or 0 if the stream is unbuffered.
Definition: raw_ostream.h:397
raw_ostream & operator<<(signed char C)
Definition: raw_ostream.h:218
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
Definition: raw_ostream.h:297
virtual void enable_colors(bool enable)
Definition: raw_ostream.h:356
raw_ostream & operator<<(int N)
Definition: raw_ostream.h:284
raw_ostream & operator<<(const char *Str)
Definition: raw_ostream.h:254
raw_ostream(const raw_ostream &)=delete
void operator=(const raw_ostream &)=delete
raw_ostream & operator<<(const SmallVectorImpl< char > &Str)
Definition: raw_ostream.h:270
raw_ostream & operator<<(StringRef Str)
Definition: raw_ostream.h:225
virtual void reserveExtraSpace(uint64_t ExtraSize)
If possible, pre-allocate ExtraSize bytes for stream data.
Definition: raw_ostream.h:161
size_t GetNumBytesInBuffer() const
Definition: raw_ostream.h:191
raw_ostream & operator<<(const std::string &Str)
Definition: raw_ostream.h:261
raw_ostream & operator<<(unsigned int N)
Definition: raw_ostream.h:280
virtual bool has_colors() const
This function determines if this stream is displayed and supports colors.
Definition: raw_ostream.h:352
OStreamKind get_kind() const
Definition: raw_ostream.h:150
bool colors_enabled() const
Definition: raw_ostream.h:358
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:435
raw_pwrite_stream(bool Unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
Definition: raw_ostream.h:440
void pwrite(const char *Ptr, size_t Size, uint64_t Offset)
Definition: raw_ostream.h:443
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:680
void reserveExtraSpace(uint64_t ExtraSize) override
If possible, pre-allocate ExtraSize bytes for stream data.
Definition: raw_ostream.h:682
raw_string_ostream(std::string &O)
Definition: raw_ostream.h:673
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:692
~raw_svector_ostream() override=default
SmallVectorImpl< char > & buffer()
Definition: raw_ostream.h:722
void reserveExtraSpace(uint64_t ExtraSize) override
If possible, pre-allocate ExtraSize bytes for stream data.
Definition: raw_ostream.h:724
StringRef str() const
Return a StringRef for the vector contents.
Definition: raw_ostream.h:721
raw_svector_ostream(SmallVectorImpl< char > &O)
Construct a new raw_svector_ostream.
Definition: raw_ostream.h:708
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1702
@ Write
Definition: CodeGenData.h:109
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
LLVM_ABI Error writeToOutput(StringRef OutputFileName, std::function< Error(raw_ostream &)> Write)
This helper creates an output stream and then passes it to Write.
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:312
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
#define N
unsigned Scale
Definition: raw_ostream.h:785
void operator+=(unsigned N)
Definition: raw_ostream.h:791
void operator-=(unsigned N)
Definition: raw_ostream.h:792
indent(unsigned NumIndents, unsigned Scale=1)
Definition: raw_ostream.h:787
indent operator+(unsigned N) const
Definition: raw_ostream.h:796
indent operator--(int)
Definition: raw_ostream.h:815
indent operator++(int)
Definition: raw_ostream.h:805
indent operator-(unsigned N) const
Definition: raw_ostream.h:797
indent & operator--()
Definition: raw_ostream.h:810
unsigned NumIndents
Definition: raw_ostream.h:784
indent & operator=(unsigned N)
Definition: raw_ostream.h:821
indent & operator++()
Definition: raw_ostream.h:801