1 //===------ omptarget.cpp - Target independent OpenMP target RTL -- 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 // Implementation of the interface to be used by Clang during the codegen of a
10 // target region.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "omptarget.h"
15 #include "device.h"
16 #include "private.h"
17 #include "rtl.h"
18 
19 #include <cassert>
20 #include <cstdint>
21 #include <vector>
22 
23 int AsyncInfoTy::synchronize() {
24   int Result = OFFLOAD_SUCCESS;
25   if (AsyncInfo.Queue) {
26     // If we have a queue we need to synchronize it now.
27     Result = Device.synchronize(*this);
28     assert(AsyncInfo.Queue == nullptr &&
29            "The device plugin should have nulled the queue to indicate there "
30            "are no outstanding actions!");
31   }
32   return Result;
33 }
34 
35 void *&AsyncInfoTy::getVoidPtrLocation() {
36   BufferLocations.push_back(nullptr);
37   return BufferLocations.back();
38 }
39 
40 /* All begin addresses for partially mapped structs must be 8-aligned in order
41  * to ensure proper alignment of members. E.g.
42  *
43  * struct S {
44  *   int a;   // 4-aligned
45  *   int b;   // 4-aligned
46  *   int *p;  // 8-aligned
47  * } s1;
48  * ...
49  * #pragma omp target map(tofrom: s1.b, s1.p[0:N])
50  * {
51  *   s1.b = 5;
52  *   for (int i...) s1.p[i] = ...;
53  * }
54  *
55  * Here we are mapping s1 starting from member b, so BaseAddress=&s1=&s1.a and
56  * BeginAddress=&s1.b. Let's assume that the struct begins at address 0x100,
57  * then &s1.a=0x100, &s1.b=0x104, &s1.p=0x108. Each member obeys the alignment
58  * requirements for its type. Now, when we allocate memory on the device, in
59  * CUDA's case cuMemAlloc() returns an address which is at least 256-aligned.
60  * This means that the chunk of the struct on the device will start at a
61  * 256-aligned address, let's say 0x200. Then the address of b will be 0x200 and
62  * address of p will be a misaligned 0x204 (on the host there was no need to add
63  * padding between b and p, so p comes exactly 4 bytes after b). If the device
64  * kernel tries to access s1.p, a misaligned address error occurs (as reported
65  * by the CUDA plugin). By padding the begin address down to a multiple of 8 and
66  * extending the size of the allocated chuck accordingly, the chuck on the
67  * device will start at 0x200 with the padding (4 bytes), then &s1.b=0x204 and
68  * &s1.p=0x208, as they should be to satisfy the alignment requirements.
69  */
70 static const int64_t Alignment = 8;
71 
72 /// Map global data and execute pending ctors
73 static int InitLibrary(DeviceTy &Device) {
74   /*
75    * Map global data
76    */
77   int32_t device_id = Device.DeviceID;
78   int rc = OFFLOAD_SUCCESS;
79   bool supportsEmptyImages = Device.RTL->supports_empty_images &&
80                              Device.RTL->supports_empty_images() > 0;
81 
82   Device.PendingGlobalsMtx.lock();
83   PM->TrlTblMtx.lock();
84   for (auto *HostEntriesBegin : PM->HostEntriesBeginRegistrationOrder) {
85     TranslationTable *TransTable =
86         &PM->HostEntriesBeginToTransTable[HostEntriesBegin];
87     if (TransTable->HostTable.EntriesBegin ==
88             TransTable->HostTable.EntriesEnd &&
89         !supportsEmptyImages) {
90       // No host entry so no need to proceed
91       continue;
92     }
93 
94     if (TransTable->TargetsTable[device_id] != 0) {
95       // Library entries have already been processed
96       continue;
97     }
98 
99     // 1) get image.
100     assert(TransTable->TargetsImages.size() > (size_t)device_id &&
101            "Not expecting a device ID outside the table's bounds!");
102     __tgt_device_image *img = TransTable->TargetsImages[device_id];
103     if (!img) {
104       REPORT("No image loaded for device id %d.\n", device_id);
105       rc = OFFLOAD_FAIL;
106       break;
107     }
108     // 2) load image into the target table.
109     __tgt_target_table *TargetTable = TransTable->TargetsTable[device_id] =
110         Device.load_binary(img);
111     // Unable to get table for this image: invalidate image and fail.
112     if (!TargetTable) {
113       REPORT("Unable to generate entries table for device id %d.\n", device_id);
114       TransTable->TargetsImages[device_id] = 0;
115       rc = OFFLOAD_FAIL;
116       break;
117     }
118 
119     // Verify whether the two table sizes match.
120     size_t hsize =
121         TransTable->HostTable.EntriesEnd - TransTable->HostTable.EntriesBegin;
122     size_t tsize = TargetTable->EntriesEnd - TargetTable->EntriesBegin;
123 
124     // Invalid image for these host entries!
125     if (hsize != tsize) {
126       REPORT("Host and Target tables mismatch for device id %d [%zx != %zx].\n",
127              device_id, hsize, tsize);
128       TransTable->TargetsImages[device_id] = 0;
129       TransTable->TargetsTable[device_id] = 0;
130       rc = OFFLOAD_FAIL;
131       break;
132     }
133 
134     // process global data that needs to be mapped.
135     Device.DataMapMtx.lock();
136     __tgt_target_table *HostTable = &TransTable->HostTable;
137     for (__tgt_offload_entry *CurrDeviceEntry = TargetTable->EntriesBegin,
138                              *CurrHostEntry = HostTable->EntriesBegin,
139                              *EntryDeviceEnd = TargetTable->EntriesEnd;
140          CurrDeviceEntry != EntryDeviceEnd;
141          CurrDeviceEntry++, CurrHostEntry++) {
142       if (CurrDeviceEntry->size != 0) {
143         // has data.
144         assert(CurrDeviceEntry->size == CurrHostEntry->size &&
145                "data size mismatch");
146 
147         // Fortran may use multiple weak declarations for the same symbol,
148         // therefore we must allow for multiple weak symbols to be loaded from
149         // the fat binary. Treat these mappings as any other "regular" mapping.
150         // Add entry to map.
151         if (Device.getTgtPtrBegin(CurrHostEntry->addr, CurrHostEntry->size))
152           continue;
153         DP("Add mapping from host " DPxMOD " to device " DPxMOD " with size %zu"
154            "\n",
155            DPxPTR(CurrHostEntry->addr), DPxPTR(CurrDeviceEntry->addr),
156            CurrDeviceEntry->size);
157         Device.HostDataToTargetMap.emplace(
158             (uintptr_t)CurrHostEntry->addr /*HstPtrBase*/,
159             (uintptr_t)CurrHostEntry->addr /*HstPtrBegin*/,
160             (uintptr_t)CurrHostEntry->addr + CurrHostEntry->size /*HstPtrEnd*/,
161             (uintptr_t)CurrDeviceEntry->addr /*TgtPtrBegin*/,
162             false /*UseHoldRefCount*/, nullptr /*Name*/,
163             true /*IsRefCountINF*/);
164       }
165     }
166     Device.DataMapMtx.unlock();
167   }
168   PM->TrlTblMtx.unlock();
169 
170   if (rc != OFFLOAD_SUCCESS) {
171     Device.PendingGlobalsMtx.unlock();
172     return rc;
173   }
174 
175   /*
176    * Run ctors for static objects
177    */
178   if (!Device.PendingCtorsDtors.empty()) {
179     AsyncInfoTy AsyncInfo(Device);
180     // Call all ctors for all libraries registered so far
181     for (auto &lib : Device.PendingCtorsDtors) {
182       if (!lib.second.PendingCtors.empty()) {
183         DP("Has pending ctors... call now\n");
184         for (auto &entry : lib.second.PendingCtors) {
185           void *ctor = entry;
186           int rc =
187               target(nullptr, Device, ctor, 0, nullptr, nullptr, nullptr,
188                      nullptr, nullptr, nullptr, 1, 1, true /*team*/, AsyncInfo);
189           if (rc != OFFLOAD_SUCCESS) {
190             REPORT("Running ctor " DPxMOD " failed.\n", DPxPTR(ctor));
191             Device.PendingGlobalsMtx.unlock();
192             return OFFLOAD_FAIL;
193           }
194         }
195         // Clear the list to indicate that this device has been used
196         lib.second.PendingCtors.clear();
197         DP("Done with pending ctors for lib " DPxMOD "\n", DPxPTR(lib.first));
198       }
199     }
200     // All constructors have been issued, wait for them now.
201     if (AsyncInfo.synchronize() != OFFLOAD_SUCCESS)
202       return OFFLOAD_FAIL;
203   }
204   Device.HasPendingGlobals = false;
205   Device.PendingGlobalsMtx.unlock();
206 
207   return OFFLOAD_SUCCESS;
208 }
209 
210 void handleTargetOutcome(bool Success, ident_t *Loc) {
211   switch (PM->TargetOffloadPolicy) {
212   case tgt_disabled:
213     if (Success) {
214       FATAL_MESSAGE0(1, "expected no offloading while offloading is disabled");
215     }
216     break;
217   case tgt_default:
218     FATAL_MESSAGE0(1, "default offloading policy must be switched to "
219                       "mandatory or disabled");
220     break;
221   case tgt_mandatory:
222     if (!Success) {
223       if (getInfoLevel() & OMP_INFOTYPE_DUMP_TABLE)
224         for (auto &Device : PM->Devices)
225           dumpTargetPointerMappings(Loc, *Device);
226       else
227         FAILURE_MESSAGE("Consult https://openmp.llvm.org/design/Runtimes.html "
228                         "for debugging options.\n");
229 
230       SourceInfo info(Loc);
231       if (info.isAvailible())
232         fprintf(stderr, "%s:%d:%d: ", info.getFilename(), info.getLine(),
233                 info.getColumn());
234       else
235         FAILURE_MESSAGE("Source location information not present. Compile with "
236                         "-g or -gline-tables-only.\n");
237       FATAL_MESSAGE0(
238           1, "failure of target construct while offloading is mandatory");
239     } else {
240       if (getInfoLevel() & OMP_INFOTYPE_DUMP_TABLE)
241         for (auto &Device : PM->Devices)
242           dumpTargetPointerMappings(Loc, *Device);
243     }
244     break;
245   }
246 }
247 
248 static void handleDefaultTargetOffload() {
249   PM->TargetOffloadMtx.lock();
250   if (PM->TargetOffloadPolicy == tgt_default) {
251     if (omp_get_num_devices() > 0) {
252       DP("Default TARGET OFFLOAD policy is now mandatory "
253          "(devices were found)\n");
254       PM->TargetOffloadPolicy = tgt_mandatory;
255     } else {
256       DP("Default TARGET OFFLOAD policy is now disabled "
257          "(no devices were found)\n");
258       PM->TargetOffloadPolicy = tgt_disabled;
259     }
260   }
261   PM->TargetOffloadMtx.unlock();
262 }
263 
264 static bool isOffloadDisabled() {
265   if (PM->TargetOffloadPolicy == tgt_default)
266     handleDefaultTargetOffload();
267   return PM->TargetOffloadPolicy == tgt_disabled;
268 }
269 
270 // If offload is enabled, ensure that device DeviceID has been initialized,
271 // global ctors have been executed, and global data has been mapped.
272 //
273 // The return bool indicates if the offload is to the host device
274 // There are three possible results:
275 // - Return false if the taregt device is ready for offload
276 // - Return true without reporting a runtime error if offload is
277 //   disabled, perhaps because the initial device was specified.
278 // - Report a runtime error and return true.
279 //
280 // If DeviceID == OFFLOAD_DEVICE_DEFAULT, set DeviceID to the default device.
281 // This step might be skipped if offload is disabled.
282 bool checkDeviceAndCtors(int64_t &DeviceID, ident_t *Loc) {
283   if (isOffloadDisabled()) {
284     DP("Offload is disabled\n");
285     return true;
286   }
287 
288   if (DeviceID == OFFLOAD_DEVICE_DEFAULT) {
289     DeviceID = omp_get_default_device();
290     DP("Use default device id %" PRId64 "\n", DeviceID);
291   }
292 
293   // Proposed behavior for OpenMP 5.2 in OpenMP spec github issue 2669.
294   if (omp_get_num_devices() == 0) {
295     DP("omp_get_num_devices() == 0 but offload is manadatory\n");
296     handleTargetOutcome(false, Loc);
297     return true;
298   }
299 
300   if (DeviceID == omp_get_initial_device()) {
301     DP("Device is host (%" PRId64 "), returning as if offload is disabled\n",
302        DeviceID);
303     return true;
304   }
305 
306   // Is device ready?
307   if (!device_is_ready(DeviceID)) {
308     REPORT("Device %" PRId64 " is not ready.\n", DeviceID);
309     handleTargetOutcome(false, Loc);
310     return true;
311   }
312 
313   // Get device info.
314   DeviceTy &Device = *PM->Devices[DeviceID];
315 
316   // Check whether global data has been mapped for this device
317   Device.PendingGlobalsMtx.lock();
318   bool hasPendingGlobals = Device.HasPendingGlobals;
319   Device.PendingGlobalsMtx.unlock();
320   if (hasPendingGlobals && InitLibrary(Device) != OFFLOAD_SUCCESS) {
321     REPORT("Failed to init globals on device %" PRId64 "\n", DeviceID);
322     handleTargetOutcome(false, Loc);
323     return true;
324   }
325 
326   return false;
327 }
328 
329 static int32_t getParentIndex(int64_t type) {
330   return ((type & OMP_TGT_MAPTYPE_MEMBER_OF) >> 48) - 1;
331 }
332 
333 void *targetAllocExplicit(size_t size, int device_num, int kind,
334                           const char *name) {
335   TIMESCOPE();
336   DP("Call to %s for device %d requesting %zu bytes\n", name, device_num, size);
337 
338   if (size <= 0) {
339     DP("Call to %s with non-positive length\n", name);
340     return NULL;
341   }
342 
343   void *rc = NULL;
344 
345   if (device_num == omp_get_initial_device()) {
346     rc = malloc(size);
347     DP("%s returns host ptr " DPxMOD "\n", name, DPxPTR(rc));
348     return rc;
349   }
350 
351   if (!device_is_ready(device_num)) {
352     DP("%s returns NULL ptr\n", name);
353     return NULL;
354   }
355 
356   DeviceTy &Device = *PM->Devices[device_num];
357   rc = Device.allocData(size, nullptr, kind);
358   DP("%s returns device ptr " DPxMOD "\n", name, DPxPTR(rc));
359   return rc;
360 }
361 
362 /// Call the user-defined mapper function followed by the appropriate
363 // targetData* function (targetData{Begin,End,Update}).
364 int targetDataMapper(ident_t *loc, DeviceTy &Device, void *arg_base, void *arg,
365                      int64_t arg_size, int64_t arg_type,
366                      map_var_info_t arg_names, void *arg_mapper,
367                      AsyncInfoTy &AsyncInfo,
368                      TargetDataFuncPtrTy target_data_function) {
369   TIMESCOPE_WITH_IDENT(loc);
370   DP("Calling the mapper function " DPxMOD "\n", DPxPTR(arg_mapper));
371 
372   // The mapper function fills up Components.
373   MapperComponentsTy MapperComponents;
374   MapperFuncPtrTy MapperFuncPtr = (MapperFuncPtrTy)(arg_mapper);
375   (*MapperFuncPtr)((void *)&MapperComponents, arg_base, arg, arg_size, arg_type,
376                    arg_names);
377 
378   // Construct new arrays for args_base, args, arg_sizes and arg_types
379   // using the information in MapperComponents and call the corresponding
380   // targetData* function using these new arrays.
381   std::vector<void *> MapperArgsBase(MapperComponents.Components.size());
382   std::vector<void *> MapperArgs(MapperComponents.Components.size());
383   std::vector<int64_t> MapperArgSizes(MapperComponents.Components.size());
384   std::vector<int64_t> MapperArgTypes(MapperComponents.Components.size());
385   std::vector<void *> MapperArgNames(MapperComponents.Components.size());
386 
387   for (unsigned I = 0, E = MapperComponents.Components.size(); I < E; ++I) {
388     auto &C = MapperComponents.Components[I];
389     MapperArgsBase[I] = C.Base;
390     MapperArgs[I] = C.Begin;
391     MapperArgSizes[I] = C.Size;
392     MapperArgTypes[I] = C.Type;
393     MapperArgNames[I] = C.Name;
394   }
395 
396   int rc = target_data_function(loc, Device, MapperComponents.Components.size(),
397                                 MapperArgsBase.data(), MapperArgs.data(),
398                                 MapperArgSizes.data(), MapperArgTypes.data(),
399                                 MapperArgNames.data(), /*arg_mappers*/ nullptr,
400                                 AsyncInfo, /*FromMapper=*/true);
401 
402   return rc;
403 }
404 
405 /// Internal function to do the mapping and transfer the data to the device
406 int targetDataBegin(ident_t *loc, DeviceTy &Device, int32_t arg_num,
407                     void **args_base, void **args, int64_t *arg_sizes,
408                     int64_t *arg_types, map_var_info_t *arg_names,
409                     void **arg_mappers, AsyncInfoTy &AsyncInfo,
410                     bool FromMapper) {
411   // process each input.
412   for (int32_t i = 0; i < arg_num; ++i) {
413     // Ignore private variables and arrays - there is no mapping for them.
414     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
415         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
416       continue;
417 
418     if (arg_mappers && arg_mappers[i]) {
419       // Instead of executing the regular path of targetDataBegin, call the
420       // targetDataMapper variant which will call targetDataBegin again
421       // with new arguments.
422       DP("Calling targetDataMapper for the %dth argument\n", i);
423 
424       map_var_info_t arg_name = (!arg_names) ? nullptr : arg_names[i];
425       int rc = targetDataMapper(loc, Device, args_base[i], args[i],
426                                 arg_sizes[i], arg_types[i], arg_name,
427                                 arg_mappers[i], AsyncInfo, targetDataBegin);
428 
429       if (rc != OFFLOAD_SUCCESS) {
430         REPORT("Call to targetDataBegin via targetDataMapper for custom mapper"
431                " failed.\n");
432         return OFFLOAD_FAIL;
433       }
434 
435       // Skip the rest of this function, continue to the next argument.
436       continue;
437     }
438 
439     void *HstPtrBegin = args[i];
440     void *HstPtrBase = args_base[i];
441     int64_t data_size = arg_sizes[i];
442     map_var_info_t HstPtrName = (!arg_names) ? nullptr : arg_names[i];
443 
444     // Adjust for proper alignment if this is a combined entry (for structs).
445     // Look at the next argument - if that is MEMBER_OF this one, then this one
446     // is a combined entry.
447     int64_t padding = 0;
448     const int next_i = i + 1;
449     if (getParentIndex(arg_types[i]) < 0 && next_i < arg_num &&
450         getParentIndex(arg_types[next_i]) == i) {
451       padding = (int64_t)HstPtrBegin % Alignment;
452       if (padding) {
453         DP("Using a padding of %" PRId64 " bytes for begin address " DPxMOD
454            "\n",
455            padding, DPxPTR(HstPtrBegin));
456         HstPtrBegin = (char *)HstPtrBegin - padding;
457         data_size += padding;
458       }
459     }
460 
461     // Address of pointer on the host and device, respectively.
462     void *Pointer_HstPtrBegin, *PointerTgtPtrBegin;
463     TargetPointerResultTy Pointer_TPR;
464     bool IsHostPtr = false;
465     bool IsImplicit = arg_types[i] & OMP_TGT_MAPTYPE_IMPLICIT;
466     // Force the creation of a device side copy of the data when:
467     // a close map modifier was associated with a map that contained a to.
468     bool HasCloseModifier = arg_types[i] & OMP_TGT_MAPTYPE_CLOSE;
469     bool HasPresentModifier = arg_types[i] & OMP_TGT_MAPTYPE_PRESENT;
470     bool HasHoldModifier = arg_types[i] & OMP_TGT_MAPTYPE_OMPX_HOLD;
471     // UpdateRef is based on MEMBER_OF instead of TARGET_PARAM because if we
472     // have reached this point via __tgt_target_data_begin and not __tgt_target
473     // then no argument is marked as TARGET_PARAM ("omp target data map" is not
474     // associated with a target region, so there are no target parameters). This
475     // may be considered a hack, we could revise the scheme in the future.
476     bool UpdateRef =
477         !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) && !(FromMapper && i == 0);
478     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
479       DP("Has a pointer entry: \n");
480       // Base is address of pointer.
481       //
482       // Usually, the pointer is already allocated by this time.  For example:
483       //
484       //   #pragma omp target map(s.p[0:N])
485       //
486       // The map entry for s comes first, and the PTR_AND_OBJ entry comes
487       // afterward, so the pointer is already allocated by the time the
488       // PTR_AND_OBJ entry is handled below, and PointerTgtPtrBegin is thus
489       // non-null.  However, "declare target link" can produce a PTR_AND_OBJ
490       // entry for a global that might not already be allocated by the time the
491       // PTR_AND_OBJ entry is handled below, and so the allocation might fail
492       // when HasPresentModifier.
493       Pointer_TPR = Device.getTargetPointer(
494           HstPtrBase, HstPtrBase, sizeof(void *), /*HstPtrName=*/nullptr,
495           /*HasFlagTo=*/false, /*HasFlagAlways=*/false, IsImplicit, UpdateRef,
496           HasCloseModifier, HasPresentModifier, HasHoldModifier, AsyncInfo);
497       PointerTgtPtrBegin = Pointer_TPR.TargetPointer;
498       IsHostPtr = Pointer_TPR.Flags.IsHostPointer;
499       if (!PointerTgtPtrBegin) {
500         REPORT("Call to getTargetPointer returned null pointer (%s).\n",
501                HasPresentModifier ? "'present' map type modifier"
502                                   : "device failure or illegal mapping");
503         return OFFLOAD_FAIL;
504       }
505       DP("There are %zu bytes allocated at target address " DPxMOD " - is%s new"
506          "\n",
507          sizeof(void *), DPxPTR(PointerTgtPtrBegin),
508          (Pointer_TPR.Flags.IsNewEntry ? "" : " not"));
509       Pointer_HstPtrBegin = HstPtrBase;
510       // modify current entry.
511       HstPtrBase = *(void **)HstPtrBase;
512       // No need to update pointee ref count for the first element of the
513       // subelement that comes from mapper.
514       UpdateRef =
515           (!FromMapper || i != 0); // subsequently update ref count of pointee
516     }
517 
518     const bool HasFlagTo = arg_types[i] & OMP_TGT_MAPTYPE_TO;
519     const bool HasFlagAlways = arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS;
520     auto TPR = Device.getTargetPointer(
521         HstPtrBegin, HstPtrBase, data_size, HstPtrName, HasFlagTo,
522         HasFlagAlways, IsImplicit, UpdateRef, HasCloseModifier,
523         HasPresentModifier, HasHoldModifier, AsyncInfo);
524     void *TgtPtrBegin = TPR.TargetPointer;
525     IsHostPtr = TPR.Flags.IsHostPointer;
526     // If data_size==0, then the argument could be a zero-length pointer to
527     // NULL, so getOrAlloc() returning NULL is not an error.
528     if (!TgtPtrBegin && (data_size || HasPresentModifier)) {
529       REPORT("Call to getTargetPointer returned null pointer (%s).\n",
530              HasPresentModifier ? "'present' map type modifier"
531                                 : "device failure or illegal mapping");
532       return OFFLOAD_FAIL;
533     }
534     DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
535        " - is%s new\n",
536        data_size, DPxPTR(TgtPtrBegin), (TPR.Flags.IsNewEntry ? "" : " not"));
537 
538     if (arg_types[i] & OMP_TGT_MAPTYPE_RETURN_PARAM) {
539       uintptr_t Delta = (uintptr_t)HstPtrBegin - (uintptr_t)HstPtrBase;
540       void *TgtPtrBase = (void *)((uintptr_t)TgtPtrBegin - Delta);
541       DP("Returning device pointer " DPxMOD "\n", DPxPTR(TgtPtrBase));
542       args_base[i] = TgtPtrBase;
543     }
544 
545     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ && !IsHostPtr) {
546       // Check whether we need to update the pointer on the device
547       bool UpdateDevPtr = false;
548 
549       uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
550       void *ExpectedTgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
551 
552       Device.ShadowMtx.lock();
553       auto Entry = Device.ShadowPtrMap.find(Pointer_HstPtrBegin);
554       // If this pointer is not in the map we need to insert it. If the map
555       // contains a stale entry, we need to update it (e.g. if the pointee was
556       // deallocated and later on is reallocated at another device address). The
557       // latter scenario is the subject of LIT test env/base_ptr_ref_count.c. An
558       // entry is removed from ShadowPtrMap only when the PTR of a PTR_AND_OBJ
559       // pair is deallocated, not when the OBJ is deallocated. In
560       // env/base_ptr_ref_count.c the PTR is a global "declare target" pointer,
561       // so it stays in the map for the lifetime of the application. When the
562       // OBJ is deallocated and later on allocated again (at a different device
563       // address), ShadowPtrMap still contains an entry for Pointer_HstPtrBegin
564       // which is stale, pointing to the old ExpectedTgtPtrBase of the OBJ.
565       if (Entry == Device.ShadowPtrMap.end() ||
566           Entry->second.TgtPtrVal != ExpectedTgtPtrBase) {
567         // create or update shadow pointers for this entry
568         Device.ShadowPtrMap[Pointer_HstPtrBegin] = {
569             HstPtrBase, PointerTgtPtrBegin, ExpectedTgtPtrBase};
570         Pointer_TPR.MapTableEntry->setMayContainAttachedPointers();
571         UpdateDevPtr = true;
572       }
573 
574       if (UpdateDevPtr) {
575         HostDataToTargetTy::LockGuard LG(*Pointer_TPR.MapTableEntry);
576         Device.ShadowMtx.unlock();
577 
578         DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
579            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
580 
581         void *&TgtPtrBase = AsyncInfo.getVoidPtrLocation();
582         TgtPtrBase = ExpectedTgtPtrBase;
583 
584         int Ret = Device.submitData(PointerTgtPtrBegin, &TgtPtrBase,
585                                     sizeof(void *), AsyncInfo);
586         if (Ret != OFFLOAD_SUCCESS) {
587           REPORT("Copying data to device failed.\n");
588           return OFFLOAD_FAIL;
589         }
590         if (Pointer_TPR.MapTableEntry->addEventIfNecessary(Device, AsyncInfo) !=
591             OFFLOAD_SUCCESS)
592           return OFFLOAD_FAIL;
593       } else
594         Device.ShadowMtx.unlock();
595     }
596   }
597 
598   return OFFLOAD_SUCCESS;
599 }
600 
601 namespace {
602 /// This structure contains information to deallocate a target pointer, aka.
603 /// used to call the function \p DeviceTy::deallocTgtPtr.
604 struct DeallocTgtPtrInfo {
605   /// Host pointer used to look up into the map table
606   void *HstPtrBegin;
607   /// Size of the data
608   int64_t DataSize;
609   /// Whether it has \p ompx_hold modifier
610   bool HasHoldModifier;
611 
612   DeallocTgtPtrInfo(void *HstPtr, int64_t Size, bool HasHoldModifier)
613       : HstPtrBegin(HstPtr), DataSize(Size), HasHoldModifier(HasHoldModifier) {}
614 };
615 
616 /// Apply \p CB to the shadow map pointer entries in the range \p Begin, to
617 /// \p Begin + \p Size. \p CB is called with a locked shadow pointer map and the
618 /// passed iterator can be updated. If the callback returns OFFLOAD_FAIL the
619 /// rest of the map is not checked anymore.
620 template <typename CBTy>
621 static void applyToShadowMapEntries(DeviceTy &Device, CBTy CB, void *Begin,
622                                     uintptr_t Size,
623                                     const TargetPointerResultTy &TPR) {
624   // If we have an object that is too small to hold a pointer subobject, no need
625   // to do any checking.
626   if (Size < sizeof(void *))
627     return;
628 
629   // If the map entry for the object was never marked as containing attached
630   // pointers, no need to do any checking.
631   if (TPR.MapTableEntry == HostDataToTargetListTy::iterator{} ||
632       !TPR.MapTableEntry->getMayContainAttachedPointers())
633     return;
634 
635   uintptr_t LB = (uintptr_t)Begin;
636   uintptr_t UB = LB + Size;
637   // Now we are looking into the shadow map so we need to lock it.
638   Device.ShadowMtx.lock();
639   for (ShadowPtrListTy::iterator Itr = Device.ShadowPtrMap.begin();
640        Itr != Device.ShadowPtrMap.end();) {
641     uintptr_t ShadowHstPtrAddr = (uintptr_t)Itr->first;
642 
643     // An STL map is sorted on its keys; use this property
644     // to quickly determine when to break out of the loop.
645     if (ShadowHstPtrAddr < LB) {
646       ++Itr;
647       continue;
648     }
649     if (ShadowHstPtrAddr >= UB)
650       break;
651 
652     if (CB(Itr) == OFFLOAD_FAIL)
653       break;
654   }
655   Device.ShadowMtx.unlock();
656 }
657 
658 } // namespace
659 
660 /// Internal function to undo the mapping and retrieve the data from the device.
661 int targetDataEnd(ident_t *loc, DeviceTy &Device, int32_t ArgNum,
662                   void **ArgBases, void **Args, int64_t *ArgSizes,
663                   int64_t *ArgTypes, map_var_info_t *ArgNames,
664                   void **ArgMappers, AsyncInfoTy &AsyncInfo, bool FromMapper) {
665   int Ret;
666   std::vector<DeallocTgtPtrInfo> DeallocTgtPtrs;
667   void *FromMapperBase = nullptr;
668   // process each input.
669   for (int32_t I = ArgNum - 1; I >= 0; --I) {
670     // Ignore private variables and arrays - there is no mapping for them.
671     // Also, ignore the use_device_ptr directive, it has no effect here.
672     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) ||
673         (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE))
674       continue;
675 
676     if (ArgMappers && ArgMappers[I]) {
677       // Instead of executing the regular path of targetDataEnd, call the
678       // targetDataMapper variant which will call targetDataEnd again
679       // with new arguments.
680       DP("Calling targetDataMapper for the %dth argument\n", I);
681 
682       map_var_info_t ArgName = (!ArgNames) ? nullptr : ArgNames[I];
683       Ret = targetDataMapper(loc, Device, ArgBases[I], Args[I], ArgSizes[I],
684                              ArgTypes[I], ArgName, ArgMappers[I], AsyncInfo,
685                              targetDataEnd);
686 
687       if (Ret != OFFLOAD_SUCCESS) {
688         REPORT("Call to targetDataEnd via targetDataMapper for custom mapper"
689                " failed.\n");
690         return OFFLOAD_FAIL;
691       }
692 
693       // Skip the rest of this function, continue to the next argument.
694       continue;
695     }
696 
697     void *HstPtrBegin = Args[I];
698     int64_t DataSize = ArgSizes[I];
699     // Adjust for proper alignment if this is a combined entry (for structs).
700     // Look at the next argument - if that is MEMBER_OF this one, then this one
701     // is a combined entry.
702     const int NextI = I + 1;
703     if (getParentIndex(ArgTypes[I]) < 0 && NextI < ArgNum &&
704         getParentIndex(ArgTypes[NextI]) == I) {
705       int64_t Padding = (int64_t)HstPtrBegin % Alignment;
706       if (Padding) {
707         DP("Using a Padding of %" PRId64 " bytes for begin address " DPxMOD
708            "\n",
709            Padding, DPxPTR(HstPtrBegin));
710         HstPtrBegin = (char *)HstPtrBegin - Padding;
711         DataSize += Padding;
712       }
713     }
714 
715     bool IsLast, IsHostPtr;
716     bool IsImplicit = ArgTypes[I] & OMP_TGT_MAPTYPE_IMPLICIT;
717     bool UpdateRef = (!(ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
718                       (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) &&
719                      !(FromMapper && I == 0);
720     bool ForceDelete = ArgTypes[I] & OMP_TGT_MAPTYPE_DELETE;
721     bool HasPresentModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_PRESENT;
722     bool HasHoldModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_OMPX_HOLD;
723 
724     // If PTR_AND_OBJ, HstPtrBegin is address of pointee
725     TargetPointerResultTy TPR = Device.getTgtPtrBegin(
726         HstPtrBegin, DataSize, IsLast, UpdateRef, HasHoldModifier, IsHostPtr,
727         !IsImplicit, ForceDelete);
728     void *TgtPtrBegin = TPR.TargetPointer;
729     if (!TgtPtrBegin && (DataSize || HasPresentModifier)) {
730       DP("Mapping does not exist (%s)\n",
731          (HasPresentModifier ? "'present' map type modifier" : "ignored"));
732       if (HasPresentModifier) {
733         // OpenMP 5.1, sec. 2.21.7.1 "map Clause", p. 350 L10-13:
734         // "If a map clause appears on a target, target data, target enter data
735         // or target exit data construct with a present map-type-modifier then
736         // on entry to the region if the corresponding list item does not appear
737         // in the device data environment then an error occurs and the program
738         // terminates."
739         //
740         // This should be an error upon entering an "omp target exit data".  It
741         // should not be an error upon exiting an "omp target data" or "omp
742         // target".  For "omp target data", Clang thus doesn't include present
743         // modifiers for end calls.  For "omp target", we have not found a valid
744         // OpenMP program for which the error matters: it appears that, if a
745         // program can guarantee that data is present at the beginning of an
746         // "omp target" region so that there's no error there, that data is also
747         // guaranteed to be present at the end.
748         MESSAGE("device mapping required by 'present' map type modifier does "
749                 "not exist for host address " DPxMOD " (%" PRId64 " bytes)",
750                 DPxPTR(HstPtrBegin), DataSize);
751         return OFFLOAD_FAIL;
752       }
753     } else {
754       DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
755          " - is%s last\n",
756          DataSize, DPxPTR(TgtPtrBegin), (IsLast ? "" : " not"));
757     }
758 
759     // OpenMP 5.1, sec. 2.21.7.1 "map Clause", p. 351 L14-16:
760     // "If the map clause appears on a target, target data, or target exit data
761     // construct and a corresponding list item of the original list item is not
762     // present in the device data environment on exit from the region then the
763     // list item is ignored."
764     if (!TgtPtrBegin)
765       continue;
766 
767     bool DelEntry = IsLast;
768 
769     // If the last element from the mapper (for end transfer args comes in
770     // reverse order), do not remove the partial entry, the parent struct still
771     // exists.
772     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
773         !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
774       DelEntry = false; // protect parent struct from being deallocated
775     }
776 
777     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
778       // Move data back to the host
779       if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
780         bool Always = ArgTypes[I] & OMP_TGT_MAPTYPE_ALWAYS;
781         if ((Always || IsLast) && !IsHostPtr) {
782           DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
783              DataSize, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
784           Ret = Device.retrieveData(HstPtrBegin, TgtPtrBegin, DataSize,
785                                     AsyncInfo);
786           if (Ret != OFFLOAD_SUCCESS) {
787             REPORT("Copying data from device failed.\n");
788             return OFFLOAD_FAIL;
789           }
790         }
791       }
792       if (DelEntry && FromMapper && I == 0) {
793         DelEntry = false;
794         FromMapperBase = HstPtrBegin;
795       }
796 
797       // If we copied back to the host a struct/array containing pointers, we
798       // need to restore the original host pointer values from their shadow
799       // copies. If the struct is going to be deallocated, remove any remaining
800       // shadow pointer entries for this struct.
801       auto CB = [&](ShadowPtrListTy::iterator &Itr) {
802         // If we copied the struct to the host, we need to restore the pointer.
803         if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
804           void **ShadowHstPtrAddr = (void **)Itr->first;
805           *ShadowHstPtrAddr = Itr->second.HstPtrVal;
806           DP("Restoring original host pointer value " DPxMOD " for host "
807              "pointer " DPxMOD "\n",
808              DPxPTR(Itr->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
809         }
810         // If the struct is to be deallocated, remove the shadow entry.
811         if (DelEntry) {
812           DP("Removing shadow pointer " DPxMOD "\n",
813              DPxPTR((void **)Itr->first));
814           Itr = Device.ShadowPtrMap.erase(Itr);
815         } else {
816           ++Itr;
817         }
818         return OFFLOAD_SUCCESS;
819       };
820       applyToShadowMapEntries(Device, CB, HstPtrBegin, DataSize, TPR);
821 
822       // Add pointer to the buffer for later deallocation
823       if (DelEntry && !IsHostPtr)
824         DeallocTgtPtrs.emplace_back(HstPtrBegin, DataSize, HasHoldModifier);
825     }
826   }
827 
828   // TODO: We should not synchronize here but pass the AsyncInfo object to the
829   //       allocate/deallocate device APIs.
830   //
831   // We need to synchronize before deallocating data.
832   Ret = AsyncInfo.synchronize();
833   if (Ret != OFFLOAD_SUCCESS)
834     return OFFLOAD_FAIL;
835 
836   // Deallocate target pointer
837   for (DeallocTgtPtrInfo &Info : DeallocTgtPtrs) {
838     if (FromMapperBase && FromMapperBase == Info.HstPtrBegin)
839       continue;
840     Ret = Device.deallocTgtPtr(Info.HstPtrBegin, Info.DataSize,
841                                Info.HasHoldModifier);
842     if (Ret != OFFLOAD_SUCCESS) {
843       REPORT("Deallocating data from device failed.\n");
844       return OFFLOAD_FAIL;
845     }
846   }
847 
848   return OFFLOAD_SUCCESS;
849 }
850 
851 static int targetDataContiguous(ident_t *loc, DeviceTy &Device, void *ArgsBase,
852                                 void *HstPtrBegin, int64_t ArgSize,
853                                 int64_t ArgType, AsyncInfoTy &AsyncInfo) {
854   TIMESCOPE_WITH_IDENT(loc);
855   bool IsLast, IsHostPtr;
856   TargetPointerResultTy TPR = Device.getTgtPtrBegin(
857       HstPtrBegin, ArgSize, IsLast, /*UpdateRefCount=*/false,
858       /*UseHoldRefCount=*/false, IsHostPtr, /*MustContain=*/true);
859   void *TgtPtrBegin = TPR.TargetPointer;
860   if (!TgtPtrBegin) {
861     DP("hst data:" DPxMOD " not found, becomes a noop\n", DPxPTR(HstPtrBegin));
862     if (ArgType & OMP_TGT_MAPTYPE_PRESENT) {
863       MESSAGE("device mapping required by 'present' motion modifier does not "
864               "exist for host address " DPxMOD " (%" PRId64 " bytes)",
865               DPxPTR(HstPtrBegin), ArgSize);
866       return OFFLOAD_FAIL;
867     }
868     return OFFLOAD_SUCCESS;
869   }
870 
871   if (IsHostPtr) {
872     DP("hst data:" DPxMOD " unified and shared, becomes a noop\n",
873        DPxPTR(HstPtrBegin));
874     return OFFLOAD_SUCCESS;
875   }
876 
877   if (ArgType & OMP_TGT_MAPTYPE_FROM) {
878     DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
879        ArgSize, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
880     int Ret = Device.retrieveData(HstPtrBegin, TgtPtrBegin, ArgSize, AsyncInfo);
881     if (Ret != OFFLOAD_SUCCESS) {
882       REPORT("Copying data from device failed.\n");
883       return OFFLOAD_FAIL;
884     }
885 
886     auto CB = [&](ShadowPtrListTy::iterator &Itr) {
887       void **ShadowHstPtrAddr = (void **)Itr->first;
888       *ShadowHstPtrAddr = Itr->second.HstPtrVal;
889       DP("Restoring original host pointer value " DPxMOD
890          " for host pointer " DPxMOD "\n",
891          DPxPTR(Itr->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
892       ++Itr;
893       return OFFLOAD_SUCCESS;
894     };
895     applyToShadowMapEntries(Device, CB, HstPtrBegin, ArgSize, TPR);
896   }
897 
898   if (ArgType & OMP_TGT_MAPTYPE_TO) {
899     DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
900        ArgSize, DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
901     int Ret = Device.submitData(TgtPtrBegin, HstPtrBegin, ArgSize, AsyncInfo);
902     if (Ret != OFFLOAD_SUCCESS) {
903       REPORT("Copying data to device failed.\n");
904       return OFFLOAD_FAIL;
905     }
906 
907     auto CB = [&](ShadowPtrListTy::iterator &Itr) {
908       DP("Restoring original target pointer value " DPxMOD " for target "
909          "pointer " DPxMOD "\n",
910          DPxPTR(Itr->second.TgtPtrVal), DPxPTR(Itr->second.TgtPtrAddr));
911       Ret = Device.submitData(Itr->second.TgtPtrAddr, &Itr->second.TgtPtrVal,
912                               sizeof(void *), AsyncInfo);
913       if (Ret != OFFLOAD_SUCCESS)
914         REPORT("Copying data to device failed.\n");
915       ++Itr;
916       return Ret;
917     };
918     applyToShadowMapEntries(Device, CB, HstPtrBegin, ArgSize, TPR);
919   }
920   return OFFLOAD_SUCCESS;
921 }
922 
923 static int targetDataNonContiguous(ident_t *loc, DeviceTy &Device,
924                                    void *ArgsBase,
925                                    __tgt_target_non_contig *NonContig,
926                                    uint64_t Size, int64_t ArgType,
927                                    int CurrentDim, int DimSize, uint64_t Offset,
928                                    AsyncInfoTy &AsyncInfo) {
929   TIMESCOPE_WITH_IDENT(loc);
930   int Ret = OFFLOAD_SUCCESS;
931   if (CurrentDim < DimSize) {
932     for (unsigned int I = 0; I < NonContig[CurrentDim].Count; ++I) {
933       uint64_t CurOffset =
934           (NonContig[CurrentDim].Offset + I) * NonContig[CurrentDim].Stride;
935       // we only need to transfer the first element for the last dimension
936       // since we've already got a contiguous piece.
937       if (CurrentDim != DimSize - 1 || I == 0) {
938         Ret = targetDataNonContiguous(loc, Device, ArgsBase, NonContig, Size,
939                                       ArgType, CurrentDim + 1, DimSize,
940                                       Offset + CurOffset, AsyncInfo);
941         // Stop the whole process if any contiguous piece returns anything
942         // other than OFFLOAD_SUCCESS.
943         if (Ret != OFFLOAD_SUCCESS)
944           return Ret;
945       }
946     }
947   } else {
948     char *Ptr = (char *)ArgsBase + Offset;
949     DP("Transfer of non-contiguous : host ptr " DPxMOD " offset %" PRIu64
950        " len %" PRIu64 "\n",
951        DPxPTR(Ptr), Offset, Size);
952     Ret = targetDataContiguous(loc, Device, ArgsBase, Ptr, Size, ArgType,
953                                AsyncInfo);
954   }
955   return Ret;
956 }
957 
958 static int getNonContigMergedDimension(__tgt_target_non_contig *NonContig,
959                                        int32_t DimSize) {
960   int RemovedDim = 0;
961   for (int I = DimSize - 1; I > 0; --I) {
962     if (NonContig[I].Count * NonContig[I].Stride == NonContig[I - 1].Stride)
963       RemovedDim++;
964   }
965   return RemovedDim;
966 }
967 
968 /// Internal function to pass data to/from the target.
969 int targetDataUpdate(ident_t *loc, DeviceTy &Device, int32_t ArgNum,
970                      void **ArgsBase, void **Args, int64_t *ArgSizes,
971                      int64_t *ArgTypes, map_var_info_t *ArgNames,
972                      void **ArgMappers, AsyncInfoTy &AsyncInfo, bool) {
973   // process each input.
974   for (int32_t I = 0; I < ArgNum; ++I) {
975     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) ||
976         (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE))
977       continue;
978 
979     if (ArgMappers && ArgMappers[I]) {
980       // Instead of executing the regular path of targetDataUpdate, call the
981       // targetDataMapper variant which will call targetDataUpdate again
982       // with new arguments.
983       DP("Calling targetDataMapper for the %dth argument\n", I);
984 
985       map_var_info_t ArgName = (!ArgNames) ? nullptr : ArgNames[I];
986       int Ret = targetDataMapper(loc, Device, ArgsBase[I], Args[I], ArgSizes[I],
987                                  ArgTypes[I], ArgName, ArgMappers[I], AsyncInfo,
988                                  targetDataUpdate);
989 
990       if (Ret != OFFLOAD_SUCCESS) {
991         REPORT("Call to targetDataUpdate via targetDataMapper for custom mapper"
992                " failed.\n");
993         return OFFLOAD_FAIL;
994       }
995 
996       // Skip the rest of this function, continue to the next argument.
997       continue;
998     }
999 
1000     int Ret = OFFLOAD_SUCCESS;
1001 
1002     if (ArgTypes[I] & OMP_TGT_MAPTYPE_NON_CONTIG) {
1003       __tgt_target_non_contig *NonContig = (__tgt_target_non_contig *)Args[I];
1004       int32_t DimSize = ArgSizes[I];
1005       uint64_t Size =
1006           NonContig[DimSize - 1].Count * NonContig[DimSize - 1].Stride;
1007       int32_t MergedDim = getNonContigMergedDimension(NonContig, DimSize);
1008       Ret = targetDataNonContiguous(
1009           loc, Device, ArgsBase[I], NonContig, Size, ArgTypes[I],
1010           /*current_dim=*/0, DimSize - MergedDim, /*offset=*/0, AsyncInfo);
1011     } else {
1012       Ret = targetDataContiguous(loc, Device, ArgsBase[I], Args[I], ArgSizes[I],
1013                                  ArgTypes[I], AsyncInfo);
1014     }
1015     if (Ret == OFFLOAD_FAIL)
1016       return OFFLOAD_FAIL;
1017   }
1018   return OFFLOAD_SUCCESS;
1019 }
1020 
1021 static const unsigned LambdaMapping = OMP_TGT_MAPTYPE_PTR_AND_OBJ |
1022                                       OMP_TGT_MAPTYPE_LITERAL |
1023                                       OMP_TGT_MAPTYPE_IMPLICIT;
1024 static bool isLambdaMapping(int64_t Mapping) {
1025   return (Mapping & LambdaMapping) == LambdaMapping;
1026 }
1027 
1028 namespace {
1029 /// Find the table information in the map or look it up in the translation
1030 /// tables.
1031 TableMap *getTableMap(void *HostPtr) {
1032   std::lock_guard<std::mutex> TblMapLock(PM->TblMapMtx);
1033   HostPtrToTableMapTy::iterator TableMapIt =
1034       PM->HostPtrToTableMap.find(HostPtr);
1035 
1036   if (TableMapIt != PM->HostPtrToTableMap.end())
1037     return &TableMapIt->second;
1038 
1039   // We don't have a map. So search all the registered libraries.
1040   TableMap *TM = nullptr;
1041   std::lock_guard<std::mutex> TrlTblLock(PM->TrlTblMtx);
1042   for (HostEntriesBeginToTransTableTy::iterator Itr =
1043            PM->HostEntriesBeginToTransTable.begin();
1044        Itr != PM->HostEntriesBeginToTransTable.end(); ++Itr) {
1045     // get the translation table (which contains all the good info).
1046     TranslationTable *TransTable = &Itr->second;
1047     // iterate over all the host table entries to see if we can locate the
1048     // host_ptr.
1049     __tgt_offload_entry *Cur = TransTable->HostTable.EntriesBegin;
1050     for (uint32_t I = 0; Cur < TransTable->HostTable.EntriesEnd; ++Cur, ++I) {
1051       if (Cur->addr != HostPtr)
1052         continue;
1053       // we got a match, now fill the HostPtrToTableMap so that we
1054       // may avoid this search next time.
1055       TM = &(PM->HostPtrToTableMap)[HostPtr];
1056       TM->Table = TransTable;
1057       TM->Index = I;
1058       return TM;
1059     }
1060   }
1061 
1062   return nullptr;
1063 }
1064 
1065 /// Get loop trip count
1066 /// FIXME: This function will not work right if calling
1067 /// __kmpc_push_target_tripcount_mapper in one thread but doing offloading in
1068 /// another thread, which might occur when we call task yield.
1069 uint64_t getLoopTripCount(int64_t DeviceId) {
1070   DeviceTy &Device = *PM->Devices[DeviceId];
1071   uint64_t LoopTripCount = 0;
1072 
1073   {
1074     std::lock_guard<std::mutex> TblMapLock(PM->TblMapMtx);
1075     auto I = Device.LoopTripCnt.find(__kmpc_global_thread_num(NULL));
1076     if (I != Device.LoopTripCnt.end()) {
1077       LoopTripCount = I->second;
1078       Device.LoopTripCnt.erase(I);
1079       DP("loop trip count is %" PRIu64 ".\n", LoopTripCount);
1080     }
1081   }
1082 
1083   return LoopTripCount;
1084 }
1085 
1086 /// A class manages private arguments in a target region.
1087 class PrivateArgumentManagerTy {
1088   /// A data structure for the information of first-private arguments. We can
1089   /// use this information to optimize data transfer by packing all
1090   /// first-private arguments and transfer them all at once.
1091   struct FirstPrivateArgInfoTy {
1092     /// The index of the element in \p TgtArgs corresponding to the argument
1093     const int Index;
1094     /// Host pointer begin
1095     const char *HstPtrBegin;
1096     /// Host pointer end
1097     const char *HstPtrEnd;
1098     /// Aligned size
1099     const int64_t AlignedSize;
1100     /// Host pointer name
1101     const map_var_info_t HstPtrName = nullptr;
1102 
1103     FirstPrivateArgInfoTy(int Index, const void *HstPtr, int64_t Size,
1104                           const map_var_info_t HstPtrName = nullptr)
1105         : Index(Index), HstPtrBegin(reinterpret_cast<const char *>(HstPtr)),
1106           HstPtrEnd(HstPtrBegin + Size), AlignedSize(Size + Size % Alignment),
1107           HstPtrName(HstPtrName) {}
1108   };
1109 
1110   /// A vector of target pointers for all private arguments
1111   std::vector<void *> TgtPtrs;
1112 
1113   /// A vector of information of all first-private arguments to be packed
1114   std::vector<FirstPrivateArgInfoTy> FirstPrivateArgInfo;
1115   /// Host buffer for all arguments to be packed
1116   std::vector<char> FirstPrivateArgBuffer;
1117   /// The total size of all arguments to be packed
1118   int64_t FirstPrivateArgSize = 0;
1119 
1120   /// A reference to the \p DeviceTy object
1121   DeviceTy &Device;
1122   /// A pointer to a \p AsyncInfoTy object
1123   AsyncInfoTy &AsyncInfo;
1124 
1125   // TODO: What would be the best value here? Should we make it configurable?
1126   // If the size is larger than this threshold, we will allocate and transfer it
1127   // immediately instead of packing it.
1128   static constexpr const int64_t FirstPrivateArgSizeThreshold = 1024;
1129 
1130 public:
1131   /// Constructor
1132   PrivateArgumentManagerTy(DeviceTy &Dev, AsyncInfoTy &AsyncInfo)
1133       : Device(Dev), AsyncInfo(AsyncInfo) {}
1134 
1135   /// Add a private argument
1136   int addArg(void *HstPtr, int64_t ArgSize, int64_t ArgOffset,
1137              bool IsFirstPrivate, void *&TgtPtr, int TgtArgsIndex,
1138              const map_var_info_t HstPtrName = nullptr,
1139              const bool AllocImmediately = false) {
1140     // If the argument is not first-private, or its size is greater than a
1141     // predefined threshold, we will allocate memory and issue the transfer
1142     // immediately.
1143     if (ArgSize > FirstPrivateArgSizeThreshold || !IsFirstPrivate ||
1144         AllocImmediately) {
1145       TgtPtr = Device.allocData(ArgSize, HstPtr);
1146       if (!TgtPtr) {
1147         DP("Data allocation for %sprivate array " DPxMOD " failed.\n",
1148            (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtr));
1149         return OFFLOAD_FAIL;
1150       }
1151 #ifdef OMPTARGET_DEBUG
1152       void *TgtPtrBase = (void *)((intptr_t)TgtPtr + ArgOffset);
1153       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD
1154          " for %sprivate array " DPxMOD " - pushing target argument " DPxMOD
1155          "\n",
1156          ArgSize, DPxPTR(TgtPtr), (IsFirstPrivate ? "first-" : ""),
1157          DPxPTR(HstPtr), DPxPTR(TgtPtrBase));
1158 #endif
1159       // If first-private, copy data from host
1160       if (IsFirstPrivate) {
1161         DP("Submitting firstprivate data to the device.\n");
1162         int Ret = Device.submitData(TgtPtr, HstPtr, ArgSize, AsyncInfo);
1163         if (Ret != OFFLOAD_SUCCESS) {
1164           DP("Copying data to device failed, failed.\n");
1165           return OFFLOAD_FAIL;
1166         }
1167       }
1168       TgtPtrs.push_back(TgtPtr);
1169     } else {
1170       DP("Firstprivate array " DPxMOD " of size %" PRId64 " will be packed\n",
1171          DPxPTR(HstPtr), ArgSize);
1172       // When reach this point, the argument must meet all following
1173       // requirements:
1174       // 1. Its size does not exceed the threshold (see the comment for
1175       // FirstPrivateArgSizeThreshold);
1176       // 2. It must be first-private (needs to be mapped to target device).
1177       // We will pack all this kind of arguments to transfer them all at once
1178       // to reduce the number of data transfer. We will not take
1179       // non-first-private arguments, aka. private arguments that doesn't need
1180       // to be mapped to target device, into account because data allocation
1181       // can be very efficient with memory manager.
1182 
1183       // Placeholder value
1184       TgtPtr = nullptr;
1185       FirstPrivateArgInfo.emplace_back(TgtArgsIndex, HstPtr, ArgSize,
1186                                        HstPtrName);
1187       FirstPrivateArgSize += FirstPrivateArgInfo.back().AlignedSize;
1188     }
1189 
1190     return OFFLOAD_SUCCESS;
1191   }
1192 
1193   /// Pack first-private arguments, replace place holder pointers in \p TgtArgs,
1194   /// and start the transfer.
1195   int packAndTransfer(std::vector<void *> &TgtArgs) {
1196     if (!FirstPrivateArgInfo.empty()) {
1197       assert(FirstPrivateArgSize != 0 &&
1198              "FirstPrivateArgSize is 0 but FirstPrivateArgInfo is empty");
1199       FirstPrivateArgBuffer.resize(FirstPrivateArgSize, 0);
1200       auto Itr = FirstPrivateArgBuffer.begin();
1201       // Copy all host data to this buffer
1202       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
1203         std::copy(Info.HstPtrBegin, Info.HstPtrEnd, Itr);
1204         Itr = std::next(Itr, Info.AlignedSize);
1205       }
1206       // Allocate target memory
1207       void *TgtPtr =
1208           Device.allocData(FirstPrivateArgSize, FirstPrivateArgBuffer.data());
1209       if (TgtPtr == nullptr) {
1210         DP("Failed to allocate target memory for private arguments.\n");
1211         return OFFLOAD_FAIL;
1212       }
1213       TgtPtrs.push_back(TgtPtr);
1214       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD "\n",
1215          FirstPrivateArgSize, DPxPTR(TgtPtr));
1216       // Transfer data to target device
1217       int Ret = Device.submitData(TgtPtr, FirstPrivateArgBuffer.data(),
1218                                   FirstPrivateArgSize, AsyncInfo);
1219       if (Ret != OFFLOAD_SUCCESS) {
1220         DP("Failed to submit data of private arguments.\n");
1221         return OFFLOAD_FAIL;
1222       }
1223       // Fill in all placeholder pointers
1224       auto TP = reinterpret_cast<uintptr_t>(TgtPtr);
1225       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
1226         void *&Ptr = TgtArgs[Info.Index];
1227         assert(Ptr == nullptr && "Target pointer is already set by mistaken");
1228         Ptr = reinterpret_cast<void *>(TP);
1229         TP += Info.AlignedSize;
1230         DP("Firstprivate array " DPxMOD " of size %" PRId64 " mapped to " DPxMOD
1231            "\n",
1232            DPxPTR(Info.HstPtrBegin), Info.HstPtrEnd - Info.HstPtrBegin,
1233            DPxPTR(Ptr));
1234       }
1235     }
1236 
1237     return OFFLOAD_SUCCESS;
1238   }
1239 
1240   /// Free all target memory allocated for private arguments
1241   int free() {
1242     for (void *P : TgtPtrs) {
1243       int Ret = Device.deleteData(P);
1244       if (Ret != OFFLOAD_SUCCESS) {
1245         DP("Deallocation of (first-)private arrays failed.\n");
1246         return OFFLOAD_FAIL;
1247       }
1248     }
1249 
1250     TgtPtrs.clear();
1251 
1252     return OFFLOAD_SUCCESS;
1253   }
1254 };
1255 
1256 /// Process data before launching the kernel, including calling targetDataBegin
1257 /// to map and transfer data to target device, transferring (first-)private
1258 /// variables.
1259 static int processDataBefore(ident_t *loc, int64_t DeviceId, void *HostPtr,
1260                              int32_t ArgNum, void **ArgBases, void **Args,
1261                              int64_t *ArgSizes, int64_t *ArgTypes,
1262                              map_var_info_t *ArgNames, void **ArgMappers,
1263                              std::vector<void *> &TgtArgs,
1264                              std::vector<ptrdiff_t> &TgtOffsets,
1265                              PrivateArgumentManagerTy &PrivateArgumentManager,
1266                              AsyncInfoTy &AsyncInfo) {
1267   TIMESCOPE_WITH_NAME_AND_IDENT("mappingBeforeTargetRegion", loc);
1268   DeviceTy &Device = *PM->Devices[DeviceId];
1269   int Ret = targetDataBegin(loc, Device, ArgNum, ArgBases, Args, ArgSizes,
1270                             ArgTypes, ArgNames, ArgMappers, AsyncInfo);
1271   if (Ret != OFFLOAD_SUCCESS) {
1272     REPORT("Call to targetDataBegin failed, abort target.\n");
1273     return OFFLOAD_FAIL;
1274   }
1275 
1276   // List of (first-)private arrays allocated for this target region
1277   std::vector<int> TgtArgsPositions(ArgNum, -1);
1278 
1279   for (int32_t I = 0; I < ArgNum; ++I) {
1280     if (!(ArgTypes[I] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
1281       // This is not a target parameter, do not push it into TgtArgs.
1282       // Check for lambda mapping.
1283       if (isLambdaMapping(ArgTypes[I])) {
1284         assert((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1285                "PTR_AND_OBJ must be also MEMBER_OF.");
1286         unsigned Idx = getParentIndex(ArgTypes[I]);
1287         int TgtIdx = TgtArgsPositions[Idx];
1288         assert(TgtIdx != -1 && "Base address must be translated already.");
1289         // The parent lambda must be processed already and it must be the last
1290         // in TgtArgs and TgtOffsets arrays.
1291         void *HstPtrVal = Args[I];
1292         void *HstPtrBegin = ArgBases[I];
1293         void *HstPtrBase = Args[Idx];
1294         bool IsLast, IsHostPtr; // IsLast is unused.
1295         void *TgtPtrBase =
1296             (void *)((intptr_t)TgtArgs[TgtIdx] + TgtOffsets[TgtIdx]);
1297         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
1298         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
1299         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
1300         void *&PointerTgtPtrBegin = AsyncInfo.getVoidPtrLocation();
1301         TargetPointerResultTy TPR = Device.getTgtPtrBegin(
1302             HstPtrVal, ArgSizes[I], IsLast, /*UpdateRefCount=*/false,
1303             /*UseHoldRefCount=*/false, IsHostPtr);
1304         PointerTgtPtrBegin = TPR.TargetPointer;
1305         if (!PointerTgtPtrBegin) {
1306           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
1307              DPxPTR(HstPtrVal));
1308           continue;
1309         }
1310         if (IsHostPtr) {
1311           DP("Unified memory is active, no need to map lambda captured"
1312              "variable (" DPxMOD ")\n",
1313              DPxPTR(HstPtrVal));
1314           continue;
1315         }
1316         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
1317            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
1318         Ret = Device.submitData(TgtPtrBegin, &PointerTgtPtrBegin,
1319                                 sizeof(void *), AsyncInfo);
1320         if (Ret != OFFLOAD_SUCCESS) {
1321           REPORT("Copying data to device failed.\n");
1322           return OFFLOAD_FAIL;
1323         }
1324       }
1325       continue;
1326     }
1327     void *HstPtrBegin = Args[I];
1328     void *HstPtrBase = ArgBases[I];
1329     void *TgtPtrBegin;
1330     map_var_info_t HstPtrName = (!ArgNames) ? nullptr : ArgNames[I];
1331     ptrdiff_t TgtBaseOffset;
1332     bool IsLast, IsHostPtr; // unused.
1333     TargetPointerResultTy TPR;
1334     if (ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) {
1335       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
1336          DPxPTR(HstPtrBase));
1337       TgtPtrBegin = HstPtrBase;
1338       TgtBaseOffset = 0;
1339     } else if (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE) {
1340       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1341       const bool IsFirstPrivate = (ArgTypes[I] & OMP_TGT_MAPTYPE_TO);
1342       // If there is a next argument and it depends on the current one, we need
1343       // to allocate the private memory immediately. If this is not the case,
1344       // then the argument can be marked for optimization and packed with the
1345       // other privates.
1346       const bool AllocImmediately =
1347           (I < ArgNum - 1 && (ArgTypes[I + 1] & OMP_TGT_MAPTYPE_MEMBER_OF));
1348       Ret = PrivateArgumentManager.addArg(
1349           HstPtrBegin, ArgSizes[I], TgtBaseOffset, IsFirstPrivate, TgtPtrBegin,
1350           TgtArgs.size(), HstPtrName, AllocImmediately);
1351       if (Ret != OFFLOAD_SUCCESS) {
1352         REPORT("Failed to process %sprivate argument " DPxMOD "\n",
1353                (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtrBegin));
1354         return OFFLOAD_FAIL;
1355       }
1356     } else {
1357       if (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
1358         HstPtrBase = *reinterpret_cast<void **>(HstPtrBase);
1359       TPR = Device.getTgtPtrBegin(HstPtrBegin, ArgSizes[I], IsLast,
1360                                   /*UpdateRefCount=*/false,
1361                                   /*UseHoldRefCount=*/false, IsHostPtr);
1362       TgtPtrBegin = TPR.TargetPointer;
1363       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1364 #ifdef OMPTARGET_DEBUG
1365       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
1366       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
1367          DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
1368 #endif
1369     }
1370     TgtArgsPositions[I] = TgtArgs.size();
1371     TgtArgs.push_back(TgtPtrBegin);
1372     TgtOffsets.push_back(TgtBaseOffset);
1373   }
1374 
1375   assert(TgtArgs.size() == TgtOffsets.size() &&
1376          "Size mismatch in arguments and offsets");
1377 
1378   // Pack and transfer first-private arguments
1379   Ret = PrivateArgumentManager.packAndTransfer(TgtArgs);
1380   if (Ret != OFFLOAD_SUCCESS) {
1381     DP("Failed to pack and transfer first private arguments\n");
1382     return OFFLOAD_FAIL;
1383   }
1384 
1385   return OFFLOAD_SUCCESS;
1386 }
1387 
1388 /// Process data after launching the kernel, including transferring data back to
1389 /// host if needed and deallocating target memory of (first-)private variables.
1390 static int processDataAfter(ident_t *loc, int64_t DeviceId, void *HostPtr,
1391                             int32_t ArgNum, void **ArgBases, void **Args,
1392                             int64_t *ArgSizes, int64_t *ArgTypes,
1393                             map_var_info_t *ArgNames, void **ArgMappers,
1394                             PrivateArgumentManagerTy &PrivateArgumentManager,
1395                             AsyncInfoTy &AsyncInfo) {
1396   TIMESCOPE_WITH_NAME_AND_IDENT("mappingAfterTargetRegion", loc);
1397   DeviceTy &Device = *PM->Devices[DeviceId];
1398 
1399   // Move data from device.
1400   int Ret = targetDataEnd(loc, Device, ArgNum, ArgBases, Args, ArgSizes,
1401                           ArgTypes, ArgNames, ArgMappers, AsyncInfo);
1402   if (Ret != OFFLOAD_SUCCESS) {
1403     REPORT("Call to targetDataEnd failed, abort target.\n");
1404     return OFFLOAD_FAIL;
1405   }
1406 
1407   // Free target memory for private arguments
1408   Ret = PrivateArgumentManager.free();
1409   if (Ret != OFFLOAD_SUCCESS) {
1410     REPORT("Failed to deallocate target memory for private args\n");
1411     return OFFLOAD_FAIL;
1412   }
1413 
1414   return OFFLOAD_SUCCESS;
1415 }
1416 } // namespace
1417 
1418 /// performs the same actions as data_begin in case arg_num is
1419 /// non-zero and initiates run of the offloaded region on the target platform;
1420 /// if arg_num is non-zero after the region execution is done it also
1421 /// performs the same action as data_update and data_end above. This function
1422 /// returns 0 if it was able to transfer the execution to a target and an
1423 /// integer different from zero otherwise.
1424 int target(ident_t *loc, DeviceTy &Device, void *HostPtr, int32_t ArgNum,
1425            void **ArgBases, void **Args, int64_t *ArgSizes, int64_t *ArgTypes,
1426            map_var_info_t *ArgNames, void **ArgMappers, int32_t TeamNum,
1427            int32_t ThreadLimit, int IsTeamConstruct, AsyncInfoTy &AsyncInfo) {
1428   int32_t DeviceId = Device.DeviceID;
1429 
1430   TableMap *TM = getTableMap(HostPtr);
1431   // No map for this host pointer found!
1432   if (!TM) {
1433     REPORT("Host ptr " DPxMOD " does not have a matching target pointer.\n",
1434            DPxPTR(HostPtr));
1435     return OFFLOAD_FAIL;
1436   }
1437 
1438   // get target table.
1439   __tgt_target_table *TargetTable = nullptr;
1440   {
1441     std::lock_guard<std::mutex> TrlTblLock(PM->TrlTblMtx);
1442     assert(TM->Table->TargetsTable.size() > (size_t)DeviceId &&
1443            "Not expecting a device ID outside the table's bounds!");
1444     TargetTable = TM->Table->TargetsTable[DeviceId];
1445   }
1446   assert(TargetTable && "Global data has not been mapped\n");
1447 
1448   // We need to keep bases and offsets separate. Sometimes (e.g. in OpenCL) we
1449   // need to manifest base pointers prior to launching a kernel. Even if we have
1450   // mapped an object only partially, e.g. A[N:M], although the kernel is
1451   // expected to access elements starting at address &A[N] and beyond, we still
1452   // need to manifest the base of the array &A[0]. In other cases, e.g. the COI
1453   // API, we need the begin address itself, i.e. &A[N], as the API operates on
1454   // begin addresses, not bases. That's why we pass args and offsets as two
1455   // separate entities so that each plugin can do what it needs. This behavior
1456   // was introdued via https://reviews.llvm.org/D33028 and commit 1546d319244c.
1457   std::vector<void *> TgtArgs;
1458   std::vector<ptrdiff_t> TgtOffsets;
1459 
1460   PrivateArgumentManagerTy PrivateArgumentManager(Device, AsyncInfo);
1461 
1462   int Ret;
1463   if (ArgNum) {
1464     // Process data, such as data mapping, before launching the kernel
1465     Ret = processDataBefore(loc, DeviceId, HostPtr, ArgNum, ArgBases, Args,
1466                             ArgSizes, ArgTypes, ArgNames, ArgMappers, TgtArgs,
1467                             TgtOffsets, PrivateArgumentManager, AsyncInfo);
1468     if (Ret != OFFLOAD_SUCCESS) {
1469       REPORT("Failed to process data before launching the kernel.\n");
1470       return OFFLOAD_FAIL;
1471     }
1472   }
1473 
1474   // Launch device execution.
1475   void *TgtEntryPtr = TargetTable->EntriesBegin[TM->Index].addr;
1476   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
1477      TargetTable->EntriesBegin[TM->Index].name, DPxPTR(TgtEntryPtr), TM->Index);
1478 
1479   {
1480     TIMESCOPE_WITH_NAME_AND_IDENT(
1481         IsTeamConstruct ? "runTargetTeamRegion" : "runTargetRegion", loc);
1482     if (IsTeamConstruct)
1483       Ret = Device.runTeamRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1484                                  TgtArgs.size(), TeamNum, ThreadLimit,
1485                                  getLoopTripCount(DeviceId), AsyncInfo);
1486     else
1487       Ret = Device.runRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1488                              TgtArgs.size(), AsyncInfo);
1489   }
1490 
1491   if (Ret != OFFLOAD_SUCCESS) {
1492     REPORT("Executing target region abort target.\n");
1493     return OFFLOAD_FAIL;
1494   }
1495 
1496   if (ArgNum) {
1497     // Transfer data back and deallocate target memory for (first-)private
1498     // variables
1499     Ret = processDataAfter(loc, DeviceId, HostPtr, ArgNum, ArgBases, Args,
1500                            ArgSizes, ArgTypes, ArgNames, ArgMappers,
1501                            PrivateArgumentManager, AsyncInfo);
1502     if (Ret != OFFLOAD_SUCCESS) {
1503       REPORT("Failed to process data after launching the kernel.\n");
1504       return OFFLOAD_FAIL;
1505     }
1506   }
1507 
1508   return OFFLOAD_SUCCESS;
1509 }
1510