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