summaryrefslogtreecommitdiff
path: root/tests/cpp-compiler/cpp-compile.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'tests/cpp-compiler/cpp-compile.cpp')
0 files changed, 0 insertions, 0 deletions
='n76' href='#n76'>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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
// main.cpp

// This file provides the application code for the `hello-world` example.
//

// This example uses Vulkan to run a simple compute shader written in Slang.
// The goal is to demonstrate how to use the Slang API to cross compile
// shader code.
//
#include "core/slang-string-util.h"
#include "examples/example-base/example-base.h"
#include "examples/example-base/test-base.h"
#include "slang-com-ptr.h"
#include "slang.h"
#include "vulkan-api.h"

using Slang::ComPtr;

static const ExampleResources resourceBase("hello-world");

struct HelloWorldExample : public TestBase
{
    // The Vulkan functions pointers result from loading the vulkan library.
    VulkanAPI vkAPI;

    // Vulkan objects used in this example.
    VkQueue queue;
    VkCommandPool commandPool = VK_NULL_HANDLE;

    // Input and output buffers.
    VkBuffer inOutBuffers[3] = {};
    VkDeviceMemory bufferMemories[3] = {};

    const size_t inputElementCount = 16;
    const size_t bufferSize = sizeof(float) * inputElementCount;

    // We use a staging buffer allocated on host-visible memory to
    // upload/download data from GPU.
    VkBuffer stagingBuffer = VK_NULL_HANDLE;
    VkDeviceMemory stagingMemory = VK_NULL_HANDLE;

    VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
    VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
    VkPipeline pipeline = VK_NULL_HANDLE;

    // Initializes the Vulkan instance and device.
    int initVulkanInstanceAndDevice();

    // This function contains the most interesting part of this example.
    // It loads the `hello-world.slang` shader and compile it using the Slang API
    // into a SPIRV module, then create a Vulkan pipeline from the compiled shader.
    int createComputePipelineFromShader();

    // Creates the input and output buffers.
    int createInOutBuffers();

    // Sets up descriptor set bindings and dispatches the compute task.
    int dispatchCompute();

    // Reads back and prints the result of the compute task.
    int printComputeResults();

    // Main logic of this example.
    int run();

    ~HelloWorldExample();
};


int exampleMain(int argc, char** argv)
{
    initDebugCallback();
    HelloWorldExample example;
    example.parseOption(argc, argv);
    return example.run();
}

/************************************************************/
/* HelloWorldExample Implementation */
/************************************************************/

int HelloWorldExample::run()
{
    // If VK failed to initialize, skip running but return success anyway.
    // This allows our automated testing to distinguish between essential failures and the
    // case where the application is just not supported.
    if (int result = initVulkanInstanceAndDevice())
        return (vkAPI.device == VK_NULL_HANDLE) ? 0 : result;
    RETURN_ON_FAIL(createComputePipelineFromShader());
    RETURN_ON_FAIL(createInOutBuffers());
    RETURN_ON_FAIL(dispatchCompute());
    RETURN_ON_FAIL(printComputeResults());
    return 0;
}

int HelloWorldExample::initVulkanInstanceAndDevice()
{
    if (initializeVulkanDevice(vkAPI) != 0)
    {
        printf("Failed to load Vulkan.\n");
        return -1;
    }

    VkCommandPoolCreateInfo poolCreateInfo = {};
    poolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
    poolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
    poolCreateInfo.queueFamilyIndex = vkAPI.queueFamilyIndex;
    RETURN_ON_FAIL(vkAPI.vkCreateCommandPool(vkAPI.device, &poolCreateInfo, nullptr, &commandPool));

    vkAPI.vkGetDeviceQueue(vkAPI.device, vkAPI.queueFamilyIndex, 0, &queue);
    return 0;
}

int HelloWorldExample::createComputePipelineFromShader()
{
    // First we need to create slang global session with work with the Slang API.
    ComPtr<slang::IGlobalSession> slangGlobalSession;
    RETURN_ON_FAIL(slang::createGlobalSession(slangGlobalSession.writeRef()));

    // Next we create a compilation session to generate SPIRV code from Slang source.
    slang::SessionDesc sessionDesc = {};
    slang::TargetDesc targetDesc = {};
    targetDesc.format = SLANG_SPIRV;
    targetDesc.profile = slangGlobalSession->findProfile("spirv_1_5");
    targetDesc.flags = 0;


    sessionDesc.targets = &targetDesc;
    sessionDesc.targetCount = 1;

    std::vector<slang::CompilerOptionEntry> options;
    options.push_back(
        {slang::CompilerOptionName::EmitSpirvDirectly,
         {slang::CompilerOptionValueKind::Int, 1, 0, nullptr, nullptr}});
    sessionDesc.compilerOptionEntries = options.data();
    sessionDesc.compilerOptionEntryCount = options.size();

    ComPtr<slang::ISession> session;
    RETURN_ON_FAIL(slangGlobalSession->createSession(sessionDesc, session.writeRef()));

    // Once the session has been obtained, we can start loading code into it.
    //
    // The simplest way to load code is by calling `loadModule` with the name of a Slang
    // module. A call to `loadModule("hello-world")` will behave more or less as if you
    // wrote:
    //
    //      import hello_world;
    //
    // In a Slang shader file. The compiler will use its search paths to try to locate
    // `hello-world.slang`, then compile and load that file. If a matching module had
    // already been loaded previously, that would be used directly.
    slang::IModule* slangModule = nullptr;
    {
        ComPtr<slang::IBlob> diagnosticBlob;
        Slang::String path = resourceBase.resolveResource("hello-world.slang");
        slangModule = session->loadModule(path.getBuffer(), diagnosticBlob.writeRef());
        diagnoseIfNeeded(diagnosticBlob);
        if (!slangModule)
            return -1;
    }

    // Loading the `hello-world` module will compile and check all the shader code in it,
    // including the shader entry points we want to use. Now that the module is loaded
    // we can look up those entry points by name.
    //
    // Note: If you are using this `loadModule` approach to load your shader code it is
    // important to tag your entry point functions with the `[shader("...")]` attribute
    // (e.g., `[shader("compute")] void computeMain(...)`). Without that information there
    // is no umambiguous way for the compiler to know which functions represent entry
    // points when it parses your code via `loadModule()`.
    //
    ComPtr<slang::IEntryPoint> entryPoint;
    slangModule->findEntryPointByName("computeMain", entryPoint.writeRef());

    // At this point we have a few different Slang API objects that represent
    // pieces of our code: `module`, `vertexEntryPoint`, and `fragmentEntryPoint`.
    //
    // A single Slang module could contain many different entry points (e.g.,
    // four vertex entry points, three fragment entry points, and two compute
    // shaders), and before we try to generate output code for our target API
    // we need to identify which entry points we plan to use together.
    //
    // Modules and entry points are both examples of *component types* in the
    // Slang API. The API also provides a way to build a *composite* out of
    // other pieces, and that is what we are going to do with our module
    // and entry points.
    //
    Slang::List<slang::IComponentType*> componentTypes;
    componentTypes.add(slangModule);
    componentTypes.add(entryPoint);

    // Actually creating the composite component type is a single operation
    // on the Slang session, but the operation could potentially fail if
    // something about the composite was invalid (e.g., you are trying to
    // combine multiple copies of the same module), so we need to deal
    // with the possibility of diagnostic output.
    //
    ComPtr<slang::IComponentType> composedProgram;
    {
        ComPtr<slang::IBlob> diagnosticsBlob;
        SlangResult result = session->createCompositeComponentType(
            componentTypes.getBuffer(),
            componentTypes.getCount(),
            composedProgram.writeRef(),
            diagnosticsBlob.writeRef());
        diagnoseIfNeeded(diagnosticsBlob);
        RETURN_ON_FAIL(result);
    }

    // Now we can call `composedProgram->getEntryPointCode()` to retrieve the
    // compiled SPIRV code that we will use to create a vulkan compute pipeline.
    // This will trigger the final Slang compilation and spirv code generation.
    ComPtr<slang::IBlob> spirvCode;
    {
        ComPtr<slang::IBlob> diagnosticsBlob;
        SlangResult result = composedProgram->getEntryPointCode(
            0,
            0,
            spirvCode.writeRef(),
            diagnosticsBlob.writeRef());
        diagnoseIfNeeded(diagnosticsBlob);
        RETURN_ON_FAIL(result);

        if (isTestMode())
        {
            printEntrypointHashes(1, 1, composedProgram);
        }
    }

    // The following steps are all Vulkan API calls to create a pipeline.

    // First we need to create a descriptor set layout and a pipeline layout.
    // In this example, the pipeline layout is simple: we have a single descriptor
    // set with three buffer descriptors for our input/output storage buffers.
    // General applications typically has much more complicated pipeline layouts,
    // and should consider using Slang's reflection API to learn about the shader
    // parameter layout of a shader program. However, Slang's reflection API is
    // out of scope of this example.
    VkDescriptorSetLayoutCreateInfo descSetLayoutCreateInfo = {
        VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
    descSetLayoutCreateInfo.bindingCount = 3;
    VkDescriptorSetLayoutBinding bindings[3];
    for (int i = 0; i < 3; i++)
    {
        auto& binding = bindings[i];
        binding.binding = i;
        binding.descriptorCount = 1;
        binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
        binding.stageFlags = VK_SHADER_STAGE_ALL;
        binding.pImmutableSamplers = nullptr;
    }
    descSetLayoutCreateInfo.pBindings = bindings;
    RETURN_ON_FAIL(vkAPI.vkCreateDescriptorSetLayout(
        vkAPI.device,
        &descSetLayoutCreateInfo,
        nullptr,
        &descriptorSetLayout));
    VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {
        VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
    pipelineLayoutCreateInfo.setLayoutCount = 1;
    pipelineLayoutCreateInfo.pSetLayouts = &descriptorSetLayout;
    RETURN_ON_FAIL(vkAPI.vkCreatePipelineLayout(
        vkAPI.device,
        &pipelineLayoutCreateInfo,
        nullptr,
        &pipelineLayout));

    // Next we create a shader module from the compiled SPIRV code.
    VkShaderModuleCreateInfo shaderCreateInfo = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
    shaderCreateInfo.codeSize = spirvCode->getBufferSize();
    shaderCreateInfo.pCode = static_cast<const uint32_t*>(spirvCode->getBufferPointer());
    VkShaderModule vkShaderModule;
    RETURN_ON_FAIL(
        vkAPI.vkCreateShaderModule(vkAPI.device, &shaderCreateInfo, nullptr, &vkShaderModule));

    // Now we have all we need to create a compute pipeline.
    VkComputePipelineCreateInfo pipelineCreateInfo = {
        VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
    pipelineCreateInfo.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    pipelineCreateInfo.stage.module = vkShaderModule;
    pipelineCreateInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
    pipelineCreateInfo.stage.pName = "main";
    pipelineCreateInfo.layout = pipelineLayout;
    RETURN_ON_FAIL(vkAPI.vkCreateComputePipelines(
        vkAPI.device,
        VK_NULL_HANDLE,
        1,
        &pipelineCreateInfo,
        nullptr,
        &pipeline));

    // We can destroy shader module now since it will no longer be used.
    vkAPI.vkDestroyShaderModule(vkAPI.device, vkShaderModule, nullptr);

    return 0;
}

int HelloWorldExample::createInOutBuffers()
{
    // Create input and output buffers that resides in device-local memory.
    for (int i = 0; i < 3; i++)
    {
        VkBufferCreateInfo bufferCreateInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
        bufferCreateInfo.size = bufferSize;
        bufferCreateInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
                                 VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
                                 VK_BUFFER_USAGE_TRANSFER_DST_BIT;
        RETURN_ON_FAIL(
            vkAPI.vkCreateBuffer(vkAPI.device, &bufferCreateInfo, nullptr, &inOutBuffers[i]));
        VkMemoryRequirements memoryReqs = {};
        vkAPI.vkGetBufferMemoryRequirements(vkAPI.device, inOutBuffers[i], &memoryReqs);

        int memoryTypeIndex = vkAPI.findMemoryTypeIndex(
            memoryReqs.memoryTypeBits,
            VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
        assert(memoryTypeIndex >= 0);

        VkMemoryPropertyFlags actualMemoryProperites =
            vkAPI.deviceMemoryProperties.memoryTypes[memoryTypeIndex].propertyFlags;

        VkMemoryAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
        allocateInfo.allocationSize = memoryReqs.size;
        allocateInfo.memoryTypeIndex = memoryTypeIndex;
        RETURN_ON_FAIL(
            vkAPI.vkAllocateMemory(vkAPI.device, &allocateInfo, nullptr, &bufferMemories[i]));
        RETURN_ON_FAIL(
            vkAPI.vkBindBufferMemory(vkAPI.device, inOutBuffers[i], bufferMemories[i], 0));
    }

    // Create the device memory and buffer object used for reading/writing
    // data to/from the device local buffers.
    {
        VkBufferCreateInfo bufferCreateInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
        bufferCreateInfo.size = bufferSize;
        bufferCreateInfo.usage =
            VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
        RETURN_ON_FAIL(
            vkAPI.vkCreateBuffer(vkAPI.device, &bufferCreateInfo, nullptr, &stagingBuffer));
        VkMemoryRequirements memoryReqs = {};
        vkAPI.vkGetBufferMemoryRequirements(vkAPI.device, stagingBuffer, &memoryReqs);

        int memoryTypeIndex = vkAPI.findMemoryTypeIndex(
            memoryReqs.memoryTypeBits,
            VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
        assert(memoryTypeIndex >= 0);

        VkMemoryPropertyFlags actualMemoryProperites =
            vkAPI.deviceMemoryProperties.memoryTypes[memoryTypeIndex].propertyFlags;

        VkMemoryAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
        allocateInfo.allocationSize = memoryReqs.size;
        allocateInfo.memoryTypeIndex = memoryTypeIndex;
        RETURN_ON_FAIL(
            vkAPI.vkAllocateMemory(vkAPI.device, &allocateInfo, nullptr, &stagingMemory));
        RETURN_ON_FAIL(vkAPI.vkBindBufferMemory(vkAPI.device, stagingBuffer, stagingMemory, 0));
    }

    // Map staging buffer and writes in the initial input content.
    float* stagingBufferData = nullptr;
    vkAPI.vkMapMemory(vkAPI.device, stagingMemory, 0, bufferSize, 0, (void**)&stagingBufferData);
    if (!stagingBufferData)
        return -1;
    for (size_t i = 0; i < inputElementCount; i++)
        stagingBufferData[i] = static_cast<float>(i);
    vkAPI.vkUnmapMemory(vkAPI.device, stagingMemory);

    // Create a temporary command buffer for recording commands that writes initial
    // data into the input buffers.
    VkCommandBuffer uploadCommandBuffer;
    VkCommandBufferAllocateInfo commandBufferAllocInfo = {
        VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
    commandBufferAllocInfo.commandBufferCount = 1;
    commandBufferAllocInfo.commandPool = commandPool;
    commandBufferAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
    RETURN_ON_FAIL(vkAPI.vkAllocateCommandBuffers(
        vkAPI.device,
        &commandBufferAllocInfo,
        &uploadCommandBuffer));

    VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
    vkAPI.vkBeginCommandBuffer(uploadCommandBuffer, &beginInfo);
    VkBufferCopy bufferCopy = {};
    bufferCopy.size = bufferSize;
    vkAPI.vkCmdCopyBuffer(uploadCommandBuffer, stagingBuffer, inOutBuffers[0], 1, &bufferCopy);
    vkAPI.vkCmdCopyBuffer(uploadCommandBuffer, stagingBuffer, inOutBuffers[1], 1, &bufferCopy);
    vkAPI.vkEndCommandBuffer(uploadCommandBuffer);
    VkSubmitInfo submitInfo = {VK_STRUCTURE_TYPE_SUBMIT_INFO};
    submitInfo.commandBufferCount = 1;
    submitInfo.pCommandBuffers = &uploadCommandBuffer;
    vkAPI.vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
    vkAPI.vkQueueWaitIdle(queue);
    vkAPI.vkFreeCommandBuffers(vkAPI.device, commandPool, 1, &uploadCommandBuffer);
    return 0;
}

int HelloWorldExample::dispatchCompute()
{
    // Create a descriptor pool.
    VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = {
        VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
    VkDescriptorPoolSize poolSizes[] = {
        VkDescriptorPoolSize{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 16}};
    descriptorPoolCreateInfo.maxSets = 4;
    descriptorPoolCreateInfo.poolSizeCount = sizeof(poolSizes) / sizeof(VkDescriptorPoolSize);
    descriptorPoolCreateInfo.pPoolSizes = poolSizes;
    descriptorPoolCreateInfo.flags = 0;
    VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
    RETURN_ON_FAIL(vkAPI.vkCreateDescriptorPool(
        vkAPI.device,
        &descriptorPoolCreateInfo,
        nullptr,
        &descriptorPool));

    // Allocate descriptor set.
    VkDescriptorSetAllocateInfo descSetAllocInfo = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
    descSetAllocInfo.descriptorPool = descriptorPool;
    descSetAllocInfo.descriptorSetCount = 1;
    descSetAllocInfo.pSetLayouts = &descriptorSetLayout;
    VkDescriptorSet descriptorSet = VK_NULL_HANDLE;
    RETURN_ON_FAIL(vkAPI.vkAllocateDescriptorSets(vkAPI.device, &descSetAllocInfo, &descriptorSet));

    // Write descriptor set.
    VkWriteDescriptorSet descriptorSetWrites[3] = {};
    VkDescriptorBufferInfo bufferInfo[3];
    for (int i = 0; i < 3; i++)
    {
        bufferInfo[i].buffer = inOutBuffers[i];
        bufferInfo[i].offset = 0;
        bufferInfo[i].range = bufferSize;

        descriptorSetWrites[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
        descriptorSetWrites[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
        descriptorSetWrites[i].descriptorCount = 1;
        descriptorSetWrites[i].dstBinding = i;
        descriptorSetWrites[i].dstSet = descriptorSet;
        descriptorSetWrites[i].pBufferInfo = &bufferInfo[i];
    }