okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
80.7 KiB2061 linesraw
1//===--- bindless_images.hpp ----------------------*- C++ -*---------------===//
2//
3// Copyright (C) Intel Corporation
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5// See https://llvm.org/LICENSE.txt for license information.
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef __DPCT_BINDLESS_IMAGE_HPP__
10#define __DPCT_BINDLESS_IMAGE_HPP__
11
12#ifdef _WIN32
13// DirectX headers
14#include <d3d11.h>
15#include <dxgi.h>
16#include <dxgi1_2.h>
17#endif // _WIN32
18
19namespace dpct {
20namespace experimental {
21
22#ifdef SYCL_EXT_ONEAPI_BINDLESS_IMAGES
23
24/// The wrapper structure for external memory resource handle desc
25class external_mem_handle_desc {
26#ifdef _WIN32
27  void *handle;
28  const void *name;
29#else
30  int handle;
31#endif // _WIN32
32  sycl::ext::oneapi::experimental::external_mem_handle_type handle_type;
33  size_t size_in_bytes;
34  int flags;
35
36public:
37  external_mem_handle_desc() {
38#ifdef _WIN32
39    handle = nullptr;
40    name = nullptr;
41#else
42    handle = -1;
43#endif // _WIN32
44    handle_type =
45        sycl::ext::oneapi::experimental::external_mem_handle_type::opaque_fd;
46    size_in_bytes = 0;
47    flags = 0;
48  }
49
50#ifdef _WIN32
51  /// handle setter
52  /// \param [in] win32_handle The win32 NT handle of the external memory
53  /// resource
54  void set_win32_handle(void *win32_handle) { handle = win32_handle; }
55
56  /// name setter
57  /// \param [in] win32_obj_name The object of the external memory resource
58  void set_win32_obj_name(const void *win32_obj_name) { name = win32_obj_name; }
59#else
60  /// fd setter
61  /// \param [in] fd The file descriptor of the external memory resource
62  void set_fd_handle(int fd) { handle = fd; }
63#endif // _WIN32
64
65  /// handle_type setter
66  /// \param [in] type The type of the external memory resource handle
67  void set_handle_type(
68      sycl::ext::oneapi::experimental::external_mem_handle_type type) {
69    handle_type = type;
70  }
71
72  /// size setter
73  /// \param [in] size The size (in bytes) of the external memory resource
74  void set_res_size(unsigned long long size) { size_in_bytes = size; }
75
76  /// flags setter
77  /// \param [in] flags The flags used to handle importing of external memory
78  /// resource
79  void set_flags(int flags) { this->flags = flags; }
80
81#ifdef _WIN32
82  /// handle getter
83  /// \param [out] handle The win32 NT handle of the external memory resource
84  void *get_win32_handle() { return handle; }
85
86  /// name getter
87  /// \param [out] name The object of the external memory resource
88  const void *get_win32_obj_name() { return name; }
89#else
90  /// fd getter
91  /// \param [out] fd The file descriptor of the external memory resource
92  int get_fd_handle() { return handle; }
93#endif // _WIN32
94
95  /// handle_type getter
96  /// \param [out] handle_type The type of the external memory resource handle
97  sycl::ext::oneapi::experimental::external_mem_handle_type get_handle_type() {
98    return handle_type;
99  }
100
101  /// size getter
102  /// \param [out] size The size (in bytes) of the external memory resource
103  unsigned long long get_res_size() { return size_in_bytes; }
104
105  /// flags getter
106  /// \param [out] flags The flags used to handle importing of external memory
107  /// resource
108  int get_flags() { return flags; }
109};
110
111/// The wrapper structure for external image memory desc
112class external_mem_img_desc {
113  sycl::range<3> size;
114  image_channel channel;
115  unsigned int num_levels;
116  sycl::ext::oneapi::experimental::image_type type;
117
118public:
119  external_mem_img_desc() {
120    size = sycl::range<3>{0, 0, 0};
121    channel = image_channel::create<float>();
122    num_levels = 1;
123    type = sycl::ext::oneapi::experimental::image_type::standard;
124  }
125
126  /// size setter
127  /// \param [in] img_dims The dimensions of the imported image resource
128  void set_size(sycl::range<3> img_dims) {
129    size = img_dims;
130
131    for (int i = 0; i < 3; i++) {
132      if (size[i] == 1) {
133        size[i] = 0;
134      }
135    }
136  }
137
138  /// image_channel setter
139  /// \param [in] img_ch The channel info of the imported image resource
140  void set_image_channel(image_channel img_ch) { channel = img_ch; }
141
142  /// num_levels setter
143  /// \param [in] numLevels The no. of levels in the imported image resource
144  void set_num_levels(unsigned int num_levels) {
145    this->num_levels = num_levels;
146
147    if (num_levels > 1) {
148      set_image_type(sycl::ext::oneapi::experimental::image_type::mipmap);
149    }
150  }
151
152  /// type setter
153  /// \param [in] img_type The type of the imported image resource
154  void set_image_type(sycl::ext::oneapi::experimental::image_type img_type) {
155    type = img_type;
156  }
157
158  /// size getter
159  /// \param [out] size The dimensions of the imported image resource
160  sycl::range<3> get_size() { return size; }
161
162  /// image_channel getter
163  /// \param [out] image_channel The channel info of the imported image resource
164  image_channel get_image_channel() { return channel; }
165
166  /// num_levels getter
167  /// \param [out] num_levels The no. of levels in the imported image resource
168  unsigned int get_num_levels() { return num_levels; }
169
170  /// type getter
171  /// \param [out] type The image type of the imported image resource
172  sycl::ext::oneapi::experimental::image_type get_image_type() { return type; }
173};
174
175/// The wrapper structure for external buffer memory desc
176class external_mem_buf_desc {
177  uint64_t size_in_bytes;
178  uint64_t offset;
179  unsigned int flags;
180
181public:
182  external_mem_buf_desc() {
183    size_in_bytes = 0;
184    offset = 0;
185    flags = 0;
186  }
187
188  /// size setter
189  /// \param [in] size The size (in bytes) of the external buffer resource
190  void set_res_size(uint64_t size) { size_in_bytes = size; }
191
192  /// offset setter
193  /// \param [in] offset The memory offset of the external buffer resource
194  void set_mem_offset(uint64_t offset) { this->offset = offset; }
195
196  /// flags setter
197  /// \param [in] flags The flags used to import external buffer resource
198  void set_flags(unsigned int flags) { this->flags = flags; }
199
200  /// size getter
201  /// \param [out] size_in_bytes The size (in bytes) of the external buffer res
202  uint64_t get_res_size() { return size_in_bytes; }
203
204  /// offset getter
205  /// \param [out] offset The memory offset of the external buffer resource
206  uint64_t get_mem_offset() { return offset; }
207
208  /// flags getter
209  /// \param [out] flags The flags used to import external buffer resource
210  unsigned int get_flags() { return flags; }
211};
212
213/// The wrapper class for external semaphore resource handle desc
214class external_sem_handle_desc {
215#ifdef _WIN32
216  void *handle;
217  const void *name;
218#else
219  int handle;
220#endif // _WIN32
221  sycl::ext::oneapi::experimental::external_semaphore_handle_type handle_type;
222  int flags;
223
224public:
225  external_sem_handle_desc() {
226#ifdef _WIN32
227    handle = nullptr;
228    name = nullptr;
229#else
230    handle = -1;
231#endif // _WIN32
232    handle_type = sycl::ext::oneapi::experimental::
233        external_semaphore_handle_type::opaque_fd;
234    flags = 0;
235  }
236
237#ifdef _WIN32
238  /// handle setter
239  /// \param [in] win32_handle The win32 NT handle of the external semaphore
240  /// resource
241  void set_win32_handle(void *win32_handle) { handle = win32_handle; }
242
243  /// name setter
244  /// \param [in] win32_obj_name The object of the external semaphore resource
245  void set_win32_obj_name(const void *win32_obj_name) { name = win32_obj_name; }
246#else
247  /// fd setter
248  /// \param [in] fd The file descriptor of the external semaphore resource
249  void set_fd_handle(int fd) { handle = fd; }
250#endif // _WIN32
251
252  /// handle_type setter
253  /// \param [in] type The type of the external semaphore resource handle
254  void set_handle_type(
255      sycl::ext::oneapi::experimental::external_semaphore_handle_type type) {
256    handle_type = type;
257  }
258
259  /// flags setter
260  /// \param [in] flags The flags used to handle importing of external semaphore
261  /// resource
262  void set_flags(int flags) { this->flags = flags; }
263
264#ifdef _WIN32
265  /// handle getter
266  /// \param [out] handle The win32 NT handle of the external semaphore resource
267  void *get_win32_handle() { return handle; }
268
269  /// name getter
270  /// \param [out] name The object of the external semaphore resource
271  const void *get_win32_obj_name() { return name; }
272#else
273  /// fd getter
274  /// \param [out] fd The file descriptor of the external semaphore resource
275  int get_fd_handle() { return handle; }
276#endif // _WIN32
277
278  /// handle_type getter
279  /// \param [out] handle_type The type of the external semaphore resource
280  /// handle
281  sycl::ext::oneapi::experimental::external_semaphore_handle_type
282  get_handle_type() {
283    return handle_type;
284  }
285
286  /// flags getter
287  /// \param [out] flags The flags used to handle importing of external
288  /// semaphore
289  int get_flags() { return flags; }
290};
291
292/// The wrapper structure for external semaphore signal/wait params
293class external_sem_params {
294  uint64_t value;
295
296public:
297  external_sem_params() { value = 0; }
298
299  /// value setter
300  /// \param [in] val The state value of the semaphore
301  void set_value(unsigned long long val) { value = val; }
302
303  /// value getter
304  /// \param [out] value The state value of the semaphore
305  unsigned long long get_value() { return value; }
306};
307
308/// The wrapper class of external semaphore
309class external_sem_wrapper {
310  sycl::ext::oneapi::experimental::external_semaphore ext_sem;
311  sycl::ext::oneapi::experimental::external_semaphore_handle_type
312      ext_sem_handle_type;
313
314public:
315  /// Create external semaphore wrapper.
316  /// \param [in] ext_sem The external semaphore resource object
317  /// \param [in] ext_sem_handle_type The external semaphore resource handle
318  /// type
319  external_sem_wrapper(
320      sycl::ext::oneapi::experimental::external_semaphore ext_sem,
321      sycl::ext::oneapi::experimental::external_semaphore_handle_type
322          ext_sem_handle_type) {
323    this->ext_sem = ext_sem;
324    this->ext_sem_handle_type = ext_sem_handle_type;
325  }
326
327  /// destory external semaphore resource
328  ~external_sem_wrapper() {
329    sycl::ext::oneapi::experimental::release_external_semaphore(
330        ext_sem, get_default_queue());
331  }
332
333  /// ext_sem getter
334  /// \param [out] ext_sem The external semaphore resource object
335  sycl::ext::oneapi::experimental::external_semaphore get() { return ext_sem; }
336
337  /// ext_sem_handle_type getter
338  /// \param [out] ext_sem_handle_type The external semaphore resource handle
339  /// type
340  sycl::ext::oneapi::experimental::external_semaphore_handle_type
341  get_handle_type() {
342    return ext_sem_handle_type;
343  }
344};
345
346/// The wrapper class of bindless image memory handle.
347class image_mem_wrapper {
348public:
349  /// Create bindless image memory wrapper.
350  /// \tparam dimensions The dimensions of image memory.
351  /// \param [in] channel The image channel used to create bindless image
352  /// \param [in] range The sizes of each dimension of bindless image memory.
353  /// memory.
354  template <int dimensions = 3>
355  image_mem_wrapper(image_channel channel, sycl::range<dimensions> range,
356                    sycl::ext::oneapi::experimental::image_type type =
357                        sycl::ext::oneapi::experimental::image_type::standard,
358                    unsigned int num_levels = 1)
359      : _channel(channel) {
360    unsigned array_size = 1;
361    if (type == sycl::ext::oneapi::experimental::image_type::array) {
362      assert(dimensions == 3);
363      array_size = range[2];
364      range[2] = 0;
365    }
366    _desc = sycl::ext::oneapi::experimental::image_descriptor(
367        range, _channel.get_channel_num(), _channel.get_channel_type(), type,
368        num_levels, array_size);
369    auto q = get_default_queue();
370    _handle = alloc_image_mem(_desc, q);
371    init_mip_level_wrappers(q);
372  }
373  /// Create bindless image memory wrapper.
374  /// \param [in] channel The image channel used to create bindless image
375  /// \param [in] width The width of bindless image memory.
376  /// \param [in] height The height of bindless image memory.
377  /// \param [in] depth The depth of bindless image memory.
378  image_mem_wrapper(image_channel channel, size_t width, size_t height = 0,
379                    size_t depth = 0)
380      : image_mem_wrapper(channel, {width, height, depth}) {}
381  /// Create bindless image memory wrapper.
382  /// \param [in] desc The image descriptor used to create bindless image
383  image_mem_wrapper(
384      const sycl::ext::oneapi::experimental::image_descriptor *desc)
385      : _desc(*desc) {
386    _channel.set_channel_type(desc->channel_type);
387    _channel.set_channel_num(desc->num_channels);
388    auto q = get_default_queue();
389    _handle = alloc_image_mem(_desc, q);
390  }
391  /// Create bindless image memory wrapper.
392  /// \param [in] desc The image descriptor of bindless image.
393  /// \param [in] img_mem_handle The memory handle of bindless image.
394  image_mem_wrapper(
395      sycl::ext::oneapi::experimental::image_descriptor desc,
396      sycl::ext::oneapi::experimental::image_mem_handle img_mem_handle)
397      : _desc(desc), _handle(img_mem_handle) {
398    _channel.set_channel_type(_desc.channel_type);
399#if (__SYCL_COMPILER_VERSION && __SYCL_COMPILER_VERSION >= 20240725)
400    _channel.set_channel_num(_desc.num_channels);
401#endif
402    auto q = get_default_queue();
403    init_mip_level_wrappers(q);
404  }
405  /// Create bindless image memory wrapper.
406  /// \param [in] extMem SYCL external memory resource object.
407  /// \param [in] ext_img_mem_desc The img desc of the imported image resource.
408  image_mem_wrapper(sycl::ext::oneapi::experimental::external_mem extMem,
409                    external_mem_img_desc *ext_img_mem_desc) {
410    auto q = get_default_queue();
411    unsigned int array_size = 1;
412
413    _channel = ext_img_mem_desc->get_image_channel();
414    _desc = sycl::ext::oneapi::experimental::image_descriptor(
415        ext_img_mem_desc->get_size(), _channel.get_channel_num(),
416        _channel.get_channel_type(), ext_img_mem_desc->get_image_type(),
417        ext_img_mem_desc->get_num_levels(), array_size);
418    _handle = sycl::ext::oneapi::experimental::map_external_image_memory(
419        extMem, _desc, q);
420
421    init_mip_level_wrappers(q);
422  }
423  /// Create bindless image memory wrapper.
424  /// \param [in] desc The image descriptor of bindless image.
425  /// \param [in] num_levels Number of mipmap levels to allocate
426  image_mem_wrapper(sycl::ext::oneapi::experimental::image_descriptor desc,
427                    unsigned int num_levels)
428      : _desc(desc) {
429    _desc.type = sycl::ext::oneapi::experimental::image_type::mipmap;
430    _desc.num_levels = num_levels;
431    auto q = get_default_queue();
432    _handle = alloc_image_mem(_desc, q);
433    init_mip_level_wrappers(q);
434  }
435
436  image_mem_wrapper(const image_mem_wrapper &) = delete;
437  image_mem_wrapper &operator=(const image_mem_wrapper &) = delete;
438  /// Destroy bindless image memory wrapper.
439  ~image_mem_wrapper() {
440    if (_sub_wrappers) {
441      std::destroy_n(_sub_wrappers, _desc.num_levels);
442      std::free(_sub_wrappers);
443    }
444    free_image_mem(_handle, _desc.type, get_default_queue());
445  }
446  /// Get the image channel of the bindless image memory.
447  /// \returns The image channel of bindless image memory.
448  image_channel get_channel() const noexcept { return _channel; }
449  /// Get the sizes of each dimension of the bindless image memory.
450  /// \returns The sizes of each dimension of bindless image memory.
451  sycl::range<3> get_range() const {
452    return {_desc.width, _desc.height, _desc.depth};
453  }
454  /// Get the image descriptor of the bindless image memory.
455  /// \returns The image descriptor of bindless image memory.
456  const sycl::ext::oneapi::experimental::image_descriptor &
457  get_desc() const noexcept {
458    return _desc;
459  }
460  /// Get the image handle of the bindless image memory.
461  /// \returns The image handle of bindless image memory.
462  sycl::ext::oneapi::experimental::image_mem_handle
463  get_handle() const noexcept {
464    return _handle;
465  }
466  /// Get the image mip level of the bindless image memory.
467  /// \returns The image mip level of the bindless image memory.
468  image_mem_wrapper *get_mip_level(unsigned int level) {
469    if (_desc.type == sycl::ext::oneapi::experimental::image_type::standard) {
470      assert(level == 0);
471      return this;
472    }
473
474    assert(_desc.type == sycl::ext::oneapi::experimental::image_type::mipmap);
475    return _sub_wrappers + level;
476  }
477
478  sycl::ext::oneapi::experimental::image_type get_image_type(void) {
479    return _desc.type;
480  }
481
482private:
483  image_mem_wrapper(
484      const image_channel &channel,
485      const sycl::ext::oneapi::experimental::image_descriptor &desc,
486      const sycl::ext::oneapi::experimental::image_mem_handle &handle)
487      : _channel(channel), _desc(desc), _handle(handle) {}
488
489  /// Initialize image mem wrappers for all the levels of mipmap image
490  /// \param [in] q The Queue to be used to query the mip levels
491  void init_mip_level_wrappers(sycl::queue q) {
492    auto num_levels = _desc.num_levels;
493    if (_desc.type == sycl::ext::oneapi::experimental::image_type::mipmap) {
494      assert(num_levels > 1);
495      _sub_wrappers = (image_mem_wrapper *)std::malloc(
496          sizeof(image_mem_wrapper) * num_levels);
497      for (unsigned i = 0; i < num_levels; ++i)
498        new (_sub_wrappers + i) image_mem_wrapper(
499            _channel, _desc.get_mip_level_desc(i),
500            sycl::ext::oneapi::experimental::get_mip_level_mem_handle(
501                _handle, i, q.get_device(), q.get_context()));
502    }
503  }
504
505  image_channel _channel;
506  sycl::ext::oneapi::experimental::image_descriptor _desc;
507  sycl::ext::oneapi::experimental::image_mem_handle _handle;
508  image_mem_wrapper *_sub_wrappers{nullptr};
509};
510
511/// The base wrapper class of external memory resource handle.
512class external_mem_wrapper_base {
513public:
514  /// Cleans up the external mem wrapper by releasing the SYCL external
515  /// memory handle
516  virtual ~external_mem_wrapper_base() {}
517
518  external_mem_wrapper_base(const external_mem_wrapper_base &) = delete;
519
520  external_mem_wrapper_base &
521  operator=(const external_mem_wrapper_base &) = delete;
522
523  const sycl::ext::oneapi::experimental::external_mem
524  get_external_mem() const noexcept {
525    return _res_external_mem;
526  }
527
528  /// Map the buf/texture resource memory and get its pointer/mem handle.
529  /// \param [in] q The queue used to map the resource with.
530  void map_resource(sycl::queue q) {
531    if (_res_is_buffer) {
532      if (_res_buf_ptr) {
533        throw std::runtime_error("Resource is already mapped! "
534                                 "Resource cannot be mapped more than once.");
535      }
536
537#if (__SYCL_COMPILER_VERSION && __SYCL_COMPILER_VERSION >= 20240823)
538      _res_buf_ptr =
539          sycl::ext::oneapi::experimental::map_external_linear_memory(
540              get_external_mem(), 0, _res_size_bytes, q);
541#else
542      throw std::runtime_error(
543          "Mapping a buffer resoure is not yet supported!");
544#endif
545    } else {
546      if (_res_img_mem_wrapper_ptr) {
547        throw std::runtime_error("Resource is already mapped! "
548                                 "Resource cannot be mapped more than once.");
549      }
550
551      auto img_mem_handle =
552          sycl::ext::oneapi::experimental::map_external_image_memory(
553              get_external_mem(), _res_img_desc, q);
554
555      _res_img_mem_wrapper_ptr =
556          new image_mem_wrapper(_res_img_desc, img_mem_handle);
557    }
558  }
559
560  /// Gets the pointer and size of the mapped resource
561  /// \param [out] ptr The pointer to the resource memory.
562  /// \param [out] size The size of the resource memory.
563  /// and resource size.
564  void get_mapped_pointer(void **ptr, size_t *size) {
565    if (!_res_is_buffer) {
566      throw std::runtime_error(
567          "Non buffer resouce cannot be accessed as a pointer!");
568    }
569
570    *ptr = _res_buf_ptr;
571    if (!*ptr) {
572      throw std::runtime_error(
573          "Resource is not mapped! "
574          "Resource should be mapped before accessing its memory");
575    }
576
577    *size = _res_size_bytes;
578  }
579
580  /// Returns mapped memory as image_mem_wrapper*
581  image_mem_wrapper *get_mapped_mipmapped_array() {
582    if (_res_is_buffer) {
583      throw std::runtime_error(
584          "Buffer resource cannot be accessed as an array!");
585    }
586    if (!_res_img_mem_wrapper_ptr) {
587      throw std::runtime_error(
588          "Resource is not mapped! "
589          "Resource should be mapped before accessing its memory.");
590    }
591
592    return _res_img_mem_wrapper_ptr;
593  }
594
595  /// Returns mapped subresource memory as image_mem_wrapper*
596  /// \param [in] array_index The layer of the image array to be returned.
597  /// \param [in] mip_level The level of the mipmap image to be returned.
598  image_mem_wrapper *get_sub_resource_mapped_array(unsigned int array_index,
599                                                   unsigned int mip_level) {
600    if (_res_is_buffer) {
601      throw std::runtime_error(
602          "Buffer resouce cannot be accessed as an array!");
603    }
604    if (array_index != 0) {
605      throw std::runtime_error("Retrieving a particular layer from image array "
606                               "is not yet supported!");
607    }
608    if (array_index >= _res_img_desc.array_size) {
609      throw std::runtime_error(
610          "Array index requested exceeds total array size in resource!");
611    }
612    if (mip_level >= _res_img_desc.num_levels) {
613      throw std::runtime_error(
614          "Mip level requested exceeds total num of levels in resource!");
615    }
616    if (!_res_img_mem_wrapper_ptr) {
617      throw std::runtime_error(
618          "Resouce is not mapped! "
619          "Resource should be mapped before accessing its memory");
620    }
621
622    return (mip_level == 0)
623               ? _res_img_mem_wrapper_ptr
624               : _res_img_mem_wrapper_ptr->get_mip_level(mip_level);
625  }
626
627  /// Unmap the buf/texture resource memory and get its pointer/mem handle.
628  /// \param [in] q The queue used to unmap the resource with.
629  void unmap_resource(sycl::queue q) {
630    if (_res_is_buffer) {
631      if (!_res_buf_ptr) {
632        throw std::runtime_error("Resource is not mapped! "
633                                 "Resource should be mapped before unmapping.");
634      }
635
636      _res_buf_ptr = nullptr;
637
638      throw std::runtime_error(
639          "Unmapping a buffer resoure is not yet supported!");
640    } else {
641      if (!_res_img_mem_wrapper_ptr) {
642        throw std::runtime_error("Resource is not mapped! "
643                                 "Resource should be mapped before unmapping.");
644      }
645
646      delete _res_img_mem_wrapper_ptr;
647      _res_img_mem_wrapper_ptr = nullptr;
648    }
649  }
650
651protected:
652  /// Init external mem handle for a given resource.
653  external_mem_wrapper_base(
654      sycl::ext::oneapi::experimental::external_mem external_mem,
655      unsigned reg_flags)
656      : _res_external_mem(external_mem), _res_reg_flags(reg_flags) {}
657
658  unsigned _res_reg_flags = 0;
659  bool _res_is_buffer = false;
660  size_t _res_size_bytes = 0;
661
662  sycl::ext::oneapi::experimental::image_descriptor _res_img_desc;
663  sycl::ext::oneapi::experimental::external_mem _res_external_mem;
664
665private:
666  void *_res_buf_ptr = nullptr;
667  image_mem_wrapper *_res_img_mem_wrapper_ptr = nullptr;
668};
669
670#ifdef _WIN32
671class external_mem_wrapper : public external_mem_wrapper_base {
672public:
673  /// Creates external memory resource wrapper for a given DX11 resource.
674  /// \param [in] d3d11_res Pointer to the ID3D11Resource to be wrapped.
675  /// \param [in] reg_flags Registration flags used for resource registration.
676  external_mem_wrapper(ID3D11Resource *d3d11_res, unsigned reg_flags)
677      : _res_D3D11(d3d11_res),
678        external_mem_wrapper_base(
679            sycl::ext::oneapi::experimental::external_mem(), reg_flags) {
680    // Check if the resource is already registered to prevent double
681    // registration.
682    if (_res_D3D11_set.find(_res_D3D11) != _res_D3D11_set.end()) {
683      throw std::runtime_error("This D3D11 resource is already registered!");
684    }
685
686    // Query the information from D3D11 resource object
687    query_res_info(_res_D3D11);
688
689    // Create a shared handle for the DX11 resource to enable interoperability.
690    _res_win_nt_handle = create_shared_handle(_res_D3D11);
691
692    // Prepare the external memory resource descriptor for SYCL interop.
693    sycl::ext::oneapi::experimental::resource_win32_handle ext_mem_win_handle{
694        _res_win_nt_handle};
695
696    sycl::ext::oneapi::experimental::external_mem_descriptor<
697        sycl::ext::oneapi::experimental::resource_win32_handle>
698        ext_mem_desc{ext_mem_win_handle,
699                     sycl::ext::oneapi::experimental::external_mem_handle_type::
700                         win32_nt_dx12_resource,
701                     _res_size_bytes};
702
703    // Import resource's external memory into SYCL for use with SYCL APIs.
704    _res_external_mem = sycl::ext::oneapi::experimental::external_mem(
705        sycl::ext::oneapi::experimental::import_external_memory(
706            ext_mem_desc, get_default_queue()));
707
708    // Register the resource to track its uniqueness.
709    _res_D3D11_set.insert(_res_D3D11);
710  }
711
712  /// Cleans up the external mem wrapper by releasing the SYCL external
713  /// memory handle and the shared handle created for the DX11 resource.
714  virtual ~external_mem_wrapper() {
715    // Release the mutex when done
716    _res_keyed_mutex->ReleaseSync(0);
717
718    // Release the keyed mutex interface
719    _res_keyed_mutex->Release();
720
721    // Close the shared handle to the DX11 resource.
722    CloseHandle(_res_win_nt_handle);
723
724    // Release the resource's external memory associated with the SYCL external
725    // mem handle.
726    sycl::ext::oneapi::experimental::release_external_memory(
727        get_external_mem(), get_default_queue());
728
729    // Remove the resource from the tracking set.
730    if (_res_D3D11_set.find(_res_D3D11) != _res_D3D11_set.end()) {
731      _res_D3D11_set.erase(_res_D3D11);
732    }
733  }
734
735private:
736  inline static std::set<ID3D11Resource *> _res_D3D11_set;
737
738  ID3D11Resource *_res_D3D11 = nullptr;
739  IDXGIKeyedMutex *_res_keyed_mutex = nullptr;
740  HANDLE _res_win_nt_handle = nullptr;
741
742  /// Helper function to query the properties of DX11 resource
743  void query_res_info(ID3D11Resource *resource) {
744    unsigned int res_width = 0;
745    unsigned int res_height = 0;
746    unsigned int res_depth = 0;
747    unsigned int res_num_levels = 1;
748    unsigned int res_arr_size = 1;
749
750    image_channel channel;
751
752    // Get the dimension info of DX11 resource
753    D3D11_RESOURCE_DIMENSION dimension;
754    resource->GetType(&dimension);
755
756    switch (dimension) {
757    case D3D11_RESOURCE_DIMENSION_BUFFER: {
758      _res_is_buffer = true;
759
760      D3D11_BUFFER_DESC desc;
761      ((ID3D11Buffer *)resource)->GetDesc(&desc);
762
763      _res_size_bytes = desc.ByteWidth;
764      break;
765    }
766    case D3D11_RESOURCE_DIMENSION_TEXTURE1D: {
767      D3D11_TEXTURE1D_DESC desc;
768      ((ID3D11Texture1D *)resource)->GetDesc(&desc);
769
770      res_width = desc.Width;
771      res_arr_size = desc.ArraySize;
772      res_num_levels = (desc.MipLevels ? desc.MipLevels : 1);
773
774      channel = get_img_ch_info(desc.Format);
775      _res_size_bytes = res_width;
776      break;
777    }
778    case D3D11_RESOURCE_DIMENSION_TEXTURE2D: {
779      D3D11_TEXTURE2D_DESC desc;
780      ((ID3D11Texture2D *)resource)->GetDesc(&desc);
781
782      res_width = desc.Width;
783      res_height = desc.Height;
784      res_arr_size = desc.ArraySize;
785      res_num_levels = (desc.MipLevels ? desc.MipLevels : 1);
786
787      channel = get_img_ch_info(desc.Format);
788      _res_size_bytes = res_width * res_height;
789      break;
790    }
791    case D3D11_RESOURCE_DIMENSION_TEXTURE3D: {
792      D3D11_TEXTURE3D_DESC desc;
793      ((ID3D11Texture3D *)resource)->GetDesc(&desc);
794
795      res_width = desc.Width;
796      res_height = desc.Height;
797      res_depth = desc.Depth;
798      res_num_levels = (desc.MipLevels ? desc.MipLevels : 1);
799
800      channel = get_img_ch_info(desc.Format);
801      _res_size_bytes = res_width * res_height * res_depth;
802      break;
803    }
804    default:
805      throw std::runtime_error("Unsupported DX11 resource type!");
806      break;
807    }
808
809    if (!_res_is_buffer) {
810      if (res_arr_size > 1) {
811        throw std::runtime_error(
812            "Images with multiple array levels are not supported. "
813            "Only standard and mipmap images are supported!");
814      }
815
816      // Calculate the size of a resource in bytes by multiplyting its dims
817      // with arr size, num levels & channel size
818      _res_size_bytes *=
819          res_arr_size * res_num_levels * channel.get_total_size();
820
821      sycl::ext::oneapi::experimental::image_type img_type =
822          (res_num_levels > 1)
823              ? sycl::ext::oneapi::experimental::image_type::mipmap
824              : sycl::ext::oneapi::experimental::image_type::standard;
825
826      _res_img_desc = sycl::ext::oneapi::experimental::image_descriptor{
827          sycl::range<3>{res_width, res_height, res_depth},
828          channel.get_channel_num(),
829          channel.get_channel_type(),
830          img_type,
831          res_num_levels,
832          res_arr_size};
833    }
834  }
835
836  /// Helper function to create shared handle for DXD11 resource
837  HANDLE create_shared_handle(ID3D11Resource *resource) {
838    HANDLE win_nt_handle = nullptr;
839
840    IDXGIResource1 *pDXGIResource1;
841    resource->QueryInterface(__uuidof(IDXGIResource1),
842                             reinterpret_cast<void **>(&pDXGIResource1));
843
844    if (_res_is_buffer) {
845      pDXGIResource1->GetSharedHandle(&win_nt_handle);
846    } else {
847      pDXGIResource1->CreateSharedHandle(
848          nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE,
849          nullptr, &win_nt_handle);
850    }
851
852    pDXGIResource1->Release();
853
854    // Query for the keyed mutex interface
855    resource->QueryInterface(__uuidof(IDXGIKeyedMutex),
856                             reinterpret_cast<void **>(&_res_keyed_mutex));
857
858    // Use the keyed mutex to synchronize access to the shared resource
859    _res_keyed_mutex->AcquireSync(0, INFINITE);
860
861    return win_nt_handle;
862  }
863
864  /// Helper function to get the texture channel info of DX11 resource using
865  /// DXGI format
866  image_channel get_img_ch_info(DXGI_FORMAT format) {
867    image_channel channel;
868
869    switch (format) {
870    case DXGI_FORMAT_R16G16B16A16_FLOAT:
871      channel = image_channel::create<sycl::half4>();
872      break;
873    case DXGI_FORMAT_R8G8B8A8_UNORM:
874      channel = image_channel::create<sycl::uchar4>();
875      break;
876    case DXGI_FORMAT_R16G16_FLOAT:
877      channel = image_channel::create<sycl::half2>();
878      break;
879    case DXGI_FORMAT_R32_FLOAT:
880      channel = image_channel::create<float>();
881      break;
882    default:
883      throw std::runtime_error("Unsupported DX11 resource format!");
884      break;
885    }
886
887    return channel;
888  }
889};
890#endif // _WIN32
891
892namespace detail {
893struct sampled_image_handle_compare {
894  template <class T> bool operator()(T L, T R) const {
895    return L.raw_handle < R.raw_handle;
896  }
897};
898
899inline std::pair<image_data, sampling_info> &get_img_info_map(
900    const sycl::ext::oneapi::experimental::sampled_image_handle handle) {
901  static std::map<sycl::ext::oneapi::experimental::sampled_image_handle,
902                  std::pair<image_data, sampling_info>,
903                  sampled_image_handle_compare>
904      img_info_map;
905  return img_info_map[handle];
906}
907
908inline std::pair<image_data, sampling_info> &get_img_info_map(
909    const sycl::ext::oneapi::experimental::unsampled_image_handle handle) {
910  static std::map<sycl::ext::oneapi::experimental::unsampled_image_handle,
911                  std::pair<image_data, sampling_info>,
912                  sampled_image_handle_compare>
913      img_info_map;
914  return img_info_map[handle];
915}
916
917static inline size_t
918get_ele_size(const sycl::ext::oneapi::experimental::image_descriptor &decs) {
919  size_t channel_size;
920  switch (decs.channel_type) {
921  case sycl::image_channel_type::signed_int8:
922  case sycl::image_channel_type::unsigned_int8:
923    channel_size = 1;
924    break;
925  case sycl::image_channel_type::fp16:
926  case sycl::image_channel_type::signed_int16:
927  case sycl::image_channel_type::unsigned_int16:
928    channel_size = 2;
929    break;
930  case sycl::image_channel_type::fp32:
931  case sycl::image_channel_type::signed_int32:
932  case sycl::image_channel_type::unsigned_int32:
933    channel_size = 4;
934    break;
935  default:
936    throw std::runtime_error("Unsupported channel_type in get_ele_size!");
937    break;
938  }
939  return decs.num_channels * channel_size;
940}
941
942static inline sycl::event
943dpct_memcpy(sycl::ext::oneapi::experimental::image_mem_handle src,
944            const sycl::ext::oneapi::experimental::image_descriptor &desc_src,
945            size_t w_offset_src, size_t h_offset_src, void *dest, size_t p,
946            size_t w, size_t h, sycl::queue q) {
947  const auto ele_size = get_ele_size(desc_src);
948  const auto src_offset =
949      sycl::range<3>(w_offset_src / ele_size, h_offset_src, 0);
950  const auto dest_offset = sycl::range<3>(0, 0, 0);
951  const auto dest_extend = sycl::range<3>(p / ele_size, 0, 0);
952  const auto copy_extend = sycl::range<3>(w / ele_size, h, 0);
953  return q.ext_oneapi_copy(src, src_offset, desc_src, dest, dest_offset,
954                           dest_extend, copy_extend);
955}
956
957static inline std::vector<sycl::event> dpct_memcpy_to_host(
958    sycl::ext::oneapi::experimental::image_mem_handle src,
959    const sycl::ext::oneapi::experimental::image_descriptor &desc_src,
960    size_t w_offset_src, size_t h_offset_src, void *dest_host_ptr, size_t s,
961    sycl::queue q) {
962  std::vector<sycl::event> event_list;
963  const auto ele_size = get_ele_size(desc_src);
964  const auto w = desc_src.width * ele_size;
965  size_t offset_dest = 0;
966  while (s - offset_dest > w - w_offset_src) {
967    const auto src_offset =
968        sycl::range<3>(w_offset_src / ele_size, h_offset_src, 0);
969    const auto dest_offset = sycl::range<3>(offset_dest / ele_size, 0, 0);
970    const auto dest_extend = sycl::range<3>(0, 0, 0);
971    const auto copy_extend =
972        sycl::range<3>((w - w_offset_src) / ele_size, 1, 0);
973    event_list.push_back(q.ext_oneapi_copy(src, src_offset, desc_src,
974                                           dest_host_ptr, dest_offset,
975                                           dest_extend, copy_extend));
976    offset_dest += w - w_offset_src;
977    w_offset_src = 0;
978    ++h_offset_src;
979  }
980  if (s - offset_dest > 0) {
981    const auto src_offset =
982        sycl::range<3>(w_offset_src / ele_size, h_offset_src, 0);
983    const auto dest_offset = sycl::range<3>(offset_dest / ele_size, 0, 0);
984    const auto dest_extend = sycl::range<3>(0, 0, 0);
985    const auto copy_extend = sycl::range<3>((s - offset_dest) / ele_size, 1, 0);
986    event_list.push_back(q.ext_oneapi_copy(src, src_offset, desc_src,
987                                           dest_host_ptr, dest_offset,
988                                           dest_extend, copy_extend));
989  }
990  return event_list;
991}
992
993static inline std::vector<sycl::event>
994dpct_memcpy(sycl::ext::oneapi::experimental::image_mem_handle src,
995            const sycl::ext::oneapi::experimental::image_descriptor &desc_src,
996            size_t w_offset_src, size_t h_offset_src, void *dest, size_t s,
997            sycl::queue q) {
998  if (dpct::detail::get_pointer_attribute(q, dest) ==
999      dpct::detail::pointer_access_attribute::device_only) {
1000    std::vector<sycl::event> event_list;
1001    dpct::detail::host_buffer buf(s, q, event_list);
1002    auto copy_events = dpct_memcpy_to_host(src, desc_src, w_offset_src,
1003                                           h_offset_src, buf.get_ptr(), s, q);
1004    event_list.push_back(dpct::detail::dpct_memcpy(
1005        q, dest, buf.get_ptr(), s, memcpy_direction::host_to_device,
1006        copy_events));
1007    return event_list;
1008  }
1009  return dpct_memcpy_to_host(src, desc_src, w_offset_src, h_offset_src, dest, s,
1010                             q);
1011}
1012
1013static inline sycl::event
1014dpct_memcpy(const void *src,
1015            sycl::ext::oneapi::experimental::image_mem_handle dest,
1016            const sycl::ext::oneapi::experimental::image_descriptor &desc_dest,
1017            size_t w_offset_dest, size_t h_offset_dest, size_t p, size_t w,
1018            size_t h, sycl::queue q) {
1019  const auto ele_size = get_ele_size(desc_dest);
1020  const auto src_offset = sycl::range<3>(0, 0, 0);
1021  const auto src_extend = sycl::range<3>(p / ele_size, 0, 0);
1022  const auto dest_offset =
1023      sycl::range<3>(w_offset_dest / ele_size, h_offset_dest, 0);
1024  const auto copy_extend = sycl::range<3>(w / ele_size, h, 0);
1025  // TODO: Remove const_cast after refining the signature of ext_oneapi_copy.
1026  return q.ext_oneapi_copy(const_cast<void *>(src), src_offset, src_extend,
1027                           dest, dest_offset, desc_dest, copy_extend);
1028}
1029
1030static inline std::vector<sycl::event> dpct_memcpy_from_host(
1031    const void *src_host_ptr,
1032    sycl::ext::oneapi::experimental::image_mem_handle dest,
1033    const sycl::ext::oneapi::experimental::image_descriptor &desc_dest,
1034    size_t w_offset_dest, size_t h_offset_dest, size_t s, sycl::queue q) {
1035  std::vector<sycl::event> event_list;
1036  const auto ele_size = get_ele_size(desc_dest);
1037  const auto w = desc_dest.width * ele_size;
1038  size_t offset_src = 0;
1039  while (s - offset_src >= w - w_offset_dest) {
1040    const auto src_offset = sycl::range<3>(offset_src / ele_size, 0, 0);
1041    const auto src_extend = sycl::range<3>(0, 0, 0);
1042    const auto dest_offset =
1043        sycl::range<3>(w_offset_dest / ele_size, h_offset_dest, 0);
1044    const auto copy_extend =
1045        sycl::range<3>((w - w_offset_dest) / ele_size, 1, 0);
1046    // TODO: Remove const_cast after refining the signature of ext_oneapi_copy.
1047    event_list.push_back(q.ext_oneapi_copy(
1048        const_cast<void *>(src_host_ptr), src_offset, src_extend, dest,
1049        dest_offset, desc_dest, copy_extend));
1050    offset_src += w - w_offset_dest;
1051    w_offset_dest = 0;
1052    ++h_offset_dest;
1053  }
1054  if (s - offset_src > 0) {
1055    const auto src_offset = sycl::range<3>(offset_src / ele_size, 0, 0);
1056    const auto src_extend = sycl::range<3>(0, 0, 0);
1057    const auto dest_offset =
1058        sycl::range<3>(w_offset_dest / ele_size, h_offset_dest, 0);
1059    const auto copy_extend = sycl::range<3>((s - offset_src) / ele_size, 1, 0);
1060    // TODO: Remove const_cast after refining the signature of ext_oneapi_copy.
1061    event_list.push_back(q.ext_oneapi_copy(
1062        const_cast<void *>(src_host_ptr), src_offset, src_extend, dest,
1063        dest_offset, desc_dest, copy_extend));
1064  }
1065  return event_list;
1066}
1067
1068static inline std::vector<sycl::event> dpct_memcpy(
1069    const void *src, sycl::ext::oneapi::experimental::image_mem_handle dest,
1070    const sycl::ext::oneapi::experimental::image_descriptor &desc_dest,
1071    size_t w_offset_dest, size_t h_offset_dest, size_t s, sycl::queue q) {
1072  if (dpct::detail::get_pointer_attribute(q, src) ==
1073      dpct::detail::pointer_access_attribute::device_only) {
1074    std::vector<sycl::event> event_list;
1075    dpct::detail::host_buffer buf(s, q, event_list);
1076    event_list.push_back(dpct::detail::dpct_memcpy(
1077        q, buf.get_ptr(), src, s, memcpy_direction::device_to_host));
1078    auto copy_events = dpct_memcpy_from_host(
1079        buf.get_ptr(), dest, desc_dest, w_offset_dest, h_offset_dest, s, q);
1080    event_list.insert(event_list.end(), copy_events.begin(), copy_events.end());
1081    return event_list;
1082  }
1083  return dpct_memcpy_from_host(src, dest, desc_dest, w_offset_dest,
1084                               h_offset_dest, s, q);
1085}
1086
1087static inline sycl::event
1088dpct_memcpy(const image_mem_wrapper *src, const sycl::id<3> &src_id,
1089            const size_t src_x_offest_byte, pitched_data &dest,
1090            const sycl::id<3> &dest_id, const size_t dest_x_offest_byte,
1091            const sycl::range<3> &size, const size_t copy_x_size_byte,
1092            sycl::queue q) {
1093  const auto ele_size = get_ele_size(src->get_desc());
1094  const auto src_offset = sycl::range<3>(
1095      src_x_offest_byte != 0 ? src_x_offest_byte / ele_size : src_id[0],
1096      src_id[1], src_id[2]);
1097  const auto dest_offset = sycl::range<3>(
1098      dest_x_offest_byte != 0 ? dest_x_offest_byte / ele_size : dest_id[0],
1099      dest_id[1], dest_id[2]);
1100  const auto dest_extend =
1101      sycl::range<3>(dest.get_pitch() / ele_size, dest.get_y(), 1);
1102  const auto copy_extend = sycl::range<3>(
1103      copy_x_size_byte != 0 ? copy_x_size_byte / ele_size : size[0], size[1],
1104      size[2]);
1105  return q.ext_oneapi_copy(src->get_handle(), src_offset, src->get_desc(),
1106                           dest.get_data_ptr(), dest_offset, dest_extend,
1107                           copy_extend);
1108}
1109
1110static inline sycl::event
1111dpct_memcpy(pitched_data src, const sycl::id<3> &src_id,
1112            const size_t src_x_offest_byte, image_mem_wrapper *dest,
1113            const sycl::id<3> &dest_id, const size_t dest_x_offest_byte,
1114            const sycl::range<3> &size, const size_t copy_x_size_byte,
1115            sycl::queue q) {
1116  const auto ele_size = get_ele_size(dest->get_desc());
1117  const auto src_offset = sycl::range<3>(
1118      src_x_offest_byte != 0 ? src_x_offest_byte / ele_size : src_id[0],
1119      src_id[1], src_id[2]);
1120  const auto src_extend =
1121      sycl::range<3>(src.get_pitch() / ele_size, src.get_y(), 1);
1122  const auto dest_offset = sycl::range<3>(
1123      dest_x_offest_byte != 0 ? dest_x_offest_byte / ele_size : dest_id[0],
1124      dest_id[1], dest_id[2]);
1125  const auto copy_extend = sycl::range<3>(
1126      copy_x_size_byte != 0 ? copy_x_size_byte / ele_size : size[0], size[1],
1127      size[2]);
1128  return q.ext_oneapi_copy(src.get_data_ptr(), src_offset, src_extend,
1129                           dest->get_handle(), dest_offset, dest->get_desc(),
1130                           copy_extend);
1131}
1132
1133static inline sycl::event
1134dpct_memcpy(const image_mem_wrapper *src, const sycl::id<3> &src_id,
1135            const size_t src_x_offest_byte, image_mem_wrapper *dest,
1136            const sycl::id<3> &dest_id, const size_t dest_x_offest_byte,
1137            const sycl::range<3> &size, const size_t copy_x_size_byte,
1138            sycl::queue q) {
1139  // TODO: Need change logic when sycl support image_mem to image_mem copy.
1140  const auto from_ele_size = get_ele_size(src->get_desc());
1141  const auto to_ele_size = get_ele_size(dest->get_desc());
1142  const auto copy_extend = sycl::range<3>(
1143      copy_x_size_byte != 0 ? copy_x_size_byte / from_ele_size : size[0],
1144      size[1], size[2]);
1145  std::vector<sycl::event> event_list;
1146  dpct::detail::host_buffer buf(
1147      copy_extend.size() * std::max(from_ele_size, to_ele_size), q, event_list);
1148  auto to = pitched_data(buf.get_ptr(), copy_extend[0] * from_ele_size,
1149                         copy_extend[0], copy_extend[1]);
1150  dpct_memcpy(src, src_id, src_x_offest_byte, to, sycl::id<3>(0, 0, 0), 0,
1151              copy_extend, 0, q);
1152  auto from = pitched_data(buf.get_ptr(), copy_extend[0] * to_ele_size,
1153                           copy_extend[0], copy_extend[1]);
1154  event_list.push_back(dpct_memcpy(from, sycl::id<3>(0, 0, 0), 0, dest, dest_id,
1155                                   dest_x_offest_byte, copy_extend, 0, q));
1156  return event_list.front();
1157}
1158
1159template <typename T>
1160inline bool check_duplicate_entries(int count, T **entries) {
1161  std::set<T *> uniqueEntries;
1162
1163  for (size_t i = 0; i < count; ++i) {
1164    auto result = uniqueEntries.insert(entries[i]);
1165    if (!result.second) {
1166      return true;
1167    }
1168  }
1169
1170  return false;
1171}
1172} // namespace detail
1173
1174/// Get image_mem_wrapper according to sampled image handle.
1175/// \param [in] handle The bindless image handle.
1176/// \returns The image_mem_wrapper of sampled image.
1177inline image_mem_wrapper *&get_img_mem(
1178    const sycl::ext::oneapi::experimental::sampled_image_handle handle) {
1179  static std::map<sycl::ext::oneapi::experimental::sampled_image_handle,
1180                  image_mem_wrapper *, detail::sampled_image_handle_compare>
1181      img_mem_map;
1182  return img_mem_map[handle];
1183}
1184
1185/// Get image_mem_wrapper according to unsampled image handle.
1186/// \param [in] handle The unsampled bindless image handle.
1187/// \returns The image_mem_wrapper of unsampled image.
1188inline image_mem_wrapper *&get_img_mem(
1189    const sycl::ext::oneapi::experimental::unsampled_image_handle handle) {
1190  static std::map<sycl::ext::oneapi::experimental::unsampled_image_handle,
1191                  image_mem_wrapper *, detail::sampled_image_handle_compare>
1192      img_mem_map;
1193  return img_mem_map[handle];
1194}
1195
1196/// Associate an image memory wrapper with a bindless unsampled image handle in
1197/// the global registry.
1198///
1199/// Inserts or updates an entry in the internal image memory map, using the
1200/// specified bindless unsampled image handle as the key and the provided image
1201/// memory wrapper as the mapped value.
1202/// \param [in] handle The unsampled bindless image handle.
1203/// \param [in] img_mem The image_mem_wrapper associated with the unsampled handle.
1204static inline void set_img_mem(
1205    const sycl::ext::oneapi::experimental::unsampled_image_handle handle,
1206    image_mem_wrapper *img_mem) {
1207  dpct::experimental::get_img_mem(handle) = img_mem;
1208}
1209
1210/// Associate an image memory wrapper with a bindless sampled image handle in
1211/// the global registry.
1212///
1213/// Inserts or updates an entry in the internal image memory map, using the
1214/// specified bindless unsampled image handle as the key and the provided image
1215/// memory wrapper as the mapped value.
1216/// \param [in] handle The sampled bindless image handle.
1217/// \param [in] img_mem The image_mem_wrapper associated with the sampled handle.
1218static inline void set_img_mem(
1219    const sycl::ext::oneapi::experimental::sampled_image_handle handle,
1220    image_mem_wrapper *img_mem) {
1221  dpct::experimental::get_img_mem(handle) = img_mem;
1222}
1223
1224#ifdef _WIN32
1225/// Map the resource memories to mem handles
1226/// \param [in] count The count of resources to map.
1227/// \param [in] handles The external mem wrappers used to map the resources.
1228/// \param [in] q The queue used to map the resource with.
1229inline void map_resources(int count, external_mem_wrapper **handles,
1230                          queue_ptr q_ptr = &get_default_queue()) {
1231  if (detail::check_duplicate_entries(count, handles)) {
1232    throw std::runtime_error(
1233        "Duplicate handle entries found during resource mapping!");
1234  }
1235
1236  for (int i = 0; i < count; i++) {
1237    handles[i]->map_resource(*q_ptr);
1238  }
1239}
1240
1241/// Unmap the resource memories to mem handles
1242/// \param [in] count The count of resources to unmap.
1243/// \param [in] handles The external mem wrappers used to unmap the resources.
1244/// \param [in] q The queue used to unmap the resource with.
1245inline void unmap_resources(int count, external_mem_wrapper **handles,
1246                            queue_ptr q_ptr = &get_default_queue()) {
1247  if (detail::check_duplicate_entries(count, handles)) {
1248    throw std::runtime_error(
1249        "Duplicate handle entries found during resource unmapping!");
1250  }
1251
1252  for (int i = 0; i < count; i++) {
1253    handles[i]->unmap_resource(*q_ptr);
1254  }
1255}
1256#endif // _WIN32
1257
1258/// Imports resource's external memory into a SYCL external memory object.
1259/// \param [in] extMem SYCL external memory object ptr to be initialized.
1260/// \param [in] memHandleDesc Pointer to the external memory resource handle
1261/// descriptor.
1262/// \throws std::runtime_error If no valid external memory resource handle is
1263/// provided.
1264inline void
1265import_external_memory(sycl::ext::oneapi::experimental::external_mem *extMem,
1266                       external_mem_handle_desc *memHandleDesc) {
1267#ifdef _WIN32
1268  if (memHandleDesc->get_win32_handle()) {
1269    *extMem = sycl::ext::oneapi::experimental::import_external_memory(
1270        sycl::ext::oneapi::experimental::external_mem_descriptor<
1271            sycl::ext::oneapi::experimental::resource_win32_handle>{
1272            {memHandleDesc->get_win32_handle()},
1273            memHandleDesc->get_handle_type(),
1274            memHandleDesc->get_res_size()},
1275        get_default_queue());
1276  } else if (memHandleDesc->get_win32_obj_name()) {
1277    throw std::runtime_error(
1278        "Importing external memory resource using Windows NT name"
1279        " type is not supported. Only NT handle type is"
1280        " supported");
1281  }
1282#else
1283  if (memHandleDesc->get_fd_handle() != -1) {
1284    *extMem = sycl::ext::oneapi::experimental::import_external_memory(
1285        sycl::ext::oneapi::experimental::external_mem_descriptor<
1286            sycl::ext::oneapi::experimental::resource_fd>{
1287            {memHandleDesc->get_fd_handle()},
1288            memHandleDesc->get_handle_type(),
1289            memHandleDesc->get_res_size()},
1290        get_default_queue());
1291  }
1292#endif // _WIN32
1293  else {
1294    throw std::runtime_error(
1295        "No external memory resource handle is set for importing!");
1296  }
1297}
1298
1299/// Imports external semaphore resource into a SYCL external semaphore object.
1300/// \param [in] extSem SYCL external semaphore object ptr to be initialized.
1301/// \param [in] semHandleDesc Pointer to the external semaphore resource handle
1302/// descriptor.
1303/// \throws std::runtime_error If no valid external semaphore resource handle is
1304/// provided.
1305inline void import_external_semaphore(external_sem_wrapper **extSem,
1306                                      external_sem_handle_desc *semHandleDesc) {
1307  sycl::ext::oneapi::experimental::external_semaphore extSemObj;
1308#ifdef _WIN32
1309  if (semHandleDesc->get_win32_handle()) {
1310    extSemObj = sycl::ext::oneapi::experimental::import_external_semaphore(
1311        sycl::ext::oneapi::experimental::external_semaphore_descriptor<
1312            sycl::ext::oneapi::experimental::resource_win32_handle>{
1313            {semHandleDesc->get_win32_handle()},
1314            semHandleDesc->get_handle_type()},
1315        get_default_queue());
1316  } else if (semHandleDesc->get_win32_obj_name()) {
1317    throw std::runtime_error(
1318        "Importing external semaphore resource using Windows NT name"
1319        " type is not supported. Only NT handle type is"
1320        " supported");
1321  }
1322#else
1323  if (semHandleDesc->get_fd_handle() != -1) {
1324    extSemObj = sycl::ext::oneapi::experimental::import_external_semaphore(
1325        sycl::ext::oneapi::experimental::external_semaphore_descriptor<
1326            sycl::ext::oneapi::experimental::resource_fd>{
1327            {semHandleDesc->get_fd_handle()}, semHandleDesc->get_handle_type()},
1328        get_default_queue());
1329  }
1330#endif // _WIN32
1331  else {
1332    throw std::runtime_error(
1333        "No external semaphore resource handle is set for importing!");
1334  }
1335
1336  *extSem =
1337      new external_sem_wrapper(extSemObj, semHandleDesc->get_handle_type());
1338}
1339
1340/// Signals the external semaphore resource.
1341/// \param [in] extSem ptr to dpct external semaphore resource ptr
1342/// \param [in] semSignalParams Pointer to the external semaphore signal
1343/// parameters.
1344/// \param [in] numExtSems Number of external semaphores to signal.
1345/// \param [in] q_ptr The queue used to signal the external semaphore resource.
1346inline void signal_external_semaphores(external_sem_wrapper **extSem,
1347                                       external_sem_params *semSignalParams,
1348                                       unsigned int numExtSems,
1349                                       queue_ptr q_ptr = &get_default_queue()) {
1350  for (int i = 0; i < numExtSems; i++) {
1351    auto extSemType = extSem[i]->get_handle_type();
1352    switch (extSemType) {
1353#ifdef _WIN32
1354    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1355        win32_nt_dx12_fence:
1356    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1357        timeline_win32_nt_handle:
1358      q_ptr->ext_oneapi_signal_external_semaphore(
1359          extSem[i]->get(), semSignalParams[i].get_value());
1360      break;
1361    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1362        win32_nt_handle:
1363      q_ptr->ext_oneapi_signal_external_semaphore(extSem[i]->get());
1364      break;
1365#else  // _WIN32
1366    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1367        timeline_fd:
1368      q_ptr->ext_oneapi_signal_external_semaphore(
1369          extSem[i]->get(), semSignalParams[i].get_value());
1370      break;
1371    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1372        opaque_fd:
1373      q_ptr->ext_oneapi_signal_external_semaphore(extSem[i]->get());
1374      break;
1375#endif // _WIN32
1376    default:
1377      throw std::runtime_error(
1378          "Unsupported external semaphore resource handle type!");
1379      break;
1380    }
1381  }
1382}
1383
1384/// Wait for the external semaphore resource.
1385/// \param [in] extSem ptr to dpct external semaphore resource ptr
1386/// \param [in] semWaitParams Pointer to the external semaphore wait parameters.
1387/// \param [in] numExtSems Number of external semaphores to wait.
1388/// \param [in] q_ptr The queue used to wait on the external semaphore resource.
1389inline void wait_external_semaphores(external_sem_wrapper **extSem,
1390                                     external_sem_params *semWaitParams,
1391                                     unsigned int numExtSems,
1392                                     queue_ptr q_ptr = &get_default_queue()) {
1393  for (int i = 0; i < numExtSems; i++) {
1394    auto extSemType = extSem[i]->get_handle_type();
1395    switch (extSemType) {
1396#ifdef _WIN32
1397    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1398        win32_nt_dx12_fence:
1399    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1400        timeline_win32_nt_handle:
1401      q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get(),
1402                                                semWaitParams[i].get_value());
1403      break;
1404    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1405        win32_nt_handle:
1406      q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get());
1407      break;
1408#else  // _WIN32
1409    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1410        timeline_fd:
1411      q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get(),
1412                                                semWaitParams[i].get_value());
1413      break;
1414    case sycl::ext::oneapi::experimental::external_semaphore_handle_type::
1415        opaque_fd:
1416      q_ptr->ext_oneapi_wait_external_semaphore(extSem[i]->get());
1417      break;
1418#endif // _WIN32
1419    default:
1420      throw std::runtime_error(
1421          "Unsupported external semaphore resource handle type!");
1422      break;
1423    }
1424  }
1425}
1426
1427/// Create bindless image according to image data and sampling info.
1428/// \param [in] data The image data used to create bindless image.
1429/// \param [in] info The image sampling info used to create bindless image.
1430/// \param [in] q The queue where the image creation be executed.
1431/// \returns The sampled image handle of created bindless image.
1432static inline sycl::ext::oneapi::experimental::sampled_image_handle
1433create_bindless_image(image_data data, sampling_info info,
1434                      sycl::queue q = get_default_queue()) {
1435  auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler(
1436      info.get_addressing_mode(), info.get_coordinate_normalization_mode(),
1437      info.get_filtering_mode(), info.get_mipmap_filtering(),
1438      info.get_min_mipmap_level_clamp(), info.get_max_mipmap_level_clamp(),
1439      info.get_max_anisotropy());
1440
1441  switch (data.get_data_type()) {
1442  case image_data_type::linear: {
1443    // linear memory only use sycl::filtering_mode::nearest.
1444    samp.filtering = sycl::filtering_mode::nearest;
1445    // TODO: Use pointer to create image when bindless image support.
1446    auto mem = new image_mem_wrapper(
1447        data.get_channel(), data.get_x() / data.get_channel().get_total_size());
1448    auto img = sycl::ext::oneapi::experimental::create_image(
1449        mem->get_handle(), samp, mem->get_desc(), q);
1450    set_img_mem(img, mem);
1451    auto ptr = data.get_data_ptr();
1452#ifdef DPCT_USM_LEVEL_NONE
1453    q.ext_oneapi_copy(get_buffer(ptr).get_host_access().get_pointer(),
1454                      mem->get_handle(), mem->get_desc())
1455        .wait();
1456#else
1457    q.ext_oneapi_copy(ptr, mem->get_handle(), mem->get_desc()).wait();
1458#endif
1459    detail::get_img_info_map(img) = {data, info};
1460    return img;
1461  }
1462  case image_data_type::pitch: {
1463#ifdef DPCT_USM_LEVEL_NONE
1464    auto mem =
1465        new image_mem_wrapper(data.get_channel(), data.get_x(), data.get_y());
1466    auto img = sycl::ext::oneapi::experimental::create_image(
1467        mem->get_handle(), samp, mem->get_desc(), q);
1468    set_img_mem(img, mem);
1469    q.ext_oneapi_copy(
1470         get_buffer(data.get_data_ptr()).get_host_access().get_pointer(),
1471         mem->get_handle(), mem->get_desc())
1472        .wait();
1473#else
1474    auto desc = sycl::ext::oneapi::experimental::image_descriptor(
1475        {data.get_x(), data.get_y()}, data.get_channel().get_channel_num(),
1476        data.get_channel_type());
1477    auto img = sycl::ext::oneapi::experimental::create_image(
1478        data.get_data_ptr(), data.get_pitch(), samp, desc, q);
1479#endif
1480    detail::get_img_info_map(img) = {data, info};
1481    return img;
1482  }
1483  case image_data_type::matrix: {
1484    const auto mem = static_cast<image_mem_wrapper *>(data.get_data_ptr());
1485    auto img = sycl::ext::oneapi::experimental::create_image(
1486        mem->get_handle(), samp, mem->get_desc(), q);
1487    detail::get_img_info_map(img) = {data, info};
1488    return img;
1489  }
1490  default:
1491    throw std::runtime_error(
1492        "Unsupported image_data_type in create_bindless_image!");
1493    break;
1494  }
1495  // Must not reach here.
1496  return sycl::ext::oneapi::experimental::sampled_image_handle();
1497}
1498
1499/// Create bindless image according to image data.
1500/// \param [in] data The image data used to create bindless image.
1501/// \param [in] q The queue where the image creation be executed.
1502/// \returns The sampled image handle of created bindless image.
1503static inline sycl::ext::oneapi::experimental::unsampled_image_handle
1504create_bindless_image(image_data data, sycl::queue q = get_default_queue()) {
1505  switch (data.get_data_type()) {
1506  case image_data_type::linear: {
1507    // TODO: Use pointer to create image when bindless image support.
1508    auto mem = new image_mem_wrapper(
1509        data.get_channel(), data.get_x() / data.get_channel().get_total_size());
1510    auto img = sycl::ext::oneapi::experimental::create_image(
1511        mem->get_handle(), mem->get_desc(), q);
1512    set_img_mem(img, mem);
1513    auto ptr = data.get_data_ptr();
1514#ifdef DPCT_USM_LEVEL_NONE
1515    q.ext_oneapi_copy(get_buffer(ptr).get_host_access().get_pointer(),
1516                      mem->get_handle(), mem->get_desc())
1517        .wait();
1518#else
1519    q.ext_oneapi_copy(ptr, mem->get_handle(), mem->get_desc()).wait();
1520#endif
1521    return img;
1522  }
1523  case image_data_type::pitch: {
1524    auto mem =
1525        new image_mem_wrapper(data.get_channel(), data.get_x(), data.get_y());
1526    auto img = sycl::ext::oneapi::experimental::create_image(
1527        mem->get_handle(), mem->get_desc(), q);
1528    set_img_mem(img, mem);
1529#ifdef DPCT_USM_LEVEL_NONE
1530    q.ext_oneapi_copy(
1531         get_buffer(data.get_data_ptr()).get_host_access().get_pointer(),
1532         mem->get_handle(), mem->get_desc())
1533        .wait();
1534#else
1535    q.ext_oneapi_copy(data.get_data_ptr(), mem->get_handle(), mem->get_desc())
1536        .wait();
1537
1538#endif
1539    return img;
1540  }
1541  case image_data_type::matrix: {
1542    const auto mem = static_cast<image_mem_wrapper *>(data.get_data_ptr());
1543    auto img = sycl::ext::oneapi::experimental::create_image(
1544        mem->get_handle(), mem->get_desc(), q);
1545    return img;
1546  }
1547  default:
1548    throw std::runtime_error(
1549        "Unsupported image_data_type in create_bindless_image!");
1550    break;
1551  }
1552  // Must not reach here.
1553  return sycl::ext::oneapi::experimental::unsampled_image_handle();
1554}
1555
1556/// Destroy bindless image.
1557/// \param [in] handle The bindless image should be destroyed.
1558/// \param [in] q The queue where the image destruction be executed.
1559template <class T>
1560static inline void destroy_bindless_image(T handle,
1561                                          sycl::queue q = get_default_queue()) {
1562  auto &mem = get_img_mem(handle);
1563  if (mem) {
1564    delete mem;
1565    mem = nullptr;
1566  }
1567  sycl::ext::oneapi::experimental::destroy_image_handle(handle, q);
1568}
1569
1570/// Get the image data according to sampled image handle.
1571/// \param [in] handle The bindless image handle.
1572/// \returns The image data of sampled image.
1573template <class T> static inline image_data get_data(const T handle) {
1574  return detail::get_img_info_map(handle).first;
1575}
1576
1577/// Get the sampling info according to sampled image handle.
1578/// \param [in] handle The bindless image handle.
1579/// \returns The sampling info of sampled image.
1580static inline sampling_info get_sampling_info(
1581    const sycl::ext::oneapi::experimental::sampled_image_handle handle) {
1582  return detail::get_img_info_map(handle).second;
1583}
1584
1585/// The base class of different template specialization bindless_image_wrapper
1586/// class.
1587class bindless_image_wrapper_base {
1588public:
1589  bindless_image_wrapper_base() {
1590    // Make sure that singleton class dev_mgr will destruct later than this.
1591    dev_mgr::instance();
1592  }
1593
1594  /// Destroy bindless image wrapper.
1595  ~bindless_image_wrapper_base() {
1596    destroy_bindless_image(_img, get_default_queue());
1597  }
1598
1599  /// Attach linear data to bindless image.
1600  /// \param [in] data The linear data used to create bindless image.
1601  /// \param [in] size The size of linear data used to create bindless image.
1602  /// \param [in] channel The image channel used to create bindless image.
1603  /// \param [in] q The queue where the image creation be executed.
1604  void attach(void *data, size_t size, const image_channel &channel,
1605              sycl::queue q = get_default_queue()) {
1606    detach(q);
1607    auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler(
1608        _addressing_mode, _coordinate_normalization_mode, _filtering_mode);
1609    // TODO: Use pointer to create image when bindless image support.
1610    auto mem = new image_mem_wrapper(channel, size);
1611    _img = sycl::ext::oneapi::experimental::create_image(
1612        mem->get_handle(), samp, mem->get_desc(), q);
1613    set_img_mem(_img, mem);
1614    auto ptr = data;
1615#ifdef DPCT_USM_LEVEL_NONE
1616    q.ext_oneapi_copy(get_buffer(data).get_host_access().get_pointer(),
1617                      mem->get_handle(), mem->get_desc())
1618        .wait();
1619#else
1620    q.ext_oneapi_copy(ptr, mem->get_handle(), mem->get_desc()).wait();
1621#endif
1622  }
1623
1624  /// Attach linear data to bindless image.
1625  /// \param [in] data The linear data used to create bindless image.
1626  /// \param [in] size The size of linear data used to create bindless image.
1627  /// \param [in] q The queue where the image creation be executed.
1628  void attach(void *data, size_t size, sycl::queue q = get_default_queue()) {
1629    attach(data, size, _channel, q);
1630  }
1631
1632  /// Attach device_ptr data to bindless image.
1633  /// \param [in] desc The image_descriptor used to create bindless image.
1634  /// \param [in] ptr The data pointer used to create bindless image.
1635  /// \param [in] pitch The pitch of 2D data used to create bindless image.
1636  /// \param [in] q The queue where the image creation be executed.
1637  void attach(const sycl::ext::oneapi::experimental::image_descriptor *desc,
1638              device_ptr ptr, size_t pitch,
1639              sycl::queue q = get_default_queue()) {
1640    detach(q);
1641    auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler(
1642        _addressing_mode, _coordinate_normalization_mode, _filtering_mode);
1643#ifdef DPCT_USM_LEVEL_NONE
1644    auto mem = new image_mem_wrapper(desc);
1645    _img = sycl::ext::oneapi::experimental::create_image(mem->get_handle(),
1646                                                         samp, *desc, q);
1647    set_img_mem(_img, mem);
1648    q.ext_oneapi_copy(get_buffer(ptr).get_host_access().get_pointer(),
1649                      mem->get_handle(), mem->get_desc())
1650        .wait();
1651#else
1652    _img = sycl::ext::oneapi::experimental::create_image(ptr, pitch, samp,
1653                                                         *desc, q);
1654#endif
1655  }
1656
1657  /// Attach 2D data to bindless image.
1658  /// \param [in] data The 2D data used to create bindless image.
1659  /// \param [in] width The width of 2D data used to create bindless image.
1660  /// \param [in] height The height of 2D data used to create bindless image.
1661  /// \param [in] pitch The pitch of 2D data used to create bindless image.
1662  /// \param [in] channel The image channel used to create bindless image.
1663  /// \param [in] q The queue where the image creation be executed.
1664  void attach(void *data, size_t width, size_t height, size_t pitch,
1665              const image_channel &channel,
1666              sycl::queue q = get_default_queue()) {
1667    auto desc = sycl::ext::oneapi::experimental::image_descriptor(
1668        {width, height}, channel.get_channel_num(), channel.get_channel_type());
1669    attach(&desc, static_cast<device_ptr>(data), pitch, q);
1670  }
1671
1672  /// Attach 2D data to bindless image.
1673  /// \param [in] data The 2D data used to create bindless image.
1674  /// \param [in] width The width of 2D data used to create bindless image.
1675  /// \param [in] height The height of 2D data used to create bindless image.
1676  /// \param [in] pitch The pitch of 2D data used to create bindless image.
1677  /// \param [in] q The queue where the image creation be executed.
1678  void attach(void *data, size_t width, size_t height, size_t pitch,
1679              sycl::queue q = get_default_queue()) {
1680    attach(data, width, height, pitch, _channel, q);
1681  }
1682
1683  /// Attach image memory to bindless image.
1684  /// \param [in] mem The image memory used to create bindless image.
1685  /// \param [in] q The queue where the image creation be executed.
1686  void attach(image_mem_wrapper *mem, const image_channel &channel,
1687              sycl::queue q = get_default_queue()) {
1688    detach(q);
1689    auto samp = sycl::ext::oneapi::experimental::bindless_image_sampler(
1690        _addressing_mode, _coordinate_normalization_mode, _filtering_mode);
1691    _img = sycl::ext::oneapi::experimental::create_image(
1692        mem->get_handle(), samp, mem->get_desc(), q);
1693    set_img_mem(_img, mem);
1694  }
1695
1696  /// Attach image memory to bindless image.
1697  /// \param [in] mem The image memory used to create bindless image.
1698  /// \param [in] q The queue where the image creation be executed.
1699  void attach(image_mem_wrapper *mem, sycl::queue q = get_default_queue()) {
1700    attach(mem, _channel, q);
1701  }
1702
1703  /// Detach bindless image data.
1704  /// \param [in] q The queue where the image destruction be executed.
1705  void detach(sycl::queue q = get_default_queue()) {
1706    destroy_bindless_image(_img, q);
1707  }
1708
1709  /// Set image channel of bindless image.
1710  /// \param [in] channel The image channel used to set.
1711  void set_channel(image_channel channel) { _channel = channel; }
1712  /// Get image channel of bindless image.
1713  /// \returns The image channel of bindless image.
1714  image_channel get_channel() { return _channel; }
1715
1716  /// Set channel size of image channel.
1717  /// \param [in] channel_num The channels number to set.
1718  /// \param [in] channel_size The size for each channel in bits.
1719  void set_channel_size(unsigned channel_num, unsigned channel_size) {
1720    return _channel.set_channel_size(channel_num, channel_size);
1721  }
1722  /// Get channel size of image channel.
1723  /// \returns The size for each channel in bits.
1724  unsigned get_channel_size() { return _channel.get_channel_size(); }
1725
1726  /// Set image channel data type of image channel.
1727  /// \param [in] type The image channel data type to set.
1728  void set_channel_data_type(image_channel_data_type type) {
1729    _channel.set_channel_data_type(type);
1730  }
1731  /// Get image channel data type of image channel.
1732  /// \returns The image channel data type of image channel.
1733  image_channel_data_type get_channel_data_type() {
1734    return _channel.get_channel_data_type();
1735  }
1736
1737  /// Set channel num of bindless image.
1738  /// \param [in] filtering_mode The channel num used to set.
1739  void set_channel_num(unsigned num) { return _channel.set_channel_num(num); }
1740
1741  /// Set channel type of bindless image.
1742  /// \param [in] filtering_mode The channel type used to set.
1743  void set_channel_type(sycl::image_channel_type type) {
1744    return _channel.set_channel_type(type);
1745  }
1746
1747  /// Set addressing mode of bindless image.
1748  /// \param [in] addressing_mode The addressing mode used to set.
1749  void set(sycl::addressing_mode addressing_mode) {
1750    _addressing_mode = addressing_mode;
1751  }
1752  /// Get addressing mode of bindless image.
1753  /// \returns The addressing mode of bindless image.
1754  sycl::addressing_mode get_addressing_mode() { return _addressing_mode; }
1755
1756  /// Set coordinate normalization mode of bindless image.
1757  /// \param [in] coordinate_normalization_mode The coordinate normalization
1758  /// mode used to set.
1759  void set(sycl::coordinate_normalization_mode coordinate_normalization_mode) {
1760    _coordinate_normalization_mode = coordinate_normalization_mode;
1761  }
1762  /// Set coordinate normalization mode of bindless image.
1763  /// \param [in] is_normalized Determine whether the coordinate should be
1764  /// normalized.
1765  void set_coordinate_normalization_mode(int is_normalized) {
1766    _coordinate_normalization_mode =
1767        is_normalized ? sycl::coordinate_normalization_mode::normalized
1768                      : sycl::coordinate_normalization_mode::unnormalized;
1769  }
1770  /// Get coordinate normalization mode of bindless image.
1771  /// \returns The coordinate normalization mode of bindless image.
1772  bool is_coordinate_normalized() {
1773    return _coordinate_normalization_mode ==
1774           sycl::coordinate_normalization_mode::normalized;
1775  }
1776
1777  /// Set filtering mode of bindless image.
1778  /// \param [in] filtering_mode The filtering mode used to set.
1779  void set(sycl::filtering_mode filtering_mode) {
1780    _filtering_mode = filtering_mode;
1781  }
1782  /// Get filtering mode of bindless image.
1783  /// \returns The filtering mode of bindless image.
1784  sycl::filtering_mode get_filtering_mode() { return _filtering_mode; }
1785
1786  /// Get bindless image handle.
1787  /// \returns The sampled image handle of created bindless image.
1788  inline sycl::ext::oneapi::experimental::sampled_image_handle get_handle() {
1789    return _img;
1790  }
1791
1792  /// Set mipmap sample filtering mode for bindless image handle
1793  /// \param [in] filtering_mode The mipmap filtering mode
1794  inline void set_mip_filtering_mode(sycl::filtering_mode mode) {
1795    auto sampling_info = get_sampling_info(_img);
1796    sampling_info.set_mipmap_filtering(mode);
1797  }
1798
1799  /// Get mipmap sample filtering mode for bindless image handle
1800  /// \return The mipmap filtering mode
1801  inline sycl::filtering_mode get_mip_filtering_mode(void) {
1802    auto sampling_info = get_sampling_info(_img);
1803    return sampling_info.get_mipmap_filtering();
1804  }
1805
1806  /// Get mipmap sample filtering mode for bindless image handle
1807  /// \return The mipmap filtering mode
1808  inline void get_mip_level_clamp(float *min_level_clamp,
1809                                  float *max_level_clamp) {
1810    auto sampling_info = get_sampling_info(_img);
1811    *min_level_clamp = sampling_info.get_min_mipmap_level_clamp();
1812    *max_level_clamp = sampling_info.get_max_mipmap_level_clamp();
1813  }
1814
1815  /// Get mipmap memory wrapper attached the bindless image
1816  /// \return The mipmap memory wrapper
1817  inline image_mem_wrapper *get_attached_mipmap_data(void) {
1818    auto mem = get_img_mem(_img);
1819
1820    if (mem->get_image_type() !=
1821        sycl::ext::oneapi::experimental::image_type::mipmap)
1822      throw std::runtime_error("Bindless image data is not of mipmap type");
1823
1824    return mem;
1825  }
1826
1827private:
1828  image_channel _channel;
1829  sycl::addressing_mode _addressing_mode = sycl::addressing_mode::clamp_to_edge;
1830  sycl::coordinate_normalization_mode _coordinate_normalization_mode =
1831      sycl::coordinate_normalization_mode::unnormalized;
1832  sycl::filtering_mode _filtering_mode = sycl::filtering_mode::nearest;
1833  sycl::ext::oneapi::experimental::sampled_image_handle _img{0};
1834};
1835
1836/// The wrapper class of bindless image.
1837template <class T, int dimensions>
1838class bindless_image_wrapper : public bindless_image_wrapper_base {
1839public:
1840  /// Create bindless image wrapper according to template argument \p T.
1841  bindless_image_wrapper() { set_channel(image_channel::create<T>()); }
1842};
1843
1844/// Asynchronously copies from the image memory to memory specified by a
1845/// pointer, The return of the function does NOT guarantee the copy is
1846/// completed.
1847/// \param [in] dest The destination memory address.
1848/// \param [in] p The pitch of destination memory.
1849/// \param [in] src The source image memory.
1850/// \param [in] w_offset_src The x offset of source image memory.
1851/// \param [in] h_offset_src The y offset of source image memory.
1852/// \param [in] w The width of matrix to be copied.
1853/// \param [in] h The height of matrix to be copied.
1854/// \param [in] q The queue to execute the copy task.
1855static inline void async_dpct_memcpy(void *dest, size_t p,
1856                                     const image_mem_wrapper *src,
1857                                     size_t w_offset_src, size_t h_offset_src,
1858                                     size_t w, size_t h,
1859                                     sycl::queue q = get_default_queue()) {
1860  detail::dpct_memcpy(src->get_handle(), src->get_desc(), w_offset_src,
1861                      h_offset_src, dest, p, w, h, q);
1862}
1863
1864/// Synchronously copies from the image memory to memory specified by a
1865/// pointer, The function will return after the copy is completed.
1866/// \param [in] dest The destination memory address.
1867/// \param [in] p The pitch of destination memory.
1868/// \param [in] src The source image memory.
1869/// \param [in] w_offset_src The x offset of source image memory.
1870/// \param [in] h_offset_src The y offset of source image memory.
1871/// \param [in] w The width of matrix to be copied.
1872/// \param [in] h The height of matrix to be copied.
1873/// \param [in] q The queue to execute the copy task.
1874static inline void dpct_memcpy(void *dest, size_t p,
1875                               const image_mem_wrapper *src,
1876                               size_t w_offset_src, size_t h_offset_src,
1877                               size_t w, size_t h,
1878                               sycl::queue q = get_default_queue()) {
1879  detail::dpct_memcpy(src->get_handle(), src->get_desc(), w_offset_src,
1880                      h_offset_src, dest, p, w, h, q)
1881      .wait();
1882}
1883
1884/// Asynchronously copies from the image memory to memory specified by a
1885/// pointer, The return of the function does NOT guarantee the copy is
1886/// completed.
1887/// \param [in] dest The destination memory address.
1888/// \param [in] src The source image memory.
1889/// \param [in] w_offset_src The x offset of source image memory.
1890/// \param [in] h_offset_src The y offset of source image memory.
1891/// \param [in] s The size to be copied.
1892/// \param [in] q The queue to execute the copy task.
1893static inline void async_dpct_memcpy(void *dest, const image_mem_wrapper *src,
1894                                     size_t w_offset_src, size_t h_offset_src,
1895                                     size_t s,
1896                                     sycl::queue q = get_default_queue()) {
1897  detail::dpct_memcpy(src->get_handle(), src->get_desc(), w_offset_src,
1898                      h_offset_src, dest, s, q);
1899}
1900
1901/// Synchronously copies from the image memory to memory specified by a
1902/// pointer, The function will return after the copy is completed.
1903/// \param [in] dest The destination memory address.
1904/// \param [in] src The source image memory.
1905/// \param [in] w_offset_src The x offset of source image memory.
1906/// \param [in] h_offset_src The y offset of source image memory.
1907/// \param [in] s The size to be copied.
1908/// \param [in] q The queue to execute the copy task.
1909static inline void dpct_memcpy(void *dest, const image_mem_wrapper *src,
1910                               size_t w_offset_src, size_t h_offset_src,
1911                               size_t s, sycl::queue q = get_default_queue()) {
1912  sycl::event::wait(detail::dpct_memcpy(src->get_handle(), src->get_desc(),
1913                                        w_offset_src, h_offset_src, dest, s,
1914                                        q));
1915}
1916
1917/// Asynchronously copies from memory specified by a pointer to the image
1918/// memory, The return of the function does NOT guarantee the copy is completed.
1919/// \param [in] dest The destination image memory.
1920/// \param [in] w_offset_dest The x offset of destination image memory.
1921/// \param [in] h_offset_dest The y offset of destination image memory.
1922/// \param [in] src The source memory address.
1923/// \param [in] p The pitch of source memory.
1924/// \param [in] w The width of matrix to be copied.
1925/// \param [in] h The height of matrix to be copied.
1926/// \param [in] q The queue to execute the copy task.
1927static inline void async_dpct_memcpy(image_mem_wrapper *dest,
1928                                     size_t w_offset_dest, size_t h_offset_dest,
1929                                     const void *src, size_t p, size_t w,
1930                                     size_t h,
1931                                     sycl::queue q = get_default_queue()) {
1932  detail::dpct_memcpy(src, dest->get_handle(), dest->get_desc(), w_offset_dest,
1933                      h_offset_dest, p, w, h, q);
1934}
1935
1936/// Synchronously copies from memory specified by a pointer to the image
1937/// memory, The function will return after the copy is completed.
1938/// \param [in] dest The destination image memory.
1939/// \param [in] w_offset_dest The x offset of destination image memory.
1940/// \param [in] h_offset_dest The y offset of destination image memory.
1941/// \param [in] src The source memory address.
1942/// \param [in] p The pitch of source memory.
1943/// \param [in] w The width of matrix to be copied.
1944/// \param [in] h The height of matrix to be copied.
1945/// \param [in] q The queue to execute the copy task.
1946static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest,
1947                               size_t h_offset_dest, const void *src, size_t p,
1948                               size_t w, size_t h,
1949                               sycl::queue q = get_default_queue()) {
1950  detail::dpct_memcpy(src, dest->get_handle(), dest->get_desc(), w_offset_dest,
1951                      h_offset_dest, p, w, h, q)
1952      .wait();
1953}
1954
1955/// Asynchronously copies from memory specified by a pointer to the image
1956/// memory, The return of the function does NOT guarantee the copy is completed.
1957/// \param [in] dest The destination image memory.
1958/// \param [in] w_offset_dest The x offset of destination image memory.
1959/// \param [in] h_offset_dest The y offset of destination image memory.
1960/// \param [in] src The source memory address.
1961/// \param [in] s The size to be copied.
1962/// \param [in] q The queue to execute the copy task.
1963static inline void async_dpct_memcpy(image_mem_wrapper *dest,
1964                                     size_t w_offset_dest, size_t h_offset_dest,
1965                                     const void *src, size_t s,
1966                                     sycl::queue q = get_default_queue()) {
1967  detail::dpct_memcpy(src, dest->get_handle(), dest->get_desc(), w_offset_dest,
1968                      h_offset_dest, s, q);
1969}
1970
1971/// Synchronously copies from memory specified by a pointer to the image
1972/// memory, The function will return after the copy is completed.
1973/// \param [in] dest The destination image memory.
1974/// \param [in] w_offset_dest The x offset of destination image memory.
1975/// \param [in] h_offset_dest The y offset of destination image memory.
1976/// \param [in] src The source memory address.
1977/// \param [in] s The size to be copied.
1978/// \param [in] q The queue to execute the copy task.
1979static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest,
1980                               size_t h_offset_dest, const void *src, size_t s,
1981                               sycl::queue q = get_default_queue()) {
1982  sycl::event::wait(detail::dpct_memcpy(src, dest->get_handle(),
1983                                        dest->get_desc(), w_offset_dest,
1984                                        h_offset_dest, s, q));
1985}
1986
1987/// Synchronously copies from image memory to the image memory, The function
1988/// will return after the copy is completed.
1989/// \param [in] dest The destination image memory.
1990/// \param [in] w_offset_dest The x offset of destination image memory.
1991/// \param [in] h_offset_dest The y offset of destination image memory.
1992/// \param [in] src The source image memory.
1993/// \param [in] w_offset_src The x offset of source image memory.
1994/// \param [in] h_offset_src The y offset of source image memory.
1995/// \param [in] w The width of matrix to be copied.
1996/// \param [in] h The height of matrix to be copied.
1997/// \param [in] q The queue to execute the copy task.
1998static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest,
1999                               size_t h_offset_dest,
2000                               const image_mem_wrapper *src,
2001                               size_t w_offset_src, size_t h_offset_src,
2002                               size_t w, size_t h,
2003                               sycl::queue q = get_default_queue()) {
2004  auto temp = (void *)sycl::malloc_device(w * h, q);
2005  // TODO: Need change logic when sycl support image_mem to image_mem copy.
2006  dpct_memcpy(temp, w, src, w_offset_src, h_offset_src, w, h, q);
2007  dpct_memcpy(dest, w_offset_dest, h_offset_dest, temp, w, w, h, q);
2008  sycl::free(temp, q);
2009}
2010
2011/// Synchronously copies from image memory to the image memory, The function
2012/// will return after the copy is completed.
2013/// \param [in] dest The destination image memory.
2014/// \param [in] w_offset_dest The x offset of destination image memory.
2015/// \param [in] h_offset_dest The y offset of destination image memory.
2016/// \param [in] src The source image memory.
2017/// \param [in] w_offset_src The x offset of source image memory.
2018/// \param [in] h_offset_src The y offset of source image memory.
2019/// \param [in] s The size to be copied.
2020/// \param [in] q The queue to execute the copy task.
2021static inline void dpct_memcpy(image_mem_wrapper *dest, size_t w_offset_dest,
2022                               size_t h_offset_dest,
2023                               const image_mem_wrapper *src,
2024                               size_t w_offset_src, size_t h_offset_src,
2025                               size_t s, sycl::queue q = get_default_queue()) {
2026  auto temp = (void *)sycl::malloc_device(s, q);
2027  // TODO: Need change logic when sycl support image_mem to image_mem copy.
2028  dpct_memcpy(temp, src, w_offset_src, h_offset_src, s, q);
2029  dpct_memcpy(dest, w_offset_dest, h_offset_dest, temp, s, q);
2030  sycl::free(temp, q);
2031}
2032// A wrapper for sycl fetch_image function for the byte addressing image.
2033template <typename DataT, typename HintT = DataT, typename CoordT>
2034DataT fetch_image_by_byte(
2035    const sycl::ext::oneapi::experimental::unsampled_image_handle &imageHandle,
2036    CoordT &&coords) {
2037  if constexpr (std::is_scalar_v<CoordT>) {
2038    return sycl::ext::oneapi::experimental::fetch_image<DataT, HintT, CoordT>(
2039        imageHandle, coords / sizeof(DataT));
2040  } else {
2041    coords[0] = coords[0] / sizeof(DataT);
2042    return sycl::ext::oneapi::experimental::fetch_image<DataT, HintT, CoordT>(
2043        imageHandle, coords);
2044  }
2045}
2046
2047using image_mem_wrapper_ptr = image_mem_wrapper *;
2048#ifdef _WIN32
2049using external_mem_wrapper_ptr = external_mem_wrapper *;
2050#else
2051using external_mem_wrapper_ptr = external_mem_wrapper_base *;
2052#endif // _WIN32
2053using external_sem_wrapper_ptr = external_sem_wrapper *;
2054using bindless_image_wrapper_base_p = bindless_image_wrapper_base *;
2055
2056#endif
2057
2058} // namespace experimental
2059} // namespace dpct
2060
2061#endif // !__DPCT_BINDLESS_IMAGE_HPP__