1 //===----RTLs/cuda/src/rtl.cpp - Target RTLs Implementation ------- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // RTL for CUDA machine
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <cassert>
14 #include <cstddef>
15 #include <cuda.h>
16 #include <list>
17 #include <memory>
18 #include <mutex>
19 #include <string>
20 #include <unordered_map>
21 #include <vector>
22 
23 #include "Debug.h"
24 #include "DeviceEnvironment.h"
25 #include "omptargetplugin.h"
26 
27 #define TARGET_NAME CUDA
28 #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
29 
30 #include "MemoryManager.h"
31 
32 #include "llvm/Frontend/OpenMP/OMPConstants.h"
33 
34 // Utility for retrieving and printing CUDA error string.
35 #ifdef OMPTARGET_DEBUG
36 #define CUDA_ERR_STRING(err)                                                   \
37   do {                                                                         \
38     if (getDebugLevel() > 0) {                                                 \
39       const char *errStr = nullptr;                                            \
40       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
41       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
42         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
43       else if (errStr_status == CUDA_SUCCESS)                                  \
44         REPORT("CUDA error is: %s\n", errStr);                                 \
45       else {                                                                   \
46         REPORT("Unresolved CUDA error code: %d\n", err);                       \
47         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
48                errStr_status);                                                 \
49       }                                                                        \
50     } else {                                                                   \
51       const char *errStr = nullptr;                                            \
52       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
53       if (errStr_status == CUDA_SUCCESS)                                       \
54         REPORT("%s \n", errStr);                                               \
55     }                                                                          \
56   } while (false)
57 #else // OMPTARGET_DEBUG
58 #define CUDA_ERR_STRING(err)                                                   \
59   do {                                                                         \
60     const char *errStr = nullptr;                                              \
61     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
62     if (errStr_status == CUDA_SUCCESS)                                         \
63       REPORT("%s \n", errStr);                                                 \
64   } while (false)
65 #endif // OMPTARGET_DEBUG
66 
67 #define BOOL2TEXT(b) ((b) ? "Yes" : "No")
68 
69 #include "elf_common.h"
70 
71 /// Keep entries table per device.
72 struct FuncOrGblEntryTy {
73   __tgt_target_table Table;
74   std::vector<__tgt_offload_entry> Entries;
75 };
76 
77 /// Use a single entity to encode a kernel and a set of flags.
78 struct KernelTy {
79   CUfunction Func;
80 
81   // execution mode of kernel
82   llvm::omp::OMPTgtExecModeFlags ExecutionMode;
83 
84   /// Maximal number of threads per block for this kernel.
85   int MaxThreadsPerBlock = 0;
86 
87   KernelTy(CUfunction _Func, llvm::omp::OMPTgtExecModeFlags _ExecutionMode)
88       : Func(_Func), ExecutionMode(_ExecutionMode) {}
89 };
90 
91 namespace {
92 bool checkResult(CUresult Err, const char *ErrMsg) {
93   if (Err == CUDA_SUCCESS)
94     return true;
95 
96   REPORT("%s", ErrMsg);
97   CUDA_ERR_STRING(Err);
98   return false;
99 }
100 
101 int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
102                CUstream Stream) {
103   CUresult Err =
104       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
105 
106   if (Err != CUDA_SUCCESS) {
107     DP("Error when copying data from device to device. Pointers: src "
108        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
109        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
110     CUDA_ERR_STRING(Err);
111     return OFFLOAD_FAIL;
112   }
113 
114   return OFFLOAD_SUCCESS;
115 }
116 
117 int createEvent(void **P) {
118   CUevent Event = nullptr;
119 
120   CUresult Err = cuEventCreate(&Event, CU_EVENT_DEFAULT);
121   if (Err != CUDA_SUCCESS) {
122     DP("Error when creating event event = " DPxMOD "\n", DPxPTR(Event));
123     CUDA_ERR_STRING(Err);
124     return OFFLOAD_FAIL;
125   }
126 
127   *P = Event;
128 
129   return OFFLOAD_SUCCESS;
130 }
131 
132 int recordEvent(void *EventPtr, __tgt_async_info *AsyncInfo) {
133   CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
134   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
135 
136   CUresult Err = cuEventRecord(Event, Stream);
137   if (Err != CUDA_SUCCESS) {
138     DP("Error when recording event. stream = " DPxMOD ", event = " DPxMOD "\n",
139        DPxPTR(Stream), DPxPTR(Event));
140     CUDA_ERR_STRING(Err);
141     return OFFLOAD_FAIL;
142   }
143 
144   return OFFLOAD_SUCCESS;
145 }
146 
147 int syncEvent(void *EventPtr) {
148   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
149 
150   CUresult Err = cuEventSynchronize(Event);
151   if (Err != CUDA_SUCCESS) {
152     DP("Error when syncing event = " DPxMOD "\n", DPxPTR(Event));
153     CUDA_ERR_STRING(Err);
154     return OFFLOAD_FAIL;
155   }
156 
157   return OFFLOAD_SUCCESS;
158 }
159 
160 int destroyEvent(void *EventPtr) {
161   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
162 
163   CUresult Err = cuEventDestroy(Event);
164   if (Err != CUDA_SUCCESS) {
165     DP("Error when destroying event = " DPxMOD "\n", DPxPTR(Event));
166     CUDA_ERR_STRING(Err);
167     return OFFLOAD_FAIL;
168   }
169 
170   return OFFLOAD_SUCCESS;
171 }
172 
173 // Structure contains per-device data
174 struct DeviceDataTy {
175   /// List that contains all the kernels.
176   std::list<KernelTy> KernelsList;
177 
178   std::list<FuncOrGblEntryTy> FuncGblEntries;
179 
180   CUcontext Context = nullptr;
181   // Device properties
182   int ThreadsPerBlock = 0;
183   int BlocksPerGrid = 0;
184   int WarpSize = 0;
185   // OpenMP properties
186   int NumTeams = 0;
187   int NumThreads = 0;
188 };
189 
190 /// Resource allocator where \p T is the resource type.
191 /// Functions \p create and \p destroy return OFFLOAD_SUCCESS and OFFLOAD_FAIL
192 /// accordingly. The implementation should not raise any exception.
193 template <typename T> class AllocatorTy {
194 public:
195   /// Create a resource and assign to R.
196   int create(T &R) noexcept;
197   /// Destroy the resource.
198   int destroy(T) noexcept;
199 };
200 
201 /// Allocator for CUstream.
202 template <> class AllocatorTy<CUstream> {
203   CUcontext Context;
204 
205 public:
206   AllocatorTy(CUcontext C) noexcept : Context(C) {}
207 
208   /// See AllocatorTy<T>::create.
209   int create(CUstream &Stream) noexcept {
210     if (!checkResult(cuCtxSetCurrent(Context),
211                      "Error returned from cuCtxSetCurrent\n"))
212       return OFFLOAD_FAIL;
213 
214     if (!checkResult(cuStreamCreate(&Stream, CU_STREAM_NON_BLOCKING),
215                      "Error returned from cuStreamCreate\n"))
216       return OFFLOAD_FAIL;
217 
218     return OFFLOAD_SUCCESS;
219   }
220 
221   /// See AllocatorTy<T>::destroy.
222   int destroy(CUstream Stream) noexcept {
223     if (!checkResult(cuCtxSetCurrent(Context),
224                      "Error returned from cuCtxSetCurrent\n"))
225       return OFFLOAD_FAIL;
226     if (!checkResult(cuStreamDestroy(Stream),
227                      "Error returned from cuStreamDestroy\n"))
228       return OFFLOAD_FAIL;
229 
230     return OFFLOAD_SUCCESS;
231   }
232 };
233 
234 /// A generic pool of resources where \p T is the resource type.
235 /// \p T should be copyable as the object is stored in \p std::vector .
236 template <typename T> class ResourcePoolTy {
237   /// Index of the next available resource.
238   size_t Next = 0;
239   /// Mutex to guard the pool.
240   std::mutex Mutex;
241   /// Pool of resources.
242   std::vector<T> Resources;
243   /// A reference to the corresponding allocator.
244   AllocatorTy<T> Allocator;
245 
246   /// If `Resources` is used up, we will fill in more resources. It assumes that
247   /// the new size `Size` should be always larger than the current size.
248   bool resize(size_t Size) {
249     auto CurSize = Resources.size();
250     assert(Size > CurSize && "Unexpected smaller size");
251     Resources.reserve(Size);
252     for (auto I = CurSize; I < Size; ++I) {
253       T NewItem;
254       int Ret = Allocator.create(NewItem);
255       if (Ret != OFFLOAD_SUCCESS)
256         return false;
257       Resources.push_back(NewItem);
258     }
259     return true;
260   }
261 
262 public:
263   ResourcePoolTy(AllocatorTy<T> &&A, size_t Size = 0) noexcept
264       : Allocator(std::move(A)) {
265     (void)resize(Size);
266   }
267 
268   ~ResourcePoolTy() noexcept {
269     for (auto &R : Resources)
270       (void)Allocator.destroy(R);
271   }
272 
273   /// Get a resource from pool. `Next` always points to the next available
274   /// resource. That means, `[0, next-1]` have been assigned, and `[id,]` are
275   /// still available. If there is no resource left, we will ask for more. Each
276   /// time a resource is assigned, the id will increase one.
277   /// xxxxxs+++++++++
278   ///      ^
279   ///      Next
280   /// After assignment, the pool becomes the following and s is assigned.
281   /// xxxxxs+++++++++
282   ///       ^
283   ///       Next
284   int acquire(T &R) noexcept {
285     std::lock_guard<std::mutex> LG(Mutex);
286     if (Next == Resources.size() && !resize(Resources.size() * 2))
287       return OFFLOAD_FAIL;
288 
289     R = Resources[Next++];
290 
291     return OFFLOAD_SUCCESS;
292   }
293 
294   /// Return the resource back to the pool. When we return a resource, we need
295   /// to first decrease `Next`, and then copy the resource back. It is worth
296   /// noting that, the order of resources return might be different from that
297   /// they're assigned, that saying, at some point, there might be two identical
298   /// resources.
299   /// xxax+a+++++
300   ///     ^
301   ///     Next
302   /// However, it doesn't matter, because they're always on the two sides of
303   /// `Next`. The left one will in the end be overwritten by another resource.
304   /// Therefore, after several execution, the order of pool might be different
305   /// from its initial state.
306   void release(T R) noexcept {
307     std::lock_guard<std::mutex> LG(Mutex);
308     Resources[--Next] = R;
309   }
310 };
311 
312 class DeviceRTLTy {
313   int NumberOfDevices;
314   // OpenMP environment properties
315   int EnvNumTeams;
316   int EnvTeamLimit;
317   int EnvTeamThreadLimit;
318   // OpenMP requires flags
319   int64_t RequiresFlags;
320   // Amount of dynamic shared memory to use at launch.
321   uint64_t DynamicMemorySize;
322   // Number of initial streams for each device.
323   int NumInitialStreams = 32;
324 
325   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
326   static constexpr const int HardThreadLimit = 1024;
327   static constexpr const int DefaultNumTeams = 128;
328   static constexpr const int DefaultNumThreads = 128;
329 
330   using StreamPoolTy = ResourcePoolTy<CUstream>;
331   using StreamAllocatorTy = AllocatorTy<CUstream>;
332   std::vector<std::unique_ptr<StreamPoolTy>> StreamPool;
333 
334   std::vector<DeviceDataTy> DeviceData;
335   std::vector<CUmodule> Modules;
336 
337   /// A class responsible for interacting with device native runtime library to
338   /// allocate and free memory.
339   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
340     const int DeviceId;
341     const std::vector<DeviceDataTy> &DeviceData;
342     std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs;
343 
344   public:
345     CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData)
346         : DeviceId(DeviceId), DeviceData(DeviceData) {}
347 
348     void *allocate(size_t Size, void *, TargetAllocTy Kind) override {
349       if (Size == 0)
350         return nullptr;
351 
352       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
353       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
354         return nullptr;
355 
356       void *MemAlloc = nullptr;
357       switch (Kind) {
358       case TARGET_ALLOC_DEFAULT:
359       case TARGET_ALLOC_DEVICE:
360         CUdeviceptr DevicePtr;
361         Err = cuMemAlloc(&DevicePtr, Size);
362         MemAlloc = (void *)DevicePtr;
363         if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
364           return nullptr;
365         break;
366       case TARGET_ALLOC_HOST:
367         void *HostPtr;
368         Err = cuMemAllocHost(&HostPtr, Size);
369         MemAlloc = HostPtr;
370         if (!checkResult(Err, "Error returned from cuMemAllocHost\n"))
371           return nullptr;
372         HostPinnedAllocs[MemAlloc] = Kind;
373         break;
374       case TARGET_ALLOC_SHARED:
375         CUdeviceptr SharedPtr;
376         Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL);
377         MemAlloc = (void *)SharedPtr;
378         if (!checkResult(Err, "Error returned from cuMemAllocManaged\n"))
379           return nullptr;
380         break;
381       }
382 
383       return MemAlloc;
384     }
385 
386     int free(void *TgtPtr) override {
387       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
388       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
389         return OFFLOAD_FAIL;
390 
391       // Host pinned memory must be freed differently.
392       TargetAllocTy Kind =
393           (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end())
394               ? TARGET_ALLOC_DEFAULT
395               : TARGET_ALLOC_HOST;
396       switch (Kind) {
397       case TARGET_ALLOC_DEFAULT:
398       case TARGET_ALLOC_DEVICE:
399       case TARGET_ALLOC_SHARED:
400         Err = cuMemFree((CUdeviceptr)TgtPtr);
401         if (!checkResult(Err, "Error returned from cuMemFree\n"))
402           return OFFLOAD_FAIL;
403         break;
404       case TARGET_ALLOC_HOST:
405         Err = cuMemFreeHost(TgtPtr);
406         if (!checkResult(Err, "Error returned from cuMemFreeHost\n"))
407           return OFFLOAD_FAIL;
408         break;
409       }
410 
411       return OFFLOAD_SUCCESS;
412     }
413   };
414 
415   /// A vector of device allocators
416   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
417 
418   /// A vector of memory managers. Since the memory manager is non-copyable and
419   // non-removable, we wrap them into std::unique_ptr.
420   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
421 
422   /// Whether use memory manager
423   bool UseMemoryManager = true;
424 
425   // Record entry point associated with device
426   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
427     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
428     E.Entries.push_back(entry);
429   }
430 
431   // Return a pointer to the entry associated with the pointer
432   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
433                                              const void *Addr) const {
434     for (const __tgt_offload_entry &Itr :
435          DeviceData[DeviceId].FuncGblEntries.back().Entries)
436       if (Itr.addr == Addr)
437         return &Itr;
438 
439     return nullptr;
440   }
441 
442   // Return the pointer to the target entries table
443   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
444     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
445 
446     if (E.Entries.empty())
447       return nullptr;
448 
449     // Update table info according to the entries and return the pointer
450     E.Table.EntriesBegin = E.Entries.data();
451     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
452 
453     return &E.Table;
454   }
455 
456   // Clear entries table for a device
457   void clearOffloadEntriesTable(const int DeviceId) {
458     DeviceData[DeviceId].FuncGblEntries.emplace_back();
459     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
460     E.Entries.clear();
461     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
462   }
463 
464   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const {
465     assert(AsyncInfo && "AsyncInfo is nullptr");
466 
467     if (!AsyncInfo->Queue) {
468       CUstream S;
469       if (StreamPool[DeviceId]->acquire(S) != OFFLOAD_SUCCESS)
470         return nullptr;
471 
472       AsyncInfo->Queue = S;
473     }
474 
475     return reinterpret_cast<CUstream>(AsyncInfo->Queue);
476   }
477 
478 public:
479   // This class should not be copied
480   DeviceRTLTy(const DeviceRTLTy &) = delete;
481   DeviceRTLTy(DeviceRTLTy &&) = delete;
482 
483   DeviceRTLTy()
484       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
485         EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED),
486         DynamicMemorySize(0) {
487 
488     DP("Start initializing CUDA\n");
489 
490     CUresult Err = cuInit(0);
491     if (Err == CUDA_ERROR_INVALID_HANDLE) {
492       // Can't call cuGetErrorString if dlsym failed
493       DP("Failed to load CUDA shared library\n");
494       return;
495     }
496     if (!checkResult(Err, "Error returned from cuInit\n")) {
497       return;
498     }
499 
500     Err = cuDeviceGetCount(&NumberOfDevices);
501     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
502       return;
503 
504     if (NumberOfDevices == 0) {
505       DP("There are no devices supporting CUDA.\n");
506       return;
507     }
508 
509     DeviceData.resize(NumberOfDevices);
510     StreamPool.resize(NumberOfDevices);
511 
512     // Get environment variables regarding teams
513     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
514       // OMP_TEAM_LIMIT has been set
515       EnvTeamLimit = std::stoi(EnvStr);
516       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
517     }
518     if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) {
519       // OMP_TEAMS_THREAD_LIMIT has been set
520       EnvTeamThreadLimit = std::stoi(EnvStr);
521       DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit);
522     }
523     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
524       // OMP_NUM_TEAMS has been set
525       EnvNumTeams = std::stoi(EnvStr);
526       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
527     }
528     if (const char *EnvStr = getenv("LIBOMPTARGET_SHARED_MEMORY_SIZE")) {
529       // LIBOMPTARGET_SHARED_MEMORY_SIZE has been set
530       DynamicMemorySize = std::stoi(EnvStr);
531       DP("Parsed LIBOMPTARGET_SHARED_MEMORY_SIZE = %" PRIu64 "\n",
532          DynamicMemorySize);
533     }
534     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS")) {
535       // LIBOMPTARGET_NUM_INITIAL_STREAMS has been set
536       NumInitialStreams = std::stoi(EnvStr);
537       DP("Parsed LIBOMPTARGET_NUM_INITIAL_STREAMS=%d\n", NumInitialStreams);
538     }
539 
540     for (int I = 0; I < NumberOfDevices; ++I)
541       DeviceAllocators.emplace_back(I, DeviceData);
542 
543     // Get the size threshold from environment variable
544     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
545     UseMemoryManager = Res.second;
546     size_t MemoryManagerThreshold = Res.first;
547 
548     if (UseMemoryManager)
549       for (int I = 0; I < NumberOfDevices; ++I)
550         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
551             DeviceAllocators[I], MemoryManagerThreshold));
552   }
553 
554   ~DeviceRTLTy() {
555     // We first destruct memory managers in case that its dependent data are
556     // destroyed before it.
557     for (auto &M : MemoryManagers)
558       M.release();
559 
560     for (CUmodule &M : Modules)
561       // Close module
562       if (M)
563         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
564 
565     for (auto &S : StreamPool)
566       S = nullptr;
567 
568     for (DeviceDataTy &D : DeviceData) {
569       // Destroy context
570       if (D.Context) {
571         checkResult(cuCtxSetCurrent(D.Context),
572                     "Error returned from cuCtxSetCurrent\n");
573         CUdevice Device;
574         checkResult(cuCtxGetDevice(&Device),
575                     "Error returned from cuCtxGetDevice\n");
576         checkResult(cuDevicePrimaryCtxRelease(Device),
577                     "Error returned from cuDevicePrimaryCtxRelease\n");
578       }
579     }
580   }
581 
582   // Check whether a given DeviceId is valid
583   bool isValidDeviceId(const int DeviceId) const {
584     return DeviceId >= 0 && DeviceId < NumberOfDevices;
585   }
586 
587   int getNumOfDevices() const { return NumberOfDevices; }
588 
589   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
590 
591   int initDevice(const int DeviceId) {
592     CUdevice Device;
593 
594     DP("Getting device %d\n", DeviceId);
595     CUresult Err = cuDeviceGet(&Device, DeviceId);
596     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
597       return OFFLOAD_FAIL;
598 
599     // Query the current flags of the primary context and set its flags if
600     // it is inactive
601     unsigned int FormerPrimaryCtxFlags = 0;
602     int FormerPrimaryCtxIsActive = 0;
603     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
604                                      &FormerPrimaryCtxIsActive);
605     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
606       return OFFLOAD_FAIL;
607 
608     if (FormerPrimaryCtxIsActive) {
609       DP("The primary context is active, no change to its flags\n");
610       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
611           CU_CTX_SCHED_BLOCKING_SYNC)
612         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
613     } else {
614       DP("The primary context is inactive, set its flags to "
615          "CU_CTX_SCHED_BLOCKING_SYNC\n");
616       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
617       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
618         return OFFLOAD_FAIL;
619     }
620 
621     // Retain the per device primary context and save it to use whenever this
622     // device is selected.
623     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
624     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
625       return OFFLOAD_FAIL;
626 
627     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
628     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
629       return OFFLOAD_FAIL;
630 
631     // Initialize stream pool
632     if (!StreamPool[DeviceId])
633       StreamPool[DeviceId] = std::make_unique<StreamPoolTy>(
634           StreamAllocatorTy(DeviceData[DeviceId].Context), NumInitialStreams);
635 
636     // Query attributes to determine number of threads/block and blocks/grid.
637     int MaxGridDimX;
638     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
639                                Device);
640     if (Err != CUDA_SUCCESS) {
641       DP("Error getting max grid dimension, use default value %d\n",
642          DeviceRTLTy::DefaultNumTeams);
643       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
644     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
645       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
646       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
647     } else {
648       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
649          "at the hard limit\n",
650          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
651       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
652     }
653 
654     // We are only exploiting threads along the x axis.
655     int MaxBlockDimX;
656     Err = cuDeviceGetAttribute(&MaxBlockDimX,
657                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
658     if (Err != CUDA_SUCCESS) {
659       DP("Error getting max block dimension, use default value %d\n",
660          DeviceRTLTy::DefaultNumThreads);
661       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
662     } else {
663       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
664       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
665 
666       if (EnvTeamThreadLimit > 0 &&
667           DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) {
668         DP("Max CUDA threads per block %d exceeds the thread limit %d set by "
669            "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n",
670            DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit);
671         DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit;
672       }
673       if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) {
674         DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
675            "capping at the hard limit\n",
676            DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit);
677         DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
678       }
679     }
680 
681     // Get and set warp size
682     int WarpSize;
683     Err =
684         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
685     if (Err != CUDA_SUCCESS) {
686       DP("Error getting warp size, assume default value 32\n");
687       DeviceData[DeviceId].WarpSize = 32;
688     } else {
689       DP("Using warp size %d\n", WarpSize);
690       DeviceData[DeviceId].WarpSize = WarpSize;
691     }
692 
693     // Adjust teams to the env variables
694     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
695       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
696          EnvTeamLimit);
697       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
698     }
699 
700     size_t StackLimit;
701     size_t HeapLimit;
702     if (const char *EnvStr = getenv("LIBOMPTARGET_STACK_SIZE")) {
703       StackLimit = std::stol(EnvStr);
704       if (cuCtxSetLimit(CU_LIMIT_STACK_SIZE, StackLimit) != CUDA_SUCCESS)
705         return OFFLOAD_FAIL;
706     } else {
707       if (cuCtxGetLimit(&StackLimit, CU_LIMIT_STACK_SIZE) != CUDA_SUCCESS)
708         return OFFLOAD_FAIL;
709     }
710     if (const char *EnvStr = getenv("LIBOMPTARGET_HEAP_SIZE")) {
711       HeapLimit = std::stol(EnvStr);
712       if (cuCtxSetLimit(CU_LIMIT_MALLOC_HEAP_SIZE, HeapLimit) != CUDA_SUCCESS)
713         return OFFLOAD_FAIL;
714     } else {
715       if (cuCtxGetLimit(&HeapLimit, CU_LIMIT_MALLOC_HEAP_SIZE) != CUDA_SUCCESS)
716         return OFFLOAD_FAIL;
717     }
718 
719     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
720          "Device supports up to %d CUDA blocks and %d threads with a "
721          "warp size of %d\n",
722          DeviceData[DeviceId].BlocksPerGrid,
723          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
724     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
725          "Device heap size is %d Bytes, device stack size is %d Bytes per "
726          "thread\n",
727          (int)HeapLimit, (int)StackLimit);
728 
729     // Set default number of teams
730     if (EnvNumTeams > 0) {
731       DP("Default number of teams set according to environment %d\n",
732          EnvNumTeams);
733       DeviceData[DeviceId].NumTeams = EnvNumTeams;
734     } else {
735       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
736       DP("Default number of teams set according to library's default %d\n",
737          DeviceRTLTy::DefaultNumTeams);
738     }
739 
740     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
741       DP("Default number of teams exceeds device limit, capping at %d\n",
742          DeviceData[DeviceId].BlocksPerGrid);
743       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
744     }
745 
746     // Set default number of threads
747     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
748     DP("Default number of threads set according to library's default %d\n",
749        DeviceRTLTy::DefaultNumThreads);
750     if (DeviceData[DeviceId].NumThreads >
751         DeviceData[DeviceId].ThreadsPerBlock) {
752       DP("Default number of threads exceeds device limit, capping at %d\n",
753          DeviceData[DeviceId].ThreadsPerBlock);
754       DeviceData[DeviceId].NumThreads = DeviceData[DeviceId].ThreadsPerBlock;
755     }
756 
757     return OFFLOAD_SUCCESS;
758   }
759 
760   __tgt_target_table *loadBinary(const int DeviceId,
761                                  const __tgt_device_image *Image) {
762     // Set the context we are using
763     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
764     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
765       return nullptr;
766 
767     // Clear the offload table as we are going to create a new one.
768     clearOffloadEntriesTable(DeviceId);
769 
770     // Create the module and extract the function pointers.
771     CUmodule Module;
772     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
773     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
774     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
775       return nullptr;
776 
777     DP("CUDA module successfully loaded!\n");
778 
779     Modules.push_back(Module);
780 
781     // Find the symbols in the module by name.
782     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
783     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
784 
785     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
786     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
787       if (!E->addr) {
788         // We return nullptr when something like this happens, the host should
789         // have always something in the address to uniquely identify the target
790         // region.
791         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
792         return nullptr;
793       }
794 
795       if (E->size) {
796         __tgt_offload_entry Entry = *E;
797         CUdeviceptr CUPtr;
798         size_t CUSize;
799         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
800         // We keep this style here because we need the name
801         if (Err != CUDA_SUCCESS) {
802           REPORT("Loading global '%s' Failed\n", E->name);
803           CUDA_ERR_STRING(Err);
804           return nullptr;
805         }
806 
807         if (CUSize != E->size) {
808           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
809              CUSize, E->size);
810           return nullptr;
811         }
812 
813         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
814            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
815 
816         Entry.addr = (void *)(CUPtr);
817 
818         // Note: In the current implementation declare target variables
819         // can either be link or to. This means that once unified
820         // memory is activated via the requires directive, the variable
821         // can be used directly from the host in both cases.
822         // TODO: when variables types other than to or link are added,
823         // the below condition should be changed to explicitly
824         // check for to and link variables types:
825         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
826         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
827         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
828           // If unified memory is present any target link or to variables
829           // can access host addresses directly. There is no longer a
830           // need for device copies.
831           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
832           DP("Copy linked variable host address (" DPxMOD
833              ") to device address (" DPxMOD ")\n",
834              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
835         }
836 
837         addOffloadEntry(DeviceId, Entry);
838 
839         continue;
840       }
841 
842       CUfunction Func;
843       Err = cuModuleGetFunction(&Func, Module, E->name);
844       // We keep this style here because we need the name
845       if (Err != CUDA_SUCCESS) {
846         REPORT("Loading '%s' Failed\n", E->name);
847         CUDA_ERR_STRING(Err);
848         return nullptr;
849       }
850 
851       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
852          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
853 
854       // default value GENERIC (in case symbol is missing from cubin file)
855       llvm::omp::OMPTgtExecModeFlags ExecModeVal;
856       std::string ExecModeNameStr(E->name);
857       ExecModeNameStr += "_exec_mode";
858       const char *ExecModeName = ExecModeNameStr.c_str();
859 
860       CUdeviceptr ExecModePtr;
861       size_t CUSize;
862       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
863       if (Err == CUDA_SUCCESS) {
864         if (CUSize != sizeof(llvm::omp::OMPTgtExecModeFlags)) {
865           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
866              ExecModeName, CUSize, sizeof(llvm::omp::OMPTgtExecModeFlags));
867           return nullptr;
868         }
869 
870         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
871         if (Err != CUDA_SUCCESS) {
872           REPORT("Error when copying data from device to host. Pointers: "
873                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
874                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
875           CUDA_ERR_STRING(Err);
876           return nullptr;
877         }
878       } else {
879         DP("Loading global exec_mode '%s' - symbol missing, using default "
880            "value GENERIC (1)\n",
881            ExecModeName);
882       }
883 
884       KernelsList.emplace_back(Func, ExecModeVal);
885 
886       __tgt_offload_entry Entry = *E;
887       Entry.addr = &KernelsList.back();
888       addOffloadEntry(DeviceId, Entry);
889     }
890 
891     // send device environment data to the device
892     {
893       // TODO: The device ID used here is not the real device ID used by OpenMP.
894       DeviceEnvironmentTy DeviceEnv{0, static_cast<uint32_t>(NumberOfDevices),
895                                     static_cast<uint32_t>(DeviceId),
896                                     static_cast<uint32_t>(DynamicMemorySize)};
897 
898       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
899         DeviceEnv.DebugKind = std::stoi(EnvStr);
900 
901       const char *DeviceEnvName = "omptarget_device_environment";
902       CUdeviceptr DeviceEnvPtr;
903       size_t CUSize;
904 
905       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
906       if (Err == CUDA_SUCCESS) {
907         if (CUSize != sizeof(DeviceEnv)) {
908           REPORT(
909               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
910               DeviceEnvName, CUSize, sizeof(int32_t));
911           CUDA_ERR_STRING(Err);
912           return nullptr;
913         }
914 
915         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
916         if (Err != CUDA_SUCCESS) {
917           REPORT("Error when copying data from host to device. Pointers: "
918                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
919                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
920           CUDA_ERR_STRING(Err);
921           return nullptr;
922         }
923 
924         DP("Sending global device environment data %zu bytes\n", CUSize);
925       } else {
926         DP("Finding global device environment '%s' - symbol missing.\n",
927            DeviceEnvName);
928         DP("Continue, considering this is a device RTL which does not accept "
929            "environment setting.\n");
930       }
931     }
932 
933     return getOffloadEntriesTable(DeviceId);
934   }
935 
936   void *dataAlloc(const int DeviceId, const int64_t Size,
937                   const TargetAllocTy Kind) {
938     switch (Kind) {
939     case TARGET_ALLOC_DEFAULT:
940     case TARGET_ALLOC_DEVICE:
941       if (UseMemoryManager)
942         return MemoryManagers[DeviceId]->allocate(Size, nullptr);
943       else
944         return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
945     case TARGET_ALLOC_HOST:
946     case TARGET_ALLOC_SHARED:
947       return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
948     }
949 
950     REPORT("Invalid target data allocation kind or requested allocator not "
951            "implemented yet\n");
952 
953     return nullptr;
954   }
955 
956   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
957                  const int64_t Size, __tgt_async_info *AsyncInfo) const {
958     assert(AsyncInfo && "AsyncInfo is nullptr");
959 
960     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
961     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
962       return OFFLOAD_FAIL;
963 
964     CUstream Stream = getStream(DeviceId, AsyncInfo);
965 
966     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
967     if (Err != CUDA_SUCCESS) {
968       DP("Error when copying data from host to device. Pointers: host "
969          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
970          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
971       CUDA_ERR_STRING(Err);
972       return OFFLOAD_FAIL;
973     }
974 
975     return OFFLOAD_SUCCESS;
976   }
977 
978   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
979                    const int64_t Size, __tgt_async_info *AsyncInfo) const {
980     assert(AsyncInfo && "AsyncInfo is nullptr");
981 
982     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
983     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
984       return OFFLOAD_FAIL;
985 
986     CUstream Stream = getStream(DeviceId, AsyncInfo);
987 
988     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
989     if (Err != CUDA_SUCCESS) {
990       DP("Error when copying data from device to host. Pointers: host "
991          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
992          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
993       CUDA_ERR_STRING(Err);
994       return OFFLOAD_FAIL;
995     }
996 
997     return OFFLOAD_SUCCESS;
998   }
999 
1000   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
1001                    int64_t Size, __tgt_async_info *AsyncInfo) const {
1002     assert(AsyncInfo && "AsyncInfo is nullptr");
1003 
1004     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
1005     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
1006       return OFFLOAD_FAIL;
1007 
1008     CUstream Stream = getStream(SrcDevId, AsyncInfo);
1009 
1010     // If they are two devices, we try peer to peer copy first
1011     if (SrcDevId != DstDevId) {
1012       int CanAccessPeer = 0;
1013       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
1014       if (Err != CUDA_SUCCESS) {
1015         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
1016                ", dst = %" PRId32 "\n",
1017                SrcDevId, DstDevId);
1018         CUDA_ERR_STRING(Err);
1019         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1020       }
1021 
1022       if (!CanAccessPeer) {
1023         DP("P2P memcpy not supported so fall back to D2D memcpy");
1024         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1025       }
1026 
1027       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
1028       if (Err != CUDA_SUCCESS) {
1029         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
1030                ", dst = %" PRId32 "\n",
1031                SrcDevId, DstDevId);
1032         CUDA_ERR_STRING(Err);
1033         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1034       }
1035 
1036       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
1037                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
1038                               Size, Stream);
1039       if (Err == CUDA_SUCCESS)
1040         return OFFLOAD_SUCCESS;
1041 
1042       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
1043          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
1044          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
1045       CUDA_ERR_STRING(Err);
1046     }
1047 
1048     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1049   }
1050 
1051   int dataDelete(const int DeviceId, void *TgtPtr) {
1052     if (UseMemoryManager)
1053       return MemoryManagers[DeviceId]->free(TgtPtr);
1054 
1055     return DeviceAllocators[DeviceId].free(TgtPtr);
1056   }
1057 
1058   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
1059                           ptrdiff_t *TgtOffsets, const int ArgNum,
1060                           const int TeamNum, const int ThreadLimit,
1061                           const unsigned int LoopTripCount,
1062                           __tgt_async_info *AsyncInfo) const {
1063     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
1064     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
1065       return OFFLOAD_FAIL;
1066 
1067     // All args are references.
1068     std::vector<void *> Args(ArgNum);
1069     std::vector<void *> Ptrs(ArgNum);
1070 
1071     for (int I = 0; I < ArgNum; ++I) {
1072       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
1073       Args[I] = &Ptrs[I];
1074     }
1075 
1076     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
1077 
1078     const bool IsSPMDGenericMode =
1079         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD;
1080     const bool IsSPMDMode =
1081         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_SPMD;
1082     const bool IsGenericMode =
1083         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC;
1084 
1085     int CudaThreadsPerBlock;
1086     if (ThreadLimit > 0) {
1087       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
1088       CudaThreadsPerBlock = ThreadLimit;
1089       // Add master warp if necessary
1090       if (IsGenericMode) {
1091         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
1092         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
1093       }
1094     } else {
1095       DP("Setting CUDA threads per block to default %d\n",
1096          DeviceData[DeviceId].NumThreads);
1097       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1098     }
1099 
1100     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
1101       DP("Threads per block capped at device limit %d\n",
1102          DeviceData[DeviceId].ThreadsPerBlock);
1103       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
1104     }
1105 
1106     if (!KernelInfo->MaxThreadsPerBlock) {
1107       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
1108                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
1109                                KernelInfo->Func);
1110       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1111         return OFFLOAD_FAIL;
1112     }
1113 
1114     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1115       DP("Threads per block capped at kernel limit %d\n",
1116          KernelInfo->MaxThreadsPerBlock);
1117       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
1118     }
1119 
1120     unsigned int CudaBlocksPerGrid;
1121     if (TeamNum <= 0) {
1122       if (LoopTripCount > 0 && EnvNumTeams < 0) {
1123         if (IsSPMDGenericMode) {
1124           // If we reach this point, then we are executing a kernel that was
1125           // transformed from Generic-mode to SPMD-mode. This kernel has
1126           // SPMD-mode execution, but needs its blocks to be scheduled
1127           // differently because the current loop trip count only applies to the
1128           // `teams distribute` region and will create var too few blocks using
1129           // the regular SPMD-mode method.
1130           CudaBlocksPerGrid = LoopTripCount;
1131         } else if (IsSPMDMode) {
1132           // We have a combined construct, i.e. `target teams distribute
1133           // parallel for [simd]`. We launch so many teams so that each thread
1134           // will execute one iteration of the loop. round up to the nearest
1135           // integer
1136           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
1137         } else if (IsGenericMode) {
1138           // If we reach this point, then we have a non-combined construct, i.e.
1139           // `teams distribute` with a nested `parallel for` and each team is
1140           // assigned one iteration of the `distribute` loop. E.g.:
1141           //
1142           // #pragma omp target teams distribute
1143           // for(...loop_tripcount...) {
1144           //   #pragma omp parallel for
1145           //   for(...) {}
1146           // }
1147           //
1148           // Threads within a team will execute the iterations of the `parallel`
1149           // loop.
1150           CudaBlocksPerGrid = LoopTripCount;
1151         } else {
1152           REPORT("Unknown execution mode: %d\n",
1153                  static_cast<int8_t>(KernelInfo->ExecutionMode));
1154           return OFFLOAD_FAIL;
1155         }
1156         DP("Using %d teams due to loop trip count %" PRIu32
1157            " and number of threads per block %d\n",
1158            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
1159       } else {
1160         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
1161         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
1162       }
1163     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
1164       DP("Capping number of teams to team limit %d\n",
1165          DeviceData[DeviceId].BlocksPerGrid);
1166       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
1167     } else {
1168       DP("Using requested number of teams %d\n", TeamNum);
1169       CudaBlocksPerGrid = TeamNum;
1170     }
1171 
1172     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1173          "Launching kernel %s with %d blocks and %d threads in %s mode\n",
1174          (getOffloadEntry(DeviceId, TgtEntryPtr))
1175              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1176              : "(null)",
1177          CudaBlocksPerGrid, CudaThreadsPerBlock,
1178          (!IsSPMDMode ? (IsGenericMode ? "Generic" : "SPMD-Generic") : "SPMD"));
1179 
1180     CUstream Stream = getStream(DeviceId, AsyncInfo);
1181     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
1182                          /* gridDimZ */ 1, CudaThreadsPerBlock,
1183                          /* blockDimY */ 1, /* blockDimZ */ 1,
1184                          DynamicMemorySize, Stream, &Args[0], nullptr);
1185     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
1186       return OFFLOAD_FAIL;
1187 
1188     DP("Launch of entry point at " DPxMOD " successful!\n",
1189        DPxPTR(TgtEntryPtr));
1190 
1191     return OFFLOAD_SUCCESS;
1192   }
1193 
1194   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
1195     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
1196     CUresult Err = cuStreamSynchronize(Stream);
1197 
1198     // Once the stream is synchronized, return it to stream pool and reset
1199     // AsyncInfo. This is to make sure the synchronization only works for its
1200     // own tasks.
1201     StreamPool[DeviceId]->release(reinterpret_cast<CUstream>(AsyncInfo->Queue));
1202     AsyncInfo->Queue = nullptr;
1203 
1204     if (Err != CUDA_SUCCESS) {
1205       DP("Error when synchronizing stream. stream = " DPxMOD
1206          ", async info ptr = " DPxMOD "\n",
1207          DPxPTR(Stream), DPxPTR(AsyncInfo));
1208       CUDA_ERR_STRING(Err);
1209     }
1210     return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
1211   }
1212 
1213   void printDeviceInfo(int32_t device_id) {
1214     char TmpChar[1000];
1215     std::string TmpStr;
1216     size_t TmpSt;
1217     int TmpInt, TmpInt2, TmpInt3;
1218 
1219     CUdevice Device;
1220     checkResult(cuDeviceGet(&Device, device_id),
1221                 "Error returned from cuCtxGetDevice\n");
1222 
1223     cuDriverGetVersion(&TmpInt);
1224     printf("    CUDA Driver Version: \t\t%d \n", TmpInt);
1225     printf("    CUDA Device Number: \t\t%d \n", device_id);
1226     checkResult(cuDeviceGetName(TmpChar, 1000, Device),
1227                 "Error returned from cuDeviceGetName\n");
1228     printf("    Device Name: \t\t\t%s \n", TmpChar);
1229     checkResult(cuDeviceTotalMem(&TmpSt, Device),
1230                 "Error returned from cuDeviceTotalMem\n");
1231     printf("    Global Memory Size: \t\t%zu bytes \n", TmpSt);
1232     checkResult(cuDeviceGetAttribute(
1233                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device),
1234                 "Error returned from cuDeviceGetAttribute\n");
1235     printf("    Number of Multiprocessors: \t\t%d \n", TmpInt);
1236     checkResult(
1237         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device),
1238         "Error returned from cuDeviceGetAttribute\n");
1239     printf("    Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt));
1240     checkResult(cuDeviceGetAttribute(
1241                     &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device),
1242                 "Error returned from cuDeviceGetAttribute\n");
1243     printf("    Total Constant Memory: \t\t%d bytes\n", TmpInt);
1244     checkResult(
1245         cuDeviceGetAttribute(
1246             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device),
1247         "Error returned from cuDeviceGetAttribute\n");
1248     printf("    Max Shared Memory per Block: \t%d bytes \n", TmpInt);
1249     checkResult(
1250         cuDeviceGetAttribute(
1251             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device),
1252         "Error returned from cuDeviceGetAttribute\n");
1253     printf("    Registers per Block: \t\t%d \n", TmpInt);
1254     checkResult(
1255         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device),
1256         "Error returned from cuDeviceGetAttribute\n");
1257     printf("    Warp Size: \t\t\t\t%d Threads \n", TmpInt);
1258     checkResult(cuDeviceGetAttribute(
1259                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device),
1260                 "Error returned from cuDeviceGetAttribute\n");
1261     printf("    Maximum Threads per Block: \t\t%d \n", TmpInt);
1262     checkResult(cuDeviceGetAttribute(
1263                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device),
1264                 "Error returned from cuDeviceGetAttribute\n");
1265     checkResult(cuDeviceGetAttribute(
1266                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device),
1267                 "Error returned from cuDeviceGetAttribute\n");
1268     checkResult(cuDeviceGetAttribute(
1269                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device),
1270                 "Error returned from cuDeviceGetAttribute\n");
1271     printf("    Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2,
1272            TmpInt3);
1273     checkResult(cuDeviceGetAttribute(
1274                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device),
1275                 "Error returned from cuDeviceGetAttribute\n");
1276     checkResult(cuDeviceGetAttribute(
1277                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, Device),
1278                 "Error returned from cuDeviceGetAttribute\n");
1279     checkResult(cuDeviceGetAttribute(
1280                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, Device),
1281                 "Error returned from cuDeviceGetAttribute\n");
1282     printf("    Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2,
1283            TmpInt3);
1284     checkResult(
1285         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device),
1286         "Error returned from cuDeviceGetAttribute\n");
1287     printf("    Maximum Memory Pitch: \t\t%d bytes \n", TmpInt);
1288     checkResult(cuDeviceGetAttribute(
1289                     &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device),
1290                 "Error returned from cuDeviceGetAttribute\n");
1291     printf("    Texture Alignment: \t\t\t%d bytes \n", TmpInt);
1292     checkResult(
1293         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device),
1294         "Error returned from cuDeviceGetAttribute\n");
1295     printf("    Clock Rate: \t\t\t%d kHz\n", TmpInt);
1296     checkResult(cuDeviceGetAttribute(
1297                     &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device),
1298                 "Error returned from cuDeviceGetAttribute\n");
1299     printf("    Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1300     checkResult(
1301         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device),
1302         "Error returned from cuDeviceGetAttribute\n");
1303     printf("    Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1304     checkResult(cuDeviceGetAttribute(
1305                     &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device),
1306                 "Error returned from cuDeviceGetAttribute\n");
1307     printf("    Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1308     checkResult(
1309         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device),
1310         "Error returned from cuDeviceGetAttribute\n");
1311     if (TmpInt == CU_COMPUTEMODE_DEFAULT)
1312       TmpStr = "DEFAULT";
1313     else if (TmpInt == CU_COMPUTEMODE_PROHIBITED)
1314       TmpStr = "PROHIBITED";
1315     else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS)
1316       TmpStr = "EXCLUSIVE PROCESS";
1317     else
1318       TmpStr = "unknown";
1319     printf("    Compute Mode: \t\t\t%s \n", TmpStr.c_str());
1320     checkResult(cuDeviceGetAttribute(
1321                     &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device),
1322                 "Error returned from cuDeviceGetAttribute\n");
1323     printf("    Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt));
1324     checkResult(
1325         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device),
1326         "Error returned from cuDeviceGetAttribute\n");
1327     printf("    ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1328     checkResult(cuDeviceGetAttribute(
1329                     &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device),
1330                 "Error returned from cuDeviceGetAttribute\n");
1331     printf("    Memory Clock Rate: \t\t\t%d kHz\n", TmpInt);
1332     checkResult(
1333         cuDeviceGetAttribute(
1334             &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device),
1335         "Error returned from cuDeviceGetAttribute\n");
1336     printf("    Memory Bus Width: \t\t\t%d bits\n", TmpInt);
1337     checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE,
1338                                      Device),
1339                 "Error returned from cuDeviceGetAttribute\n");
1340     printf("    L2 Cache Size: \t\t\t%d bytes \n", TmpInt);
1341     checkResult(cuDeviceGetAttribute(
1342                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
1343                     Device),
1344                 "Error returned from cuDeviceGetAttribute\n");
1345     printf("    Max Threads Per SMP: \t\t%d \n", TmpInt);
1346     checkResult(cuDeviceGetAttribute(
1347                     &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device),
1348                 "Error returned from cuDeviceGetAttribute\n");
1349     printf("    Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt);
1350     checkResult(cuDeviceGetAttribute(
1351                     &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device),
1352                 "Error returned from cuDeviceGetAttribute\n");
1353     printf("    Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt));
1354     checkResult(cuDeviceGetAttribute(
1355                     &TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device),
1356                 "Error returned from cuDeviceGetAttribute\n");
1357     printf("    Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1358     checkResult(
1359         cuDeviceGetAttribute(
1360             &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device),
1361         "Error returned from cuDeviceGetAttribute\n");
1362     printf("    Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1363     checkResult(
1364         cuDeviceGetAttribute(
1365             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device),
1366         "Error returned from cuDeviceGetAttribute\n");
1367     printf("    Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt));
1368     checkResult(cuDeviceGetAttribute(
1369                     &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device),
1370                 "Error returned from cuDeviceGetAttribute\n");
1371     printf("    Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt));
1372     checkResult(cuDeviceGetAttribute(
1373                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, Device),
1374                 "Error returned from cuDeviceGetAttribute\n");
1375     printf("    Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt));
1376     checkResult(
1377         cuDeviceGetAttribute(
1378             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Device),
1379         "Error returned from cuDeviceGetAttribute\n");
1380     checkResult(
1381         cuDeviceGetAttribute(
1382             &TmpInt2, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Device),
1383         "Error returned from cuDeviceGetAttribute\n");
1384     printf("    Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2);
1385   }
1386 
1387   int waitEvent(const int DeviceId, __tgt_async_info *AsyncInfo,
1388                 void *EventPtr) const {
1389     CUstream Stream = getStream(DeviceId, AsyncInfo);
1390     CUevent Event = reinterpret_cast<CUevent>(EventPtr);
1391 
1392     // We don't use CU_EVENT_WAIT_DEFAULT here as it is only available from
1393     // specific CUDA version, and defined as 0x0. In previous version, per CUDA
1394     // API document, that argument has to be 0x0.
1395     CUresult Err = cuStreamWaitEvent(Stream, Event, 0);
1396     if (Err != CUDA_SUCCESS) {
1397       DP("Error when waiting event. stream = " DPxMOD ", event = " DPxMOD "\n",
1398          DPxPTR(Stream), DPxPTR(Event));
1399       CUDA_ERR_STRING(Err);
1400       return OFFLOAD_FAIL;
1401     }
1402 
1403     return OFFLOAD_SUCCESS;
1404   }
1405 };
1406 
1407 DeviceRTLTy DeviceRTL;
1408 } // namespace
1409 
1410 // Exposed library API function
1411 #ifdef __cplusplus
1412 extern "C" {
1413 #endif
1414 
1415 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
1416   return elf_check_machine(image, /* EM_CUDA */ 190);
1417 }
1418 
1419 int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
1420 
1421 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
1422   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
1423   DeviceRTL.setRequiresFlag(RequiresFlags);
1424   return RequiresFlags;
1425 }
1426 
1427 int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1428   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1429       DeviceRTL.isValidDeviceId(dst_dev_id))
1430     return 1;
1431 
1432   return 0;
1433 }
1434 
1435 int32_t __tgt_rtl_init_device(int32_t device_id) {
1436   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1437 
1438   return DeviceRTL.initDevice(device_id);
1439 }
1440 
1441 __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
1442                                           __tgt_device_image *image) {
1443   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1444 
1445   return DeviceRTL.loadBinary(device_id, image);
1446 }
1447 
1448 void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *,
1449                            int32_t kind) {
1450   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1451 
1452   return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind);
1453 }
1454 
1455 int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
1456                               int64_t size) {
1457   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1458 
1459   __tgt_async_info AsyncInfo;
1460   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
1461                                                  size, &AsyncInfo);
1462   if (rc != OFFLOAD_SUCCESS)
1463     return OFFLOAD_FAIL;
1464 
1465   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1466 }
1467 
1468 int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
1469                                     void *hst_ptr, int64_t size,
1470                                     __tgt_async_info *async_info_ptr) {
1471   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1472   assert(async_info_ptr && "async_info_ptr is nullptr");
1473 
1474   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
1475                               async_info_ptr);
1476 }
1477 
1478 int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
1479                                 int64_t size) {
1480   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1481 
1482   __tgt_async_info AsyncInfo;
1483   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
1484                                                    size, &AsyncInfo);
1485   if (rc != OFFLOAD_SUCCESS)
1486     return OFFLOAD_FAIL;
1487 
1488   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1489 }
1490 
1491 int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
1492                                       void *tgt_ptr, int64_t size,
1493                                       __tgt_async_info *async_info_ptr) {
1494   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1495   assert(async_info_ptr && "async_info_ptr is nullptr");
1496 
1497   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
1498                                 async_info_ptr);
1499 }
1500 
1501 int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1502                                       int dst_dev_id, void *dst_ptr,
1503                                       int64_t size,
1504                                       __tgt_async_info *AsyncInfo) {
1505   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1506   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1507   assert(AsyncInfo && "AsyncInfo is nullptr");
1508 
1509   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
1510                                 AsyncInfo);
1511 }
1512 
1513 int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1514                                 int32_t dst_dev_id, void *dst_ptr,
1515                                 int64_t size) {
1516   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1517   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1518 
1519   __tgt_async_info AsyncInfo;
1520   const int32_t rc = __tgt_rtl_data_exchange_async(
1521       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo);
1522   if (rc != OFFLOAD_SUCCESS)
1523     return OFFLOAD_FAIL;
1524 
1525   return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo);
1526 }
1527 
1528 int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
1529   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1530 
1531   return DeviceRTL.dataDelete(device_id, tgt_ptr);
1532 }
1533 
1534 int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
1535                                          void **tgt_args,
1536                                          ptrdiff_t *tgt_offsets,
1537                                          int32_t arg_num, int32_t team_num,
1538                                          int32_t thread_limit,
1539                                          uint64_t loop_tripcount) {
1540   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1541 
1542   __tgt_async_info AsyncInfo;
1543   const int32_t rc = __tgt_rtl_run_target_team_region_async(
1544       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1545       thread_limit, loop_tripcount, &AsyncInfo);
1546   if (rc != OFFLOAD_SUCCESS)
1547     return OFFLOAD_FAIL;
1548 
1549   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1550 }
1551 
1552 int32_t __tgt_rtl_run_target_team_region_async(
1553     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
1554     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
1555     int32_t thread_limit, uint64_t loop_tripcount,
1556     __tgt_async_info *async_info_ptr) {
1557   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1558 
1559   return DeviceRTL.runTargetTeamRegion(
1560       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1561       thread_limit, loop_tripcount, async_info_ptr);
1562 }
1563 
1564 int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
1565                                     void **tgt_args, ptrdiff_t *tgt_offsets,
1566                                     int32_t arg_num) {
1567   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1568 
1569   __tgt_async_info AsyncInfo;
1570   const int32_t rc = __tgt_rtl_run_target_region_async(
1571       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo);
1572   if (rc != OFFLOAD_SUCCESS)
1573     return OFFLOAD_FAIL;
1574 
1575   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1576 }
1577 
1578 int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
1579                                           void *tgt_entry_ptr, void **tgt_args,
1580                                           ptrdiff_t *tgt_offsets,
1581                                           int32_t arg_num,
1582                                           __tgt_async_info *async_info_ptr) {
1583   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1584 
1585   return __tgt_rtl_run_target_team_region_async(
1586       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
1587       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
1588       async_info_ptr);
1589 }
1590 
1591 int32_t __tgt_rtl_synchronize(int32_t device_id,
1592                               __tgt_async_info *async_info_ptr) {
1593   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1594   assert(async_info_ptr && "async_info_ptr is nullptr");
1595   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
1596 
1597   return DeviceRTL.synchronize(device_id, async_info_ptr);
1598 }
1599 
1600 void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
1601   std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
1602   InfoLevel.store(NewInfoLevel);
1603 }
1604 
1605 void __tgt_rtl_print_device_info(int32_t device_id) {
1606   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1607   DeviceRTL.printDeviceInfo(device_id);
1608 }
1609 
1610 int32_t __tgt_rtl_create_event(int32_t device_id, void **event) {
1611   assert(event && "event is nullptr");
1612   return createEvent(event);
1613 }
1614 
1615 int32_t __tgt_rtl_record_event(int32_t device_id, void *event_ptr,
1616                                __tgt_async_info *async_info_ptr) {
1617   assert(async_info_ptr && "async_info_ptr is nullptr");
1618   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
1619   assert(event_ptr && "event_ptr is nullptr");
1620 
1621   return recordEvent(event_ptr, async_info_ptr);
1622 }
1623 
1624 int32_t __tgt_rtl_wait_event(int32_t device_id, void *event_ptr,
1625                              __tgt_async_info *async_info_ptr) {
1626   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1627   assert(async_info_ptr && "async_info_ptr is nullptr");
1628   assert(event_ptr && "event is nullptr");
1629 
1630   return DeviceRTL.waitEvent(device_id, async_info_ptr, event_ptr);
1631 }
1632 
1633 int32_t __tgt_rtl_sync_event(int32_t device_id, void *event_ptr) {
1634   assert(event_ptr && "event is nullptr");
1635 
1636   return syncEvent(event_ptr);
1637 }
1638 
1639 int32_t __tgt_rtl_destroy_event(int32_t device_id, void *event_ptr) {
1640   assert(event_ptr && "event is nullptr");
1641 
1642   return destroyEvent(event_ptr);
1643 }
1644 
1645 #ifdef __cplusplus
1646 }
1647 #endif
1648