okami.mom/strata

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

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

main
21.9 KiB632 linesraw
1//==---- kernel.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_KERNEL_HPP__
10#define __DPCT_KERNEL_HPP__
11
12#include <cstdint>
13#include <sycl/sycl.hpp>
14#ifdef _WIN32
15#include <unordered_set>
16#include <windows.h>
17#else
18#include <dlfcn.h>
19#endif
20
21#if defined(__has_include) && __has_include(<filesystem>)
22#include <filesystem>
23#elif defined(__has_include) && __has_include(<experimental/filesystem>)
24#include <experimental/filesystem>
25#else
26#error "SYCLomatic runtime requires C++ filesystem support"
27#endif
28
29#include "image.hpp"
30#include <fstream>
31#include <mutex>
32#include <random>
33
34namespace dpct {
35
36typedef void (*kernel_functor)(sycl::queue &, const sycl::nd_range<3> &,
37                               unsigned int, void **, void **);
38
39typedef void (*host_func)(void *);
40
41struct kernel_function_info {
42  int max_work_group_size = 0;
43  int shared_size_bytes = 0;
44  int local_size_bytes = 0;
45  int const_size_bytes = 0;
46  int num_regs = 0;
47};
48
49static inline void get_kernel_function_info(kernel_function_info *kernel_info,
50                                            const void *function) {
51  kernel_info->max_work_group_size =
52      dpct::dev_mgr::instance()
53          .current_device()
54          .get_info<sycl::info::device::max_work_group_size>();
55}
56static inline kernel_function_info
57get_kernel_function_info(const void *function) {
58  kernel_function_info kernel_info;
59  kernel_info.max_work_group_size =
60      dpct::dev_mgr::instance()
61          .current_device()
62          .get_info<sycl::info::device::max_work_group_size>();
63  return kernel_info;
64}
65
66
67namespace detail {
68
69#if defined(__has_include) && __has_include(<filesystem>)
70namespace fs = std::filesystem;
71#else
72namespace fs = std::experimental::filesystem;
73#endif
74
75/// Write data to temporary file and return absolute path to temporary file.
76/// Temporary file is created in a temporary directory both of which have random
77/// names with only the user having access permissions.  Only one temporary file
78/// will be created in the temporary directory.
79static inline fs::path write_data_to_file(char const *const data, size_t size) {
80  std::error_code ec;
81
82  if (sizeof(size_t) >= sizeof(std::streamsize) &&
83      size > (std::numeric_limits<std::streamsize>::max)())
84    throw std::runtime_error("data file too large");
85
86  // random number generator
87  std::random_device dev;
88  std::mt19937 prng(dev());
89  std::uniform_int_distribution<uint64_t> rand(0);
90
91  // find temporary directory
92  auto tmp_dir = fs::temp_directory_path(ec);
93  if (ec)
94    throw std::runtime_error("could not find temporary directory");
95
96  // create private directory
97  std::stringstream directory;
98  fs::path directory_path;
99  constexpr int max_attempts = 5;
100  int i;
101
102  for (i = 0; i < max_attempts; i++) {
103    directory << std::hex << rand(prng);
104    directory_path = tmp_dir / directory.str();
105    if (fs::create_directory(directory_path)) {
106      break;
107    }
108  }
109  if (i == max_attempts)
110    throw std::runtime_error("could not create directory");
111
112  // only allow owner permissions to private directory
113  fs::permissions(directory_path, fs::perms::owner_all, ec);
114  if (ec)
115    throw std::runtime_error("could not set directory permissions");
116
117  // random filename in private directory
118  std::stringstream filename;
119  filename << std::hex << rand(prng);
120#ifdef _WIN32
121  auto filepath = directory_path / (filename.str() + ".dll");
122#else
123  auto filepath = directory_path / filename.str();
124#endif
125
126  // write data to temporary file
127  auto outfile = std::ofstream(filepath, std::ios::out | std::ios::binary);
128  if (outfile) {
129    // only allow program to write file
130    fs::permissions(filepath, fs::perms::owner_write, ec);
131    if (ec)
132      throw std::runtime_error("could not set permissions");
133
134    outfile.write(data, size);
135    if (!outfile.good())
136      throw std::runtime_error("could not write data");
137    outfile.close();
138
139    // only allow program to read/execute file
140    fs::permissions(filepath, fs::perms::owner_read | fs::perms::owner_exec,
141                    ec);
142    if (ec)
143      throw std::runtime_error("could not set permissions");
144  } else
145    throw std::runtime_error("could not write data");
146
147  // check temporary file contents
148  auto infile = std::ifstream(filepath, std::ios::in | std::ios::binary);
149  if (infile) {
150    bool mismatch = false;
151    size_t cnt = 0;
152
153    while (1) {
154      char c;
155      infile.get(c);
156      if (infile.eof())
157        break;
158      if (c != data[cnt++])
159        mismatch = true;
160    }
161    if (cnt != size || mismatch)
162      throw std::runtime_error("file contents not written correctly");
163  } else
164    throw std::runtime_error("could not validate file");
165
166  if (!filepath.is_absolute())
167    throw std::runtime_error("temporary filepath is not absolute");
168
169  return filepath;
170}
171
172static inline uint16_t extract16(unsigned char const *const ptr) {
173  uint16_t ret = 0;
174
175  ret |= static_cast<uint16_t>(ptr[0]) << 0;
176  ret |= static_cast<uint16_t>(ptr[1]) << 8;
177
178  return (ret);
179}
180
181static inline uint32_t extract32(unsigned char const *const ptr) {
182  uint32_t ret = 0;
183
184  ret |= static_cast<uint32_t>(ptr[0]) << 0;
185  ret |= static_cast<uint32_t>(ptr[1]) << 8;
186  ret |= static_cast<uint32_t>(ptr[2]) << 16;
187  ret |= static_cast<uint32_t>(ptr[3]) << 24;
188
189  return (ret);
190}
191
192static inline uint64_t extract64(unsigned char const *const ptr) {
193  uint64_t ret = 0;
194
195  ret |= static_cast<uint64_t>(ptr[0]) << 0;
196  ret |= static_cast<uint64_t>(ptr[1]) << 8;
197  ret |= static_cast<uint64_t>(ptr[2]) << 16;
198  ret |= static_cast<uint64_t>(ptr[3]) << 24;
199  ret |= static_cast<uint64_t>(ptr[4]) << 32;
200  ret |= static_cast<uint64_t>(ptr[5]) << 40;
201  ret |= static_cast<uint64_t>(ptr[6]) << 48;
202  ret |= static_cast<uint64_t>(ptr[7]) << 56;
203
204  return (ret);
205}
206
207static inline uint64_t get_lib_size(char const *const blob) {
208#ifdef _WIN32
209  ///////////////////////////////////////////////////////////////////////
210  // Analyze DOS stub
211  unsigned char const *const ublob =
212      reinterpret_cast<unsigned char const *const>(blob);
213  if (ublob[0] != 0x4d || ublob[1] != 0x5a) {
214    throw std::runtime_error("Blob is not a Windows DLL.");
215  }
216  uint32_t pe_header_offset = extract32(ublob + 0x3c);
217
218  ///////////////////////////////////////////////////////////////////////
219  // Ananlyze PE-header
220  unsigned char const *const pe_header = ublob + pe_header_offset;
221
222  // signature
223  uint32_t pe_signature = extract32(pe_header + 0);
224  if (pe_signature != 0x00004550) {
225    throw std::runtime_error("PE-header signature is not 0x00004550");
226  }
227
228  // machine
229  uint16_t machine = extract16(pe_header + 4);
230  if (machine != 0x8664) {
231    throw std::runtime_error("Only DLLs for x64 supported");
232  }
233
234  // number of sections
235  uint16_t number_of_sections = extract16(pe_header + 6);
236
237  // sizeof optional header
238  uint16_t sizeof_optional_header = extract16(pe_header + 20);
239
240  // magic
241  uint16_t magic = extract16(pe_header + 24);
242  if (magic != 0x10b && magic != 0x20b) {
243    throw std::runtime_error("MAGIC is not 0x010b or 0x020b");
244  }
245
246  ///////////////////////////////////////////////////////////////////////
247  // Analyze tail of optional header
248  constexpr int coff_header_size = 24;
249
250  unsigned char const *const tail_of_optional_header =
251      pe_header + coff_header_size + sizeof_optional_header;
252  if (extract64(tail_of_optional_header - 8) != 0) {
253    throw std::runtime_error("Optional header not zero-padded");
254  }
255
256  ///////////////////////////////////////////////////////////////////////
257  // Analyze last section header
258  constexpr int section_header_size = 40;
259  unsigned char const *const last_section_header =
260      tail_of_optional_header + section_header_size * (number_of_sections - 1);
261
262  uint32_t sizeof_raw_data = extract32(last_section_header + 16);
263  uint32_t pointer_to_raw_data = extract32(last_section_header + 20);
264
265  return sizeof_raw_data + pointer_to_raw_data;
266#else
267  if (blob[0] != 0x7F || blob[1] != 'E' || blob[2] != 'L' || blob[3] != 'F')
268    throw std::runtime_error("Blob is not in ELF format");
269
270  if (blob[4] != 0x02)
271    throw std::runtime_error("Only 64-bit headers are supported");
272
273  if (blob[5] != 0x01)
274    throw std::runtime_error("Only little-endian headers are supported");
275
276  unsigned char const *const ublob =
277      reinterpret_cast<unsigned char const *const>(blob);
278  uint64_t e_shoff = extract64(ublob + 0x28);
279  uint16_t e_shentsize = extract16(ublob + 0x3A);
280  uint16_t e_shnum = extract16(ublob + 0x3C);
281
282  return e_shoff + (e_shentsize * e_shnum);
283#endif
284}
285
286#ifdef _WIN32
287class path_lib_record {
288public:
289  void operator=(const path_lib_record &) = delete;
290  ~path_lib_record() {
291    for (auto entry : lib_to_path) {
292      FreeLibrary(static_cast<HMODULE>(entry.first));
293      fs::permissions(entry.second, fs::perms::owner_all);
294      fs::remove_all(entry.second.remove_filename());
295    }
296  }
297  static void record_lib_path(fs::path path, void *library) {
298    lib_to_path[library] = path;
299  }
300  static void remove_lib(void *library) {
301    auto path = lib_to_path[library];
302    std::error_code ec;
303
304    FreeLibrary(static_cast<HMODULE>(library));
305    fs::permissions(path, fs::perms::owner_all);
306    if (fs::remove_all(path.remove_filename(), ec) != 2 || ec)
307      // one directory and one temporary file should have been deleted
308      throw std::runtime_error("Directory delete failed");
309
310    lib_to_path.erase(library);
311  }
312
313private:
314  static inline std::unordered_map<void *, fs::path> lib_to_path;
315};
316#endif
317
318} // namespace detail
319
320class kernel_library {
321public:
322  constexpr kernel_library() : ptr{nullptr} {}
323  constexpr kernel_library(void *ptr) : ptr{ptr} {}
324  kernel_library(uint64_t addr) : ptr(reinterpret_cast<void *>(addr)) {}
325
326  operator void *() const { return ptr; }
327  explicit operator uint64_t() const { return reinterpret_cast<uint64_t>(ptr); }
328
329private:
330  void *ptr;
331#ifdef _WIN32
332  static inline detail::path_lib_record single_instance_to_trigger_destructor;
333#endif
334};
335
336namespace detail {
337
338static inline kernel_library load_dl_from_data(char const *const data,
339                                               size_t size) {
340  fs::path filename = write_data_to_file(data, size);
341#ifdef _WIN32
342  void *so = LoadLibraryW(filename.wstring().c_str());
343#else
344  void *so = dlopen(filename.c_str(), RTLD_LAZY);
345#endif
346  if (so == nullptr)
347    throw std::runtime_error("Failed to load kernel library");
348
349#ifdef _WIN32
350  detail::path_lib_record::record_lib_path(filename, so);
351#else
352  std::error_code ec;
353
354  // Windows DLL cannot be deleted while in use
355  if (fs::remove_all(filename.remove_filename(), ec) != 2 || ec)
356    // one directory and one temporary file should have been deleted
357    throw std::runtime_error("Directory delete failed");
358#endif
359
360  return so;
361}
362
363} // namespace detail
364
365/// Load kernel library and return a handle to use the library.
366/// \param [in] name The name of the library.
367static inline kernel_library load_kernel_library(const std::string &name) {
368  std::ifstream ifs;
369  ifs.open(name, std::ios::in | std::ios::binary);
370
371  std::stringstream buffer;
372  buffer << ifs.rdbuf();
373
374  const std::string buffer_string = buffer.str();
375  return detail::load_dl_from_data(buffer_string.c_str(), buffer_string.size());
376}
377
378/// Load kernel library whose image is alreay in memory and return a handle to
379/// use the library.
380/// \param [in] image A pointer to the image in memory.
381static inline kernel_library load_kernel_library_mem(char const *const image) {
382  const size_t size = detail::get_lib_size(image);
383
384  return detail::load_dl_from_data(image, size);
385}
386
387/// Unload kernel library.
388/// \param [in,out] library Handle to the library to be closed.
389static inline void unload_kernel_library(const kernel_library &library) {
390#ifdef _WIN32
391  detail::path_lib_record::remove_lib(library);
392#else
393  dlclose(library);
394#endif
395}
396
397class kernel_function {
398public:
399  constexpr kernel_function() : ptr{nullptr} {}
400  constexpr kernel_function(dpct::kernel_functor ptr) : ptr{ptr} {}
401  kernel_function(uint64_t addr)
402      : ptr(reinterpret_cast<dpct::kernel_functor>(addr)) {}
403
404  operator void *() const { return ((void *)ptr); }
405
406  void operator()(sycl::queue &q, const sycl::nd_range<3> &range,
407                  unsigned int a, void **args, void **extra) const {
408    ptr(q, range, a, args, extra);
409  }
410
411  explicit operator uint64_t() const { return reinterpret_cast<uint64_t>(ptr); }
412
413private:
414  dpct::kernel_functor ptr;
415};
416
417/// Find kernel function in a kernel library and return its address.
418/// \param [in] library Handle to the kernel library.
419/// \param [in] name Name of the kernel function.
420static inline dpct::kernel_function
421get_kernel_function(const kernel_library &library, const std::string &name) {
422#ifdef _WIN32
423  dpct::kernel_functor fn = reinterpret_cast<dpct::kernel_functor>(
424      GetProcAddress(static_cast<HMODULE>(static_cast<void *>(library)),
425                     (name + std::string("_wrapper")).c_str()));
426#else
427  dpct::kernel_functor fn = reinterpret_cast<dpct::kernel_functor>(
428      dlsym(library, (name + std::string("_wrapper")).c_str()));
429#endif
430  if (fn == nullptr)
431    throw std::runtime_error("Failed to get function");
432  return fn;
433}
434
435/// Invoke a kernel function.
436/// \param [in] function kernel function.
437/// \param [in] queue SYCL queue used to execute kernel
438/// \param [in] groupRange SYCL group range
439/// \param [in] localRange SYCL local range
440/// \param [in] localMemSize The size of local memory required by the kernel
441///             function.
442/// \param [in] kernelParams Array of pointers to kernel arguments.
443/// \param [in] extra Extra arguments.
444static inline void invoke_kernel_function(const dpct::kernel_function &function,
445                                          sycl::queue &queue,
446                                          sycl::range<3> groupRange,
447                                          sycl::range<3> localRange,
448                                          unsigned int localMemSize,
449                                          void **kernelParams, void **extra) {
450  function(queue, sycl::nd_range<3>(groupRange * localRange, localRange),
451           localMemSize, kernelParams, extra);
452}
453
454/// Utility class for launching SYCL kernels through kernel
455/// function wrapper.
456/// For example:
457/// A SYCL kernel function:
458///   void kernel_func(int *ptr, sycl::nd_item<3> item);
459/// Kernel function wrapper:
460///   void kernel_func_wrapper(int *ptr) {
461///     sycl::queue queue = *dpct::kernel_launcher::_que;
462///     unsigned int localMemSize = dpct::kernel_launcher::_local_mem_size;
463///     sycl::nd_range<3> nr = dpct::kernel_launcher::_nr;
464///     queue.parallel_for(
465///       nr,
466///       [=](sycl::nd_item<3> item_ct1) {
467///         kernel_func(ptr, item_ct1);
468///       });
469///   }
470/// Then launch the kernel through wrapper like:
471///   typedef void(*fpt)(int *);
472///   fpt fp = kernel_func_wrapper;
473///   dpct::kernel_launcher::launch(fp, dpct::dim3(1), dpct::dim3(1), 0, 0,
474///   device_ptr);
475/// If the origin function type is erased, then need to register it first:
476///   void *fp = (void *)wrapper_register(&kernel_func_wrapper).get();
477///   dpct::kernel_launcher::launch(fp, dpct::dim3(1), dpct::dim3(1), args, 0,
478///   0);
479class kernel_launcher {
480  template <typename FuncT, typename ArgSelector, std::size_t... Index>
481  static void launch_helper(FuncT &&func, ArgSelector &selector,
482                            std::index_sequence<Index...>) {
483    func(selector.template get<Index>()...);
484  }
485  static void set_execution_config(dim3 group_range, dim3 local_range,
486                                   unsigned int local_mem_size, queue_ptr que) {
487    if (que) {
488      _que = que;
489    } else {
490      _que = &get_default_queue();
491    }
492    _nr = sycl::nd_range<3>(
493        static_cast<sycl::range<3>>(group_range * local_range),
494        static_cast<sycl::range<3>>(local_range));
495    _local_mem_size = local_mem_size;
496  };
497  static inline std::mutex kernel_function_ptr_map_mutex;
498
499public:
500  /// Variables for storing execution configuration.
501  static inline thread_local sycl::queue *_que = nullptr;
502  static inline thread_local sycl::nd_range<3> _nr = sycl::nd_range<3>();
503  static inline thread_local unsigned int _local_mem_size = 0;
504  /// Map for retrieving launchable functor from a raw pointer.
505  static inline std::map<
506      const void *,
507      std::function<void(dim3, dim3, void **, unsigned int, queue_ptr)>>
508      kernel_function_ptr_map = {};
509
510  /// Registers a kernel function pointer with a corresponding launchable
511  /// functor.
512  /// \param [in] func Pointer to the kernel function.
513  /// \param [in] launcher Functor to handle kernel invocation.
514  static void register_kernel_ptr(
515      const void *func,
516      std::function<void(dim3, dim3, void **, unsigned int, queue_ptr)>
517          launcher) {
518    std::lock_guard<std::mutex> lock(kernel_function_ptr_map_mutex);
519    kernel_function_ptr_map[func] = std::move(launcher);
520  }
521  /// Launches a kernel function with arguments provided directly through
522  /// kernel function wrapper.
523  /// \tparam FuncT Type of the kernel function wrapper.
524  /// \tparam ArgsT Types of kernel arguments.
525  /// \param [in] func Pointer to the kernel function wrapper.
526  /// \param [in] group_range SYCL group range.
527  /// \param [in] local_range SYCL local range.
528  /// \param [in] local_mem_size The size of local memory required by the kernel
529  /// function.
530  /// \param [in] que SYCL queue used to execute kernel.
531  /// \param [in] args Kernel arguments.
532  template <typename FuncT, typename... ArgsT>
533  static std::enable_if_t<std::is_invocable_v<FuncT *, ArgsT...>, void>
534  launch(FuncT *func, dim3 group_range, dim3 local_range,
535         unsigned int local_mem_size, queue_ptr que, ArgsT... args) {
536    set_execution_config(group_range, local_range, local_mem_size, que);
537    func(args...);
538  }
539  /// Launches a kernel function through registered kernel function wrapper.
540  /// \param [in] func Pointer to the registered kernel function wrapper.
541  /// \param [in] group_range SYCL group range.
542  /// \param [in] local_range SYCL local range.
543  /// \param [in] args Array of pointers to kernel arguments.
544  /// \param [in] local_mem_size The size of local memory required by the kernel
545  /// function.
546  /// \param [in] que SYCL queue used to execute kernel.
547  static void launch(const void *func, dim3 group_range, dim3 local_range,
548                     void **args, unsigned int local_mem_size, queue_ptr que) {
549    std::lock_guard<std::mutex> lock(kernel_function_ptr_map_mutex);
550    auto Iter = kernel_function_ptr_map.find(func);
551    if (Iter == kernel_function_ptr_map.end()) {
552      throw std::runtime_error(
553          "dpct::launch() : no registered kernel function wrapper found.");
554    }
555    (Iter->second)(group_range, local_range, args, local_mem_size, que);
556  }
557  /// Launches a kernel function with packed arguments through kernel
558  /// function wrapper.
559  /// \tparam FuncT Type of the kernel function wrapper.
560  /// \param [in] func Pointer to the kernel function wrapper.
561  /// \param [in] group_range SYCL group range.
562  /// \param [in] local_range SYCL local range.
563  /// \param [in] args Array of pointers to kernel arguments.
564  /// \param [in] local_mem_size The size of local memory required by the kernel
565  /// function.
566  /// \param [in] que SYCL queue used to execute kernel.
567  template <typename FuncT>
568  static std::enable_if_t<std::is_function_v<FuncT>, void>
569  launch(FuncT *func, dim3 group_range, dim3 local_range, void **args,
570         unsigned int local_mem_size, queue_ptr que) {
571    constexpr size_t p_num = args_selector<0, 0, FuncT>::params_num;
572    set_execution_config(group_range, local_range, local_mem_size, que);
573    args_selector<p_num, p_num, FuncT> selector(args, nullptr);
574    launch_helper(func, selector, std::make_index_sequence<p_num>{});
575  }
576};
577
578/// Helper class to register and invoke kernel functions through a wrapper.
579template <typename F> class wrapper_register;
580template <typename Ret, typename... Args>
581class wrapper_register<Ret (*)(Args...)> {
582public:
583  typedef Ret (*FT)(Args...);
584  FT func;
585  /// Constructor to register a kernel function pointer.
586  /// \param [in] fp Pointer to the kernel function.
587  wrapper_register(FT fp) : func(fp) {
588    kernel_launcher::register_kernel_ptr((void *)func, *this);
589  }
590  /// Invokes the kernel function through the stored kernel function wrapper.
591  /// \param [in] group_range SYCL group range.
592  /// \param [in] local_range SYCL local range.
593  /// \param [in] args Array of pointers to kernel arguments.
594  /// \param [in] local_mem_size The size of local memory required by the kernel
595  /// function.
596  /// \param [in] que SYCL queue used to execute kernel.
597  void operator()(dim3 group_range, dim3 local_range, void **args,
598                  unsigned int local_mem_size, queue_ptr que) {
599    kernel_launcher::launch(func, group_range, local_range, args,
600                            local_mem_size, que);
601  }
602  /// Retrieves the original kernel function pointer.
603  /// \return The original kernel function pointer.
604  const FT &get() const noexcept { return func; }
605  /// Implicit conversion to the original kernel function pointer.
606  /// \return The original kernel function pointer.
607  operator FT() const noexcept { return func; }
608};
609/// Deduction guide for wrapper_register.
610template <typename Ret, typename... Args>
611wrapper_register(Ret (*)(Args...)) -> wrapper_register<Ret (*)(Args...)>;
612
613/// Find image wrapper in a kernel library and return its address.
614/// \param [in] library Handle to the kernel library.
615/// \param [in] name Name of the target image wrapper.
616static inline dpct::image_wrapper_base_p
617get_image_wrapper(dpct::kernel_library &library, const std::string &name) {
618#ifdef _WIN32
619  dpct::image_wrapper_base_p fn =
620      reinterpret_cast<dpct::image_wrapper_base_p>(GetProcAddress(
621          static_cast<HMODULE>(static_cast<void *>(library)), name.c_str()));
622#else
623  dpct::image_wrapper_base_p fn = reinterpret_cast<dpct::image_wrapper_base_p>(
624      dlsym(library, name.c_str()));
625#endif
626  if (fn == nullptr)
627    throw std::runtime_error("Failed to get image");
628  return fn;
629}
630
631} // namespace dpct
632#endif // __DPCT_KERNEL_HPP__