Hash :
eb614d7e
Author :
Date :
2024-11-11T13:24:35
Metal: Avoid leaking library and binary sources Reland: Fix build with metal_internal_shader_compilation_supported = false Fix leak of dispatch_data during binary load. The dispatch object was not released. Dispatch objects are Obj-C objects, so hold with AutoObjCPtr. Fix leak of MTLLibrary objects when creating the objects. The method newLibraryWithData returns +1 due to being "new" type method. This ref must be adopted. Avoid using autoreleased objects, use AutoObjCPtr. Some leaks regressed in commit c5ab1cebccaab0f8de466e5f797faa3d5a84bea5. Bug: angleproject:351165323 Change-Id: I08bc6bcb787cdc3f71e9487d80a44e24b01b6b4c Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/6017845 Auto-Submit: Kimmo Kinnunen <kkinnunen@apple.com> Reviewed-by: Geoff Lang <geofflang@chromium.org> Commit-Queue: Geoff Lang <geofflang@chromium.org>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
//
// Copyright 2023 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// mtl_library_cache.mm:
// Defines classes for caching of mtl libraries
//
#include "libANGLE/renderer/metal/mtl_library_cache.h"
#include <stdio.h>
#include <limits>
#include "common/MemoryBuffer.h"
#include "common/angleutils.h"
#include "common/hash_utils.h"
#include "common/mathutil.h"
#include "common/string_utils.h"
#include "common/system_utils.h"
#include "libANGLE/histogram_macros.h"
#include "libANGLE/renderer/metal/DisplayMtl.h"
#include "libANGLE/renderer/metal/process.h"
#include "platform/PlatformMethods.h"
namespace rx
{
namespace mtl
{
LibraryCache::LibraryCache() : mCache(kMaxCachedLibraries) {}
AutoObjCPtr<id<MTLLibrary>> LibraryCache::get(const std::shared_ptr<const std::string> &source,
const std::map<std::string, std::string> ¯os,
bool disableFastMath,
bool usesInvariance)
{
ASSERT(source != nullptr);
LibraryCache::LibraryCacheEntry &entry =
getCacheEntry(LibraryKey(source, macros, disableFastMath, usesInvariance));
// Try to lock the entry and return the library if it exists. If we can't lock then it means
// another thread is currently compiling.
std::unique_lock<std::mutex> entryLockGuard(entry.lock, std::try_to_lock);
if (entryLockGuard)
{
return entry.library;
}
else
{
return nil;
}
}
namespace
{
// Reads a metallib file at the specified path.
angle::MemoryBuffer ReadMetallibFromFile(const std::string &path)
{
// TODO: optimize this to avoid the unnecessary strings.
std::string metallib;
if (!angle::ReadFileToString(path, &metallib))
{
FATAL() << "Failed reading back metallib";
}
angle::MemoryBuffer buffer;
if (!buffer.resize(metallib.size()))
{
FATAL() << "Failed to resize metallib buffer";
}
memcpy(buffer.data(), metallib.data(), metallib.size());
return buffer;
}
// Generates a key for the BlobCache based on the specified params.
egl::BlobCache::Key GenerateBlobCacheKeyForShaderLibrary(
const std::shared_ptr<const std::string> &source,
const std::map<std::string, std::string> ¯os,
bool disableFastMath,
bool usesInvariance)
{
angle::base::SecureHashAlgorithm sha1;
sha1.Update(source->c_str(), source->size());
const size_t macro_count = macros.size();
sha1.Update(¯o_count, sizeof(size_t));
for (const auto ¯o : macros)
{
sha1.Update(macro.first.c_str(), macro.first.size());
sha1.Update(macro.second.c_str(), macro.second.size());
}
sha1.Update(&disableFastMath, sizeof(bool));
sha1.Update(&usesInvariance, sizeof(bool));
sha1.Final();
return sha1.DigestAsArray();
}
} // namespace
AutoObjCPtr<id<MTLLibrary>> LibraryCache::getOrCompileShaderLibrary(
DisplayMtl *displayMtl,
const std::shared_ptr<const std::string> &source,
const std::map<std::string, std::string> ¯os,
bool disableFastMath,
bool usesInvariance,
AutoObjCPtr<NSError *> *errorOut)
{
id<MTLDevice> metalDevice = displayMtl->getMetalDevice();
const angle::FeaturesMtl &features = displayMtl->getFeatures();
if (!features.enableInMemoryMtlLibraryCache.enabled)
{
return CreateShaderLibrary(metalDevice, *source, macros, disableFastMath, usesInvariance,
errorOut);
}
ASSERT(source != nullptr);
LibraryCache::LibraryCacheEntry &entry =
getCacheEntry(LibraryKey(source, macros, disableFastMath, usesInvariance));
// Lock this cache entry while compiling the shader. This causes other threads calling this
// function to wait and not duplicate the compilation.
std::lock_guard<std::mutex> entryLockGuard(entry.lock);
if (entry.library)
{
return entry.library;
}
if (features.printMetalShaders.enabled)
{
auto cache_key =
GenerateBlobCacheKeyForShaderLibrary(source, macros, disableFastMath, usesInvariance);
NSLog(@"Loading metal shader, key=%@ source=%s",
[NSData dataWithBytes:cache_key.data() length:cache_key.size()], source -> c_str());
}
if (features.compileMetalShaders.enabled)
{
if (features.enableParallelMtlLibraryCompilation.enabled)
{
// When enableParallelMtlLibraryCompilation is enabled, compilation happens in the
// background. Chrome's ProgramCache only saves to disk when called at certain points,
// which are not present when compiling in the background.
FATAL() << "EnableParallelMtlLibraryCompilation is not compatible with "
"compileMetalShdaders";
}
// Note: there does not seem to be a
std::string metallib_filename =
CompileShaderLibraryToFile(*source, macros, disableFastMath, usesInvariance);
angle::MemoryBuffer memory_buffer = ReadMetallibFromFile(metallib_filename);
AutoObjCPtr<NSError *> error;
entry.library = CreateShaderLibraryFromBinary(metalDevice, memory_buffer.data(),
memory_buffer.size(), &error);
auto cache_key =
GenerateBlobCacheKeyForShaderLibrary(source, macros, disableFastMath, usesInvariance);
displayMtl->getBlobCache()->put(nullptr, cache_key, std::move(memory_buffer));
return entry.library;
}
if (features.loadMetalShadersFromBlobCache.enabled)
{
auto cache_key =
GenerateBlobCacheKeyForShaderLibrary(source, macros, disableFastMath, usesInvariance);
egl::BlobCache::Value value;
angle::ScratchBuffer scratch_buffer;
if (displayMtl->getBlobCache()->get(nullptr, &scratch_buffer, cache_key, &value))
{
AutoObjCPtr<NSError *> error;
entry.library =
CreateShaderLibraryFromBinary(metalDevice, value.data(), value.size(), &error);
}
ANGLE_HISTOGRAM_BOOLEAN("GPU.ANGLE.MetalShaderInBlobCache", entry.library);
ANGLEPlatformCurrent()->recordShaderCacheUse(entry.library);
if (entry.library)
{
return entry.library;
}
}
entry.library = CreateShaderLibrary(metalDevice, *source, macros, disableFastMath,
usesInvariance, errorOut);
return entry.library;
}
LibraryCache::LibraryCacheEntry &LibraryCache::getCacheEntry(LibraryKey &&key)
{
// Lock while searching or adding new items to the cache.
std::lock_guard<std::mutex> cacheLockGuard(mCacheLock);
auto iter = mCache.Get(key);
if (iter != mCache.end())
{
return iter->second;
}
angle::TrimCache(kMaxCachedLibraries, kGCLimit, "metal library", &mCache);
iter = mCache.Put(std::move(key), LibraryCacheEntry());
return iter->second;
}
LibraryCache::LibraryKey::LibraryKey(const std::shared_ptr<const std::string> &sourceIn,
const std::map<std::string, std::string> ¯osIn,
bool disableFastMathIn,
bool usesInvarianceIn)
: source(sourceIn),
macros(macrosIn),
disableFastMath(disableFastMathIn),
usesInvariance(usesInvarianceIn)
{}
bool LibraryCache::LibraryKey::operator==(const LibraryKey &other) const
{
return std::tie(*source, macros, disableFastMath, usesInvariance) ==
std::tie(*other.source, other.macros, other.disableFastMath, other.usesInvariance);
}
size_t LibraryCache::LibraryKeyHasher::operator()(const LibraryKey &k) const
{
size_t hash = 0;
angle::HashCombine(hash, *k.source);
for (const auto ¯o : k.macros)
{
angle::HashCombine(hash, macro.first);
angle::HashCombine(hash, macro.second);
}
angle::HashCombine(hash, k.disableFastMath);
angle::HashCombine(hash, k.usesInvariance);
return hash;
}
LibraryCache::LibraryCacheEntry::~LibraryCacheEntry()
{
// Lock the cache entry before deletion to ensure there is no other thread compiling and
// preparing to write to the library. LibraryCacheEntry objects can only be deleted while the
// mCacheLock is held so only one thread modifies mCache at a time.
std::lock_guard<std::mutex> entryLockGuard(lock);
}
LibraryCache::LibraryCacheEntry::LibraryCacheEntry(LibraryCacheEntry &&moveFrom)
{
// Lock the cache entry being moved from to make sure the library can be safely accessed.
// Mutexes cannot be moved so a new one will be created in this entry
std::lock_guard<std::mutex> entryLockGuard(moveFrom.lock);
library = std::move(moveFrom.library);
moveFrom.library = nullptr;
}
} // namespace mtl
} // namespace rx