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