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 <vector>
21 
22 #include "Debug.h"
23 #include "omptargetplugin.h"
24 
25 #define TARGET_NAME CUDA
26 #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
27 
28 // Utility for retrieving and printing CUDA error string.
29 #ifdef OMPTARGET_DEBUG
30 #define CUDA_ERR_STRING(err)                                                   \
31   do {                                                                         \
32     if (getDebugLevel() > 0) {                                                      \
33       const char *errStr;                                                      \
34       cuGetErrorString(err, &errStr);                                          \
35       DP("CUDA error is: %s\n", errStr);                                       \
36     }                                                                          \
37   } while (false)
38 #else // OMPTARGET_DEBUG
39 #define CUDA_ERR_STRING(err) {}
40 #endif // OMPTARGET_DEBUG
41 
42 #include "../../common/elf_common.c"
43 
44 /// Keep entries table per device.
45 struct FuncOrGblEntryTy {
46   __tgt_target_table Table;
47   std::vector<__tgt_offload_entry> Entries;
48 };
49 
50 enum ExecutionModeType {
51   SPMD, // constructors, destructors,
52   // combined constructs (`teams distribute parallel for [simd]`)
53   GENERIC, // everything else
54   NONE
55 };
56 
57 /// Use a single entity to encode a kernel and a set of flags.
58 struct KernelTy {
59   CUfunction Func;
60 
61   // execution mode of kernel
62   // 0 - SPMD mode (without master warp)
63   // 1 - Generic mode (with master warp)
64   int8_t ExecutionMode;
65 
66   /// Maximal number of threads per block for this kernel.
67   int MaxThreadsPerBlock = 0;
68 
69   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
70       : Func(_Func), ExecutionMode(_ExecutionMode) {}
71 };
72 
73 /// Device environment data
74 /// Manually sync with the deviceRTL side for now, move to a dedicated header
75 /// file later.
76 struct omptarget_device_environmentTy {
77   int32_t debug_level;
78 };
79 
80 namespace {
81 bool checkResult(CUresult Err, const char *ErrMsg) {
82   if (Err == CUDA_SUCCESS)
83     return true;
84 
85   DP("%s", ErrMsg);
86   CUDA_ERR_STRING(Err);
87   return false;
88 }
89 
90 int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
91                CUstream Stream) {
92   CUresult Err =
93       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
94 
95   if (Err != CUDA_SUCCESS) {
96     DP("Error when copying data from device to device. Pointers: src "
97        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
98        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
99     CUDA_ERR_STRING(Err);
100     return OFFLOAD_FAIL;
101   }
102 
103   return OFFLOAD_SUCCESS;
104 }
105 
106 // Structure contains per-device data
107 struct DeviceDataTy {
108   /// List that contains all the kernels.
109   std::list<KernelTy> KernelsList;
110 
111   std::list<FuncOrGblEntryTy> FuncGblEntries;
112 
113   CUcontext Context = nullptr;
114   // Device properties
115   int ThreadsPerBlock = 0;
116   int BlocksPerGrid = 0;
117   int WarpSize = 0;
118   // OpenMP properties
119   int NumTeams = 0;
120   int NumThreads = 0;
121 };
122 
123 class StreamManagerTy {
124   int NumberOfDevices;
125   // The initial size of stream pool
126   int EnvNumInitialStreams;
127   // Per-device stream mutex
128   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
129   // Per-device stream Id indicates the next available stream in the pool
130   std::vector<int> NextStreamId;
131   // Per-device stream pool
132   std::vector<std::vector<CUstream>> StreamPool;
133   // Reference to per-device data
134   std::vector<DeviceDataTy> &DeviceData;
135 
136   // If there is no CUstream left in the pool, we will resize the pool to
137   // allocate more CUstream. This function should be called with device mutex,
138   // and we do not resize to smaller one.
139   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
140     std::vector<CUstream> &Pool = StreamPool[DeviceId];
141     const size_t CurrentSize = Pool.size();
142     assert(NewSize > CurrentSize && "new size is not larger than current size");
143 
144     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
145     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
146       // We will return if cannot switch to the right context in case of
147       // creating bunch of streams that are not corresponding to the right
148       // device. The offloading will fail later because selected CUstream is
149       // nullptr.
150       return;
151     }
152 
153     Pool.resize(NewSize, nullptr);
154 
155     for (size_t I = CurrentSize; I < NewSize; ++I) {
156       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
157                   "Error returned from cuStreamCreate\n");
158     }
159   }
160 
161 public:
162   StreamManagerTy(const int NumberOfDevices,
163                   std::vector<DeviceDataTy> &DeviceData)
164       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
165         DeviceData(DeviceData) {
166     StreamPool.resize(NumberOfDevices);
167     NextStreamId.resize(NumberOfDevices);
168     StreamMtx.resize(NumberOfDevices);
169 
170     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
171       EnvNumInitialStreams = std::stoi(EnvStr);
172 
173     // Initialize the next stream id
174     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
175 
176     // Initialize stream mutex
177     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
178       Ptr = std::make_unique<std::mutex>();
179   }
180 
181   ~StreamManagerTy() {
182     // Destroy streams
183     for (int I = 0; I < NumberOfDevices; ++I) {
184       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
185                   "Error returned from cuCtxSetCurrent\n");
186 
187       for (CUstream &S : StreamPool[I]) {
188         if (S)
189           checkResult(cuStreamDestroy(S),
190                       "Error returned from cuStreamDestroy\n");
191       }
192     }
193   }
194 
195   // Get a CUstream from pool. Per-device next stream id always points to the
196   // next available CUstream. That means, CUstreams [0, id-1] have been
197   // assigned, and [id,] are still available. If there is no CUstream left, we
198   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
199   // the id will increase one.
200   // xxxxxs+++++++++
201   //      ^
202   //      id
203   // After assignment, the pool becomes the following and s is assigned.
204   // xxxxxs+++++++++
205   //       ^
206   //       id
207   CUstream getStream(const int DeviceId) {
208     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
209     int &Id = NextStreamId[DeviceId];
210     // No CUstream left in the pool, we need to request from CUDA RT
211     if (Id == StreamPool[DeviceId].size()) {
212       // By default we double the stream pool every time
213       resizeStreamPool(DeviceId, Id * 2);
214     }
215     return StreamPool[DeviceId][Id++];
216   }
217 
218   // Return a CUstream back to pool. As mentioned above, per-device next
219   // stream is always points to the next available CUstream, so when we return
220   // a CUstream, we need to first decrease the id, and then copy the CUstream
221   // back.
222   // It is worth noting that, the order of streams return might be different
223   // from that they're assigned, that saying, at some point, there might be
224   // two identical CUstreams.
225   // xxax+a+++++
226   //     ^
227   //     id
228   // However, it doesn't matter, because they're always on the two sides of
229   // id. The left one will in the end be overwritten by another CUstream.
230   // Therefore, after several execution, the order of pool might be different
231   // from its initial state.
232   void returnStream(const int DeviceId, CUstream Stream) {
233     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
234     int &Id = NextStreamId[DeviceId];
235     assert(Id > 0 && "Wrong stream ID");
236     StreamPool[DeviceId][--Id] = Stream;
237   }
238 
239   bool initializeDeviceStreamPool(const int DeviceId) {
240     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
241 
242     resizeStreamPool(DeviceId, EnvNumInitialStreams);
243 
244     // Check the size of stream pool
245     if (StreamPool[DeviceId].size() != EnvNumInitialStreams)
246       return false;
247 
248     // Check whether each stream is valid
249     for (CUstream &S : StreamPool[DeviceId])
250       if (!S)
251         return false;
252 
253     return true;
254   }
255 };
256 
257 class DeviceRTLTy {
258   int NumberOfDevices;
259   // OpenMP environment properties
260   int EnvNumTeams;
261   int EnvTeamLimit;
262   // OpenMP requires flags
263   int64_t RequiresFlags;
264 
265   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
266   static constexpr const int HardThreadLimit = 1024;
267   static constexpr const int DefaultNumTeams = 128;
268   static constexpr const int DefaultNumThreads = 128;
269 
270   std::unique_ptr<StreamManagerTy> StreamManager;
271   std::vector<DeviceDataTy> DeviceData;
272   std::vector<CUmodule> Modules;
273 
274   // Record entry point associated with device
275   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
276     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
277     E.Entries.push_back(entry);
278   }
279 
280   // Return true if the entry is associated with device
281   bool findOffloadEntry(const int DeviceId, const void *Addr) const {
282     for (const __tgt_offload_entry &Itr :
283          DeviceData[DeviceId].FuncGblEntries.back().Entries)
284       if (Itr.addr == Addr)
285         return true;
286 
287     return false;
288   }
289 
290   // Return the pointer to the target entries table
291   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
292     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
293 
294     if (E.Entries.empty())
295       return nullptr;
296 
297     // Update table info according to the entries and return the pointer
298     E.Table.EntriesBegin = E.Entries.data();
299     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
300 
301     return &E.Table;
302   }
303 
304   // Clear entries table for a device
305   void clearOffloadEntriesTable(const int DeviceId) {
306     DeviceData[DeviceId].FuncGblEntries.emplace_back();
307     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
308     E.Entries.clear();
309     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
310   }
311 
312   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
313     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
314 
315     if (!AsyncInfoPtr->Queue)
316       AsyncInfoPtr->Queue = StreamManager->getStream(DeviceId);
317 
318     return reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
319   }
320 
321 public:
322   // This class should not be copied
323   DeviceRTLTy(const DeviceRTLTy &) = delete;
324   DeviceRTLTy(DeviceRTLTy &&) = delete;
325 
326   DeviceRTLTy()
327       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
328         RequiresFlags(OMP_REQ_UNDEFINED) {
329 
330     DP("Start initializing CUDA\n");
331 
332     CUresult Err = cuInit(0);
333     if (!checkResult(Err, "Error returned from cuInit\n")) {
334       return;
335     }
336 
337     Err = cuDeviceGetCount(&NumberOfDevices);
338     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
339       return;
340 
341     if (NumberOfDevices == 0) {
342       DP("There are no devices supporting CUDA.\n");
343       return;
344     }
345 
346     DeviceData.resize(NumberOfDevices);
347 
348     // Get environment variables regarding teams
349     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
350       // OMP_TEAM_LIMIT has been set
351       EnvTeamLimit = std::stoi(EnvStr);
352       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
353     }
354     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
355       // OMP_NUM_TEAMS has been set
356       EnvNumTeams = std::stoi(EnvStr);
357       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
358     }
359 
360     StreamManager =
361         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
362   }
363 
364   ~DeviceRTLTy() {
365     // First destruct stream manager in case of Contexts is destructed before it
366     StreamManager = nullptr;
367 
368     for (CUmodule &M : Modules)
369       // Close module
370       if (M)
371         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
372 
373     for (DeviceDataTy &D : DeviceData) {
374       // Destroy context
375       if (D.Context) {
376         checkResult(cuCtxSetCurrent(D.Context),
377                     "Error returned from cuCtxSetCurrent\n");
378         CUdevice Device;
379         checkResult(cuCtxGetDevice(&Device),
380                     "Error returned from cuCtxGetDevice\n");
381         checkResult(cuDevicePrimaryCtxRelease(Device),
382                     "Error returned from cuDevicePrimaryCtxRelease\n");
383       }
384     }
385   }
386 
387   // Check whether a given DeviceId is valid
388   bool isValidDeviceId(const int DeviceId) const {
389     return DeviceId >= 0 && DeviceId < NumberOfDevices;
390   }
391 
392   int getNumOfDevices() const { return NumberOfDevices; }
393 
394   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
395 
396   int initDevice(const int DeviceId) {
397     CUdevice Device;
398 
399     DP("Getting device %d\n", DeviceId);
400     CUresult Err = cuDeviceGet(&Device, DeviceId);
401     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
402       return OFFLOAD_FAIL;
403 
404     // Query the current flags of the primary context and set its flags if
405     // it is inactive
406     unsigned int FormerPrimaryCtxFlags = 0;
407     int FormerPrimaryCtxIsActive = 0;
408     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
409                                      &FormerPrimaryCtxIsActive);
410     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
411       return OFFLOAD_FAIL;
412 
413     if (FormerPrimaryCtxIsActive) {
414       DP("The primary context is active, no change to its flags\n");
415       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
416           CU_CTX_SCHED_BLOCKING_SYNC)
417         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
418     } else {
419       DP("The primary context is inactive, set its flags to "
420          "CU_CTX_SCHED_BLOCKING_SYNC\n");
421       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
422       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
423         return OFFLOAD_FAIL;
424     }
425 
426     // Retain the per device primary context and save it to use whenever this
427     // device is selected.
428     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
429     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
430       return OFFLOAD_FAIL;
431 
432     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
433     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
434       return OFFLOAD_FAIL;
435 
436     // Initialize stream pool
437     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
438       return OFFLOAD_FAIL;
439 
440     // Query attributes to determine number of threads/block and blocks/grid.
441     int MaxGridDimX;
442     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
443                                Device);
444     if (Err != CUDA_SUCCESS) {
445       DP("Error getting max grid dimension, use default value %d\n",
446          DeviceRTLTy::DefaultNumTeams);
447       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
448     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
449       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
450       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
451     } else {
452       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
453          "at the hard limit\n",
454          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
455       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
456     }
457 
458     // We are only exploiting threads along the x axis.
459     int MaxBlockDimX;
460     Err = cuDeviceGetAttribute(&MaxBlockDimX,
461                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
462     if (Err != CUDA_SUCCESS) {
463       DP("Error getting max block dimension, use default value %d\n",
464          DeviceRTLTy::DefaultNumThreads);
465       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
466     } else if (MaxBlockDimX <= DeviceRTLTy::HardThreadLimit) {
467       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
468       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
469     } else {
470       DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
471          "capping at the hard limit\n",
472          MaxBlockDimX, DeviceRTLTy::HardThreadLimit);
473       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
474     }
475 
476     // Get and set warp size
477     int WarpSize;
478     Err =
479         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
480     if (Err != CUDA_SUCCESS) {
481       DP("Error getting warp size, assume default value 32\n");
482       DeviceData[DeviceId].WarpSize = 32;
483     } else {
484       DP("Using warp size %d\n", WarpSize);
485       DeviceData[DeviceId].WarpSize = WarpSize;
486     }
487 
488     // Adjust teams to the env variables
489     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
490       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
491          EnvTeamLimit);
492       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
493     }
494 
495     DP("Max number of CUDA blocks %d, threads %d & warp size %d\n",
496        DeviceData[DeviceId].BlocksPerGrid, DeviceData[DeviceId].ThreadsPerBlock,
497        DeviceData[DeviceId].WarpSize);
498 
499     // Set default number of teams
500     if (EnvNumTeams > 0) {
501       DP("Default number of teams set according to environment %d\n",
502          EnvNumTeams);
503       DeviceData[DeviceId].NumTeams = EnvNumTeams;
504     } else {
505       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
506       DP("Default number of teams set according to library's default %d\n",
507          DeviceRTLTy::DefaultNumTeams);
508     }
509 
510     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
511       DP("Default number of teams exceeds device limit, capping at %d\n",
512          DeviceData[DeviceId].BlocksPerGrid);
513       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
514     }
515 
516     // Set default number of threads
517     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
518     DP("Default number of threads set according to library's default %d\n",
519        DeviceRTLTy::DefaultNumThreads);
520     if (DeviceData[DeviceId].NumThreads >
521         DeviceData[DeviceId].ThreadsPerBlock) {
522       DP("Default number of threads exceeds device limit, capping at %d\n",
523          DeviceData[DeviceId].ThreadsPerBlock);
524       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
525     }
526 
527     return OFFLOAD_SUCCESS;
528   }
529 
530   __tgt_target_table *loadBinary(const int DeviceId,
531                                  const __tgt_device_image *Image) {
532     // Set the context we are using
533     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
534     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
535       return nullptr;
536 
537     // Clear the offload table as we are going to create a new one.
538     clearOffloadEntriesTable(DeviceId);
539 
540     // Create the module and extract the function pointers.
541     CUmodule Module;
542     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
543     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
544     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
545       return nullptr;
546 
547     DP("CUDA module successfully loaded!\n");
548 
549     Modules.push_back(Module);
550 
551     // Find the symbols in the module by name.
552     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
553     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
554 
555     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
556     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
557       if (!E->addr) {
558         // We return nullptr when something like this happens, the host should
559         // have always something in the address to uniquely identify the target
560         // region.
561         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
562         return nullptr;
563       }
564 
565       if (E->size) {
566         __tgt_offload_entry Entry = *E;
567         CUdeviceptr CUPtr;
568         size_t CUSize;
569         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
570         // We keep this style here because we need the name
571         if (Err != CUDA_SUCCESS) {
572           DP("Loading global '%s' (Failed)\n", E->name);
573           CUDA_ERR_STRING(Err);
574           return nullptr;
575         }
576 
577         if (CUSize != E->size) {
578           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
579              CUSize, E->size);
580           return nullptr;
581         }
582 
583         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
584            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
585 
586         Entry.addr = (void *)(CUPtr);
587 
588         // Note: In the current implementation declare target variables
589         // can either be link or to. This means that once unified
590         // memory is activated via the requires directive, the variable
591         // can be used directly from the host in both cases.
592         // TODO: when variables types other than to or link are added,
593         // the below condition should be changed to explicitly
594         // check for to and link variables types:
595         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
596         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
597         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
598           // If unified memory is present any target link or to variables
599           // can access host addresses directly. There is no longer a
600           // need for device copies.
601           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
602           DP("Copy linked variable host address (" DPxMOD
603              ") to device address (" DPxMOD ")\n",
604              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
605         }
606 
607         addOffloadEntry(DeviceId, Entry);
608 
609         continue;
610       }
611 
612       CUfunction Func;
613       Err = cuModuleGetFunction(&Func, Module, E->name);
614       // We keep this style here because we need the name
615       if (Err != CUDA_SUCCESS) {
616         DP("Loading '%s' (Failed)\n", E->name);
617         CUDA_ERR_STRING(Err);
618         return nullptr;
619       }
620 
621       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
622          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
623 
624       // default value GENERIC (in case symbol is missing from cubin file)
625       int8_t ExecModeVal = ExecutionModeType::GENERIC;
626       std::string ExecModeNameStr(E->name);
627       ExecModeNameStr += "_exec_mode";
628       const char *ExecModeName = ExecModeNameStr.c_str();
629 
630       CUdeviceptr ExecModePtr;
631       size_t CUSize;
632       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
633       if (Err == CUDA_SUCCESS) {
634         if (CUSize != sizeof(int8_t)) {
635           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
636              ExecModeName, CUSize, sizeof(int8_t));
637           return nullptr;
638         }
639 
640         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
641         if (Err != CUDA_SUCCESS) {
642           DP("Error when copying data from device to host. Pointers: "
643              "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
644              DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
645           CUDA_ERR_STRING(Err);
646           return nullptr;
647         }
648 
649         if (ExecModeVal < 0 || ExecModeVal > 1) {
650           DP("Error wrong exec_mode value specified in cubin file: %d\n",
651              ExecModeVal);
652           return nullptr;
653         }
654       } else {
655         DP("Loading global exec_mode '%s' - symbol missing, using default "
656            "value GENERIC (1)\n",
657            ExecModeName);
658         CUDA_ERR_STRING(Err);
659       }
660 
661       KernelsList.emplace_back(Func, ExecModeVal);
662 
663       __tgt_offload_entry Entry = *E;
664       Entry.addr = &KernelsList.back();
665       addOffloadEntry(DeviceId, Entry);
666     }
667 
668     // send device environment data to the device
669     {
670       omptarget_device_environmentTy DeviceEnv{0};
671 
672 #ifdef OMPTARGET_DEBUG
673       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
674         DeviceEnv.debug_level = std::stoi(EnvStr);
675 #endif
676 
677       const char *DeviceEnvName = "omptarget_device_environment";
678       CUdeviceptr DeviceEnvPtr;
679       size_t CUSize;
680 
681       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
682       if (Err == CUDA_SUCCESS) {
683         if (CUSize != sizeof(DeviceEnv)) {
684           DP("Global device_environment '%s' - size mismatch (%zu != %zu)\n",
685              DeviceEnvName, CUSize, sizeof(int32_t));
686           CUDA_ERR_STRING(Err);
687           return nullptr;
688         }
689 
690         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
691         if (Err != CUDA_SUCCESS) {
692           DP("Error when copying data from host to device. Pointers: "
693              "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
694              DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
695           CUDA_ERR_STRING(Err);
696           return nullptr;
697         }
698 
699         DP("Sending global device environment data %zu bytes\n", CUSize);
700       } else {
701         DP("Finding global device environment '%s' - symbol missing.\n",
702            DeviceEnvName);
703         DP("Continue, considering this is a device RTL which does not accept "
704            "environment setting.\n");
705       }
706     }
707 
708     return getOffloadEntriesTable(DeviceId);
709   }
710 
711   void *dataAlloc(const int DeviceId, const int64_t Size) const {
712     if (Size == 0)
713       return nullptr;
714 
715     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
716     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
717       return nullptr;
718 
719     CUdeviceptr DevicePtr;
720     Err = cuMemAlloc(&DevicePtr, Size);
721     if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
722       return nullptr;
723 
724     return (void *)DevicePtr;
725   }
726 
727   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
728                  const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
729     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
730 
731     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
732     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
733       return OFFLOAD_FAIL;
734 
735     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
736 
737     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
738     if (Err != CUDA_SUCCESS) {
739       DP("Error when copying data from host to device. Pointers: host = " DPxMOD
740          ", device = " DPxMOD ", size = %" PRId64 "\n",
741          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
742       CUDA_ERR_STRING(Err);
743       return OFFLOAD_FAIL;
744     }
745 
746     return OFFLOAD_SUCCESS;
747   }
748 
749   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
750                    const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
751     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
752 
753     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
754     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
755       return OFFLOAD_FAIL;
756 
757     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
758 
759     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
760     if (Err != CUDA_SUCCESS) {
761       DP("Error when copying data from device to host. Pointers: host = " DPxMOD
762          ", device = " DPxMOD ", size = %" PRId64 "\n",
763          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
764       CUDA_ERR_STRING(Err);
765       return OFFLOAD_FAIL;
766     }
767 
768     return OFFLOAD_SUCCESS;
769   }
770 
771   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
772                    int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
773     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
774 
775     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
776     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
777       return OFFLOAD_FAIL;
778 
779     CUstream Stream = getStream(SrcDevId, AsyncInfoPtr);
780 
781     // If they are two devices, we try peer to peer copy first
782     if (SrcDevId != DstDevId) {
783       int CanAccessPeer = 0;
784       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
785       if (Err != CUDA_SUCCESS) {
786         DP("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
787            ", dst = %" PRId32 "\n",
788            SrcDevId, DstDevId);
789         CUDA_ERR_STRING(Err);
790         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
791       }
792 
793       if (!CanAccessPeer) {
794         DP("P2P memcpy not supported so fall back to D2D memcpy");
795         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
796       }
797 
798       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
799       if (Err != CUDA_SUCCESS) {
800         DP("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
801            ", dst = %" PRId32 "\n",
802            SrcDevId, DstDevId);
803         CUDA_ERR_STRING(Err);
804         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
805       }
806 
807       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
808                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
809                               Size, Stream);
810       if (Err == CUDA_SUCCESS)
811         return OFFLOAD_SUCCESS;
812 
813       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
814          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
815          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
816       CUDA_ERR_STRING(Err);
817     }
818 
819     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
820   }
821 
822   int dataDelete(const int DeviceId, void *TgtPtr) const {
823     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
824     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
825       return OFFLOAD_FAIL;
826 
827     Err = cuMemFree((CUdeviceptr)TgtPtr);
828     if (!checkResult(Err, "Error returned from cuMemFree\n"))
829       return OFFLOAD_FAIL;
830 
831     return OFFLOAD_SUCCESS;
832   }
833 
834   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
835                           ptrdiff_t *TgtOffsets, const int ArgNum,
836                           const int TeamNum, const int ThreadLimit,
837                           const unsigned int LoopTripCount,
838                           __tgt_async_info *AsyncInfo) const {
839     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
840     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
841       return OFFLOAD_FAIL;
842 
843     // All args are references.
844     std::vector<void *> Args(ArgNum);
845     std::vector<void *> Ptrs(ArgNum);
846 
847     for (int I = 0; I < ArgNum; ++I) {
848       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
849       Args[I] = &Ptrs[I];
850     }
851 
852     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
853 
854     int CudaThreadsPerBlock;
855     if (ThreadLimit > 0) {
856       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
857       CudaThreadsPerBlock = ThreadLimit;
858       // Add master warp if necessary
859       if (KernelInfo->ExecutionMode == GENERIC) {
860         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
861         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
862       }
863     } else {
864       DP("Setting CUDA threads per block to default %d\n",
865          DeviceData[DeviceId].NumThreads);
866       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
867     }
868 
869     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
870       DP("Threads per block capped at device limit %d\n",
871          DeviceData[DeviceId].ThreadsPerBlock);
872       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
873     }
874 
875     if (!KernelInfo->MaxThreadsPerBlock) {
876       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
877                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
878                                KernelInfo->Func);
879       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
880         return OFFLOAD_FAIL;
881     }
882 
883     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
884       DP("Threads per block capped at kernel limit %d\n",
885          KernelInfo->MaxThreadsPerBlock);
886       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
887     }
888 
889     unsigned int CudaBlocksPerGrid;
890     if (TeamNum <= 0) {
891       if (LoopTripCount > 0 && EnvNumTeams < 0) {
892         if (KernelInfo->ExecutionMode == SPMD) {
893           // We have a combined construct, i.e. `target teams distribute
894           // parallel for [simd]`. We launch so many teams so that each thread
895           // will execute one iteration of the loop. round up to the nearest
896           // integer
897           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
898         } else {
899           // If we reach this point, then we have a non-combined construct, i.e.
900           // `teams distribute` with a nested `parallel for` and each team is
901           // assigned one iteration of the `distribute` loop. E.g.:
902           //
903           // #pragma omp target teams distribute
904           // for(...loop_tripcount...) {
905           //   #pragma omp parallel for
906           //   for(...) {}
907           // }
908           //
909           // Threads within a team will execute the iterations of the `parallel`
910           // loop.
911           CudaBlocksPerGrid = LoopTripCount;
912         }
913         DP("Using %d teams due to loop trip count %" PRIu32
914            " and number of threads per block %d\n",
915            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
916       } else {
917         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
918         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
919       }
920     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
921       DP("Capping number of teams to team limit %d\n",
922          DeviceData[DeviceId].BlocksPerGrid);
923       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
924     } else {
925       DP("Using requested number of teams %d\n", TeamNum);
926       CudaBlocksPerGrid = TeamNum;
927     }
928 
929     // Run on the device.
930     DP("Launch kernel with %d blocks and %d threads\n", CudaBlocksPerGrid,
931        CudaThreadsPerBlock);
932 
933     CUstream Stream = getStream(DeviceId, AsyncInfo);
934     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
935                          /* gridDimZ */ 1, CudaThreadsPerBlock,
936                          /* blockDimY */ 1, /* blockDimZ */ 1,
937                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
938     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
939       return OFFLOAD_FAIL;
940 
941     DP("Launch of entry point at " DPxMOD " successful!\n",
942        DPxPTR(TgtEntryPtr));
943 
944     return OFFLOAD_SUCCESS;
945   }
946 
947   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
948     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
949     CUresult Err = cuStreamSynchronize(Stream);
950     if (Err != CUDA_SUCCESS) {
951       DP("Error when synchronizing stream. stream = " DPxMOD
952          ", async info ptr = " DPxMOD "\n",
953          DPxPTR(Stream), DPxPTR(AsyncInfoPtr));
954       CUDA_ERR_STRING(Err);
955       return OFFLOAD_FAIL;
956     }
957 
958     // Once the stream is synchronized, return it to stream pool and reset
959     // async_info. This is to make sure the synchronization only works for its
960     // own tasks.
961     StreamManager->returnStream(
962         DeviceId, reinterpret_cast<CUstream>(AsyncInfoPtr->Queue));
963     AsyncInfoPtr->Queue = nullptr;
964 
965     return OFFLOAD_SUCCESS;
966   }
967 };
968 
969 DeviceRTLTy DeviceRTL;
970 } // namespace
971 
972 // Exposed library API function
973 #ifdef __cplusplus
974 extern "C" {
975 #endif
976 
977 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
978   return elf_check_machine(image, /* EM_CUDA */ 190);
979 }
980 
981 int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
982 
983 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
984   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
985   DeviceRTL.setRequiresFlag(RequiresFlags);
986   return RequiresFlags;
987 }
988 
989 int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
990   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
991       DeviceRTL.isValidDeviceId(dst_dev_id))
992     return 1;
993 
994   return 0;
995 }
996 
997 int32_t __tgt_rtl_init_device(int32_t device_id) {
998   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
999 
1000   return DeviceRTL.initDevice(device_id);
1001 }
1002 
1003 __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
1004                                           __tgt_device_image *image) {
1005   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1006 
1007   return DeviceRTL.loadBinary(device_id, image);
1008 }
1009 
1010 void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *) {
1011   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1012 
1013   return DeviceRTL.dataAlloc(device_id, size);
1014 }
1015 
1016 int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
1017                               int64_t size) {
1018   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1019 
1020   __tgt_async_info async_info;
1021   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
1022                                                  size, &async_info);
1023   if (rc != OFFLOAD_SUCCESS)
1024     return OFFLOAD_FAIL;
1025 
1026   return __tgt_rtl_synchronize(device_id, &async_info);
1027 }
1028 
1029 int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
1030                                     void *hst_ptr, int64_t size,
1031                                     __tgt_async_info *async_info_ptr) {
1032   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1033   assert(async_info_ptr && "async_info_ptr is nullptr");
1034 
1035   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
1036                               async_info_ptr);
1037 }
1038 
1039 int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
1040                                 int64_t size) {
1041   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1042 
1043   __tgt_async_info async_info;
1044   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
1045                                                    size, &async_info);
1046   if (rc != OFFLOAD_SUCCESS)
1047     return OFFLOAD_FAIL;
1048 
1049   return __tgt_rtl_synchronize(device_id, &async_info);
1050 }
1051 
1052 int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
1053                                       void *tgt_ptr, int64_t size,
1054                                       __tgt_async_info *async_info_ptr) {
1055   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1056   assert(async_info_ptr && "async_info_ptr is nullptr");
1057 
1058   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
1059                                 async_info_ptr);
1060 }
1061 
1062 int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1063                                       int dst_dev_id, void *dst_ptr,
1064                                       int64_t size,
1065                                       __tgt_async_info *async_info_ptr) {
1066   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1067   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1068   assert(async_info_ptr && "async_info_ptr is nullptr");
1069 
1070   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
1071                                 async_info_ptr);
1072 }
1073 
1074 int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1075                                 int32_t dst_dev_id, void *dst_ptr,
1076                                 int64_t size) {
1077   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1078   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1079 
1080   __tgt_async_info async_info;
1081   const int32_t rc = __tgt_rtl_data_exchange_async(
1082       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &async_info);
1083   if (rc != OFFLOAD_SUCCESS)
1084     return OFFLOAD_FAIL;
1085 
1086   return __tgt_rtl_synchronize(src_dev_id, &async_info);
1087 }
1088 
1089 int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
1090   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1091 
1092   return DeviceRTL.dataDelete(device_id, tgt_ptr);
1093 }
1094 
1095 int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
1096                                          void **tgt_args,
1097                                          ptrdiff_t *tgt_offsets,
1098                                          int32_t arg_num, int32_t team_num,
1099                                          int32_t thread_limit,
1100                                          uint64_t loop_tripcount) {
1101   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1102 
1103   __tgt_async_info async_info;
1104   const int32_t rc = __tgt_rtl_run_target_team_region_async(
1105       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1106       thread_limit, loop_tripcount, &async_info);
1107   if (rc != OFFLOAD_SUCCESS)
1108     return OFFLOAD_FAIL;
1109 
1110   return __tgt_rtl_synchronize(device_id, &async_info);
1111 }
1112 
1113 int32_t __tgt_rtl_run_target_team_region_async(
1114     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
1115     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
1116     int32_t thread_limit, uint64_t loop_tripcount,
1117     __tgt_async_info *async_info_ptr) {
1118   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1119 
1120   return DeviceRTL.runTargetTeamRegion(
1121       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1122       thread_limit, loop_tripcount, async_info_ptr);
1123 }
1124 
1125 int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
1126                                     void **tgt_args, ptrdiff_t *tgt_offsets,
1127                                     int32_t arg_num) {
1128   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1129 
1130   __tgt_async_info async_info;
1131   const int32_t rc = __tgt_rtl_run_target_region_async(
1132       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &async_info);
1133   if (rc != OFFLOAD_SUCCESS)
1134     return OFFLOAD_FAIL;
1135 
1136   return __tgt_rtl_synchronize(device_id, &async_info);
1137 }
1138 
1139 int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
1140                                           void *tgt_entry_ptr, void **tgt_args,
1141                                           ptrdiff_t *tgt_offsets,
1142                                           int32_t arg_num,
1143                                           __tgt_async_info *async_info_ptr) {
1144   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1145 
1146   return __tgt_rtl_run_target_team_region_async(
1147       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
1148       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
1149       async_info_ptr);
1150 }
1151 
1152 int32_t __tgt_rtl_synchronize(int32_t device_id,
1153                               __tgt_async_info *async_info_ptr) {
1154   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1155   assert(async_info_ptr && "async_info_ptr is nullptr");
1156   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
1157 
1158   return DeviceRTL.synchronize(device_id, async_info_ptr);
1159 }
1160 
1161 #ifdef __cplusplus
1162 }
1163 #endif
1164