1 //===--------- device.cpp - Target independent OpenMP target RTL ----------===//
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 // Functionality for managing devices that are handled by RTL plugins.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "device.h"
14 #include "private.h"
15 #include "rtl.h"
16 
17 #include <cassert>
18 #include <climits>
19 #include <cstdio>
20 #include <string>
21 
22 DeviceTy::DeviceTy(const DeviceTy &D)
23     : DeviceID(D.DeviceID), RTL(D.RTL), RTLDeviceID(D.RTLDeviceID),
24       IsInit(D.IsInit), InitFlag(), HasPendingGlobals(D.HasPendingGlobals),
25       HostDataToTargetMap(D.HostDataToTargetMap),
26       PendingCtorsDtors(D.PendingCtorsDtors), ShadowPtrMap(D.ShadowPtrMap),
27       DataMapMtx(), PendingGlobalsMtx(), ShadowMtx(),
28       LoopTripCnt(D.LoopTripCnt) {}
29 
30 DeviceTy &DeviceTy::operator=(const DeviceTy &D) {
31   DeviceID = D.DeviceID;
32   RTL = D.RTL;
33   RTLDeviceID = D.RTLDeviceID;
34   IsInit = D.IsInit;
35   HasPendingGlobals = D.HasPendingGlobals;
36   HostDataToTargetMap = D.HostDataToTargetMap;
37   PendingCtorsDtors = D.PendingCtorsDtors;
38   ShadowPtrMap = D.ShadowPtrMap;
39   LoopTripCnt = D.LoopTripCnt;
40 
41   return *this;
42 }
43 
44 DeviceTy::DeviceTy(RTLInfoTy *RTL)
45     : DeviceID(-1), RTL(RTL), RTLDeviceID(-1), IsInit(false), InitFlag(),
46       HasPendingGlobals(false), HostDataToTargetMap(), PendingCtorsDtors(),
47       ShadowPtrMap(), DataMapMtx(), PendingGlobalsMtx(), ShadowMtx() {}
48 
49 DeviceTy::~DeviceTy() {
50   if (DeviceID == -1 || !(getInfoLevel() & OMP_INFOTYPE_DUMP_TABLE))
51     return;
52 
53   ident_t loc = {0, 0, 0, 0, ";libomptarget;libomptarget;0;0;;"};
54   dumpTargetPointerMappings(&loc, *this);
55 }
56 
57 int DeviceTy::associatePtr(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size) {
58   DataMapMtx.lock();
59 
60   // Check if entry exists
61   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
62   if (search != HostDataToTargetMap.end()) {
63     // Mapping already exists
64     bool isValid = search->HstPtrEnd == (uintptr_t)HstPtrBegin + Size &&
65                    search->TgtPtrBegin == (uintptr_t)TgtPtrBegin;
66     DataMapMtx.unlock();
67     if (isValid) {
68       DP("Attempt to re-associate the same device ptr+offset with the same "
69          "host ptr, nothing to do\n");
70       return OFFLOAD_SUCCESS;
71     } else {
72       REPORT("Not allowed to re-associate a different device ptr+offset with "
73              "the same host ptr\n");
74       return OFFLOAD_FAIL;
75     }
76   }
77 
78   // Mapping does not exist, allocate it with refCount=INF
79   const HostDataToTargetTy &newEntry =
80       *HostDataToTargetMap
81            .emplace(
82                /*HstPtrBase=*/(uintptr_t)HstPtrBegin,
83                /*HstPtrBegin=*/(uintptr_t)HstPtrBegin,
84                /*HstPtrEnd=*/(uintptr_t)HstPtrBegin + Size,
85                /*TgtPtrBegin=*/(uintptr_t)TgtPtrBegin, /*Name=*/nullptr,
86                /*IsRefCountINF=*/true)
87            .first;
88   DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD
89      ", HstEnd=" DPxMOD ", TgtBegin=" DPxMOD ", RefCount=%s\n",
90      DPxPTR(newEntry.HstPtrBase), DPxPTR(newEntry.HstPtrBegin),
91      DPxPTR(newEntry.HstPtrEnd), DPxPTR(newEntry.TgtPtrBegin),
92      newEntry.refCountToStr().c_str());
93 
94   DataMapMtx.unlock();
95 
96   return OFFLOAD_SUCCESS;
97 }
98 
99 int DeviceTy::disassociatePtr(void *HstPtrBegin) {
100   DataMapMtx.lock();
101 
102   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
103   if (search != HostDataToTargetMap.end()) {
104     // Mapping exists
105     if (search->isRefCountInf()) {
106       DP("Association found, removing it\n");
107       HostDataToTargetMap.erase(search);
108       DataMapMtx.unlock();
109       return OFFLOAD_SUCCESS;
110     } else {
111       REPORT("Trying to disassociate a pointer which was not mapped via "
112              "omp_target_associate_ptr\n");
113     }
114   }
115 
116   // Mapping not found
117   DataMapMtx.unlock();
118   REPORT("Association not found\n");
119   return OFFLOAD_FAIL;
120 }
121 
122 // Get ref count of map entry containing HstPtrBegin
123 uint64_t DeviceTy::getMapEntryRefCnt(void *HstPtrBegin) {
124   uintptr_t hp = (uintptr_t)HstPtrBegin;
125   uint64_t RefCnt = 0;
126 
127   DataMapMtx.lock();
128   if (!HostDataToTargetMap.empty()) {
129     auto upper = HostDataToTargetMap.upper_bound(hp);
130     if (upper != HostDataToTargetMap.begin()) {
131       upper--;
132       if (hp >= upper->HstPtrBegin && hp < upper->HstPtrEnd) {
133         DP("DeviceTy::getMapEntry: requested entry found\n");
134         RefCnt = upper->getRefCount();
135       }
136     }
137   }
138   DataMapMtx.unlock();
139 
140   if (RefCnt == 0) {
141     DP("DeviceTy::getMapEntry: requested entry not found\n");
142   }
143 
144   return RefCnt;
145 }
146 
147 LookupResult DeviceTy::lookupMapping(void *HstPtrBegin, int64_t Size) {
148   uintptr_t hp = (uintptr_t)HstPtrBegin;
149   LookupResult lr;
150 
151   DP("Looking up mapping(HstPtrBegin=" DPxMOD ", Size=%" PRId64 ")...\n",
152      DPxPTR(hp), Size);
153 
154   if (HostDataToTargetMap.empty())
155     return lr;
156 
157   auto upper = HostDataToTargetMap.upper_bound(hp);
158   // check the left bin
159   if (upper != HostDataToTargetMap.begin()) {
160     lr.Entry = std::prev(upper);
161     auto &HT = *lr.Entry;
162     // Is it contained?
163     lr.Flags.IsContained = hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd &&
164                            (hp + Size) <= HT.HstPtrEnd;
165     // Does it extend beyond the mapped region?
166     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
167   }
168 
169   // check the right bin
170   if (!(lr.Flags.IsContained || lr.Flags.ExtendsAfter) &&
171       upper != HostDataToTargetMap.end()) {
172     lr.Entry = upper;
173     auto &HT = *lr.Entry;
174     // Does it extend into an already mapped region?
175     lr.Flags.ExtendsBefore =
176         hp < HT.HstPtrBegin && (hp + Size) > HT.HstPtrBegin;
177     // Does it extend beyond the mapped region?
178     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
179   }
180 
181   if (lr.Flags.ExtendsBefore) {
182     DP("WARNING: Pointer is not mapped but section extends into already "
183        "mapped data\n");
184   }
185   if (lr.Flags.ExtendsAfter) {
186     DP("WARNING: Pointer is already mapped but section extends beyond mapped "
187        "region\n");
188   }
189 
190   return lr;
191 }
192 
193 // Used by targetDataBegin
194 // Return a struct containing target pointer begin (where the data will be
195 // moved).
196 // Allocate memory if this is the first occurrence of this mapping.
197 // Increment the reference counter.
198 // If the target pointer is NULL, then either data allocation failed or the user
199 // tried to do an illegal mapping.
200 // The returned struct also returns an iterator to the map table entry
201 // corresponding to the host pointer (if exists), and two flags indicating
202 // whether the entry is just created, and if the target pointer included is
203 // actually a host pointer (when unified memory enabled).
204 TargetPointerResultTy
205 DeviceTy::getOrAllocTgtPtr(void *HstPtrBegin, void *HstPtrBase, int64_t Size,
206                            map_var_info_t HstPtrName, bool IsImplicit,
207                            bool UpdateRefCount, bool HasCloseModifier,
208                            bool HasPresentModifier) {
209   void *TargetPointer = NULL;
210   bool IsNew = false;
211   bool IsHostPtr = false;
212   DataMapMtx.lock();
213   LookupResult LR = lookupMapping(HstPtrBegin, Size);
214   auto Entry = LR.Entry;
215 
216   // Check if the pointer is contained.
217   // If a variable is mapped to the device manually by the user - which would
218   // lead to the IsContained flag to be true - then we must ensure that the
219   // device address is returned even under unified memory conditions.
220   if (LR.Flags.IsContained ||
221       ((LR.Flags.ExtendsBefore || LR.Flags.ExtendsAfter) && IsImplicit)) {
222     auto &HT = *LR.Entry;
223     if (UpdateRefCount)
224       HT.incRefCount();
225     uintptr_t Ptr = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
226     INFO(OMP_INFOTYPE_MAPPING_EXISTS, DeviceID,
227          "Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
228          ", "
229          "Size=%" PRId64 ", RefCount=%s (%s), Name=%s\n",
230          (IsImplicit ? " (implicit)" : ""), DPxPTR(HstPtrBegin), DPxPTR(Ptr),
231          Size, HT.refCountToStr().c_str(),
232          UpdateRefCount ? "incremented" : "update suppressed",
233          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
234     TargetPointer = (void *)Ptr;
235   } else if ((LR.Flags.ExtendsBefore || LR.Flags.ExtendsAfter) && !IsImplicit) {
236     // Explicit extension of mapped data - not allowed.
237     MESSAGE("explicit extension not allowed: host address specified is " DPxMOD
238             " (%" PRId64
239             " bytes), but device allocation maps to host at " DPxMOD
240             " (%" PRId64 " bytes)",
241             DPxPTR(HstPtrBegin), Size, DPxPTR(Entry->HstPtrBegin),
242             Entry->HstPtrEnd - Entry->HstPtrBegin);
243     if (HasPresentModifier)
244       MESSAGE("device mapping required by 'present' map type modifier does not "
245               "exist for host address " DPxMOD " (%" PRId64 " bytes)",
246               DPxPTR(HstPtrBegin), Size);
247   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
248              !HasCloseModifier) {
249     // If unified shared memory is active, implicitly mapped variables that are
250     // not privatized use host address. Any explicitly mapped variables also use
251     // host address where correctness is not impeded. In all other cases maps
252     // are respected.
253     // In addition to the mapping rules above, the close map modifier forces the
254     // mapping of the variable to the device.
255     if (Size) {
256       DP("Return HstPtrBegin " DPxMOD " Size=%" PRId64 " for unified shared "
257          "memory\n",
258          DPxPTR((uintptr_t)HstPtrBegin), Size);
259       IsHostPtr = true;
260       TargetPointer = HstPtrBegin;
261     }
262   } else if (HasPresentModifier) {
263     DP("Mapping required by 'present' map type modifier does not exist for "
264        "HstPtrBegin=" DPxMOD ", Size=%" PRId64 "\n",
265        DPxPTR(HstPtrBegin), Size);
266     MESSAGE("device mapping required by 'present' map type modifier does not "
267             "exist for host address " DPxMOD " (%" PRId64 " bytes)",
268             DPxPTR(HstPtrBegin), Size);
269   } else if (Size) {
270     // If it is not contained and Size > 0, we should create a new entry for it.
271     IsNew = true;
272     uintptr_t Ptr = (uintptr_t)allocData(Size, HstPtrBegin);
273     Entry = HostDataToTargetMap
274                 .emplace((uintptr_t)HstPtrBase, (uintptr_t)HstPtrBegin,
275                          (uintptr_t)HstPtrBegin + Size, Ptr, HstPtrName)
276                 .first;
277     INFO(OMP_INFOTYPE_MAPPING_CHANGED, DeviceID,
278          "Creating new map entry with "
279          "HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", Size=%ld, "
280          "RefCount=%s, Name=%s\n",
281          DPxPTR(HstPtrBegin), DPxPTR(Ptr), Size, Entry->refCountToStr().c_str(),
282          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
283     TargetPointer = (void *)Ptr;
284   }
285 
286   DataMapMtx.unlock();
287   return {{IsNew, IsHostPtr}, Entry, TargetPointer};
288 }
289 
290 // Used by targetDataBegin, targetDataEnd, targetDataUpdate and target.
291 // Return the target pointer begin (where the data will be moved).
292 // Decrement the reference counter if called from targetDataEnd.
293 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
294                                bool UpdateRefCount, bool &IsHostPtr,
295                                bool MustContain, bool ForceDelete) {
296   void *rc = NULL;
297   IsHostPtr = false;
298   IsLast = false;
299   DataMapMtx.lock();
300   LookupResult lr = lookupMapping(HstPtrBegin, Size);
301 
302   if (lr.Flags.IsContained ||
303       (!MustContain && (lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter))) {
304     auto &HT = *lr.Entry;
305     // We do not decrement the reference count to zero here.  deallocTgtPtr does
306     // that atomically with removing the mapping.  Otherwise, before this thread
307     // removed the mapping in deallocTgtPtr, another thread could retrieve the
308     // mapping, increment and decrement back to zero, and then both threads
309     // would try to remove the mapping, resulting in a double free.
310     IsLast = HT.decShouldRemove(ForceDelete);
311     const char *RefCountAction;
312     if (!UpdateRefCount) {
313       RefCountAction = "update suppressed";
314     } else if (ForceDelete) {
315       HT.resetRefCount();
316       assert(IsLast == HT.decShouldRemove() &&
317              "expected correct IsLast prediction for reset");
318       if (IsLast)
319         RefCountAction = "reset, deferred final decrement";
320       else
321         RefCountAction = "reset";
322     } else if (IsLast) {
323       RefCountAction = "deferred final decrement";
324     } else {
325       RefCountAction = "decremented";
326       HT.decRefCount();
327     }
328     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
329     INFO(OMP_INFOTYPE_MAPPING_EXISTS, DeviceID,
330          "Mapping exists with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
331          "Size=%" PRId64 ", RefCount=%s (%s)\n",
332          DPxPTR(HstPtrBegin), DPxPTR(tp), Size, HT.refCountToStr().c_str(),
333          RefCountAction);
334     rc = (void *)tp;
335   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
336     // If the value isn't found in the mapping and unified shared memory
337     // is on then it means we have stumbled upon a value which we need to
338     // use directly from the host.
339     DP("Get HstPtrBegin " DPxMOD " Size=%" PRId64 " for unified shared "
340        "memory\n",
341        DPxPTR((uintptr_t)HstPtrBegin), Size);
342     IsHostPtr = true;
343     rc = HstPtrBegin;
344   }
345 
346   DataMapMtx.unlock();
347   return rc;
348 }
349 
350 // Return the target pointer begin (where the data will be moved).
351 // Lock-free version called when loading global symbols from the fat binary.
352 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
353   uintptr_t hp = (uintptr_t)HstPtrBegin;
354   LookupResult lr = lookupMapping(HstPtrBegin, Size);
355   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
356     auto &HT = *lr.Entry;
357     uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
358     return (void *)tp;
359   }
360 
361   return NULL;
362 }
363 
364 int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size,
365                             bool HasCloseModifier) {
366   if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
367       !HasCloseModifier)
368     return OFFLOAD_SUCCESS;
369   // Check if the pointer is contained in any sub-nodes.
370   int rc;
371   DataMapMtx.lock();
372   LookupResult lr = lookupMapping(HstPtrBegin, Size);
373   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
374     auto &HT = *lr.Entry;
375     if (HT.decRefCount() == 0) {
376       DP("Deleting tgt data " DPxMOD " of size %" PRId64 "\n",
377          DPxPTR(HT.TgtPtrBegin), Size);
378       deleteData((void *)HT.TgtPtrBegin);
379       INFO(OMP_INFOTYPE_MAPPING_CHANGED, DeviceID,
380            "Removing map entry with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
381            ", Size=%" PRId64 ", Name=%s\n",
382            DPxPTR(HT.HstPtrBegin), DPxPTR(HT.TgtPtrBegin), Size,
383            (HT.HstPtrName) ? getNameFromMapping(HT.HstPtrName).c_str()
384                            : "unknown");
385       HostDataToTargetMap.erase(lr.Entry);
386     }
387     rc = OFFLOAD_SUCCESS;
388   } else {
389     REPORT("Section to delete (hst addr " DPxMOD ") does not exist in the"
390            " allocated memory\n",
391            DPxPTR(HstPtrBegin));
392     rc = OFFLOAD_FAIL;
393   }
394 
395   DataMapMtx.unlock();
396   return rc;
397 }
398 
399 /// Init device, should not be called directly.
400 void DeviceTy::init() {
401   // Make call to init_requires if it exists for this plugin.
402   if (RTL->init_requires)
403     RTL->init_requires(PM->RTLs.RequiresFlags);
404   int32_t Ret = RTL->init_device(RTLDeviceID);
405   if (Ret != OFFLOAD_SUCCESS)
406     return;
407 
408   IsInit = true;
409 }
410 
411 /// Thread-safe method to initialize the device only once.
412 int32_t DeviceTy::initOnce() {
413   std::call_once(InitFlag, &DeviceTy::init, this);
414 
415   // At this point, if IsInit is true, then either this thread or some other
416   // thread in the past successfully initialized the device, so we can return
417   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
418   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
419   // that some other thread already attempted to execute init() and if IsInit
420   // is still false, return OFFLOAD_FAIL.
421   if (IsInit)
422     return OFFLOAD_SUCCESS;
423   else
424     return OFFLOAD_FAIL;
425 }
426 
427 // Load binary to device.
428 __tgt_target_table *DeviceTy::load_binary(void *Img) {
429   RTL->Mtx.lock();
430   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
431   RTL->Mtx.unlock();
432   return rc;
433 }
434 
435 void *DeviceTy::allocData(int64_t Size, void *HstPtr, int32_t Kind) {
436   return RTL->data_alloc(RTLDeviceID, Size, HstPtr, Kind);
437 }
438 
439 int32_t DeviceTy::deleteData(void *TgtPtrBegin) {
440   return RTL->data_delete(RTLDeviceID, TgtPtrBegin);
441 }
442 
443 // Submit data to device
444 int32_t DeviceTy::submitData(void *TgtPtrBegin, void *HstPtrBegin, int64_t Size,
445                              AsyncInfoTy &AsyncInfo) {
446   if (getInfoLevel() & OMP_INFOTYPE_DATA_TRANSFER) {
447     LookupResult LR = lookupMapping(HstPtrBegin, Size);
448     auto *HT = &*LR.Entry;
449 
450     INFO(OMP_INFOTYPE_DATA_TRANSFER, DeviceID,
451          "Copying data from host to device, HstPtr=" DPxMOD ", TgtPtr=" DPxMOD
452          ", Size=%" PRId64 ", Name=%s\n",
453          DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin), Size,
454          (HT && HT->HstPtrName) ? getNameFromMapping(HT->HstPtrName).c_str()
455                                 : "unknown");
456   }
457 
458   if (!AsyncInfo || !RTL->data_submit_async || !RTL->synchronize)
459     return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
460   else
461     return RTL->data_submit_async(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size,
462                                   AsyncInfo);
463 }
464 
465 // Retrieve data from device
466 int32_t DeviceTy::retrieveData(void *HstPtrBegin, void *TgtPtrBegin,
467                                int64_t Size, AsyncInfoTy &AsyncInfo) {
468   if (getInfoLevel() & OMP_INFOTYPE_DATA_TRANSFER) {
469     LookupResult LR = lookupMapping(HstPtrBegin, Size);
470     auto *HT = &*LR.Entry;
471     INFO(OMP_INFOTYPE_DATA_TRANSFER, DeviceID,
472          "Copying data from device to host, TgtPtr=" DPxMOD ", HstPtr=" DPxMOD
473          ", Size=%" PRId64 ", Name=%s\n",
474          DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin), Size,
475          (HT && HT->HstPtrName) ? getNameFromMapping(HT->HstPtrName).c_str()
476                                 : "unknown");
477   }
478 
479   if (!RTL->data_retrieve_async || !RTL->synchronize)
480     return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
481   else
482     return RTL->data_retrieve_async(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size,
483                                     AsyncInfo);
484 }
485 
486 // Copy data from current device to destination device directly
487 int32_t DeviceTy::dataExchange(void *SrcPtr, DeviceTy &DstDev, void *DstPtr,
488                                int64_t Size, AsyncInfoTy &AsyncInfo) {
489   if (!AsyncInfo || !RTL->data_exchange_async || !RTL->synchronize) {
490     assert(RTL->data_exchange && "RTL->data_exchange is nullptr");
491     return RTL->data_exchange(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID, DstPtr,
492                               Size);
493   } else
494     return RTL->data_exchange_async(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID,
495                                     DstPtr, Size, AsyncInfo);
496 }
497 
498 // Run region on device
499 int32_t DeviceTy::runRegion(void *TgtEntryPtr, void **TgtVarsPtr,
500                             ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
501                             AsyncInfoTy &AsyncInfo) {
502   if (!RTL->run_region || !RTL->synchronize)
503     return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
504                            TgtVarsSize);
505   else
506     return RTL->run_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
507                                  TgtOffsets, TgtVarsSize, AsyncInfo);
508 }
509 
510 // Run team region on device.
511 int32_t DeviceTy::runTeamRegion(void *TgtEntryPtr, void **TgtVarsPtr,
512                                 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
513                                 int32_t NumTeams, int32_t ThreadLimit,
514                                 uint64_t LoopTripCount,
515                                 AsyncInfoTy &AsyncInfo) {
516   if (!RTL->run_team_region_async || !RTL->synchronize)
517     return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
518                                 TgtOffsets, TgtVarsSize, NumTeams, ThreadLimit,
519                                 LoopTripCount);
520   else
521     return RTL->run_team_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
522                                       TgtOffsets, TgtVarsSize, NumTeams,
523                                       ThreadLimit, LoopTripCount, AsyncInfo);
524 }
525 
526 // Whether data can be copied to DstDevice directly
527 bool DeviceTy::isDataExchangable(const DeviceTy &DstDevice) {
528   if (RTL != DstDevice.RTL || !RTL->is_data_exchangable)
529     return false;
530 
531   if (RTL->is_data_exchangable(RTLDeviceID, DstDevice.RTLDeviceID))
532     return (RTL->data_exchange != nullptr) ||
533            (RTL->data_exchange_async != nullptr);
534 
535   return false;
536 }
537 
538 int32_t DeviceTy::synchronize(AsyncInfoTy &AsyncInfo) {
539   if (RTL->synchronize)
540     return RTL->synchronize(RTLDeviceID, AsyncInfo);
541   return OFFLOAD_SUCCESS;
542 }
543 
544 /// Check whether a device has an associated RTL and initialize it if it's not
545 /// already initialized.
546 bool device_is_ready(int device_num) {
547   DP("Checking whether device %d is ready.\n", device_num);
548   // Devices.size() can only change while registering a new
549   // library, so try to acquire the lock of RTLs' mutex.
550   PM->RTLsMtx.lock();
551   size_t DevicesSize = PM->Devices.size();
552   PM->RTLsMtx.unlock();
553   if (DevicesSize <= (size_t)device_num) {
554     DP("Device ID  %d does not have a matching RTL\n", device_num);
555     return false;
556   }
557 
558   // Get device info
559   DeviceTy &Device = PM->Devices[device_num];
560 
561   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
562      Device.RTLDeviceID, Device.IsInit);
563 
564   // Init the device if not done before
565   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
566     DP("Failed to init device %d\n", device_num);
567     return false;
568   }
569 
570   DP("Device %d is ready to use.\n", device_num);
571 
572   return true;
573 }
574