1//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===// 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 7//===----------------------------------------------------------------------===// 9// This implements support for bulk buffered stream output. 11//===----------------------------------------------------------------------===// 15#include "llvm/Config/config.h" 32// <fcntl.h> may provide O_BINARY. 35#if defined(HAVE_UNISTD_H) 39#if defined(__CYGWIN__) 46# define STDIN_FILENO 0 49# define STDOUT_FILENO 1 52# define STDERR_FILENO 2 76// raw_ostream's subclasses should take care to flush the buffer 77// in their destructors. 78assert(OutBufCur == OutBufStart &&
79"raw_ostream destructor called with non-empty buffer!");
81if (BufferMode == BufferKind::InternalBuffer)
87// On Windows BUFSIZ is only 512 which results in more calls to write. This 88// overhead can cause significant performance degradation. Therefore use a 92// BUFSIZ is intended to be a reasonable default. 98// Ask the subclass to determine an appropriate buffer size. 102// It may return 0, meaning this stream should be unbuffered. 106void raw_ostream::SetBufferAndMode(
char *BufferStart,
size_tSize,
108assert(((Mode == BufferKind::Unbuffered && !BufferStart &&
Size == 0) ||
109 (Mode != BufferKind::Unbuffered && BufferStart &&
Size != 0)) &&
110"stream must be unbuffered or have at least one byte");
111// Make sure the current buffer is free of content (we can't flush here; the 112// child buffer management logic will be in write_impl). 115if (BufferMode == BufferKind::InternalBuffer)
116delete [] OutBufStart;
117 OutBufStart = BufferStart;
118 OutBufEnd = OutBufStart+
Size;
119 OutBufCur = OutBufStart;
122assert(OutBufStart <= OutBufEnd &&
"Invalid size!");
170for (
unsignedchar c : Str) {
190// Write out the escaped representation. 193 *
this << hexdigit((c >> 4) & 0xF);
194 *
this << hexdigit((c >> 0) & 0xF);
196// Always use a full 3-character octal escape. 198 *
this <<
char(
'0' + ((c >> 6) & 7));
199 *
this <<
char(
'0' + ((c >> 3) & 7));
200 *
this <<
char(
'0' + ((c >> 0) & 7));
218void raw_ostream::flush_nonempty() {
219assert(OutBufCur > OutBufStart &&
"Invalid call to flush_nonempty.");
220size_tLength = OutBufCur - OutBufStart;
221 OutBufCur = OutBufStart;
222 write_impl(OutBufStart,
Length);
226// Group exceptional cases into a single branch. 229if (BufferMode == BufferKind::Unbuffered) {
230 write_impl(
reinterpret_cast<char *
>(&
C), 1);
233// Set up a buffer and start over. 246// Group exceptional cases into a single branch. 249if (BufferMode == BufferKind::Unbuffered) {
253// Set up a buffer and start over. 258size_t NumBytes = OutBufEnd - OutBufCur;
260// If the buffer is empty at this point we have a string that is larger 261// than the buffer. Directly write the chunk that is a multiple of the 262// preferred buffer size and put the remainder in the buffer. 264assert(NumBytes != 0 &&
"undefined behavior");
265size_t BytesToWrite =
Size - (
Size % NumBytes);
266 write_impl(
Ptr, BytesToWrite);
267size_t BytesRemaining =
Size - BytesToWrite;
268if (BytesRemaining >
size_t(OutBufEnd - OutBufCur)) {
269// Too much left over to copy into our buffer. 270returnwrite(
Ptr + BytesToWrite, BytesRemaining);
272 copy_to_buffer(
Ptr + BytesToWrite, BytesRemaining);
276// We don't have enough space in the buffer to fit the string in. Insert as 277// much as possible, flush and start over with the remainder. 278 copy_to_buffer(
Ptr, NumBytes);
288void raw_ostream::copy_to_buffer(
constchar *
Ptr,
size_tSize) {
289assert(
Size <=
size_t(OutBufEnd - OutBufCur) &&
"Buffer overrun!");
291// Handle short strings specially, memcpy isn't very good at very short 294case 4: OutBufCur[3] =
Ptr[3]; [[fallthrough]];
295case 3: OutBufCur[2] =
Ptr[2]; [[fallthrough]];
296case 2: OutBufCur[1] =
Ptr[1]; [[fallthrough]];
297case 1: OutBufCur[0] =
Ptr[0]; [[fallthrough]];
309// If we have more than a few bytes left in our output buffer, try 310// formatting directly onto its end. 311size_t NextBufferSize = 127;
312size_t BufferBytesLeft = OutBufEnd - OutBufCur;
313if (BufferBytesLeft > 3) {
314size_t BytesUsed = Fmt.
print(OutBufCur, BufferBytesLeft);
316// Common case is that we have plenty of space. 317if (BytesUsed <= BufferBytesLeft) {
318 OutBufCur += BytesUsed;
322// Otherwise, we overflowed and the return value tells us the size to try 324 NextBufferSize = BytesUsed;
327// If we got here, we didn't have enough space in the output buffer for the 328// string. Try printing into a SmallVector that is resized to have enough 329// space. Iterate until we win. 333 V.resize(NextBufferSize);
335// Try formatting into the SmallVector. 336size_t BytesUsed = Fmt.
print(V.data(), NextBufferSize);
338// If BytesUsed fit into the vector, we win. 339if (BytesUsed <= NextBufferSize)
340returnwrite(V.data(), BytesUsed);
342// Otherwise, try again with a new size. 343assert(BytesUsed > NextBufferSize &&
"Didn't grow buffer!?");
344 NextBufferSize = BytesUsed;
354unsigned LeftIndent = 0;
355unsigned RightIndent = 0;
356const ssize_t Difference = FS.Width - FS.Str.size();
362 RightIndent = Difference;
365 LeftIndent = Difference;
368 LeftIndent = Difference / 2;
369 RightIndent = Difference - LeftIndent;
382if (FN.Upper && FN.HexPrefix)
384elseif (FN.Upper && !FN.HexPrefix)
386elseif (!FN.Upper && FN.HexPrefix)
395if (Buffer.
size() < FN.Width)
407auto Bytes = FB.Bytes;
408constsize_tSize = Bytes.size();
411if (FB.FirstByteOffset) {
412// Figure out how many nibbles are needed to print the largest offset 413// represented by this data set, so that we can align the offset field 414// to the right width. 415size_t Lines =
Size / FB.NumPerLine;
416uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
420 OffsetWidth = std::max<uint64_t>(4,
llvm::alignTo(Power, 4) / 4);
423// The width of a block of data including all spaces for group separators. 424unsigned NumByteGroups =
425alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
426unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
428while (!Bytes.empty()) {
431if (FB.FirstByteOffset) {
437auto Line = Bytes.take_front(FB.NumPerLine);
439size_t CharsPrinted = 0;
440// Print the hex bytes for this line in groups 441for (
size_tI = 0;
I < Line.size(); ++
I, CharsPrinted += 2) {
442if (
I && (
I % FB.ByteGroupSize) == 0) {
450// Print any spaces needed for any bytes that we didn't print on this 451// line so that the ASCII bytes are correctly aligned. 452assert(BlockCharWidth >= CharsPrinted);
453indent(BlockCharWidth - CharsPrinted + 2);
456// Print the ASCII char values for each byte on this line 459 *this << static_cast<char>(Byte);
466 Bytes = Bytes.drop_front(Line.size());
467 LineIndex += Line.size();
476staticconstchar Chars[] = {
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
477C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
478C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
479C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
480C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C,
C};
482// Usually the indentation is small, handle it with a fastpath. 483if (NumChars < std::size(Chars))
484returnOS.
write(Chars, NumChars);
487unsigned NumToWrite = std::min(NumChars, (
unsigned)std::size(Chars) - 1);
489 NumChars -= NumToWrite;
494/// indent - Insert 'NumSpaces' spaces. 496return write_padding<' '>(*
this, NumSpaces);
499/// write_zeros - Insert 'NumZeros' nulls. 501return write_padding<'\0'>(*
this, NumZeros);
504bool raw_ostream::prepare_colors() {
505// Colors were explicitly disabled. 509// Colors require changing the terminal but this stream is not going to a 521if (!prepare_colors())
524constchar *colorcode =
529write(colorcode, strlen(colorcode));
534if (!prepare_colors())
538write(colorcode, strlen(colorcode));
543if (!prepare_colors())
547write(colorcode, strlen(colorcode));
551void raw_ostream::anchor() {}
553//===----------------------------------------------------------------------===// 555//===----------------------------------------------------------------------===// 557// Out of line virtual method. 561//===----------------------------------------------------------------------===// 563//===----------------------------------------------------------------------===// 569"Cannot make a raw_ostream from a read-only descriptor!");
571// Handle "-" as stdout. Note that when we do this, we consider ourself 572// the owner of stdout and may set the "binary" flag globally based on Flags. 574 EC = std::error_code();
575// Change stdout's text/binary mode based on the Flags. 592 :
raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
597 :
raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
606 :
raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
615/// FD is the file descriptor that this writes to. If ShouldClose is true, this 616/// closes the file when the stream is destroyed. 627// Do not attempt to close stdout or stderr. We used to try to maintain the 628// property that tools that support writing file to stdout should not also 629// write informational output to stdout, but in practice we were never able to 630// maintain this invariant. Many features have been added to LLVM and clang 631// (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so 632// users must simply be aware that mixed output and remarks is a possibility. 633if (FD <= STDERR_FILENO)
637// Check if this is a console device. This is not equivalent to isatty. 639 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
642// Get the starting position. 643 off_t loc = ::lseek(FD, 0, SEEK_CUR);
645 std::error_code EC = status(FD,
Status);
648// MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes. 649 SupportsSeeking = !EC && IsRegularFile;
651 SupportsSeeking = !EC && loc != (off_t)-1;
669// On mingw, global dtors should not call exit(). 670// report_fatal_error() invokes exit(). We know report_fatal_error() 671// might not write messages to stderr when any errors were detected 676// If there are any pending errors, report them now. Clients wishing 677// to avoid report_fatal_error calls should check for errors with 678// has_error() and clear the error flag with clear_error() before 679// destructing raw_ostream objects which may have errors. 683/*gen_crash_diag=*/false);
687// The most reliable way to print unicode in a Windows console is with 688// WriteConsoleW. To use that, first transcode from UTF-8 to UTF-16. This 689// assumes that LLVM programs always print valid UTF-8 to the console. The data 690// might not be UTF-8 for two major reasons: 691// 1. The program is printing binary (-filetype=obj -o -), in which case it 692// would have been gibberish anyway. 693// 2. The program is printing text in a semi-ascii compatible codepage like 694// shift-jis or cp1252. 696// Most LLVM programs don't produce non-ascii text unless they are quoting 697// user source input. A well-behaved LLVM program should either validate that 698// the input is UTF-8 or transcode from the local codepage to UTF-8 before 699// quoting it. If they don't, this may mess up the encoding, but this is still 700// probably the best compromise we can make. 704// Fall back to ::write if it wasn't valid UTF-8. 705if (
auto EC = sys::windows::UTF8ToUTF16(
Data, WideText))
708// On Windows 7 and earlier, WriteConsoleW has a low maximum amount of data 709// that can be written to the console at a time. 710size_t MaxWriteSize = WideText.
size();
712 MaxWriteSize = 32767;
714size_t WCharsWritten = 0;
716size_t WCharsToWrite =
717 std::min(MaxWriteSize, WideText.
size() - WCharsWritten);
718 DWORD ActuallyWritten;
720 ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
721 WCharsToWrite, &ActuallyWritten,
722/*Reserved=*/nullptr);
724// The most likely reason for WriteConsoleW to fail is that FD no longer 725// points to a console. Fall back to ::write. If this isn't the first loop 726// iteration, something is truly wrong. 730 WCharsWritten += ActuallyWritten;
731 }
while (WCharsWritten != WideText.
size());
736void raw_fd_ostream::write_impl(
constchar *
Ptr,
size_tSize) {
740assert(FD >= 0 &&
"File already closed.");
744// If this is a Windows console device, try re-encoding from UTF-8 to UTF-16 745// and using WriteConsoleW. If that fails, fall back to plain write(). 751// The maximum write size is limited to INT32_MAX. A write 752// greater than SSIZE_MAX is implementation-defined in POSIX, 753// and Windows _write requires 32 bit input. 754size_t MaxWriteSize = INT32_MAX;
756#if defined(__linux__) 757// It is observed that Linux returns EINVAL for a very large write (>2G). 758// Make it a reasonably small value. 759 MaxWriteSize = 1024 * 1024 * 1024;
763size_t ChunkSize = std::min(
Size, MaxWriteSize);
767// If it's a recoverable error, swallow it and retry the write. 769// Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since 770// raw_ostream isn't designed to do non-blocking I/O. However, some 771// programs, such as old versions of bjam, have mistakenly used 772// O_NONBLOCK. For compatibility, emulate blocking semantics by 773// spinning until the write succeeds. If you don't want spinning, 774// don't use O_NONBLOCK file descriptors with raw_ostream. 775if (errno == EINTR || errno == EAGAIN
777 || errno == EWOULDBLOCK
783// Windows equivalents of SIGPIPE/EPIPE. 784DWORD WinLastError = GetLastError();
785if (WinLastError == ERROR_BROKEN_PIPE ||
786 (WinLastError == ERROR_NO_DATA && errno == EINVAL)) {
787 llvm::sys::CallOneShotPipeSignalHandler();
791// Otherwise it's a non-recoverable error. Note it and quit. 796// The write may have written some or all of the data. Update the 797// size and buffer pointer to reflect the remainder that needs 798// to be written. If there are no bytes left, we're done. 814assert(SupportsSeeking &&
"Stream does not support seeking!");
817 pos = ::_lseeki64(FD, off, SEEK_SET);
819 pos = ::lseek(FD, off, SEEK_SET);
826void raw_fd_ostream::pwrite_impl(
constchar *
Ptr,
size_tSize,
834size_t raw_fd_ostream::preferred_buffer_size()
const{
836// Disable buffering for console devices. Console output is re-encoded from 837// UTF-8 to UTF-16 on Windows, and buffering it would require us to split the 838// buffer on a valid UTF-8 codepoint boundary. Terminal buffering is disabled 839// below on most other OSs, so do the same thing on Windows and avoid that 844#elif defined(__MVS__) 845// The buffer size on z/OS is defined with macro BUFSIZ, which can be 846// retrieved by invoking function raw_ostream::preferred_buffer_size(). 849assert(FD >= 0 &&
"File not yet open!");
851if (fstat(FD, &statbuf) != 0)
854// If this is a terminal, don't use buffering. Line buffering 855// would be a more traditional thing to do, but it's not worth 859// Return the preferred block size. 860return statbuf.st_blksize;
889void raw_fd_ostream::anchor() {}
891//===----------------------------------------------------------------------===// 892// outs(), errs(), nulls() 893//===----------------------------------------------------------------------===// 896// Set buffer settings to model stdout behavior. 899 EC = enablezOSAutoConversion(STDOUT_FILENO);
908// Set standard error to be unbuffered. 910 std::error_code EC = enablezOSAutoConversion(STDERR_FILENO);
917/// nulls() - This returns a reference to a raw_ostream which discards output. 923//===----------------------------------------------------------------------===// 925//===----------------------------------------------------------------------===// 929 sys::fs::FA_Write | sys::fs::FA_Read,
936 EC = std::make_error_code(std::errc::invalid_argument);
956//===----------------------------------------------------------------------===// 958//===----------------------------------------------------------------------===// 960void raw_string_ostream::write_impl(
constchar *
Ptr,
size_tSize) {
964//===----------------------------------------------------------------------===// 965// raw_svector_ostream 966//===----------------------------------------------------------------------===// 968uint64_t raw_svector_ostream::current_pos()
const{
returnOS.size(); }
970void raw_svector_ostream::write_impl(
constchar *
Ptr,
size_tSize) {
974void raw_svector_ostream::pwrite_impl(
constchar *
Ptr,
size_tSize,
983//===----------------------------------------------------------------------===// 985//===----------------------------------------------------------------------===// 989// ~raw_ostream asserts that the buffer is empty. This isn't necessary 990// with raw_null_ostream, but it's better to have raw_null_ostream follow 991// the rules than to change the rules just for raw_null_ostream. 996void raw_null_ostream::write_impl(
constchar *
Ptr,
size_tSize) {
999uint64_t raw_null_ostream::current_pos()
const{
1003void raw_null_ostream::pwrite_impl(
constchar *
Ptr,
size_tSize,
1006void raw_pwrite_stream::anchor() {}
1008void buffer_ostream::anchor() {}
1010void buffer_unique_ostream::anchor() {}
1014if (OutputFileName ==
"-")
1017if (OutputFileName ==
"/dev/null") {
1031if (
Error DiscardError = Temp->discard())
1032returnjoinErrors(std::move(
E), std::move(DiscardError));
1037return Temp->keep(OutputFileName);
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Provides a library for accessing information about this process and other processes on the operating ...
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())
This file contains some functions that are useful when dealing with strings.
std::pair< llvm::MachO::Target, std::string > UUID
bool empty() const
empty - Check if the array is empty.
std::chrono::milliseconds getDuration() const
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
This is a helper class used for format_hex() and format_decimal().
This is a helper class for left_justify, right_justify, and center_justify.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
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.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is a helper class used for handling formatted output.
unsigned print(char *Buffer, unsigned BufferSize) const
Format the object into the specified buffer.
void format(raw_ostream &S) const
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.
~raw_fd_ostream() override
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.
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 bool classof(const raw_ostream *OS)
Check if OS is a pointer of type raw_fd_stream*.
raw_fd_stream(StringRef Filename, std::error_code &EC)
Open the specified file for reading/writing/seeking.
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.
~raw_null_ostream() override
This class implements an extremely fast bulk output stream that can only output to a stream.
static constexpr Colors YELLOW
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
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.
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)
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.
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.
static constexpr Colors RESET
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
static constexpr Colors MAGENTA
virtual void enable_colors(bool enable)
static constexpr Colors SAVEDCOLOR
size_t GetNumBytesInBuffer() const
static constexpr Colors BLACK
static constexpr Colors GREEN
static constexpr Colors RED
OStreamKind get_kind() const
void SetBuffered()
Set the stream to be buffered, with an automatically determined buffer size.
static constexpr Colors WHITE
An abstract base class for streams implementations that also support a pwrite operation.
A raw_ostream that writes to an SmallVector or SmallString.
static bool classof(const raw_ostream *OS)
static std::error_code SafelyCloseFileDescriptor(int FD)
static const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
static bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window.
static const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
static bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
static const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
static const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
static bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
RAII class that facilitates file locking.
static Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write, OpenFlags ExtraFlags=OF_None)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Represents the result of a call to sys::fs::status().
@ C
The default llvm calling convention, compatible with C.
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0))
Try to locks the file during the specified time.
std::error_code lockFile(int FD)
Lock the file.
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
std::error_code ChangeStdoutMode(fs::OpenFlags Flags)
This is an optimization pass for GlobalISel generic memory operations.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
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.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
void write_double(raw_ostream &S, double D, FloatStyle Style, std::optional< size_t > Precision=std::nullopt)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
static int getFD(StringRef Filename, std::error_code &EC, sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, sys::fs::OpenFlags Flags)
static raw_ostream & write_padding(raw_ostream &OS, unsigned NumChars)