Skip to content
17 changes: 16 additions & 1 deletion docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,22 @@ This page collects the setup steps and the problems testers have run into so far
- Linux: CMake 3.24+, GCC or Clang, and the Vulkan headers and loader. The headers should be recent enough
for `VK_KHR_maintenance8`; older ones still build, but skip what needs it.
- macOS: `brew install llvm molten-vk vulkan-headers vulkan-loader spirv-tools vulkan-tools`. The test programs
load MoltenVK directly; set `LEONIDA_VULKAN_LOADER` to use the Vulkan loader instead.
load MoltenVK directly; set `LEONIDA_VULKAN_LOADER` to use the Vulkan loader instead. Through the loader, the
C++ tools and `tools/vk_subgroup_info.py` opt in to `VK_KHR_portability_enumeration`, so MoltenVK is listed (pick
it with `VK_DRIVER_FILES=$(brew --prefix)/etc/vulkan/icd.d/MoltenVK_icd.json`). That is the way to run with
`LEONIDA_VK_VALIDATION=1` on a Mac: `brew install vulkan-validationlayers`, then set
`VK_LAYER_PATH=$(brew --prefix)/opt/vulkan-validationlayers/share/vulkan/explicit_layer.d` and
`DYLD_FALLBACK_LIBRARY_PATH=$(brew --prefix)/lib`. On MoltenVK 1.4.2 the layer reports three messages that are
not test failures. `VUID-RuntimeSpirv-shaderDenormPreserveFloat16-06296` and
`VUID-VkShaderModuleCreateInfo-pCode-08740` come from `DenormPreserve 16`, which MoltenVK does not report support
for; that is the documented trade-off (design.md, "Float controls (f16 denormals)").
`VUID-vkCreateDescriptorSetLayout-support-09582` comes from `vk_bindless_test`, `vk_bindless_grow_test` and
`vk_null_descriptor_test`, whose bindless set has about 11,800 descriptors. MoltenVK's
`vkGetDescriptorSetLayoutSupport` answers false above `maxPerSetDescriptors`, which it computes as 4 × (31 buffers + 256 textures + 16 samplers) =
1212, from its per-stage counts without Metal argument buffers
([KhronosGroup/MoltenVK#2573](https://github.com/KhronosGroup/MoltenVK/issues/2573)). Yet it reports update-after-bind limits far above
that, and the draws through the full set read back exact. Hide the three with
`VK_LAYER_MESSAGE_ID_FILTER=VUID-RuntimeSpirv-shaderDenormPreserveFloat16-06296,VUID-VkShaderModuleCreateInfo-pCode-08740,VUID-vkCreateDescriptorSetLayout-support-09582`.

## Build the test programs

Expand Down
105 changes: 104 additions & 1 deletion runtime/test/vulkan_loader.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,113 @@

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>

#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif

#ifdef __APPLE__
// Behind the Vulkan loader (LEONIDA_VULKAN_LOADER, the way to reach VK_LAYER_KHRONOS_validation on a Mac), MoltenVK
// is a portability driver: the loader lists it only for an instance created with VK_KHR_portability_enumeration and
// VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR, and a device it exposes must enable VK_KHR_portability_subset.
// None of the test tools ask for either, so through the loader they found no device ("Found drivers that contain
// devices which support the portability subset, but the instance does not enumerate portability drivers").
// load_vulkan() then hands out these wrappers, which add both where the loader and the device offer them.
namespace leonida_vulkan_loader {
inline PFN_vkGetInstanceProcAddr& real_gipa() {
static PFN_vkGetInstanceProcAddr gipa = nullptr;
return gipa;
}
// The instance the device wrapper queries through. Each test tool makes one instance, so the last one created is
// the one its device comes from; a tool that made two would still get the loader's same device entry points.
inline VkInstance& last_instance() {
static VkInstance instance = VK_NULL_HANDLE;
return instance;
}
inline bool requested(const char* const* names, uint32_t count, const char* name) {
for (uint32_t i = 0; i < count; ++i)
if (names[i] && !std::strcmp(names[i], name)) return true;
return false;
}
inline bool offered(const std::vector<VkExtensionProperties>& extensions, const char* name) {
for (const auto& e : extensions)
if (!std::strcmp(e.extensionName, name)) return true;
return false;
}
inline VKAPI_ATTR VkResult VKAPI_CALL create_instance(const VkInstanceCreateInfo* info, const VkAllocationCallbacks* a,
VkInstance* out) {
const auto real = reinterpret_cast<PFN_vkCreateInstance>(real_gipa()(nullptr, "vkCreateInstance"));
const auto enumerate = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
real_gipa()(nullptr, "vkEnumerateInstanceExtensionProperties"));
if (!real) return VK_ERROR_INITIALIZATION_FAILED;
VkInstanceCreateInfo copy = *info;
std::vector<const char*> names;
if (info->enabledExtensionCount) // ppEnabledExtensionNames may be null when the count is 0
names.assign(info->ppEnabledExtensionNames, info->ppEnabledExtensionNames + info->enabledExtensionCount);
uint32_t count = 0;
std::vector<VkExtensionProperties> extensions;
if (enumerate && enumerate(nullptr, &count, nullptr) == VK_SUCCESS) {
extensions.resize(count);
if (enumerate(nullptr, &count, extensions.data()) != VK_SUCCESS) extensions.clear();
extensions.resize(count);
}
const char* portability = "VK_KHR_portability_enumeration";
if (offered(extensions, portability)) {
if (!requested(names.data(), uint32_t(names.size()), portability)) names.push_back(portability);
copy.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
copy.enabledExtensionCount = uint32_t(names.size());
copy.ppEnabledExtensionNames = names.data();
}
const VkResult result = real(&copy, a, out);
if (result == VK_SUCCESS) last_instance() = *out;
return result;
}
inline VKAPI_ATTR VkResult VKAPI_CALL create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo* info,
const VkAllocationCallbacks* a, VkDevice* out) {
const VkInstance instance = last_instance();
const auto real = reinterpret_cast<PFN_vkCreateDevice>(real_gipa()(instance, "vkCreateDevice"));
const auto enumerate = reinterpret_cast<PFN_vkEnumerateDeviceExtensionProperties>(
real_gipa()(instance, "vkEnumerateDeviceExtensionProperties"));
if (!real) return VK_ERROR_INITIALIZATION_FAILED;
VkDeviceCreateInfo copy = *info;
std::vector<const char*> names;
if (info->enabledExtensionCount) // ppEnabledExtensionNames may be null when the count is 0
names.assign(info->ppEnabledExtensionNames, info->ppEnabledExtensionNames + info->enabledExtensionCount);
uint32_t count = 0;
std::vector<VkExtensionProperties> extensions;
if (enumerate && enumerate(physical, nullptr, &count, nullptr) == VK_SUCCESS) {
extensions.resize(count);
if (enumerate(physical, nullptr, &count, extensions.data()) != VK_SUCCESS) extensions.clear();
extensions.resize(count);
}
const char* subset = "VK_KHR_portability_subset";
if (offered(extensions, subset) && !requested(names.data(), uint32_t(names.size()), subset)) {
names.push_back(subset);
copy.enabledExtensionCount = uint32_t(names.size());
copy.ppEnabledExtensionNames = names.data();
}
return real(physical, &copy, a, out);
}
inline VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance_proc_addr(VkInstance instance, const char* name);
inline PFN_vkVoidFunction wrapped(const char* name) {
if (!std::strcmp(name, "vkCreateInstance")) return reinterpret_cast<PFN_vkVoidFunction>(&create_instance);
if (!std::strcmp(name, "vkCreateDevice")) return reinterpret_cast<PFN_vkVoidFunction>(&create_device);
if (!std::strcmp(name, "vkGetInstanceProcAddr"))
return reinterpret_cast<PFN_vkVoidFunction>(&get_instance_proc_addr);
return nullptr;
}
inline VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance_proc_addr(VkInstance instance, const char* name) {
if (name)
if (const auto f = wrapped(name)) return f;
return real_gipa()(instance, name);
}
} // namespace leonida_vulkan_loader
#endif

inline PFN_vkGetInstanceProcAddr load_vulkan() {
// Keep the Vulkan library loaded for the lifetime of the tool.
#ifdef _WIN32
Expand Down Expand Up @@ -43,7 +143,10 @@ inline PFN_vkGetInstanceProcAddr load_vulkan() {
}
const auto symbol = dlsym(library, "vkGetInstanceProcAddr");
if (!symbol) std::fprintf(stderr, "%s has no vkGetInstanceProcAddr\n", name);
return symbol;
if (!symbol || !overridden) return symbol;
// Through the loader: opt in to portability drivers (MoltenVK) for the tool (see above).
leonida_vulkan_loader::real_gipa() = reinterpret_cast<PFN_vkGetInstanceProcAddr>(symbol);
return reinterpret_cast<void*>(&leonida_vulkan_loader::get_instance_proc_addr);
}();
#else
constexpr auto library_name = "libvulkan.so.1";
Expand Down
38 changes: 38 additions & 0 deletions tests/test_vk_subgroup_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,44 @@ def test_posix_failure_lists_all_tried_names(self):
vk_info.load_vulkan()


class PortabilityEnumerationTest(unittest.TestCase):
"""Behind the Vulkan loader on a Mac, MoltenVK is listed only for an instance that opts in."""

@staticmethod
def loader(names):
def enumerate_(_layer, count, props):
count = ctypes.cast(count, ctypes.POINTER(ctypes.c_uint32))
if props is None:
count[0] = len(names)
return 0
arr = ctypes.cast(props, ctypes.POINTER(vk_info.ExtensionProperties))
for i, n in enumerate(names[:count[0]]):
arr[i].extensionName = n
return 0

class Loader:
vkEnumerateInstanceExtensionProperties = staticmethod(enumerate_)
return Loader()

def test_opts_in_through_the_loader_on_macos(self):
vk = self.loader([b"VK_KHR_surface", b"VK_KHR_portability_enumeration"])
with mock.patch.object(vk_info.sys, "platform", "darwin"), \
mock.patch.dict(os.environ, {"LEONIDA_VULKAN_LOADER": "/x/libvulkan.1.dylib"}):
names = vk_info.portability_enumeration(vk)
self.assertIsNotNone(names)
self.assertEqual(names[0], b"VK_KHR_portability_enumeration")

def test_no_opt_in_without_the_extension_or_the_loader(self):
with mock.patch.object(vk_info.sys, "platform", "darwin"), \
mock.patch.dict(os.environ, {"LEONIDA_VULKAN_LOADER": "/x/libvulkan.1.dylib"}):
self.assertIsNone(vk_info.portability_enumeration(self.loader([b"VK_KHR_surface"])))
with mock.patch.object(vk_info.sys, "platform", "darwin"), mock.patch.dict(os.environ, {}, clear=True):
self.assertIsNone(vk_info.portability_enumeration(self.loader([b"VK_KHR_portability_enumeration"])))
with mock.patch.object(vk_info.sys, "platform", "linux"), \
mock.patch.dict(os.environ, {"LEONIDA_VULKAN_LOADER": "/x/libvulkan.1.dylib"}):
self.assertIsNone(vk_info.portability_enumeration(self.loader([b"VK_KHR_portability_enumeration"])))


class PhysicalDevicesTest(unittest.TestCase):
def _make_enum_vk(self, steps):
"""Build a minimal vk object whose vkEnumeratePhysicalDevices replays (status, handles) steps."""
Expand Down
36 changes: 36 additions & 0 deletions tools/vk_subgroup_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,35 @@ def load_vulkan():
raise RuntimeError("no Vulkan loader found (" + ", ".join(names) + ")")


VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR = 0x1
PORTABILITY_ENUMERATION = b"VK_KHR_portability_enumeration"


class ExtensionProperties(ctypes.Structure):
_fields_ = [("extensionName", ctypes.c_char * 256), ("specVersion", ctypes.c_uint32)]


def portability_enumeration(vk):
"""A one-name array for ppEnabledExtensionNames when the Vulkan loader (LEONIDA_VULKAN_LOADER on macOS) offers
VK_KHR_portability_enumeration, else None. MoltenVK opened directly needs no opt-in."""
if sys.platform != "darwin" or not os.environ.get("LEONIDA_VULKAN_LOADER"):
return None
enumerate_ = getattr(vk, "vkEnumerateInstanceExtensionProperties", None)
if enumerate_ is None:
return None
vp = ctypes.c_void_p
enumerate_.argtypes = [vp, vp, vp]
count = ctypes.c_uint32()
if enumerate_(None, ctypes.byref(count), None) != 0 or not count.value:
return None
props = (ExtensionProperties * count.value)()
if enumerate_(None, ctypes.byref(count), props) not in (0, 5): # VK_SUCCESS, VK_INCOMPLETE
return None
if not any(p.extensionName == PORTABILITY_ENUMERATION for p in props[:count.value]):
return None
return (ctypes.c_char_p * 1)(PORTABILITY_ENUMERATION)


def rdna2_amd_windows(vendor_id: int, device_id: int, driver_id: int) -> bool:
"""An RDNA2 GPU under AMD's proprietary (Windows) driver: the one whose compiler crashes on #857's modules."""
return (vendor_id == AMD_VENDOR_ID and driver_id == VK_DRIVER_ID_AMD_PROPRIETARY
Expand Down Expand Up @@ -256,6 +285,13 @@ def query(*, stage_caps=False) -> dict:
vk.vkDestroyInstance.argtypes = [vp, vp]
app = AppInfo(VK_STRUCTURE_TYPE_APPLICATION_INFO, None, b"leonida-subgroup-info", 1, None, 0, VK_API_VERSION_1_3)
info = InstanceInfo(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, None, 0, ctypes.pointer(app), 0, None, 0, None)
portability = portability_enumeration(vk)
if portability is not None:
# Behind the Vulkan loader on a Mac, MoltenVK is a portability driver that the loader lists only for an
# instance that opts in, as runtime/test/vulkan_loader.h does for the C++ test tools.
info.flags = VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR
info.enabledExtensionCount = 1
info.ppEnabledExtensionNames = ctypes.cast(portability, ctypes.c_void_p)
inst = ctypes.c_void_p()
r = vk.vkCreateInstance(ctypes.byref(info), None, ctypes.byref(inst))
if r != 0:
Expand Down
Loading