LLVM 24.0.0git
Caching.cpp
Go to the documentation of this file.
1//===-Caching.cpp - LLVM Local File Cache ---------------------------------===//
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 implements the localCache function, which simplifies creating,
10// adding to, and querying a local file system cache. localCache takes care of
11// periodically pruning older files from the cache using a CachePruningPolicy.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/Support/Errc.h"
19#include "llvm/Support/Path.h"
20
21#if !defined(_MSC_VER) && !defined(__MINGW32__)
22#include <unistd.h>
23#else
25#include <io.h>
26#endif
27
28using namespace llvm;
29
31 const Twine &TempFilePrefixRef,
32 const Twine &CacheDirectoryPathRef,
33 AddBufferFn AddBuffer, bool CacheRename) {
34
35 // Create local copies which are safely captured-by-copy in lambdas
36 SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath;
37 CacheNameRef.toVector(CacheName);
38 TempFilePrefixRef.toVector(TempFilePrefix);
39 CacheDirectoryPathRef.toVector(CacheDirectoryPath);
40
41 auto Func = [=](unsigned Task, StringRef Key,
43 // This choice of file name allows the cache to be pruned (see pruneCache()
44 // in include/llvm/Support/CachePruning.h).
45 SmallString<64> EntryPath;
46 sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key);
47 // First, see if we have a cache hit.
48 SmallString<64> ResultPath;
50 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
51 std::error_code EC;
52 if (FDOrErr) {
54 MemoryBuffer::getOpenFile(*FDOrErr, EntryPath,
55 /*FileSize=*/-1,
56 /*RequiresNullTerminator=*/false);
57 sys::fs::closeFile(*FDOrErr);
58 if (MBOrErr) {
59 AddBuffer(Task, ModuleName, std::move(*MBOrErr));
60 return AddStreamFn();
61 }
62 EC = MBOrErr.getError();
63 } else {
64 EC = errorToErrorCode(FDOrErr.takeError());
65 }
66
67 // On Windows we can fail to open a cache file with a permission denied
68 // error. This generally means that another process has requested to delete
69 // the file while it is still open, but it could also mean that another
70 // process has opened the file without the sharing permissions we need.
71 // Since the file is probably being deleted we handle it in the same way as
72 // if the file did not exist at all.
74 return createStringError(EC, Twine("Failed to open cache file ") +
75 EntryPath + ": " + EC.message() + "\n");
76
77 // This file stream is responsible for commiting the resulting file to the
78 // cache and calling AddBuffer to add it to the link.
79 struct CacheStream : CachedFileStream {
80 AddBufferFn AddBuffer;
81 sys::fs::TempFile TempFile;
82 std::string ModuleName;
83 unsigned Task;
84
85 CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer,
86 sys::fs::TempFile TempFile, std::string EntryPath,
87 std::string ModuleName, unsigned Task)
88 : CachedFileStream(std::move(OS), std::move(EntryPath)),
89 AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)),
90 ModuleName(ModuleName), Task(Task) {}
91
92 Error commit() override {
94 if (E)
95 return E;
96
97 // Make sure the stream is closed before committing it.
98 OS.reset();
99
100 // Open the file first to avoid racing with a cache pruner.
103 sys::fs::convertFDToNativeFile(TempFile.FD), ObjectPathName,
104 /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
105 if (!MBOrErr) {
106 std::error_code EC = MBOrErr.getError();
107 return createStringError(EC, Twine("Failed to open new cache file ") +
108 TempFile.TmpName + ": " +
109 EC.message() + "\n");
110 }
111
112 // On POSIX systems, this will atomically replace the destination if
113 // it already exists. We try to emulate this on Windows, but this may
114 // fail with a permission denied error (for example, if the destination
115 // is currently opened by another process that does not give us the
116 // sharing permissions we need). Since the existing file should be
117 // semantically equivalent to the one we are trying to write, we give
118 // AddBuffer a copy of the bytes we wrote in that case. We do this
119 // instead of just using the existing file, because the pruner might
120 // delete the file before we get a chance to use it.
121 E = TempFile.keep(ObjectPathName);
122 E = handleErrors(std::move(E), [&](const ECError &E) -> Error {
123 std::error_code EC = E.convertToErrorCode();
124 if (EC != errc::permission_denied)
125 return createStringError(
126 EC, Twine("Failed to rename temporary file ") +
127 TempFile.TmpName + " to " + ObjectPathName + ": " +
128 EC.message() + "\n");
129
130 auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(),
131 ObjectPathName);
132 MBOrErr = std::move(MBCopy);
133
134 // FIXME: should we consume the discard error?
135 consumeError(TempFile.discard());
136
137 return Error::success();
138 });
139
140 if (E)
141 return E;
142
143 AddBuffer(Task, ModuleName, std::move(*MBOrErr));
144 return Error::success();
145 }
146 };
147
148 // This class is responsible for renaming/moving existing file into a
149 // cache directory. The path for an input file is passed through a string
150 // stream.
151 struct MoveFileToCache : CachedFileStream {
152 AddBufferFn AddBuffer;
153 std::string ModuleName;
154 size_t Task;
155 StringRef FilePath;
156
157 MoveFileToCache(AddBufferFn AddBuffer, std::string EntryPath,
158 std::string ModuleID, size_t Task)
159 : CachedFileStream({}, std::move(EntryPath)),
160 AddBuffer(std::move(AddBuffer)), ModuleName(ModuleID), Task(Task) {}
161 virtual ~MoveFileToCache() = default;
162
163 virtual Error commit(std::unique_ptr<MemoryBuffer> MemBuf) override {
165 if (E)
166 return E;
167
168 FilePath = MemBuf->getBufferIdentifier();
169 assert(!FilePath.empty() && "File path is empty.");
170
171 // Rename/move native object file into cache directory, if they are
172 // located the same device/logical drive, otherwise we use a copy.
173 std::error_code EC = sys::fs::rename(FilePath, ObjectPathName);
174#ifdef _WIN32
175 if (EC ==
176 std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category()))
177#else
178 if (EC == std::make_error_code(std::errc::cross_device_link))
179#endif
180 EC = sys::fs::copy_file(FilePath, ObjectPathName);
181 if (EC)
182 return createStringError(EC, Twine("Failed to rename or copy file ") +
183 FilePath + " to " + ObjectPathName +
184 ": " + EC.message() + "\n");
185
186 AddBuffer(Task, ModuleName, std::move(MemBuf));
187
188 return Error::success();
189 }
190 };
191
192 return [=](size_t Task, const Twine &ModuleName)
193 -> Expected<std::unique_ptr<CachedFileStream>> {
194 // Create the cache directory if not already done. Doing this lazily
195 // ensures the filesystem isn't mutated until the cache is.
196 if (std::error_code EC = sys::fs::create_directories(
197 CacheDirectoryPath, /*IgnoreExisting=*/true))
198 return createStringError(EC, Twine("can't create cache directory ") +
199 CacheDirectoryPath + ": " +
200 EC.message());
201 // MoveFileToChache class will rename/move the file into the cache on
202 // destruction.
203 if (CacheRename) {
204 return std::make_unique<MoveFileToCache>(
205 AddBuffer, std::string(EntryPath.str()), ModuleName.str(), Task);
206 }
207
208 // Write to a temporary to avoid race condition
209 SmallString<64> TempFilenameModel;
210 sys::path::append(TempFilenameModel, CacheDirectoryPath,
211 TempFilePrefix + "-%%%%%%.tmp.o");
213 TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write);
214 if (!Temp)
216 toString(Temp.takeError()) + ": " + CacheName +
217 ": Can't get a temporary file");
218
219 // This CacheStream will move the temporary file into the cache when done.
220 return std::make_unique<CacheStream>(
221 std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false),
222 AddBuffer, std::move(*Temp), std::string(EntryPath), ModuleName.str(),
223 Task);
224 };
225 };
226 return FileCache(Func, CacheDirectoryPathRef.str());
227}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This class wraps an output stream for a file.
Definition Caching.h:29
CachedFileStream(std::unique_ptr< raw_pwrite_stream > OS, std::string OSPath="")
Definition Caching.h:31
virtual Error commit()
Must be called exactly once after the writes to OS have been completed but before the CachedFileStrea...
Definition Caching.h:37
This class wraps a std::error_code in a Error.
Definition Error.h:1209
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition Twine.cpp:32
Represents a temporary file.
Definition FileSystem.h:895
static LLVM_ABI 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...
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition FileSystem.h:819
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition Path.cpp:993
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1042
LLVM_ABI file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
@ no_such_file_or_directory
Definition Errc.h:65
@ io_error
Definition Errc.h:58
@ permission_denied
Definition Errc.h:71
std::function< void(unsigned Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB)> AddBufferFn
This type defines the callback to add a pre-existing file (e.g.
Definition Caching.h:111
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI Expected< FileCache > localCache(const Twine &CacheNameRef, const Twine &TempFilePrefixRef, const Twine &CacheDirectoryPathRef, AddBufferFn AddBuffer=[](size_t Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB) {}, bool CacheFileRename=false)
Create a local file system cache which uses the given cache name, temporary file prefix,...
Definition Caching.cpp:30
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:62
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:113
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
This type represents a file cache system that manages caching of files.
Definition Caching.h:88