• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IntelPython / dpctl / 47405022849

04 Dec 2026 07:07PM UTC coverage: 76.45% (+1.3%) from 75.182%
47405022849

Pull #2440

github

web-flow
Merge 90ec03eae into aacf76633
Pull Request #2440: Add kernel bundle states, kernel ids and SYCL library loading

1203 of 1660 branches covered (72.47%)

Branch coverage included in aggregate %.

761 of 957 new or added lines in 4 files covered. (79.52%)

13 existing lines in 2 files now uncovered.

4809 of 6204 relevant lines covered (77.51%)

281.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

57.02
/libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp
1
//===- dpctl_sycl_kernel_bundle_interface.cpp - Implements C API for
2
//    sycl::kernel_bundle<sycl::bundle_state::executable>  ---------------===//
3
//
4
//                      Data Parallel Control (dpctl)
5
//
6
// Copyright 2020 Intel Corporation
7
//
8
// Licensed under the Apache License, Version 2.0 (the "License");
9
// you may not use this file except in compliance with the License.
10
// You may obtain a copy of the License at
11
//
12
//    http://www.apache.org/licenses/LICENSE-2.0
13
//
14
// Unless required by applicable law or agreed to in writing, software
15
// distributed under the License is distributed on an "AS IS" BASIS,
16
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
// See the License for the specific language governing permissions and
18
// limitations under the License.
19
//
20
//===----------------------------------------------------------------------===//
21
///
22
/// \file
23
/// This file implements the functions declared in
24
/// dpctl_sycl_kernel_bundle_interface.h.
25
///
26
//===----------------------------------------------------------------------===//
27

28
#ifndef __ADAPTIVECPP__
29
#include <CL/cl.h> /* OpenCL headers     */
30
#include <sycl/backend/opencl.hpp>
31
#endif
32

33
#include "Config/dpctl_config.h"
34
#include "dpctl_dynamic_lib_helper.h"
35
#include "dpctl_error_handlers.h"
36
#include "dpctl_sycl_kernel_bundle_interface.h"
37
#include "dpctl_sycl_type_casters.hpp"
38
#include <cstdint>
39
#include <cstring>
40
#include <sstream>
41
#include <stddef.h>
42
#include <sycl/sycl.hpp> /* Sycl headers       */
43
#include <utility>
44

45
#ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION
46
#ifndef __ADAPTIVECPP__
47
// Note: include ze_api.h before level_zero.hpp. Make sure clang-format does
48
// not reorder the includes.
49
// clang-format off
50
#include "ze_api.h" /* Level Zero headers */
51
#include <sycl/ext/oneapi/backend/level_zero.hpp>
52
// clang-format on
53
#endif
54
#endif
55

56
using namespace sycl;
57

58
namespace
59
{
60
#ifndef __ADAPTIVECPP__
61
static_assert(__SYCL_COMPILER_VERSION >= __SYCL_COMPILER_VERSION_REQUIRED,
62
              "The compiler does not meet minimum version requirement");
63
#endif
64

65
using namespace dpctl::syclinterface;
66

67
#ifndef __ADAPTIVECPP__
68

69
#ifdef __linux__
70
static const char *clLoaderName = DPCTL_LIBCL_LOADER_FILENAME;
71
static const int clLibLoadFlags = RTLD_NOLOAD | RTLD_NOW | RTLD_LOCAL;
72
#elif defined(_WIN64)
73
static const char *clLoaderName = "OpenCL.dll";
74
static const int clLibLoadFlags = 0;
75
#else
76
#error "OpenCL kernel bundle compilation is unavailable for this platform"
77
#endif
78

79
#define CodeStringSuffix(code)                                                 \
80
    std::string(" (code=") + std::to_string(static_cast<int>(code)) + ")"
15 ✔
81

82
#define EnumCaseString(code)                                                   \
83
    case code:                                                                 \
5 ✔
84
        return std::string(#code) + CodeStringSuffix(code)
5 ✔
85

86
static constexpr backend cl_be = backend::opencl;
87

88
struct cl_loader
89
{
90
public:
91
    static cl_loader &get()
92
    {
19 ✔
93
        static cl_loader _loader;
19 ✔
94
        return _loader;
19 ✔
95
    }
19 ✔
96

97
    template <typename retTy> retTy getSymbol(const char *name)
98
    {
19 ✔
99
        if (!opened) {
19 !
100
            error_handler("The OpenCL loader dynamic library could not "
×
101
                          "be opened.",
×
102
                          __FILE__, __func__, __LINE__);
×
103

104
            return nullptr;
×
105
        }
×
106
        return clLib.getSymbol<retTy>(name);
19 ✔
107
    }
19 ✔
108

109
private:
110
    dpctl::DynamicLibHelper clLib;
111
    bool opened;
112
    cl_loader() : clLib(clLoaderName, clLibLoadFlags), opened(clLib.opened()) {}
2 ✔
113
};
114

115
typedef cl_program (*clCreateProgramWithSourceFT)(cl_context,
116
                                                  cl_uint,
117
                                                  const char **,
118
                                                  const size_t *,
119
                                                  cl_int *);
120
const char *clCreateProgramWithSource_Name = "clCreateProgramWithSource";
121
clCreateProgramWithSourceFT get_clCreateProgramWithSource()
122
{
39 ✔
123
    static auto st_clCreateProgramWithSourceF =
39 ✔
124
        cl_loader::get().getSymbol<clCreateProgramWithSourceFT>(
39 ✔
125
            clCreateProgramWithSource_Name);
39 ✔
126

127
    return st_clCreateProgramWithSourceF;
39 ✔
128
}
39 ✔
129

130
typedef cl_program (*clCreateProgramWithILFT)(cl_context,
131
                                              const void *,
132
                                              size_t,
133
                                              cl_int *);
134
const char *clCreateProgramWithIL_Name = "clCreateProgramWithIL";
135
clCreateProgramWithILFT get_clCreateProgramWithIL()
136
{
100 ✔
137
    static auto st_clCreateProgramWithILF =
100 ✔
138
        cl_loader::get().getSymbol<clCreateProgramWithILFT>(
100 ✔
139
            clCreateProgramWithIL_Name);
100 ✔
140

141
    return st_clCreateProgramWithILF;
100 ✔
142
}
100 ✔
143
typedef cl_int (*clBuildProgramFT)(cl_program,
144
                                   cl_uint,
145
                                   const cl_device_id *,
146
                                   const char *,
147
                                   void (*)(cl_program, void *),
148
                                   void *);
149
const char *clBuildProgram_Name = "clBuildProgram";
150
clBuildProgramFT get_clBuildProgram()
151
{
139 ✔
152
    static auto st_clBuildProgramF =
139 ✔
153
        cl_loader::get().getSymbol<clBuildProgramFT>(clBuildProgram_Name);
139 ✔
154

155
    return st_clBuildProgramF;
139 ✔
156
}
139 ✔
157

158
typedef cl_kernel (*clCreateKernelFT)(cl_program, const char *, cl_int *);
159
const char *clCreateKernel_Name = "clCreateKernel";
160
clCreateKernelFT get_clCreateKernel()
161
{
193 ✔
162
    static auto st_clCreateKernelF =
193 ✔
163
        cl_loader::get().getSymbol<clCreateKernelFT>(clCreateKernel_Name);
193 ✔
164

165
    return st_clCreateKernelF;
193 ✔
166
}
193 ✔
167

168
std::string _GetErrorCode_ocl_impl(cl_int code)
169
{
5 ✔
170
    switch (code) {
5 ✔
171
        EnumCaseString(CL_BUILD_PROGRAM_FAILURE);
5 !
172
        EnumCaseString(CL_INVALID_CONTEXT);
×
173
        EnumCaseString(CL_INVALID_DEVICE);
×
174
        EnumCaseString(CL_INVALID_VALUE);
×
175
        EnumCaseString(CL_OUT_OF_RESOURCES);
×
176
        EnumCaseString(CL_OUT_OF_HOST_MEMORY);
×
177
        EnumCaseString(CL_INVALID_OPERATION);
×
178
        EnumCaseString(CL_INVALID_BINARY);
×
179
    default:
×
180
        return "<< ERROR CODE UNRECOGNIZED >>" + CodeStringSuffix(code);
×
181
    }
5 ✔
182
}
5 ✔
183

184
typedef cl_int (*clSetProgramSpecializationConstantFT)(cl_program,
185
                                                       cl_uint,
186
                                                       size_t,
187
                                                       const void *);
188
const char *clSetProgramSpecializationConstant_Name =
189
    "clSetProgramSpecializationConstant";
190
clSetProgramSpecializationConstantFT get_clSetProgramSpecializationConstant()
191
{
2 ✔
192
    static auto st_clSetProgramSpecializationConstantF =
2 ✔
193
        cl_loader::get().getSymbol<clSetProgramSpecializationConstantFT>(
2 ✔
194
            clSetProgramSpecializationConstant_Name);
2 ✔
195

196
    return st_clSetProgramSpecializationConstantF;
2 ✔
197
}
2 ✔
198

199
typedef cl_int (*clReleaseProgramFT)(cl_program);
200
const char *clReleaseProgram_Name = "clReleaseProgram";
201
clReleaseProgramFT get_clReleaseProgram()
202
{
333 ✔
203
    static auto st_clReleaseProgramF =
333 ✔
204
        cl_loader::get().getSymbol<clReleaseProgramFT>(clReleaseProgram_Name);
333 ✔
205

206
    return st_clReleaseProgramF;
333 ✔
207
}
333 ✔
208

209
typedef cl_int (*clReleaseKernelFT)(cl_kernel);
210
const char *clReleaseKernel_Name = "clReleaseKernel";
211
clReleaseKernelFT get_clReleaseKernel()
212
{
190 ✔
213
    static auto st_clReleaseKernelF =
190 ✔
214
        cl_loader::get().getSymbol<clReleaseKernelFT>(clReleaseKernel_Name);
190 ✔
215

216
    return st_clReleaseKernelF;
190 ✔
217
}
190 ✔
218

219
typedef cl_int (*clReleaseContextFT)(cl_context);
220
const char *clReleaseContext_Name = "clReleaseContext";
221
clReleaseContextFT get_clReleaseContext()
222
{
139 ✔
223
    static auto st_clReleaseContextF =
139 ✔
224
        cl_loader::get().getSymbol<clReleaseContextFT>(clReleaseContext_Name);
139 ✔
225

226
    return st_clReleaseContextF;
139 ✔
227
}
139 ✔
228

229
typedef cl_int (*clReleaseDeviceFT)(cl_device_id);
230
const char *clReleaseDevice_Name = "clReleaseDevice";
231
clReleaseDeviceFT get_clReleaseDevice()
232
{
139 ✔
233
    static auto st_clReleaseDeviceF =
139 ✔
234
        cl_loader::get().getSymbol<clReleaseDeviceFT>(clReleaseDevice_Name);
139 ✔
235

236
    return st_clReleaseDeviceF;
139 ✔
237
}
139 ✔
238

239
typedef cl_int (*clGetProgramBuildInfoFT)(cl_program,
240
                                          cl_device_id,
241
                                          cl_program_build_info,
242
                                          size_t,
243
                                          void *,
244
                                          size_t *);
245
const char *clGetProgramBuildInfo_Name = "clGetProgramBuildInfo";
246
clGetProgramBuildInfoFT get_clGetProgramBuildInfo()
247
{
5 ✔
248
    static auto st_clGetProgramBuildInfoF =
5 ✔
249
        cl_loader::get().getSymbol<clGetProgramBuildInfoFT>(
5 ✔
250
            clGetProgramBuildInfo_Name);
5 ✔
251

252
    return st_clGetProgramBuildInfoF;
5 ✔
253
}
5 ✔
254

255
void _Release_ocl_impl(cl_program clProgram)
256
{
333 ✔
257
    if (auto clReleaseProgramF = get_clReleaseProgram()) {
333 !
258
        clReleaseProgramF(clProgram);
333 ✔
259
    }
333 ✔
260
}
333 ✔
261

262
void _Release_ocl_impl(cl_kernel clKernel)
263
{
190 ✔
264
    if (auto clReleaseKernelF = get_clReleaseKernel()) {
190 !
265
        clReleaseKernelF(clKernel);
190 ✔
266
    }
190 ✔
267
}
190 ✔
268

269
void _Release_ocl_impl(cl_context clContext)
270
{
139 ✔
271
    if (auto clReleaseContextF = get_clReleaseContext()) {
139 !
272
        clReleaseContextF(clContext);
139 ✔
273
    }
139 ✔
274
}
139 ✔
275

276
void _Release_ocl_impl(cl_device_id clDevice)
277
{
139 ✔
278
    if (auto clReleaseDeviceF = get_clReleaseDevice()) {
139 !
279
        clReleaseDeviceF(clDevice);
139 ✔
280
    }
139 ✔
281
}
139 ✔
282

283
/*! Releases one reference to an OpenCL object on scope exit.
284
 * sycl::get_native and sycl::make_* retain the OpenCL object, so references
285
 * returned by get_native or clCreate* must be released by the caller.
286
 */
287
template <typename T> class cl_ref_guard
288
{
289
public:
290
    explicit cl_ref_guard(T obj) : obj_(obj) {}
716 ✔
291
    ~cl_ref_guard()
292
    {
716 ✔
293
        if (obj_) {
716 !
294
            _Release_ocl_impl(obj_);
716 ✔
295
        }
716 ✔
296
    }
716 ✔
297
    cl_ref_guard(const cl_ref_guard &) = delete;
298
    cl_ref_guard &operator=(const cl_ref_guard &) = delete;
299

300
private:
301
    T obj_;
302
};
303

304
std::string _GetBuildLog_ocl_impl(cl_program clProgram, cl_device_id clDevice)
305
{
5 ✔
306
    auto clGetProgramBuildInfoF = get_clGetProgramBuildInfo();
5 ✔
307
    if (clGetProgramBuildInfoF == nullptr) {
5 !
NEW
308
        return std::string{};
×
NEW
309
    }
×
310
    size_t log_size = 0;
5 ✔
311
    if (clGetProgramBuildInfoF(clProgram, clDevice, CL_PROGRAM_BUILD_LOG, 0,
5 !
312
                               nullptr, &log_size) != CL_SUCCESS ||
5 ✔
313
        log_size == 0)
5 !
NEW
314
    {
×
NEW
315
        return std::string{};
×
NEW
316
    }
×
317
    std::string log(log_size, '\0');
5 ✔
318
    if (clGetProgramBuildInfoF(clProgram, clDevice, CL_PROGRAM_BUILD_LOG,
5 !
319
                               log_size, log.data(), nullptr) != CL_SUCCESS)
5 ✔
NEW
320
    {
×
NEW
321
        return std::string{};
×
NEW
322
    }
×
323
    // drop the terminating null character(s)
324
    log.resize(std::strlen(log.c_str()));
5 ✔
325
    return log;
5 ✔
326
}
5 ✔
327

328
/*! Builds clProgram and wraps it in a kernel bundle. The caller keeps its
329
 * reference to clProgram and must release it. On a build failure the error
330
 * and build log are stored in Log, if not NULL.
331
 */
332
DPCTLSyclKernelBundleRef
333
_CreateKernelBundle_common_ocl_impl(cl_program clProgram,
334
                                    const context &ctx,
335
                                    const device &dev,
336
                                    const char *CompileOpts,
337
                                    std::string *Log)
338
{
139 ✔
339
    backend_traits<cl_be>::return_type<device> clDevice;
139 ✔
340
    clDevice = get_native<cl_be>(dev);
139 ✔
341
    cl_ref_guard<cl_device_id> clDeviceGuard(clDevice);
139 ✔
342

343
    // Last two pointers are notification function pointer and user-data pointer
344
    // that can be passed to the notification function.
345
    auto clBuildProgramF = get_clBuildProgram();
139 ✔
346
    if (clBuildProgramF == nullptr) {
139 !
347
        return nullptr;
×
348
    }
×
349
    cl_int build_status =
139 ✔
350
        clBuildProgramF(clProgram, 1, &clDevice, CompileOpts, nullptr, nullptr);
139 ✔
351

352
    if (build_status != CL_SUCCESS) {
139 ✔
353
        std::string msg =
5 ✔
354
            "clBuildProgram failed: " + _GetErrorCode_ocl_impl(build_status);
5 ✔
355
        const std::string &log = _GetBuildLog_ocl_impl(clProgram, clDevice);
5 ✔
356
        if (!log.empty()) {
5 !
357
            msg += "\nBuild log:\n" + log;
5 ✔
358
        }
5 ✔
359
        if (Log) {
5 ✔
360
            *Log = msg;
3 ✔
361
        }
3 ✔
362
        error_handler(msg, __FILE__, __func__, __LINE__, error_level::error);
5 ✔
363
        return nullptr;
5 ✔
364
    }
5 ✔
365

366
    using ekbTy = kernel_bundle<bundle_state::executable>;
134 ✔
367
    return wrap<ekbTy>(new ekbTy(
134 ✔
368
        make_kernel_bundle<cl_be, bundle_state::executable>(clProgram, ctx)));
134 ✔
369
}
139 ✔
370

371
DPCTLSyclKernelBundleRef
372
_CreateKernelBundleWithOCLSource_ocl_impl(const context &ctx,
373
                                          const device &dev,
374
                                          const char *oclSrc,
375
                                          const char *CompileOpts,
376
                                          std::string *Log)
377
{
39 ✔
378
    auto clCreateProgramWithSourceF = get_clCreateProgramWithSource();
39 ✔
379
    if (clCreateProgramWithSourceF == nullptr) {
39 !
380
        return nullptr;
×
381
    }
×
382

383
    backend_traits<cl_be>::return_type<context> clContext;
39 ✔
384
    clContext = get_native<cl_be>(ctx);
39 ✔
385
    cl_ref_guard<cl_context> clContextGuard(clContext);
39 ✔
386

387
    cl_int build_with_source_err_code = CL_SUCCESS;
39 ✔
388
    cl_program clProgram = clCreateProgramWithSourceF(
39 ✔
389
        clContext, 1, &oclSrc, nullptr, &build_with_source_err_code);
39 ✔
390

391
    if (build_with_source_err_code != CL_SUCCESS) {
39 !
392
        error_handler("clPCreateProgramWithSource failed with " +
×
393
                          _GetErrorCode_ocl_impl(build_with_source_err_code),
×
394
                      __FILE__, __func__, __LINE__);
×
395
        return nullptr;
×
396
    }
×
397
    cl_ref_guard<cl_program> clProgramGuard(clProgram);
39 ✔
398

399
    return _CreateKernelBundle_common_ocl_impl(clProgram, ctx, dev, CompileOpts,
39 ✔
400
                                               Log);
39 ✔
401
}
39 ✔
402

403
DPCTLSyclKernelBundleRef
404
_CreateKernelBundleWithIL_ocl_impl(const context &ctx,
405
                                   const device &dev,
406
                                   const void *IL,
407
                                   size_t il_length,
408
                                   const char *CompileOpts,
409
                                   size_t NumSpecConsts,
410
                                   const DPCTLSpecConst *SpecConsts,
411
                                   std::string *Log)
412
{
100 ✔
413
    auto clCreateProgramWithILF = get_clCreateProgramWithIL();
100 ✔
414
    if (clCreateProgramWithILF == nullptr) {
100 !
415
        return nullptr;
×
416
    }
×
417

418
    if (NumSpecConsts > 0 && SpecConsts == nullptr) {
100 !
UNCOV
419
        error_handler("NumSpecConsts > 0 but SpecConsts is NULL.", __FILE__,
×
420
                      __func__, __LINE__);
×
421
        return nullptr;
×
422
    }
×
423

424
    backend_traits<cl_be>::return_type<context> clContext;
100 ✔
425
    clContext = get_native<cl_be>(ctx);
100 ✔
426
    cl_ref_guard<cl_context> clContextGuard(clContext);
100 ✔
427

428
    cl_int create_err_code = CL_SUCCESS;
100 ✔
429
    cl_program clProgram =
100 ✔
430
        clCreateProgramWithILF(clContext, IL, il_length, &create_err_code);
100 ✔
431

432
    if (create_err_code != CL_SUCCESS) {
100 !
433
        error_handler("OpenCL program could not be created from the SPIR-V "
×
434
                      "binary. OpenCL Error " +
×
435
                          _GetErrorCode_ocl_impl(create_err_code),
×
436
                      __FILE__, __func__, __LINE__);
×
437
        return nullptr;
×
438
    }
×
439
    cl_ref_guard<cl_program> clProgramGuard(clProgram);
100 ✔
440

441
    if (SpecConsts != nullptr && NumSpecConsts > 0) {
100 !
442
        auto clSetProgramSpecConstF = get_clSetProgramSpecializationConstant();
2 ✔
443
        if (clSetProgramSpecConstF) {
2 !
444
            for (size_t i = 0; i < NumSpecConsts; ++i) {
6 ✔
445
                cl_int spec_err = clSetProgramSpecConstF(
4 ✔
446
                    clProgram, SpecConsts[i].id, SpecConsts[i].size,
4 ✔
447
                    SpecConsts[i].value);
4 ✔
448
                if (spec_err != CL_SUCCESS) {
4 !
449
                    error_handler(
×
450
                        "clSetProgramSpecializationConstant failed for "
×
451
                        "spec constant id " +
×
452
                            std::to_string(SpecConsts[i].id) +
×
453
                            ". OpenCL Error " +
×
454
                            _GetErrorCode_ocl_impl(spec_err),
×
455
                        __FILE__, __func__, __LINE__);
×
UNCOV
456
                    return nullptr;
×
457
                }
×
458
            }
4 ✔
459
        }
2 ✔
460
        else {
×
461
            error_handler("clSetProgramSpecializationConstant is not available "
×
462
                          "in the OpenCL implementation.",
×
463
                          __FILE__, __func__, __LINE__);
×
UNCOV
464
            return nullptr;
×
465
        }
×
466
    }
2 ✔
467

468
    return _CreateKernelBundle_common_ocl_impl(clProgram, ctx, dev, CompileOpts,
100 ✔
469
                                               Log);
100 ✔
470
}
100 ✔
471

472
bool _HasKernel_ocl_impl(const kernel_bundle<bundle_state::executable> &kb,
473
                         const char *kernel_name)
474
{
86 ✔
475
    auto clCreateKernelF = get_clCreateKernel();
86 ✔
476
    if (clCreateKernelF == nullptr) {
86 !
477
        return false;
×
478
    }
×
479

480
    std::vector<cl_program> oclKB = get_native<cl_be>(kb);
86 ✔
481

482
    bool found = false;
86 ✔
483
    for (auto &cl_pr : oclKB) {
86 ✔
484
        cl_ref_guard<cl_program> clProgramGuard(cl_pr);
86 ✔
485
        if (found) {
86 !
NEW
486
            continue;
×
NEW
487
        }
×
488
        cl_int create_kernel_err_code = CL_SUCCESS;
86 ✔
489
        cl_kernel try_kern =
86 ✔
490
            clCreateKernelF(cl_pr, kernel_name, &create_kernel_err_code);
86 ✔
491
        if (create_kernel_err_code == CL_SUCCESS) {
86 ✔
492
            found = true;
85 ✔
493
            _Release_ocl_impl(try_kern);
85 ✔
494
        }
85 ✔
495
    }
86 ✔
496
    return found;
86 ✔
497
}
86 ✔
498

499
__dpctl_give DPCTLSyclKernelRef
500
_GetKernel_ocl_impl(const kernel_bundle<bundle_state::executable> &kb,
501
                    const char *kernel_name)
502
{
107 ✔
503
    auto clCreateKernelF = get_clCreateKernel();
107 ✔
504
    if (clCreateKernelF == nullptr) {
107 !
505
        return nullptr;
×
506
    }
×
507

508
    std::vector<cl_program> oclKB = get_native<cl_be>(kb);
107 ✔
509

510
    cl_kernel ocl_kernel_from_kb = nullptr;
107 ✔
511
    for (auto &cl_pr : oclKB) {
108 ✔
512
        cl_ref_guard<cl_program> clProgramGuard(cl_pr);
108 ✔
513
        if (ocl_kernel_from_kb) {
108 ✔
514
            continue;
1 ✔
515
        }
1 ✔
516
        cl_int create_kernel_err_code = CL_SUCCESS;
107 ✔
517
        cl_kernel try_kern =
107 ✔
518
            clCreateKernelF(cl_pr, kernel_name, &create_kernel_err_code);
107 ✔
519
        if (create_kernel_err_code == CL_SUCCESS) {
107 ✔
520
            ocl_kernel_from_kb = try_kern;
105 ✔
521
        }
105 ✔
522
    }
107 ✔
523
    if (!ocl_kernel_from_kb) {
107 ✔
524
        error_handler("Kernel " + std::string(kernel_name) + " not found.",
2 ✔
525
                      __FILE__, __func__, __LINE__);
2 ✔
526
        return nullptr;
2 ✔
527
    }
2 ✔
528
    cl_ref_guard<cl_kernel> clKernelGuard(ocl_kernel_from_kb);
105 ✔
529
    try {
105 ✔
530
        context ctx = kb.get_context();
105 ✔
531
        return wrap<kernel>(
105 ✔
532
            new kernel(make_kernel<cl_be>(ocl_kernel_from_kb, ctx)));
105 ✔
533
    } catch (std::exception const &e) {
105 ✔
NEW
534
        error_handler(e, __FILE__, __func__, __LINE__);
×
NEW
535
        return nullptr;
×
NEW
536
    }
×
537
}
105 ✔
538

539
#ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION
540

541
#ifdef __linux__
542
static const char *zeLoaderName = DPCTL_LIBZE_LOADER_FILENAME;
543
static const int zeLibLoadFlags = RTLD_NOLOAD | RTLD_NOW | RTLD_LOCAL;
544
#elif defined(_WIN64)
545
static const char *zeLoaderName = "ze_loader.dll";
546
static const int zeLibLoadFlags = 0;
547
#else
548
#error "Level Zero kernel bundle compilation is unavailable for this platform"
549
#endif
550

551
static constexpr sycl::backend ze_be = sycl::backend::ext_oneapi_level_zero;
552

553
struct ze_loader
554
{
555
public:
556
    static ze_loader &get()
557
    {
×
558
        static ze_loader _loader;
×
559
        return _loader;
×
560
    }
×
561

562
    template <typename retTy> retTy getSymbol(const char *name)
563
    {
×
564
        if (!opened) {
×
565
            error_handler("The Level-Zero loader dynamic library could not "
×
566
                          "be opened.",
×
567
                          __FILE__, __func__, __LINE__);
×
568

569
            return nullptr;
×
570
        }
×
571
        return zeLib.getSymbol<retTy>(name);
×
572
    }
×
573

574
private:
575
    dpctl::DynamicLibHelper zeLib;
576
    bool opened;
577
    ze_loader() : zeLib(zeLoaderName, zeLibLoadFlags), opened(zeLib.opened()) {}
×
578
};
579

580
typedef ze_result_t (*zeModuleCreateFT)(ze_context_handle_t,
581
                                        ze_device_handle_t,
582
                                        const ze_module_desc_t *,
583
                                        ze_module_handle_t *,
584
                                        ze_module_build_log_handle_t *);
585
const char *zeModuleCreate_Name = "zeModuleCreate";
586
zeModuleCreateFT get_zeModuleCreate()
587
{
×
588
    static auto st_zeModuleCreateF =
×
589
        ze_loader::get().getSymbol<zeModuleCreateFT>(zeModuleCreate_Name);
×
590

591
    return st_zeModuleCreateF;
×
592
}
×
593

594
typedef ze_result_t (*zeKernelCreateFT)(ze_module_handle_t,
595
                                        const ze_kernel_desc_t *,
596
                                        ze_kernel_handle_t *);
597
const char *zeKernelCreate_Name = "zeKernelCreate";
598
zeKernelCreateFT get_zeKernelCreate()
599
{
×
600
    static auto st_zeKernelCreateF =
×
601
        ze_loader::get().getSymbol<zeKernelCreateFT>(zeKernelCreate_Name);
×
602

603
    return st_zeKernelCreateF;
×
604
}
×
605

606
typedef ze_result_t (*zeKernelDestroyFT)(ze_kernel_handle_t);
607
const char *zeKernelDestroy_Name = "zeKernelDestroy";
608
zeKernelDestroyFT get_zeKernelDestroy()
NEW
609
{
×
NEW
610
    static auto st_zeKernelDestroyF =
×
NEW
611
        ze_loader::get().getSymbol<zeKernelDestroyFT>(zeKernelDestroy_Name);
×
612

NEW
613
    return st_zeKernelDestroyF;
×
NEW
614
}
×
615

616
typedef ze_result_t (*zeModuleBuildLogGetStringFT)(ze_module_build_log_handle_t,
617
                                                   size_t *,
618
                                                   char *);
619
const char *zeModuleBuildLogGetString_Name = "zeModuleBuildLogGetString";
620
zeModuleBuildLogGetStringFT get_zeModuleBuildLogGetString()
NEW
621
{
×
NEW
622
    static auto st_zeModuleBuildLogGetStringF =
×
NEW
623
        ze_loader::get().getSymbol<zeModuleBuildLogGetStringFT>(
×
NEW
624
            zeModuleBuildLogGetString_Name);
×
625

NEW
626
    return st_zeModuleBuildLogGetStringF;
×
NEW
627
}
×
628

629
typedef ze_result_t (*zeModuleBuildLogDestroyFT)(ze_module_build_log_handle_t);
630
const char *zeModuleBuildLogDestroy_Name = "zeModuleBuildLogDestroy";
631
zeModuleBuildLogDestroyFT get_zeModuleBuildLogDestroy()
NEW
632
{
×
NEW
633
    static auto st_zeModuleBuildLogDestroyF =
×
NEW
634
        ze_loader::get().getSymbol<zeModuleBuildLogDestroyFT>(
×
NEW
635
            zeModuleBuildLogDestroy_Name);
×
636

NEW
637
    return st_zeModuleBuildLogDestroyF;
×
NEW
638
}
×
639

640
void _DestroyKernel_ze_impl(ze_kernel_handle_t ZeKernel)
NEW
641
{
×
NEW
642
    if (auto zeKernelDestroyFn = get_zeKernelDestroy()) {
×
NEW
643
        zeKernelDestroyFn(ZeKernel);
×
NEW
644
    }
×
NEW
645
}
×
646

647
/*! Returns the contents of the build log and destroys it. */
648
std::string _ConsumeBuildLog_ze_impl(ze_module_build_log_handle_t ZeBuildLog)
NEW
649
{
×
NEW
650
    std::string log{};
×
NEW
651
    if (ZeBuildLog == nullptr) {
×
NEW
652
        return log;
×
NEW
653
    }
×
NEW
654
    auto zeModuleBuildLogGetStringFn = get_zeModuleBuildLogGetString();
×
NEW
655
    size_t log_size = 0;
×
NEW
656
    if (zeModuleBuildLogGetStringFn &&
×
NEW
657
        zeModuleBuildLogGetStringFn(ZeBuildLog, &log_size, nullptr) ==
×
NEW
658
            ZE_RESULT_SUCCESS &&
×
NEW
659
        log_size > 0)
×
NEW
660
    {
×
NEW
661
        log.resize(log_size);
×
NEW
662
        if (zeModuleBuildLogGetStringFn(ZeBuildLog, &log_size, log.data()) ==
×
NEW
663
            ZE_RESULT_SUCCESS)
×
NEW
664
        {
×
665
            // drop the terminating null character(s)
NEW
666
            log.resize(std::strlen(log.c_str()));
×
NEW
667
        }
×
NEW
668
        else {
×
NEW
669
            log.clear();
×
NEW
670
        }
×
NEW
671
    }
×
NEW
672
    if (auto zeModuleBuildLogDestroyFn = get_zeModuleBuildLogDestroy()) {
×
NEW
673
        zeModuleBuildLogDestroyFn(ZeBuildLog);
×
NEW
674
    }
×
NEW
675
    return log;
×
NEW
676
}
×
677

678
std::string _GetErrorCode_ze_impl(ze_result_t code)
679
{
×
680
    switch (code) {
×
681
        EnumCaseString(ZE_RESULT_ERROR_UNINITIALIZED);
×
682
        EnumCaseString(ZE_RESULT_ERROR_DEVICE_LOST);
×
683
        EnumCaseString(ZE_RESULT_ERROR_INVALID_NULL_HANDLE);
×
684
        EnumCaseString(ZE_RESULT_ERROR_INVALID_NULL_POINTER);
×
685
        EnumCaseString(ZE_RESULT_ERROR_INVALID_ENUMERATION);
×
686
        EnumCaseString(ZE_RESULT_ERROR_INVALID_NATIVE_BINARY);
×
687
        EnumCaseString(ZE_RESULT_ERROR_INVALID_SIZE);
×
688
        EnumCaseString(ZE_RESULT_ERROR_OUT_OF_HOST_MEMORY);
×
689
        EnumCaseString(ZE_RESULT_ERROR_OUT_OF_DEVICE_MEMORY);
×
690
        EnumCaseString(ZE_RESULT_ERROR_MODULE_BUILD_FAILURE);
×
691
        EnumCaseString(ZE_RESULT_ERROR_INVALID_MODULE_UNLINKED);
×
692
    default:
×
693
        return "<< UNRECOGNIZED ZE_RESULT_T CODE >> " + CodeStringSuffix(code);
×
694
    }
×
695
}
×
696

697
__dpctl_give DPCTLSyclKernelBundleRef
698
_CreateKernelBundleWithIL_ze_impl(const context &SyclCtx,
699
                                  const device &SyclDev,
700
                                  const void *IL,
701
                                  size_t il_length,
702
                                  const char *CompileOpts,
703
                                  size_t NumSpecConsts,
704
                                  const DPCTLSpecConst *SpecConsts,
705
                                  std::string *Log)
706
{
×
707
    auto zeModuleCreateFn = get_zeModuleCreate();
×
708
    if (zeModuleCreateFn == nullptr) {
×
709
        error_handler("ZeModuleCreateFn is invalid.", __FILE__, __func__,
×
710
                      __LINE__);
×
711
        return nullptr;
×
712
    }
×
713

714
    backend_traits<ze_be>::return_type<context> ZeContext;
×
715
    ZeContext = get_native<ze_be>(SyclCtx);
×
716

717
    backend_traits<ze_be>::return_type<device> ZeDevice;
×
718
    ZeDevice = get_native<ze_be>(SyclDev);
×
719

720
    if (NumSpecConsts > 0 && SpecConsts == nullptr) {
×
721
        error_handler("NumSpecConsts > 0 but SpecConsts is NULL.", __FILE__,
×
722
                      __func__, __LINE__);
×
723
        return nullptr;
×
724
    }
×
725

726
    std::vector<std::uint32_t> spec_ids;
×
727
    std::vector<const void *> spec_values;
×
728

729
    if (SpecConsts != nullptr && NumSpecConsts > 0) {
×
730
        spec_ids.reserve(NumSpecConsts);
×
731
        spec_values.reserve(NumSpecConsts);
×
732
        for (size_t i = 0; i < NumSpecConsts; ++i) {
×
733
            spec_ids.push_back(SpecConsts[i].id);
×
734
            spec_values.push_back(SpecConsts[i].value);
×
735
        }
×
736
    }
×
737
    ze_module_constants_t ZeSpecConstants = {};
×
738
    ZeSpecConstants.numConstants = static_cast<std::uint32_t>(spec_ids.size());
×
739
    ZeSpecConstants.pConstantIds = spec_ids.empty() ? nullptr : spec_ids.data();
×
740
    ZeSpecConstants.pConstantValues =
×
741
        spec_values.empty() ? nullptr : spec_values.data();
×
742

743
    // Populate the Level Zero module descriptions
744
    ze_module_desc_t ZeModuleDesc = {};
×
745
    ZeModuleDesc.stype = ZE_STRUCTURE_TYPE_MODULE_DESC;
×
746
    ZeModuleDesc.format = ZE_MODULE_FORMAT_IL_SPIRV;
×
747
    ZeModuleDesc.inputSize = il_length;
×
748
    ZeModuleDesc.pInputModule = (uint8_t *)IL;
×
749
    ZeModuleDesc.pBuildFlags = CompileOpts;
×
750
    ZeModuleDesc.pConstants = &ZeSpecConstants;
×
751

NEW
752
    ze_module_handle_t ZeModule = nullptr;
×
NEW
753
    ze_module_build_log_handle_t ZeBuildLog = nullptr;
×
754

755
    auto ret_code = zeModuleCreateFn(ZeContext, ZeDevice, &ZeModuleDesc,
×
NEW
756
                                     &ZeModule, &ZeBuildLog);
×
NEW
757
    const std::string &log = _ConsumeBuildLog_ze_impl(ZeBuildLog);
×
758
    if (ret_code != ZE_RESULT_SUCCESS) {
×
NEW
759
        std::string msg =
×
NEW
760
            "Module creation failed " + _GetErrorCode_ze_impl(ret_code);
×
NEW
761
        if (!log.empty()) {
×
NEW
762
            msg += "\nBuild log:\n" + log;
×
NEW
763
        }
×
NEW
764
        if (Log) {
×
NEW
765
            *Log = msg;
×
NEW
766
        }
×
NEW
767
        error_handler(msg, __FILE__, __func__, __LINE__, error_level::error);
×
768
        return nullptr;
×
769
    }
×
770

771
    // With ownership::transfer the kernel bundle destroys ZeModule. If
772
    // make_kernel_bundle throws, it may already own ZeModule, so ZeModule is
773
    // leaked rather than destroyed.
NEW
774
    using ekbTy = kernel_bundle<bundle_state::executable>;
×
775
    try {
×
NEW
776
        return wrap<ekbTy>(
×
NEW
777
            new ekbTy(make_kernel_bundle<ze_be, bundle_state::executable>(
×
NEW
778
                {ZeModule, ext::oneapi::level_zero::ownership::transfer},
×
NEW
779
                SyclCtx)));
×
780
    } catch (std::exception const &e) {
×
781
        error_handler(e, __FILE__, __func__, __LINE__);
×
782
        return nullptr;
×
783
    }
×
784
}
×
785

786
__dpctl_give DPCTLSyclKernelRef
787
_GetKernel_ze_impl(const kernel_bundle<bundle_state::executable> &kb,
788
                   const char *kernel_name)
789
{
×
790
    auto zeKernelCreateFn = get_zeKernelCreate();
×
791
    if (zeKernelCreateFn == nullptr) {
×
792
        error_handler("Could not load zeKernelCreate function.", __FILE__,
×
793
                      __func__, __LINE__);
×
794
        return nullptr;
×
795
    }
×
796

797
    auto ZeKernelBundle = sycl::get_native<ze_be>(kb);
×
798

799
    // Populate the Level Zero kernel descriptions
800
    ze_kernel_desc_t ZeKernelDescr = {ZE_STRUCTURE_TYPE_KERNEL_DESC, nullptr,
×
801
                                      0, // flags
×
802
                                      kernel_name};
×
803

804
    for (auto &ZeM : ZeKernelBundle) {
×
NEW
805
        ze_kernel_handle_t ZeKern = nullptr;
×
UNCOV
806
        ze_result_t ze_status = zeKernelCreateFn(ZeM, &ZeKernelDescr, &ZeKern);
×
807

808
        if (ze_status == ZE_RESULT_SUCCESS) {
×
809
            // With ownership::transfer the kernel destroys ZeKern. If
810
            // make_kernel throws, it may already own ZeKern, so ZeKern is
811
            // leaked rather than destroyed.
NEW
812
            try {
×
NEW
813
                const auto &ctx = kb.get_context();
×
NEW
814
                return wrap<kernel>(new kernel(make_kernel<ze_be>(
×
NEW
815
                    {kb, ZeKern, ext::oneapi::level_zero::ownership::transfer},
×
NEW
816
                    ctx)));
×
NEW
817
            } catch (std::exception const &e) {
×
NEW
818
                error_handler(e, __FILE__, __func__, __LINE__);
×
NEW
819
                return nullptr;
×
NEW
820
            }
×
821
        }
×
822
        else {
×
823
            if (ze_status != ZE_RESULT_ERROR_INVALID_KERNEL_NAME) {
×
824
                error_handler("zeKernelCreate failed: " +
×
825
                                  _GetErrorCode_ze_impl(ze_status),
×
826
                              __FILE__, __func__, __LINE__);
×
827
                return nullptr;
×
828
            }
×
829
        }
×
830
    }
×
831

NEW
832
    error_handler("Kernel named " + std::string(kernel_name) +
×
NEW
833
                      " could not be found.",
×
NEW
834
                  __FILE__, __func__, __LINE__, error_level::error);
×
NEW
835
    return nullptr;
×
UNCOV
836
}
×
837

838
bool _HasKernel_ze_impl(const kernel_bundle<bundle_state::executable> &kb,
839
                        const char *kernel_name)
840
{
×
841
    auto zeKernelCreateFn = get_zeKernelCreate();
×
842
    if (zeKernelCreateFn == nullptr) {
×
843
        error_handler("Could not load zeKernelCreate function.", __FILE__,
×
844
                      __func__, __LINE__, error_level::error);
×
845
        return false;
×
846
    }
×
847

848
    auto ZeKernelBundle = sycl::get_native<ze_be>(kb);
×
849

850
    // Populate the Level Zero kernel descriptions
851
    ze_kernel_desc_t ZeKernelDescr = {ZE_STRUCTURE_TYPE_KERNEL_DESC, nullptr,
×
852
                                      0, // flags
×
853
                                      kernel_name};
×
854

855
    for (auto &ZeM : ZeKernelBundle) {
×
NEW
856
        ze_kernel_handle_t ZeKern = nullptr;
×
UNCOV
857
        ze_result_t ze_status = zeKernelCreateFn(ZeM, &ZeKernelDescr, &ZeKern);
×
858

859
        if (ze_status == ZE_RESULT_SUCCESS) {
×
NEW
860
            _DestroyKernel_ze_impl(ZeKern);
×
861
            return true;
×
862
        }
×
863
        else {
×
864
            if (ze_status != ZE_RESULT_ERROR_INVALID_KERNEL_NAME) {
×
865
                error_handler("zeKernelCreate failed: " +
×
866
                                  _GetErrorCode_ze_impl(ze_status),
×
867
                              __FILE__, __func__, __LINE__, error_level::error);
×
868
                return false;
×
869
            }
×
870
        }
×
871
    }
×
872

873
    return false;
×
874
}
×
875

876
#endif /* #ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION */
877

878
#endif /* #ifndef __ADAPTIVECPP__ */
879

880
} /* end of anonymous namespace */
881

882
__dpctl_give DPCTLSyclKernelBundleRef
883
DPCTLKernelBundle_CreateFromSpirv(__dpctl_keep const DPCTLSyclContextRef CtxRef,
884
                                  __dpctl_keep const DPCTLSyclDeviceRef DevRef,
885
                                  __dpctl_keep const void *IL,
886
                                  size_t length,
887
                                  const char *CompileOpts,
888
                                  size_t NumSpecConsts,
889
                                  const DPCTLSpecConst *SpecConsts)
890
{
89 ✔
891
    return DPCTLKernelBundle_CreateFromSpirvWithBuildLog(
89 ✔
892
        CtxRef, DevRef, IL, length, CompileOpts, NumSpecConsts, SpecConsts,
89 ✔
893
        nullptr);
89 ✔
894
}
89 ✔
895

896
__dpctl_give DPCTLSyclKernelBundleRef
897
DPCTLKernelBundle_CreateFromSpirvWithBuildLog(
898
    __dpctl_keep const DPCTLSyclContextRef CtxRef,
899
    __dpctl_keep const DPCTLSyclDeviceRef DevRef,
900
    __dpctl_keep const void *IL,
901
    size_t length,
902
    const char *CompileOpts,
903
    size_t NumSpecConsts,
904
    const DPCTLSpecConst *SpecConsts,
905
    __dpctl_keep DPCTLKernelBuildLogRef BuildLog)
906
{
112 ✔
907
#ifndef __ADAPTIVECPP__
112 ✔
908
    auto Log = reinterpret_cast<std::string *>(BuildLog);
112 ✔
909
    DPCTLSyclKernelBundleRef KBRef = nullptr;
112 ✔
910
    if (!CtxRef) {
112 ✔
911
        error_handler("Cannot create kernel bundle from SPIR-V as the supplied "
6 ✔
912
                      "SYCL context is NULL.",
6 ✔
913
                      __FILE__, __func__, __LINE__);
6 ✔
914
        return KBRef;
6 ✔
915
    }
6 ✔
916
    if (!DevRef) {
106 ✔
917
        error_handler("Cannot create kernel bundle from SPIR-V as the supplied "
3 ✔
918
                      "SYCL device is NULL.",
3 ✔
919
                      __FILE__, __func__, __LINE__);
3 ✔
920
        return KBRef;
3 ✔
921
    }
3 ✔
922
    if ((!IL) || (length == 0)) {
103 !
923
        error_handler("Cannot create kernel bundle from null SPIR-V buffer.",
3 ✔
924
                      __FILE__, __func__, __LINE__);
3 ✔
925
        return KBRef;
3 ✔
926
    }
3 ✔
927

928
    context *SyclCtx = unwrap<context>(CtxRef);
100 ✔
929
    device *SyclDev = unwrap<device>(DevRef);
100 ✔
930
    // get the backend type
931
    try {
100 ✔
932
        auto BE = SyclCtx->get_platform().get_backend();
100 ✔
933
        switch (BE) {
100 ✔
934
        case backend::opencl:
100 !
935
            KBRef = _CreateKernelBundleWithIL_ocl_impl(
100 ✔
936
                *SyclCtx, *SyclDev, IL, length, CompileOpts, NumSpecConsts,
100 ✔
937
                SpecConsts, Log);
100 ✔
938
            break;
100 ✔
939
        case backend::ext_oneapi_level_zero:
×
940
#ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION
×
941
            KBRef = _CreateKernelBundleWithIL_ze_impl(
×
942
                *SyclCtx, *SyclDev, IL, length, CompileOpts, NumSpecConsts,
×
NEW
943
                SpecConsts, Log);
×
944
            break;
×
945
#endif
×
946
        default:
×
947
            std::ostringstream os;
×
948
            os << "Backend " << BE << " is not supported";
×
949
            error_handler(os.str(), __FILE__, __func__, __LINE__);
×
950
            break;
×
951
        }
100 ✔
952
    } catch (std::exception const &e) {
100 ✔
953
        error_handler(e, __FILE__, __func__, __LINE__);
×
954
        return nullptr;
×
955
    }
×
956
    return KBRef;
100 ✔
957
#else
958
    error_handler(
959
        "Dynamic kernel bundle creation is not supported in AdaptiveCpp",
960
        __FILE__, __func__, __LINE__, error_level::error);
961
    return nullptr;
962
#endif
963
}
100 ✔
964

965
__dpctl_give DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromOCLSource(
966
    __dpctl_keep const DPCTLSyclContextRef Ctx,
967
    __dpctl_keep const DPCTLSyclDeviceRef Dev,
968
    __dpctl_keep const char *Source,
969
    __dpctl_keep const char *CompileOpts)
970
{
33 ✔
971
    return DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog(
33 ✔
972
        Ctx, Dev, Source, CompileOpts, nullptr);
33 ✔
973
}
33 ✔
974

975
__dpctl_give DPCTLSyclKernelBundleRef
976
DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog(
977
    __dpctl_keep const DPCTLSyclContextRef Ctx,
978
    __dpctl_keep const DPCTLSyclDeviceRef Dev,
979
    __dpctl_keep const char *Source,
980
    __dpctl_keep const char *CompileOpts,
981
    __dpctl_keep DPCTLKernelBuildLogRef BuildLog)
982
{
53 ✔
983
#ifndef __ADAPTIVECPP__
53 ✔
984
    auto Log = reinterpret_cast<std::string *>(BuildLog);
53 ✔
985
    context *SyclCtx = nullptr;
53 ✔
986
    device *SyclDev = nullptr;
53 ✔
987

988
    if (!Ctx) {
53 ✔
989
        error_handler("Input Ctx is nullptr.", __FILE__, __func__, __LINE__);
13 ✔
990
        return nullptr;
13 ✔
991
    }
13 ✔
992
    if (!Dev) {
40 ✔
993
        error_handler("Input Dev is nullptr.", __FILE__, __func__, __LINE__);
1 ✔
994
        return nullptr;
1 ✔
995
    }
1 ✔
996
    if (!Source) {
39 !
997
        error_handler("Input Source is nullptr.", __FILE__, __func__, __LINE__);
×
998
        return nullptr;
×
999
    }
×
1000

1001
    SyclCtx = unwrap<context>(Ctx);
39 ✔
1002
    SyclDev = unwrap<device>(Dev);
39 ✔
1003

1004
    try {
39 ✔
1005
        // get the backend type
1006
        auto BE = SyclCtx->get_platform().get_backend();
39 ✔
1007
        switch (BE) {
39 ✔
1008
        case backend::opencl:
39 !
1009
            return _CreateKernelBundleWithOCLSource_ocl_impl(
39 ✔
1010
                *SyclCtx, *SyclDev, Source, CompileOpts, Log);
39 ✔
NEW
1011
        case backend::ext_oneapi_level_zero:
×
NEW
1012
            error_handler(
×
NEW
1013
                "CreateFromSource is not supported for Level Zero backend.",
×
NEW
1014
                __FILE__, __func__, __LINE__);
×
NEW
1015
            return nullptr;
×
NEW
1016
        default:
×
NEW
1017
            error_handler(
×
NEW
1018
                "CreateFromSource is not supported in unknown backend.",
×
NEW
1019
                __FILE__, __func__, __LINE__);
×
1020
            return nullptr;
×
1021
        }
39 ✔
1022
    } catch (std::exception const &e) {
39 ✔
NEW
1023
        error_handler(e, __FILE__, __func__, __LINE__);
×
UNCOV
1024
        return nullptr;
×
UNCOV
1025
    }
×
1026
#else
1027
    error_handler(
1028
        "Dynamic kernel bundle creation is not supported in AdaptiveCpp",
1029
        __FILE__, __func__, __LINE__, error_level::error);
1030
    return nullptr;
1031
#endif
1032
}
39 ✔
1033

1034
__dpctl_give DPCTLSyclKernelRef
1035
DPCTLKernelBundle_GetKernel(__dpctl_keep DPCTLSyclKernelBundleRef KBRef,
1036
                            __dpctl_keep const char *KernelName)
1037
{
137 ✔
1038
#ifndef __ADAPTIVECPP__
137 ✔
1039
    if (!KBRef) {
137 ✔
1040
        error_handler("Input KBRef is nullptr", __FILE__, __func__, __LINE__);
27 ✔
1041
        return nullptr;
27 ✔
1042
    }
27 ✔
1043
    if (!KernelName) {
110 ✔
1044
        error_handler("Input KernelName is nullptr", __FILE__, __func__,
3 ✔
1045
                      __LINE__);
3 ✔
1046
        return nullptr;
3 ✔
1047
    }
3 ✔
1048
    try {
107 ✔
1049
        auto SyclKB = unwrap<kernel_bundle<bundle_state::executable>>(KBRef);
107 ✔
1050
        sycl::backend be = SyclKB->get_backend();
107 ✔
1051
        switch (be) {
107 ✔
1052
        case sycl::backend::opencl:
107 !
1053
            return _GetKernel_ocl_impl(*SyclKB, KernelName);
107 ✔
NEW
1054
        case sycl::backend::ext_oneapi_level_zero:
×
1055
#ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION
×
NEW
1056
            return _GetKernel_ze_impl(*SyclKB, KernelName);
×
1057
#endif
×
NEW
1058
        default:
×
NEW
1059
            std::ostringstream os;
×
NEW
1060
            os << "Backend " << be << " is not supported";
×
NEW
1061
            error_handler(os.str(), __FILE__, __func__, __LINE__);
×
NEW
1062
            return nullptr;
×
1063
        }
107 ✔
1064
    } catch (std::exception const &e) {
107 ✔
NEW
1065
        error_handler(e, __FILE__, __func__, __LINE__);
×
UNCOV
1066
        return nullptr;
×
UNCOV
1067
    }
×
1068
#else
1069
    error_handler("Dynamic kernel querying is not supported in AdaptiveCpp",
1070
                  __FILE__, __func__, __LINE__, error_level::error);
1071
    return nullptr;
1072
#endif
1073
}
107 ✔
1074

1075
bool DPCTLKernelBundle_HasKernel(__dpctl_keep DPCTLSyclKernelBundleRef KBRef,
1076
                                 __dpctl_keep const char *KernelName)
1077
{
92 ✔
1078
#ifndef __ADAPTIVECPP__
92 ✔
1079
    if (!KBRef) {
92 ✔
1080
        error_handler("Input KBRef is nullptr", __FILE__, __func__, __LINE__);
3 ✔
1081
        return false;
3 ✔
1082
    }
3 ✔
1083
    if (!KernelName) {
89 ✔
1084
        error_handler("Input KernelName is nullptr", __FILE__, __func__,
3 ✔
1085
                      __LINE__);
3 ✔
1086
        return false;
3 ✔
1087
    }
3 ✔
1088

1089
    try {
86 ✔
1090
        auto SyclKB = unwrap<kernel_bundle<bundle_state::executable>>(KBRef);
86 ✔
1091
        sycl::backend be = SyclKB->get_backend();
86 ✔
1092
        switch (be) {
86 ✔
1093
        case sycl::backend::opencl:
86 !
1094
            return _HasKernel_ocl_impl(*SyclKB, KernelName);
86 ✔
NEW
1095
        case sycl::backend::ext_oneapi_level_zero:
×
1096
#ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION
×
NEW
1097
            return _HasKernel_ze_impl(*SyclKB, KernelName);
×
1098
#endif
×
NEW
1099
        default:
×
NEW
1100
            std::ostringstream os;
×
NEW
1101
            os << "Backend " << be << " is not supported";
×
NEW
1102
            error_handler(os.str(), __FILE__, __func__, __LINE__);
×
NEW
1103
            return false;
×
1104
        }
86 ✔
1105
    } catch (std::exception const &e) {
86 ✔
NEW
1106
        error_handler(e, __FILE__, __func__, __LINE__);
×
UNCOV
1107
        return false;
×
UNCOV
1108
    }
×
1109
#else
1110
    error_handler("Dynamic kernel querying is not supported in AdaptiveCpp",
1111
                  __FILE__, __func__, __LINE__, error_level::error);
1112
    return false;
1113
#endif
1114
}
86 ✔
1115

1116
void DPCTLKernelBundle_Delete(__dpctl_take DPCTLSyclKernelBundleRef KBRef)
1117
{
211 ✔
1118
#ifndef __ADAPTIVECPP__
211 ✔
1119
    delete unwrap<kernel_bundle<bundle_state::executable>>(KBRef);
211 ✔
1120
#endif
211 ✔
1121
}
211 ✔
1122

1123
__dpctl_give DPCTLSyclKernelBundleRef
1124
DPCTLKernelBundle_Copy(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef)
1125
{
9 ✔
1126
#ifndef __ADAPTIVECPP__
9 ✔
1127
    auto Bundle = unwrap<kernel_bundle<bundle_state::executable>>(KBRef);
9 ✔
1128
    if (!Bundle) {
9 ✔
1129
        error_handler(
3 ✔
1130
            "Cannot copy DPCTLSyclKernelBundleRef as input is a nullptr",
3 ✔
1131
            __FILE__, __func__, __LINE__);
3 ✔
1132
        return nullptr;
3 ✔
1133
    }
3 ✔
1134
    try {
6 ✔
1135
        auto CopiedBundle =
6 ✔
1136
            new kernel_bundle<bundle_state::executable>(*Bundle);
6 ✔
1137
        return wrap<kernel_bundle<bundle_state::executable>>(CopiedBundle);
6 ✔
1138
    } catch (std::exception const &e) {
6 ✔
1139
        error_handler(e, __FILE__, __func__, __LINE__);
×
1140
        return nullptr;
×
1141
    }
×
1142
#else
1143
    error_handler("Kernel bundle copies are not supported in AdaptiveCpp",
1144
                  __FILE__, __func__, __LINE__, error_level::error);
1145
    return nullptr;
1146
#endif
1147
}
6 ✔
1148

1149
using build_option_list_t = std::vector<std::string>;
1150

1151
__dpctl_give DPCTLBuildOptionListRef DPCTLBuildOptionList_Create()
1152
{
24 ✔
1153
    auto BuildOptionList =
24 ✔
1154
        std::unique_ptr<build_option_list_t>(new build_option_list_t());
24 ✔
1155
    auto *RetVal =
24 ✔
1156
        reinterpret_cast<DPCTLBuildOptionListRef>(BuildOptionList.get());
24 ✔
1157
    BuildOptionList.release();
24 ✔
1158
    return RetVal;
24 ✔
1159
}
24 ✔
1160

1161
void DPCTLBuildOptionList_Delete(__dpctl_take DPCTLBuildOptionListRef Ref)
1162
{
24 ✔
1163
    delete reinterpret_cast<build_option_list_t *>(Ref);
24 ✔
1164
}
24 ✔
1165

1166
void DPCTLBuildOptionList_Append(__dpctl_keep DPCTLBuildOptionListRef Ref,
1167
                                 __dpctl_keep const char *Option)
1168
{
9 ✔
1169
    reinterpret_cast<build_option_list_t *>(Ref)->emplace_back(Option);
9 ✔
1170
}
9 ✔
1171

1172
using kernel_name_list_t = std::vector<std::string>;
1173

1174
__dpctl_give DPCTLKernelNameListRef DPCTLKernelNameList_Create()
1175
{
24 ✔
1176
    auto KernelNameList =
24 ✔
1177
        std::unique_ptr<kernel_name_list_t>(new kernel_name_list_t());
24 ✔
1178
    auto *RetVal =
24 ✔
1179
        reinterpret_cast<DPCTLKernelNameListRef>(KernelNameList.get());
24 ✔
1180
    KernelNameList.release();
24 ✔
1181
    return RetVal;
24 ✔
1182
}
24 ✔
1183

1184
void DPCTLKernelNameList_Delete(__dpctl_take DPCTLKernelNameListRef Ref)
1185
{
24 ✔
1186
    delete reinterpret_cast<kernel_name_list_t *>(Ref);
24 ✔
1187
}
24 ✔
1188

1189
void DPCTLKernelNameList_Append(__dpctl_keep DPCTLKernelNameListRef Ref,
1190
                                __dpctl_keep const char *Option)
1191
{
8 ✔
1192
    reinterpret_cast<kernel_name_list_t *>(Ref)->emplace_back(Option);
8 ✔
1193
}
8 ✔
1194

1195
using virtual_header_list_t = std::vector<std::pair<std::string, std::string>>;
1196

1197
__dpctl_give DPCTLVirtualHeaderListRef DPCTLVirtualHeaderList_Create()
1198
{
24 ✔
1199
    auto HeaderList =
24 ✔
1200
        std::unique_ptr<virtual_header_list_t>(new virtual_header_list_t());
24 ✔
1201
    auto *RetVal =
24 ✔
1202
        reinterpret_cast<DPCTLVirtualHeaderListRef>(HeaderList.get());
24 ✔
1203
    HeaderList.release();
24 ✔
1204
    return RetVal;
24 ✔
1205
}
24 ✔
1206

1207
void DPCTLVirtualHeaderList_Delete(__dpctl_take DPCTLVirtualHeaderListRef Ref)
1208
{
24 ✔
1209
    delete reinterpret_cast<virtual_header_list_t *>(Ref);
24 ✔
1210
}
24 ✔
1211

1212
void DPCTLVirtualHeaderList_Append(__dpctl_keep DPCTLVirtualHeaderListRef Ref,
1213
                                   __dpctl_keep const char *Name,
1214
                                   __dpctl_keep const char *Content)
1215
{
15 ✔
1216
    auto Header = std::make_pair<std::string, std::string>(Name, Content);
15 ✔
1217
    reinterpret_cast<virtual_header_list_t *>(Ref)->push_back(Header);
15 ✔
1218
}
15 ✔
1219

1220
using kernel_build_log_t = std::string;
1221

1222
__dpctl_give DPCTLKernelBuildLogRef DPCTLKernelBuildLog_Create()
1223
{
60 ✔
1224
    auto BuildLog =
60 ✔
1225
        std::unique_ptr<kernel_build_log_t>(new kernel_build_log_t(""));
60 ✔
1226
    auto *RetVal = reinterpret_cast<DPCTLKernelBuildLogRef>(BuildLog.get());
60 ✔
1227
    BuildLog.release();
60 ✔
1228
    return RetVal;
60 ✔
1229
}
60 ✔
1230

1231
void DPCTLKernelBuildLog_Delete(__dpctl_take DPCTLKernelBuildLogRef Ref)
1232
{
60 ✔
1233
    delete reinterpret_cast<kernel_build_log_t *>(Ref);
60 ✔
1234
}
60 ✔
1235

1236
const char *DPCTLKernelBuildLog_Get(__dpctl_keep DPCTLKernelBuildLogRef Ref)
1237
{
8 ✔
1238
    return reinterpret_cast<kernel_build_log_t *>(Ref)->data();
8 ✔
1239
}
8 ✔
1240

1241
#if defined(SYCL_EXT_ONEAPI_KERNEL_COMPILER) &&                                \
1242
    defined(__SYCL_COMPILER_VERSION) && !defined(SUPPORTS_SYCL_COMPILATION)
1243
// SYCL source code compilation is supported from 2025.1 onwards.
1244
#if __SYCL_COMPILER_VERSION >= 20250317u
1245
#define SUPPORTS_SYCL_COMPILATION 1
1246
#else
1247
#define SUPPORTS_SYCL_COMPILATION 0
1248
#endif
1249
#endif
1250

1251
bool DPCTLKernelBundle_CreateFromSYCLSource_Available()
1252
{
18 ✔
1253
#if (SUPPORTS_SYCL_COMPILATION > 0)
18 ✔
1254
    return true;
18 ✔
1255
#else
1256
    return false;
1257
#endif
1258
}
18 ✔
1259

1260
#if (SUPPORTS_SYCL_COMPILATION > 0)
1261
namespace syclex = sycl::ext::oneapi::experimental;
1262

1263
// The property for registering names was renamed between DPC++ versions 2025.1
1264
// and 2025.2. The original name was `registered_kernel_names`, the new name is
1265
// `registered_names`. To select the correct name without being overly reliant
1266
// on the SYCL compiler version definition, we forward declare both names and
1267
// then select the new name if it is defined (i.e., not only declared).
1268
namespace sycl::ext::oneapi::experimental
1269
{
1270
struct registered_names;
1271
struct registered_kernel_names;
1272
} // namespace sycl::ext::oneapi::experimental
1273

1274
template <typename NewT, typename FallbackT, typename = void>
1275
struct new_type_if_defined
1276
{
1277
    using type = FallbackT;
1278
};
1279

1280
template <typename NewT, typename FallbackT>
1281
struct new_type_if_defined<NewT, FallbackT, std::void_t<decltype(sizeof(NewT))>>
1282
{
1283
    using type = NewT;
1284
};
1285

1286
using registered_names_property_t =
1287
    new_type_if_defined<syclex::registered_names,
1288
                        syclex::registered_kernel_names>::type;
1289
#endif
1290

1291
__dpctl_give DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromSYCLSource(
1292
    __dpctl_keep const DPCTLSyclContextRef Ctx,
1293
    __dpctl_keep const DPCTLSyclDeviceRef Dev,
1294
    __dpctl_keep const char *Source,
1295
    __dpctl_keep DPCTLVirtualHeaderListRef Headers,
1296
    __dpctl_keep DPCTLKernelNameListRef Names,
1297
    __dpctl_keep DPCTLBuildOptionListRef BuildOptions,
1298
    __dpctl_keep DPCTLKernelBuildLogRef BuildLog)
1299
{
19 ✔
1300
#if (SUPPORTS_SYCL_COMPILATION > 0)
19 ✔
1301
    // optional arguments and BuildLog may be NULL, which is equivalent to
1302
    // passing an empty list or discarding the log
1303
    // Writing to the log is routed through a helper
1304
    auto *RawBuildLog = reinterpret_cast<kernel_build_log_t *>(BuildLog);
19 ✔
1305
    auto set_build_log = [RawBuildLog](const std::string &Msg) {
19 ✔
1306
        if (RawBuildLog)
5 ✔
1307
            *RawBuildLog = Msg;
4 ✔
1308
    };
5 ✔
1309
    auto fail = [&set_build_log](const char *Msg, int Line) {
19 ✔
1310
        set_build_log(Msg);
3 ✔
1311
        error_handler(Msg, __FILE__, "DPCTLKernelBundle_CreateFromSYCLSource",
3 ✔
1312
                      Line);
3 ✔
1313
        return nullptr;
3 ✔
1314
    };
3 ✔
1315

1316
    if (!Ctx)
19 ✔
1317
        return fail("Input Ctx is nullptr.", __LINE__);
1 ✔
1318
    if (!Dev)
18 ✔
1319
        return fail("Input Dev is nullptr.", __LINE__);
1 ✔
1320
    if (!Source)
17 ✔
1321
        return fail("Input Source is nullptr.", __LINE__);
1 ✔
1322

1323
    static const virtual_header_list_t EmptyHeaders{};
16 ✔
1324
    static const kernel_name_list_t EmptyNames{};
16 ✔
1325
    static const build_option_list_t EmptyOptions{};
16 ✔
1326

1327
    const auto &IncludeFiles =
16 ✔
1328
        Headers ? *reinterpret_cast<virtual_header_list_t *>(Headers)
16 ✔
1329
                : EmptyHeaders;
16 ✔
1330
    const auto &KernelNames =
16 ✔
1331
        Names ? *reinterpret_cast<kernel_name_list_t *>(Names) : EmptyNames;
16 ✔
1332
    const auto &Options =
16 ✔
1333
        BuildOptions ? *reinterpret_cast<build_option_list_t *>(BuildOptions)
16 ✔
1334
                     : EmptyOptions;
16 ✔
1335

1336
    context *SyclCtx = unwrap<context>(Ctx);
16 ✔
1337
    device *SyclDev = unwrap<device>(Dev);
16 ✔
1338
    try {
16 ✔
1339
        if (!SyclDev->ext_oneapi_can_compile(syclex::source_language::sycl)) {
16 !
1340
            set_build_log(
×
1341
                "Device does not support compilation of SYCL source.");
×
1342
            return nullptr;
×
1343
        }
×
1344

1345
        std::unique_ptr<kernel_bundle<bundle_state::ext_oneapi_source>>
16 ✔
1346
            SrcBundle;
16 ✔
1347
        std::string Src(Source);
16 ✔
1348
        // The following logic is to work around a bug in DPC++ version 2025.1.
1349
        // This version declares a constructor with no parameters for the
1350
        // `include_files` property, but does not implement it. Therefore, the
1351
        // only way to create `include_files` is with the name and content of
1352
        // the first virtual header, if any.
1353
        if (!IncludeFiles.empty()) {
16 ✔
1354
            auto IncludeFileIt = IncludeFiles.begin();
8 ✔
1355
            syclex::include_files IncludeFilesProp{IncludeFileIt->first,
8 ✔
1356
                                                   IncludeFileIt->second};
8 ✔
1357
            for (std::advance(IncludeFileIt, 1);
8 ✔
1358
                 IncludeFileIt != IncludeFiles.end(); ++IncludeFileIt)
15 ✔
1359
            {
7 ✔
1360
                IncludeFilesProp.add(IncludeFileIt->first,
7 ✔
1361
                                     IncludeFileIt->second);
7 ✔
1362
            }
7 ✔
1363
            SrcBundle = std::make_unique<
8 ✔
1364
                kernel_bundle<bundle_state::ext_oneapi_source>>(
8 ✔
1365
                syclex::create_kernel_bundle_from_source(
8 ✔
1366
                    *SyclCtx, syclex::source_language::sycl, Src,
8 ✔
1367
                    syclex::properties{IncludeFilesProp}));
8 ✔
1368
        }
8 ✔
1369
        else {
8 ✔
1370
            SrcBundle = std::make_unique<
8 ✔
1371
                kernel_bundle<bundle_state::ext_oneapi_source>>(
8 ✔
1372
                syclex::create_kernel_bundle_from_source(
8 ✔
1373
                    *SyclCtx, syclex::source_language::sycl, Src));
8 ✔
1374
        }
8 ✔
1375

1376
        registered_names_property_t RegisteredNames;
16 ✔
1377
        for (const std::string &Name : KernelNames) {
16 ✔
1378
            RegisteredNames.add(Name);
7 ✔
1379
        }
7 ✔
1380

1381
        syclex::build_options Opts{Options};
16 ✔
1382

1383
        std::vector<sycl::device> Devices({*SyclDev});
16 ✔
1384

1385
        auto ExeBundle = syclex::build(
16 ✔
1386
            *SrcBundle, Devices, syclex::properties{RegisteredNames, Opts});
16 ✔
1387
        auto ResultBundle =
16 ✔
1388
            std::make_unique<sycl::kernel_bundle<bundle_state::executable>>(
16 ✔
1389
                ExeBundle);
16 ✔
1390
        return wrap<kernel_bundle<bundle_state::executable>>(
16 ✔
1391
            ResultBundle.release());
16 ✔
1392
    } catch (const std::exception &e) {
16 ✔
1393
        set_build_log(e.what());
2 ✔
1394
        return nullptr;
2 ✔
1395
    }
2 ✔
1396
#else
1397
    return nullptr;
1398
#endif
1399
}
16 ✔
1400

1401
__dpctl_give DPCTLSyclKernelRef
1402
DPCTLKernelBundle_GetSyclKernel(__dpctl_keep DPCTLSyclKernelBundleRef KBRef,
1403
                                __dpctl_keep const char *KernelName)
1404
{
11 ✔
1405
#if (SUPPORTS_SYCL_COMPILATION > 0)
11 ✔
1406
    if (!KBRef) {
11 ✔
1407
        error_handler("Input KBRef is nullptr", __FILE__, __func__, __LINE__);
1 ✔
1408
        return nullptr;
1 ✔
1409
    }
1 ✔
1410
    if (!KernelName) {
10 ✔
1411
        error_handler("Input KernelName is nullptr", __FILE__, __func__,
1 ✔
1412
                      __LINE__);
1 ✔
1413
        return nullptr;
1 ✔
1414
    }
1 ✔
1415
    try {
9 ✔
1416
        auto KernelBundle =
9 ✔
1417
            unwrap<sycl::kernel_bundle<bundle_state::executable>>(KBRef);
9 ✔
1418
        auto Kernel = KernelBundle->ext_oneapi_get_kernel(KernelName);
9 ✔
1419
        return wrap<sycl::kernel>(new sycl::kernel(Kernel));
9 ✔
1420
    } catch (const std::exception &e) {
9 ✔
1421
        error_handler(e, __FILE__, __func__, __LINE__);
×
1422
        return nullptr;
×
1423
    }
×
1424
#else
1425
    return nullptr;
1426
#endif
1427
}
9 ✔
1428

1429
bool DPCTLKernelBundle_HasSyclKernel(__dpctl_keep DPCTLSyclKernelBundleRef
1430
                                         KBRef,
1431
                                     __dpctl_keep const char *KernelName)
1432
{
9 ✔
1433
#if (SUPPORTS_SYCL_COMPILATION > 0)
9 ✔
1434
    if (!KBRef) {
9 ✔
1435
        error_handler("Input KBRef is nullptr", __FILE__, __func__, __LINE__);
1 ✔
1436
        return false;
1 ✔
1437
    }
1 ✔
1438
    if (!KernelName) {
8 ✔
1439
        error_handler("Input KernelName is nullptr", __FILE__, __func__,
1 ✔
1440
                      __LINE__);
1 ✔
1441
        return false;
1 ✔
1442
    }
1 ✔
1443
    try {
7 ✔
1444
        auto KernelBundle =
7 ✔
1445
            unwrap<sycl::kernel_bundle<bundle_state::executable>>(KBRef);
7 ✔
1446
        return KernelBundle->ext_oneapi_has_kernel(KernelName);
7 ✔
1447
    } catch (const std::exception &e) {
7 ✔
1448
        error_handler(e, __FILE__, __func__, __LINE__);
×
1449
        return false;
×
1450
    }
×
1451
#else
1452
    return false;
1453
#endif
1454
}
7 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc