LLVM 23.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
18#include "llvm/ADT/StringRef.h"
21#include <cassert>
22#include <cstddef>
23#include <cstdint>
24#include <cstring>
25#include <optional>
26#include <string>
27#include <string_view>
28#include <system_error>
29#include <type_traits>
30
31namespace llvm {
32
33class Duration;
35class FormattedString;
36class FormattedNumber;
37class FormattedBytes;
38template <class T> class [[nodiscard]] Expected;
39
40namespace sys {
41namespace fs {
42enum FileAccess : unsigned;
43enum OpenFlags : unsigned;
44enum CreationDisposition : 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.
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
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;
132 static constexpr Colors RESET = Colors::RESET;
133
134 explicit raw_ostream(bool unbuffered = false,
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];
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.
308 raw_ostream &operator<<(function_ref<int(char *, size_t)> Snprint);
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 ///
336 /// FIXME: If Color == SAVEDCOLOR, Bold == false is currently ignored.
337 virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false,
338 bool BG = false);
339
340 /// Resets the colors to terminal defaults. Call this when you are done
341 /// outputting colored text, or before program exit.
342 virtual raw_ostream &resetColor();
343
344 /// Reverses the foreground and background colors.
345 virtual raw_ostream &reverseColor();
346
347 /// This function determines if this stream is connected to a "tty" or
348 /// "console" window. That is, the output would be displayed to the user
349 /// rather than being put on a pipe or stored in a file.
350 virtual bool is_displayed() const { return false; }
351
352 /// This function determines if this stream is displayed and supports colors.
353 /// The result is unaffected by calls to enable_color().
354 virtual bool has_colors() const { return is_displayed(); }
355
356 // Enable or disable colors. Once enable_colors(false) is called,
357 // changeColor() has no effect until enable_colors(true) is called.
358 virtual void enable_colors(bool enable) { ColorEnabled = enable; }
359
360 bool colors_enabled() const { return ColorEnabled; }
361
362 //===--------------------------------------------------------------------===//
363 // Subclass Interface
364 //===--------------------------------------------------------------------===//
365
366private:
367 /// The is the piece of the class that is implemented by subclasses. This
368 /// writes the \p Size bytes starting at
369 /// \p Ptr to the underlying stream.
370 ///
371 /// This function is guaranteed to only be called at a point at which it is
372 /// safe for the subclass to install a new buffer via SetBuffer.
373 ///
374 /// \param Ptr The start of the data to be written. For buffered streams this
375 /// is guaranteed to be the start of the buffer.
376 ///
377 /// \param Size The number of bytes to be written.
378 ///
379 /// \invariant { Size > 0 }
380 virtual void write_impl(const char *Ptr, size_t Size) = 0;
381
382 /// Return the current position within the stream, not counting the bytes
383 /// currently in the buffer.
384 virtual uint64_t current_pos() const = 0;
385
386protected:
387 /// Use the provided buffer as the raw_ostream buffer. This is intended for
388 /// use only by subclasses which can arrange for the output to go directly
389 /// into the desired output buffer, instead of being copied on each flush.
390 void SetBuffer(char *BufferStart, size_t Size) {
391 SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
392 }
393
394 /// Return an efficient buffer size for the underlying output mechanism.
395 virtual size_t preferred_buffer_size() const;
396
397 /// Return the beginning of the current stream buffer, or 0 if the stream is
398 /// unbuffered.
399 const char *getBufferStart() const { return OutBufStart; }
400
401 //===--------------------------------------------------------------------===//
402 // Private Interface
403 //===--------------------------------------------------------------------===//
404private:
405 /// Install the given buffer and mode.
406 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
407
408 /// Flush the current buffer, which is known to be non-empty. This outputs the
409 /// currently buffered data and resets the buffer to empty.
410 void flush_nonempty();
411
412 /// Copy data into the buffer. Size must not be greater than the number of
413 /// unused bytes in the buffer.
414 void copy_to_buffer(const char *Ptr, size_t Size);
415
416 /// Compute whether colors should be used and do the necessary work such as
417 /// flushing. The result is affected by calls to enable_color().
418 bool prepare_colors();
419
420 virtual void anchor();
421};
422
423/// Call the appropriate insertion operator, given an rvalue reference to a
424/// raw_ostream object and return a stream of the same type as the argument.
425template <typename OStream, typename T>
426std::enable_if_t<!std::is_reference_v<OStream> &&
427 std::is_base_of_v<raw_ostream, OStream>,
428 OStream &&>
429operator<<(OStream &&OS, const T &Value) {
430 OS << Value;
431 return std::move(OS);
432}
433
434/// An abstract base class for streams implementations that also support a
435/// pwrite operation. This is useful for code that can mostly stream out data,
436/// but needs to patch in a header that needs to know the output size.
438 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
439 void anchor() override;
440
441public:
442 explicit raw_pwrite_stream(bool Unbuffered = false,
444 : raw_ostream(Unbuffered, K) {}
445 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
446#ifndef NDEBUG
447 uint64_t Pos = tell();
448 // /dev/null always reports a pos of 0, so we cannot perform this check
449 // in that case.
450 if (Pos)
451 assert(Size + Offset <= Pos && "We don't support extending the stream");
452#endif
453 pwrite_impl(Ptr, Size, Offset);
454 }
455};
456
457//===----------------------------------------------------------------------===//
458// File Output Streams
459//===----------------------------------------------------------------------===//
460
461/// A raw_ostream that writes to a file descriptor.
462///
464 int FD;
465 bool ShouldClose;
466 bool SupportsSeeking = false;
467 bool IsRegularFile = false;
468 mutable std::optional<bool> HasColors;
469
470 /// Optional stream this stream is tied to. If this stream is written to, the
471 /// tied-to stream will be flushed first.
472 raw_ostream *TiedStream = nullptr;
473
474#ifdef _WIN32
475 /// True if this fd refers to a Windows console device. Mintty and other
476 /// terminal emulators are TTYs, but they are not consoles.
477 bool IsWindowsConsole = false;
478#endif
479
480 std::error_code EC;
481
482 uint64_t pos = 0;
483
484 /// See raw_ostream::write_impl.
485 void write_impl(const char *Ptr, size_t Size) override;
486
487 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
488
489 /// Return the current position within the stream, not counting the bytes
490 /// currently in the buffer.
491 uint64_t current_pos() const override { return pos; }
492
493 /// Determine an efficient buffer size.
494 size_t preferred_buffer_size() const override;
495
496 void anchor() override;
497
498protected:
499 /// Set the flag indicating that an output error has been encountered.
500 void error_detected(std::error_code EC) { this->EC = EC; }
501
502 /// Return the file descriptor.
503 int get_fd() const { return FD; }
504
505 // Update the file position by increasing \p Delta.
506 void inc_pos(uint64_t Delta) { pos += Delta; }
507
508public:
509 /// Open the specified file for writing. If an error occurs, information
510 /// about the error is put into EC, and the stream should be immediately
511 /// destroyed;
512 /// \p Flags allows optional flags to control how the file will be opened.
513 ///
514 /// As a special case, if Filename is "-", then the stream will use
515 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
516 /// descriptor.
517 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,
522 raw_fd_ostream(StringRef Filename, std::error_code &EC,
523 sys::fs::OpenFlags Flags);
524 raw_fd_ostream(StringRef Filename, std::error_code &EC,
526 sys::fs::OpenFlags Flags);
527
528 /// FD is the file descriptor that this writes to. If ShouldClose is true,
529 /// this closes the file when the stream is destroyed. If FD is for stdout or
530 /// stderr, it will not be closed.
531 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false,
532 OStreamKind K = OStreamKind::OK_OStream);
533
534 ~raw_fd_ostream() override;
535
536 /// Manually flush the stream and close the file. Note that this does not call
537 /// fsync.
538 void close();
539
540 bool supportsSeeking() const { return SupportsSeeking; }
541
542 bool isRegularFile() const { return IsRegularFile; }
543
544 /// Flushes the stream and repositions the underlying file descriptor position
545 /// to the offset specified from the beginning of the file.
546 uint64_t seek(uint64_t off);
547
548 bool is_displayed() const override;
549
550 bool has_colors() const override;
551
552 /// Tie this stream to the specified stream. Replaces any existing tied-to
553 /// stream. Specifying a nullptr unties the stream. This is intended for to
554 /// tie errs() to outs(), so that outs() is flushed whenever something is
555 /// written to errs(), preventing weird and hard-to-test output when stderr
556 /// is redirected to stdout.
557 void tie(raw_ostream *TieTo) { TiedStream = TieTo; }
558
559 std::error_code error() const { return EC; }
560
561 /// Return the value of the flag in this raw_fd_ostream indicating whether an
562 /// output error has been encountered.
563 /// This doesn't implicitly flush any pending output. Also, it doesn't
564 /// guarantee to detect all errors unless the stream has been closed.
565 bool has_error() const { return bool(EC); }
566
567 /// Set the flag read by has_error() to false. If the error flag is set at the
568 /// time when this raw_ostream's destructor is called, report_fatal_error is
569 /// called to report the error. Use clear_error() after handling the error to
570 /// avoid this behavior.
571 ///
572 /// "Errors should never pass silently.
573 /// Unless explicitly silenced."
574 /// - from The Zen of Python, by Tim Peters
575 ///
576 void clear_error() { EC = std::error_code(); }
577
578 /// Locks the underlying file.
579 ///
580 /// @returns RAII object that releases the lock upon leaving the scope, if the
581 /// locking was successful. Otherwise returns corresponding
582 /// error code.
583 ///
584 /// The function blocks the current thread until the lock become available or
585 /// error occurs.
586 ///
587 /// Possible use of this function may be as follows:
588 ///
589 /// @code{.cpp}
590 /// if (auto L = stream.lock()) {
591 /// // ... do action that require file to be locked.
592 /// } else {
593 /// handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) {
594 /// // ... handle lock error.
595 /// });
596 /// }
597 /// @endcode
598 [[nodiscard]] Expected<sys::fs::FileLocker> lock();
599
600 /// Tries to lock the underlying file within the specified period.
601 ///
602 /// @returns RAII object that releases the lock upon leaving the scope, if the
603 /// locking was successful. Otherwise returns corresponding
604 /// error code.
605 ///
606 /// It is used as @ref lock.
608 tryLockFor(Duration const &Timeout);
609};
610
611/// This returns a reference to a raw_fd_ostream for standard output. Use it
612/// like: outs() << "foo" << "bar";
613LLVM_ABI raw_fd_ostream &outs();
614
615/// This returns a reference to a raw_ostream for standard error.
616/// Use it like: errs() << "foo" << "bar";
617/// By default, the stream is tied to stdout to ensure stdout is flushed before
618/// stderr is written, to ensure the error messages are written in their
619/// expected place.
620LLVM_ABI raw_fd_ostream &errs();
621
622/// This returns a reference to a raw_ostream which simply discards output.
623LLVM_ABI raw_ostream &nulls();
624
625//===----------------------------------------------------------------------===//
626// File Streams
627//===----------------------------------------------------------------------===//
628
629/// A raw_ostream of a file for reading/writing/seeking.
630///
632public:
633 /// Open the specified file for reading/writing/seeking. If an error occurs,
634 /// information about the error is put into EC, and the stream should be
635 /// immediately destroyed.
636 LLVM_ABI raw_fd_stream(StringRef Filename, std::error_code &EC);
637
638 LLVM_ABI raw_fd_stream(int fd, bool shouldClose);
639
640 /// This reads the \p Size bytes into a buffer pointed by \p Ptr.
641 ///
642 /// \param Ptr The start of the buffer to hold data to be read.
643 ///
644 /// \param Size The number of bytes to be read.
645 ///
646 /// On success, the number of bytes read is returned, and the file position is
647 /// advanced by this number. On error, -1 is returned, use error() to get the
648 /// error code.
649 LLVM_ABI ssize_t read(char *Ptr, size_t Size);
650
651 /// Check if \p OS is a pointer of type raw_fd_stream*.
652 LLVM_ABI static bool classof(const raw_ostream *OS);
653};
654
655//===----------------------------------------------------------------------===//
656// Output Stream Adaptors
657//===----------------------------------------------------------------------===//
658
659/// A raw_ostream that writes to an std::string. This is a simple adaptor
660/// class. This class does not encounter output errors.
661/// raw_string_ostream operates without a buffer, delegating all memory
662/// management to the std::string. Thus the std::string is always up-to-date,
663/// may be used directly and there is no need to call flush().
665 std::string &OS;
666
667 /// See raw_ostream::write_impl.
668 void write_impl(const char *Ptr, size_t Size) override;
669
670 /// Return the current position within the stream, not counting the bytes
671 /// currently in the buffer.
672 uint64_t current_pos() const override { return OS.size(); }
673
674public:
675 explicit raw_string_ostream(std::string &O) : OS(O) {
677 }
678
679 /// Returns the string's reference. In most cases it is better to simply use
680 /// the underlying std::string directly.
681 /// TODO: Consider removing this API.
682 std::string &str() { return OS; }
683
684 void reserveExtraSpace(uint64_t ExtraSize) override {
685 OS.reserve(tell() + ExtraSize);
686 }
687};
688
689/// A raw_ostream that writes to an SmallVector or SmallString. This is a
690/// simple adaptor class. This class does not encounter output errors.
691/// raw_svector_ostream operates without a buffer, delegating all memory
692/// management to the SmallString. Thus the SmallString is always up-to-date,
693/// may be used directly and there is no need to call flush().
696
697 /// See raw_ostream::write_impl.
698 void write_impl(const char *Ptr, size_t Size) override;
699
700 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
701
702 /// Return the current position within the stream.
703 uint64_t current_pos() const override;
704
705public:
706 /// Construct a new raw_svector_ostream.
707 ///
708 /// \param O The vector to write to; this should generally have at least 128
709 /// bytes free to avoid any extraneous memory overhead.
712 OS(O) {
713 // FIXME: here and in a few other places, set directly to unbuffered in the
714 // ctor.
716 }
717
718 ~raw_svector_ostream() override = default;
719
720 void flush() = delete;
721
722 /// Return a StringRef for the vector contents.
723 StringRef str() const { return StringRef(OS.data(), OS.size()); }
725
726 void reserveExtraSpace(uint64_t ExtraSize) override {
727 OS.reserve(tell() + ExtraSize);
728 }
729
730 static bool classof(const raw_ostream *OS);
731};
732
733/// A raw_ostream that discards all output.
735 /// See raw_ostream::write_impl.
736 void write_impl(const char *Ptr, size_t size) override;
737 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
738
739 /// Return the current position within the stream, not counting the bytes
740 /// currently in the buffer.
741 uint64_t current_pos() const override;
742
743public:
744 explicit raw_null_ostream() : raw_pwrite_stream(/*Unbuffered=*/true) {}
745 ~raw_null_ostream() override;
746};
747
749 raw_ostream &OS;
751
752 void anchor() override;
753
754public:
756 ~buffer_ostream() override { OS << str(); }
757};
758
760 std::unique_ptr<raw_ostream> OS;
762
763 void anchor() override;
764
765public:
766 buffer_unique_ostream(std::unique_ptr<raw_ostream> OS)
767 : raw_svector_ostream(Buffer), OS(std::move(OS)) {
768 // Turn off buffering on OS, which we now own, to avoid allocating a buffer
769 // when the destructor writes only to be immediately flushed again.
770 this->OS->SetUnbuffered();
771 }
772 ~buffer_unique_ostream() override { *OS << str(); }
773};
774
775// Helper struct to add indentation to raw_ostream. Instead of
776// OS.indent(6) << "more stuff";
777// you can use
778// OS << indent(6) << "more stuff";
779// which has better ergonomics (and clang-formats better as well).
780//
781// If indentation is always in increments of a fixed value, you can use Scale
782// to set that value once. So indent(1, 2) will add 2 spaces and
783// indent(1,2) + 1 will add 4 spaces.
784struct indent {
785 // Indentation is represented as `NumIndents` steps of size `Scale` each.
786 unsigned NumIndents;
787 unsigned Scale;
788
789 explicit indent(unsigned NumIndents, unsigned Scale = 1)
791
792 // These arithmeric operators preserve scale.
793 void operator+=(unsigned N) { NumIndents += N; }
794 void operator-=(unsigned N) {
795 assert(NumIndents >= N && "Indentation underflow");
796 NumIndents -= N;
797 }
798 indent operator+(unsigned N) const { return indent(NumIndents + N, Scale); }
799 indent operator-(unsigned N) const {
800 assert(NumIndents >= N && "Indentation undeflow");
801 return indent(NumIndents - N, Scale);
802 }
803 indent &operator++() { // Prefix ++.
804 ++NumIndents;
805 return *this;
806 }
807 indent operator++(int) { // Postfix ++.
808 indent Old = *this;
809 ++NumIndents;
810 return Old;
811 }
812 indent &operator--() { // Prefix --.
813 assert(NumIndents >= 1);
814 --NumIndents;
815 return *this;
816 }
817 indent operator--(int) { // Postfix --.
818 indent Old = *this;
819 assert(NumIndents >= 1);
820 --NumIndents;
821 return Old;
822 }
823 indent &operator=(unsigned N) {
824 NumIndents = N;
825 return *this;
826 }
827};
828
829inline raw_ostream &operator<<(raw_ostream &OS, const indent &Indent) {
830 return OS.indent(Indent.NumIndents * Indent.Scale);
831}
832
833class Error;
834
835/// This helper creates an output stream and then passes it to \p Write.
836/// The stream created is based on the specified \p OutputFileName:
837/// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream
838/// for other names. For raw_fd_ostream instances, the stream writes to
839/// a temporary file. The final output file is atomically replaced with the
840/// temporary file after the \p Write function is finished.
841LLVM_ABI Error writeToOutput(StringRef OutputFileName,
842 std::function<Error(raw_ostream &)> Write);
843
844LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, std::nullopt_t);
845
846template <typename T, typename = decltype(std::declval<raw_ostream &>()
847 << std::declval<const T &>())>
848raw_ostream &operator<<(raw_ostream &OS, const std::optional<T> &O) {
849 if (O)
850 OS << *O;
851 else
852 OS << std::nullopt;
853 return OS;
854}
855
856} // end namespace llvm
857
858#endif // LLVM_SUPPORT_RAW_OSTREAM_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
DXIL Resource Access
static raw_ostream & operator<<(raw_ostream &OS, const MatchPosition &Pos)
#define T
static constexpr StringLiteral Filename
#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)
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:134
This is a helper class for left_justify, right_justify, and center_justify.
Definition Format.h:99
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
buffer_ostream(raw_ostream &OS)
~buffer_ostream() override
buffer_unique_ostream(std::unique_ptr< raw_ostream > OS)
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
bool has_error() const
Return the value of the flag in this raw_fd_ostream indicating whether an output error has been encou...
std::error_code error() const
void inc_pos(uint64_t Delta)
void tie(raw_ostream *TieTo)
Tie this stream to the specified stream.
bool supportsSeeking() const
void clear_error()
Set the flag read by has_error() to false.
bool isRegularFile() const
int get_fd() const
Return the file descriptor.
raw_fd_ostream(StringRef Filename, std::error_code &EC)
Open the specified file for writing.
void error_detected(std::error_code EC)
Set the flag indicating that an output error has been encountered.
static LLVM_ABI bool classof(const raw_ostream *OS)
Check if OS is a pointer of type raw_fd_stream*.
LLVM_ABI raw_fd_stream(StringRef Filename, std::error_code &EC)
Open the specified file for reading/writing/seeking.
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.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
raw_ostream & operator<<(unsigned char C)
raw_ostream(bool unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
uint64_t tell() const
tell - Return the current offset with the file.
static constexpr Colors WHITE
raw_ostream & operator<<(const std::string_view &Str)
static constexpr Colors BRIGHT_RED
void SetBufferSize(size_t Size)
Set the stream to be buffered, using the specified buffer size.
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.
size_t GetBufferSize() const
virtual raw_ostream & resetColor()
Resets the colors to terminal defaults.
static constexpr Colors BLACK
raw_ostream & write_uuid(const uuid_t UUID)
raw_ostream & operator<<(char C)
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.
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
static constexpr Colors RESET
void SetUnbuffered()
Set the stream to be unbuffered.
static constexpr Colors GREEN
virtual bool is_displayed() const
This function determines if this stream is connected to a "tty" or "console" window.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
static constexpr Colors BLUE
static constexpr Colors RED
static constexpr Colors MAGENTA
const char * getBufferStart() const
Return the beginning of the current stream buffer, or 0 if the stream is unbuffered.
raw_ostream & operator<<(signed char C)
static constexpr Colors SAVEDCOLOR
static constexpr Colors BRIGHT_MAGENTA
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
static constexpr Colors YELLOW
virtual void enable_colors(bool enable)
raw_ostream & operator<<(int N)
raw_ostream & operator<<(const char *Str)
raw_ostream(const raw_ostream &)=delete
void operator=(const raw_ostream &)=delete
static constexpr Colors BRIGHT_YELLOW
raw_ostream & operator<<(const SmallVectorImpl< char > &Str)
raw_ostream & operator<<(StringRef Str)
static constexpr Colors BRIGHT_CYAN
static constexpr Colors CYAN
virtual void reserveExtraSpace(uint64_t ExtraSize)
If possible, pre-allocate ExtraSize bytes for stream data.
size_t GetNumBytesInBuffer() const
raw_ostream & operator<<(const std::string &Str)
raw_ostream & operator<<(unsigned int N)
static constexpr Colors BRIGHT_BLACK
static constexpr Colors BRIGHT_WHITE
virtual bool has_colors() const
This function determines if this stream is displayed and supports colors.
static constexpr Colors BRIGHT_GREEN
static constexpr Colors BRIGHT_BLUE
OStreamKind get_kind() const
bool colors_enabled() const
raw_pwrite_stream(bool Unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
void pwrite(const char *Ptr, size_t Size, uint64_t Offset)
std::string & str()
Returns the string's reference.
void reserveExtraSpace(uint64_t ExtraSize) override
If possible, pre-allocate ExtraSize bytes for stream data.
raw_string_ostream(std::string &O)
~raw_svector_ostream() override=default
SmallVectorImpl< char > & buffer()
void reserveExtraSpace(uint64_t ExtraSize) override
If possible, pre-allocate ExtraSize bytes for stream data.
StringRef str() const
Return a StringRef for the vector contents.
raw_svector_ostream(SmallVectorImpl< char > &O)
Construct a new raw_svector_ostream.
RAII class that facilitates file locking.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:573
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:1669
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.
@ Timeout
Reached timeout while waiting for the owner to release the lock.
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)
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:1917
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:860
#define N
unsigned Scale
void operator+=(unsigned N)
void operator-=(unsigned N)
indent(unsigned NumIndents, unsigned Scale=1)
indent operator+(unsigned N) const
indent operator--(int)
indent operator++(int)
indent operator-(unsigned N) const
indent & operator--()
unsigned NumIndents
indent & operator=(unsigned N)
indent & operator++()