LLVM 20.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 {
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.
55enum classOStreamKind {
59 };
60
61private:
62OStreamKind 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.
82char *OutBufStart, *OutBufEnd, *OutBufCur;
83bool ColorEnabled = false;
84
85enum class BufferKind {
86 Unbuffered = 0,
87 InternalBuffer,
88 ExternalBuffer
89 } BufferMode;
90
91public:
92// color order matches ANSI escape sequence, don't change
93enum classColors {
94BLACK = 0,
95RED,
96GREEN,
97YELLOW,
98BLUE,
100CYAN,
101WHITE,
111RESET,
112 };
113
114staticconstexprColorsBLACK = Colors::BLACK;
115staticconstexprColorsRED = Colors::RED;
116staticconstexprColorsGREEN = Colors::GREEN;
118staticconstexprColorsBLUE = Colors::BLUE;
120staticconstexprColorsCYAN = Colors::CYAN;
121staticconstexprColorsWHITE = Colors::WHITE;
131staticconstexprColorsRESET = Colors::RESET;
132
133explicitraw_ostream(bool unbuffered = false,
135 : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered
136 : BufferKind::InternalBuffer) {
137// Start out ready to flush.
138 OutBufStart = OutBufEnd = OutBufCur = nullptr;
139 }
140
141raw_ostream(constraw_ostream &) = delete;
142voidoperator=(constraw_ostream &) = delete;
143
144virtual~raw_ostream();
145
146 /// tell - Return the current offset with the file.
147uint64_ttell() const { return current_pos() + GetNumBytesInBuffer(); }
148
149OStreamKindget_kind() const { return Kind; }
150
151//===--------------------------------------------------------------------===//
152// Configuration Interface
153//===--------------------------------------------------------------------===//
154
155 /// If possible, pre-allocate \p ExtraSize bytes for stream data.
156 /// i.e. it extends internal buffers to keep additional ExtraSize bytes.
157 /// So that the stream could keep at least tell() + ExtraSize bytes
158 /// without re-allocations. reserveExtraSpace() does not change
159 /// the size/data of the stream.
160virtualvoidreserveExtraSpace(uint64_t ExtraSize) { (void)ExtraSize; }
161
162 /// Set the stream to be buffered, with an automatically determined buffer
163 /// size.
164voidSetBuffered();
165
166 /// Set the stream to be buffered, using the specified buffer size.
167voidSetBufferSize(size_tSize) {
168flush();
169 SetBufferAndMode(newchar[Size], Size, BufferKind::InternalBuffer);
170 }
171
172size_tGetBufferSize() const {
173// If we're supposed to be buffered but haven't actually gotten around
174// to allocating the buffer yet, return the value that would be used.
175if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
177
178// Otherwise just return the size of the allocated buffer.
179return OutBufEnd - OutBufStart;
180 }
181
182 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
183 /// after every write. This routine will also flush the buffer immediately
184 /// when the stream is being set to unbuffered.
186flush();
187 SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
188 }
189
190size_tGetNumBytesInBuffer() const {
191return OutBufCur - OutBufStart;
192 }
193
194//===--------------------------------------------------------------------===//
195// Data Output Interface
196//===--------------------------------------------------------------------===//
197
198voidflush() {
199if (OutBufCur != OutBufStart)
200 flush_nonempty();
201 }
202
204if (OutBufCur >= OutBufEnd)
205returnwrite(C);
206 *OutBufCur++ = C;
207return *this;
208 }
209
210raw_ostream &operator<<(unsignedcharC) {
211if (OutBufCur >= OutBufEnd)
212returnwrite(C);
213 *OutBufCur++ = C;
214return *this;
215 }
216
218if (OutBufCur >= OutBufEnd)
219returnwrite(C);
220 *OutBufCur++ = C;
221return *this;
222 }
223
225// Inline fast path, particularly for strings with a known length.
226size_tSize = Str.size();
227
228// Make sure we can use the fast path.
229if (Size > (size_t)(OutBufEnd - OutBufCur))
230returnwrite(Str.data(), Size);
231
232if (Size) {
233 memcpy(OutBufCur, Str.data(), Size);
234 OutBufCur += Size;
235 }
236return *this;
237 }
238
239#if defined(__cpp_char8_t)
240// When using `char8_t *` integers or pointers are written to the ostream
241// instead of UTF-8 code as one might expect. This might lead to unexpected
242// behavior, especially as `u8""` literals are of type `char8_t*` instead of
243// type `char_t*` from C++20 onwards. Thus we disallow using them with
244// raw_ostreams.
245// If you have u8"" literals to stream, you can rewrite them as ordinary
246// literals with escape sequences
247// e.g. replace `u8"\u00a0"` by `"\xc2\xa0"`
248// or use `reinterpret_cast`:
249// e.g. replace `u8"\u00a0"` by `reinterpret_cast<const char *>(u8"\u00a0")`
250raw_ostream &operator<<(constchar8_t *Str) = delete;
251#endif
252
253raw_ostream &operator<<(constchar *Str) {
254// Inline fast path, particularly for constant strings where a sufficiently
255// smart compiler will simplify strlen.
256
257return this->operator<<(StringRef(Str));
258 }
259
260raw_ostream &operator<<(const std::string &Str) {
261// Avoid the fast path, it would only increase code size for a marginal win.
262returnwrite(Str.data(), Str.length());
263 }
264
265raw_ostream &operator<<(const std::string_view &Str) {
266returnwrite(Str.data(), Str.length());
267 }
268
270returnwrite(Str.data(), Str.size());
271 }
272
273raw_ostream &operator<<(unsignedlongN);
275raw_ostream &operator<<(unsignedlonglongN);
276raw_ostream &operator<<(longlongN);
277raw_ostream &operator<<(constvoid *P);
278
280return this->operator<<(static_cast<unsigned long>(N));
281 }
282
284return this->operator<<(static_cast<long>(N));
285 }
286
287raw_ostream &operator<<(doubleN);
288
289 /// Output \p N in hexadecimal, without any prefix or padding.
290raw_ostream &write_hex(unsignedlonglongN);
291
292// Change the foreground color of text.
294
295 /// Output a formatted UUID with dash separators.
296using uuid_t = uint8_t[16];
298
299 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
300 /// satisfy llvm::isPrint into an escape sequence.
301raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
302
303raw_ostream &write(unsignedcharC);
304raw_ostream &write(constchar *Ptr, size_tSize);
305
306// Formatted output, see the format() function in Support/Format.h.
308
309// Formatted output, see the leftJustify() function in Support/Format.h.
311
312// Formatted output, see the formatHex() function in Support/Format.h.
314
315// Formatted output, see the formatv() function in Support/FormatVariadic.h.
317
318// Formatted output, see the format_bytes() function in Support/Format.h.
320
321 /// indent - Insert 'NumSpaces' spaces.
322raw_ostream &indent(unsigned NumSpaces);
323
324 /// write_zeros - Insert 'NumZeros' nulls.
325raw_ostream &write_zeros(unsigned NumZeros);
326
327 /// Changes the foreground color of text that will be output from this point
328 /// forward.
329 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
330 /// change only the bold attribute, and keep colors untouched
331 /// @param Bold bold/brighter text, default false
332 /// @param BG if true change the background, default: change foreground
333 /// @returns itself so it can be used within << invocations
334virtualraw_ostream &changeColor(enumColors Color, bool Bold = false,
335bool BG = false);
336
337 /// Resets the colors to terminal defaults. Call this when you are done
338 /// outputting colored text, or before program exit.
339virtualraw_ostream &resetColor();
340
341 /// Reverses the foreground and background colors.
342virtualraw_ostream &reverseColor();
343
344 /// This function determines if this stream is connected to a "tty" or
345 /// "console" window. That is, the output would be displayed to the user
346 /// rather than being put on a pipe or stored in a file.
347virtualboolis_displayed() const { returnfalse; }
348
349 /// This function determines if this stream is displayed and supports colors.
350 /// The result is unaffected by calls to enable_color().
351virtualboolhas_colors() const { returnis_displayed(); }
352
353// Enable or disable colors. Once enable_colors(false) is called,
354// changeColor() has no effect until enable_colors(true) is called.
355virtualvoidenable_colors(bool enable) { ColorEnabled = enable; }
356
357boolcolors_enabled() const { return ColorEnabled; }
358
359//===--------------------------------------------------------------------===//
360// Subclass Interface
361//===--------------------------------------------------------------------===//
362
363private:
364 /// The is the piece of the class that is implemented by subclasses. This
365 /// writes the \p Size bytes starting at
366 /// \p Ptr to the underlying stream.
367 ///
368 /// This function is guaranteed to only be called at a point at which it is
369 /// safe for the subclass to install a new buffer via SetBuffer.
370 ///
371 /// \param Ptr The start of the data to be written. For buffered streams this
372 /// is guaranteed to be the start of the buffer.
373 ///
374 /// \param Size The number of bytes to be written.
375 ///
376 /// \invariant { Size > 0 }
377virtualvoid write_impl(constchar *Ptr, size_tSize) = 0;
378
379 /// Return the current position within the stream, not counting the bytes
380 /// currently in the buffer.
381virtualuint64_t current_pos() const = 0;
382
383protected:
384 /// Use the provided buffer as the raw_ostream buffer. This is intended for
385 /// use only by subclasses which can arrange for the output to go directly
386 /// into the desired output buffer, instead of being copied on each flush.
387voidSetBuffer(char *BufferStart, size_tSize) {
388 SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
389 }
390
391 /// Return an efficient buffer size for the underlying output mechanism.
392virtualsize_tpreferred_buffer_size() const;
393
394 /// Return the beginning of the current stream buffer, or 0 if the stream is
395 /// unbuffered.
396constchar *getBufferStart() const { return OutBufStart; }
397
398//===--------------------------------------------------------------------===//
399// Private Interface
400//===--------------------------------------------------------------------===//
401private:
402 /// Install the given buffer and mode.
403void SetBufferAndMode(char *BufferStart, size_tSize, BufferKind Mode);
404
405 /// Flush the current buffer, which is known to be non-empty. This outputs the
406 /// currently buffered data and resets the buffer to empty.
407void flush_nonempty();
408
409 /// Copy data into the buffer. Size must not be greater than the number of
410 /// unused bytes in the buffer.
411void copy_to_buffer(constchar *Ptr, size_tSize);
412
413 /// Compute whether colors should be used and do the necessary work such as
414 /// flushing. The result is affected by calls to enable_color().
415bool prepare_colors();
416
417virtualvoid anchor();
418};
419
420/// Call the appropriate insertion operator, given an rvalue reference to a
421/// raw_ostream object and return a stream of the same type as the argument.
422template <typename OStream, typename T>
423std::enable_if_t<!std::is_reference_v<OStream> &&
424 std::is_base_of_v<raw_ostream, OStream>,
425 OStream &&>
426operator<<(OStream &&OS, constT &Value) {
427OS << Value;
428return std::move(OS);
429}
430
431/// An abstract base class for streams implementations that also support a
432/// pwrite operation. This is useful for code that can mostly stream out data,
433/// but needs to patch in a header that needs to know the output size.
435virtualvoid pwrite_impl(constchar *Ptr, size_tSize, uint64_tOffset) = 0;
436void anchor() override;
437
438public:
439explicitraw_pwrite_stream(bool Unbuffered = false,
441 : raw_ostream(Unbuffered, K) {}
442voidpwrite(constchar *Ptr, size_tSize, uint64_tOffset) {
443#ifndef NDEBUG
444uint64_t Pos = tell();
445// /dev/null always reports a pos of 0, so we cannot perform this check
446// in that case.
447if (Pos)
448assert(Size + Offset <= Pos && "We don't support extending the stream");
449#endif
450 pwrite_impl(Ptr, Size, Offset);
451 }
452};
453
454//===----------------------------------------------------------------------===//
455// File Output Streams
456//===----------------------------------------------------------------------===//
457
458/// A raw_ostream that writes to a file descriptor.
459///
461int FD;
462bool ShouldClose;
463bool SupportsSeeking = false;
464bool IsRegularFile = false;
465mutable std::optional<bool> HasColors;
466
467 /// Optional stream this stream is tied to. If this stream is written to, the
468 /// tied-to stream will be flushed first.
469raw_ostream *TiedStream = nullptr;
470
471#ifdef _WIN32
472 /// True if this fd refers to a Windows console device. Mintty and other
473 /// terminal emulators are TTYs, but they are not consoles.
474bool IsWindowsConsole = false;
475#endif
476
477 std::error_code EC;
478
479uint64_t pos = 0;
480
481 /// See raw_ostream::write_impl.
482void write_impl(constchar *Ptr, size_tSize) override;
483
484void pwrite_impl(constchar *Ptr, size_tSize, uint64_tOffset) override;
485
486 /// Return the current position within the stream, not counting the bytes
487 /// currently in the buffer.
488uint64_t current_pos() const override { return pos; }
489
490 /// Determine an efficient buffer size.
491size_t preferred_buffer_size() const override;
492
493void anchor() override;
494
495protected:
496 /// Set the flag indicating that an output error has been encountered.
497voiderror_detected(std::error_code EC) { this->EC = EC; }
498
499 /// Return the file descriptor.
500intget_fd() const { return FD; }
501
502// Update the file position by increasing \p Delta.
503voidinc_pos(uint64_t Delta) { pos += Delta; }
504
505public:
506 /// Open the specified file for writing. If an error occurs, information
507 /// about the error is put into EC, and the stream should be immediately
508 /// destroyed;
509 /// \p Flags allows optional flags to control how the file will be opened.
510 ///
511 /// As a special case, if Filename is "-", then the stream will use
512 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
513 /// descriptor.
514raw_fd_ostream(StringRef Filename, std::error_code &EC);
515raw_fd_ostream(StringRef Filename, std::error_code &EC,
517raw_fd_ostream(StringRef Filename, std::error_code &EC,
519raw_fd_ostream(StringRef Filename, std::error_code &EC,
520sys::fs::OpenFlags Flags);
521raw_fd_ostream(StringRef Filename, std::error_code &EC,
523sys::fs::OpenFlags Flags);
524
525 /// FD is the file descriptor that this writes to. If ShouldClose is true,
526 /// this closes the file when the stream is destroyed. If FD is for stdout or
527 /// stderr, it will not be closed.
528raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false,
530
531~raw_fd_ostream() override;
532
533 /// Manually flush the stream and close the file. Note that this does not call
534 /// fsync.
535voidclose();
536
537boolsupportsSeeking() const { return SupportsSeeking; }
538
539boolisRegularFile() const { return IsRegularFile; }
540
541 /// Flushes the stream and repositions the underlying file descriptor position
542 /// to the offset specified from the beginning of the file.
544
545boolis_displayed() const override;
546
547boolhas_colors() const override;
548
549 /// Tie this stream to the specified stream. Replaces any existing tied-to
550 /// stream. Specifying a nullptr unties the stream. This is intended for to
551 /// tie errs() to outs(), so that outs() is flushed whenever something is
552 /// written to errs(), preventing weird and hard-to-test output when stderr
553 /// is redirected to stdout.
554voidtie(raw_ostream *TieTo) { TiedStream = TieTo; }
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.
562boolhas_error() const { returnbool(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 ///
573voidclear_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.
605tryLockFor(Durationconst &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.
633raw_fd_stream(StringRef Filename, std::error_code &EC);
634
635raw_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_tSize);
647
648 /// Check if \p OS is a pointer of type raw_fd_stream*.
649staticboolclassof(constraw_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.
665void write_impl(constchar *Ptr, size_tSize) override;
666
667 /// Return the current position within the stream, not counting the bytes
668 /// currently in the buffer.
669uint64_t current_pos() const override { returnOS.size(); }
670
671public:
672explicitraw_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() { returnOS; }
680
681voidreserveExtraSpace(uint64_t ExtraSize) override {
682OS.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.
695void write_impl(constchar *Ptr, size_tSize) override;
696
697void pwrite_impl(constchar *Ptr, size_tSize, uint64_tOffset) override;
698
699 /// Return the current position within the stream.
700uint64_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.
709OS(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
717voidflush() = delete;
718
719 /// Return a StringRef for the vector contents.
720StringRefstr() const { returnStringRef(OS.data(), OS.size()); }
722
723voidreserveExtraSpace(uint64_t ExtraSize) override {
724OS.reserve(tell() + ExtraSize);
725 }
726
727staticboolclassof(constraw_ostream *OS);
728};
729
730/// A raw_ostream that discards all output.
732 /// See raw_ostream::write_impl.
733void write_impl(constchar *Ptr, size_tsize) override;
734void pwrite_impl(constchar *Ptr, size_tSize, uint64_tOffset) override;
735
736 /// Return the current position within the stream, not counting the bytes
737 /// currently in the buffer.
738uint64_t current_pos() const override;
739
740public:
741explicitraw_null_ostream() = default;
742~raw_null_ostream() override;
743};
744
746raw_ostream &OS;
748
749void anchor() override;
750
751public:
753~buffer_ostream() override { OS << str(); }
754};
755
757 std::unique_ptr<raw_ostream> OS;
759
760void anchor() override;
761
762public:
763buffer_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
772// Helper struct to add indentation to raw_ostream. Instead of
773// OS.indent(6) << "more stuff";
774// you can use
775// OS << indent(6) << "more stuff";
776// which has better ergonomics (and clang-formats better as well).
777//
778// If indentation is always in increments of a fixed value, you can use Scale
779// to set that value once. So indent(1, 2) will add 2 spaces and
780// indent(1,2) + 1 will add 4 spaces.
781struct indent {
782// Indentation is represented as `NumIndents` steps of size `Scale` each.
784unsignedScale;
785
786explicitindent(unsignedNumIndents, unsignedScale = 1)
788
789// These arithmeric operators preserve scale.
790voidoperator+=(unsignedN) { NumIndents += N; }
791voidoperator-=(unsignedN) {
792assert(NumIndents >= N && "Indentation underflow");
793NumIndents -= N;
794 }
795indentoperator+(unsignedN) const { returnindent(NumIndents + N, Scale); }
796indentoperator-(unsignedN) const {
797assert(NumIndents >= N && "Indentation undeflow");
798returnindent(NumIndents - N, Scale);
799 }
800indent &operator++() { // Prefix ++.
801 ++NumIndents;
802return *this;
803 }
804indentoperator++(int) { // Postfix ++.
805indent Old = *this;
806 ++NumIndents;
807return Old;
808 }
809indent &operator--() { // Prefix --.
810assert(NumIndents >= 1);
811 --NumIndents;
812return *this;
813 }
814indentoperator--(int) { // Postfix --.
815indent Old = *this;
816assert(NumIndents >= 1);
817 --NumIndents;
818return Old;
819 }
820indent &operator=(unsignedN) {
821NumIndents = N;
822return *this;
823 }
824};
825
827returnOS.indent(Indent.NumIndents * Indent.Scale);
828}
829
830class Error;
831
832/// This helper creates an output stream and then passes it to \p Write.
833/// The stream created is based on the specified \p OutputFileName:
834/// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream
835/// for other names. For raw_fd_ostream instances, the stream writes to
836/// a temporary file. The final output file is atomically replaced with the
837/// temporary file after the \p Write function is finished.
838Error writeToOutput(StringRef OutputFileName,
839 std::function<Error(raw_ostream &)> Write);
840
841raw_ostream &operator<<(raw_ostream &OS, std::nullopt_t);
842
843template <typename T, typename = decltype(std::declval<raw_ostream &>()
844 << std::declval<const T &>())>
845raw_ostream &operator<<(raw_ostream &OS, const std::optional<T> &O) {
846if (O)
847OS << *O;
848else
849OS << std::nullopt;
850returnOS;
851}
852
853} // end namespace llvm
854
855#endif // LLVM_SUPPORT_RAW_OSTREAM_H
DXIL Resource Access
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...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition:StringRef.h:51
buffer_ostream(raw_ostream &OS)
~buffer_ostream() override
buffer_unique_ostream(std::unique_ptr< raw_ostream > OS)
This is a helper class used for handling formatted output.
Definition:Format.h:39
A raw_ostream that writes to a file descriptor.
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...
std::error_code error() const
void close()
Manually flush the stream and close the file.
void inc_pos(uint64_t Delta)
Expected< sys::fs::FileLocker > lock()
Locks the underlying file.
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 has_colors() const override
This function determines if this stream is displayed and supports colors.
bool isRegularFile() const
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.
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.
A raw_ostream of a file for reading/writing/seeking.
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.
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
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.
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.
static constexpr Colors CYAN
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
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)
virtual ~raw_ostream()
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.
static constexpr Colors BLUE
virtual size_t preferred_buffer_size() const
Return an efficient buffer size for the underlying output mechanism.
raw_ostream & write(unsigned char C)
void SetUnbuffered()
Set the stream to be unbuffered.
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.
const char * getBufferStart() const
Return the beginning of the current stream buffer, or 0 if the stream is unbuffered.
static constexpr Colors RESET
raw_ostream & operator<<(signed char C)
static constexpr Colors BRIGHT_MAGENTA
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
static constexpr Colors MAGENTA
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 SAVEDCOLOR
virtual void reserveExtraSpace(uint64_t ExtraSize)
If possible, pre-allocate ExtraSize bytes for stream data.
size_t GetNumBytesInBuffer() const
static constexpr Colors BLACK
raw_ostream & operator<<(const std::string &Str)
raw_ostream & operator<<(unsigned int N)
static constexpr Colors BRIGHT_BLACK
static constexpr Colors BRIGHT_WHITE
static constexpr Colors GREEN
virtual bool has_colors() const
This function determines if this stream is displayed and supports colors.
static constexpr Colors RED
static constexpr Colors BRIGHT_GREEN
static constexpr Colors BRIGHT_BLUE
OStreamKind get_kind() const
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
static constexpr Colors WHITE
bool colors_enabled() const
An abstract base class for streams implementations that also support a pwrite operation.
raw_pwrite_stream(bool Unbuffered=false, OStreamKind K=OStreamKind::OK_OStream)
void pwrite(const char *Ptr, size_t Size, uint64_t Offset)
A raw_ostream that writes to an std::string.
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)
A raw_ostream that writes to an SmallVector or SmallString.
static bool classof(const raw_ostream *OS)
~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.
@ 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: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:1697
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)
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:1873
Implement std::hash so that hash_code can be used in STL containers.
Definition:BitVector.h:858
#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++()
close