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 "device.h"
15 #include "private.h"
16 #include "rtl.h"
17 
18 #include <cassert>
19 #include <vector>
20 
21 /* All begin addresses for partially mapped structs must be 8-aligned in order
22  * to ensure proper alignment of members. E.g.
23  *
24  * struct S {
25  *   int a;   // 4-aligned
26  *   int b;   // 4-aligned
27  *   int *p;  // 8-aligned
28  * } s1;
29  * ...
30  * #pragma omp target map(tofrom: s1.b, s1.p[0:N])
31  * {
32  *   s1.b = 5;
33  *   for (int i...) s1.p[i] = ...;
34  * }
35  *
36  * Here we are mapping s1 starting from member b, so BaseAddress=&s1=&s1.a and
37  * BeginAddress=&s1.b. Let's assume that the struct begins at address 0x100,
38  * then &s1.a=0x100, &s1.b=0x104, &s1.p=0x108. Each member obeys the alignment
39  * requirements for its type. Now, when we allocate memory on the device, in
40  * CUDA's case cuMemAlloc() returns an address which is at least 256-aligned.
41  * This means that the chunk of the struct on the device will start at a
42  * 256-aligned address, let's say 0x200. Then the address of b will be 0x200 and
43  * address of p will be a misaligned 0x204 (on the host there was no need to add
44  * padding between b and p, so p comes exactly 4 bytes after b). If the device
45  * kernel tries to access s1.p, a misaligned address error occurs (as reported
46  * by the CUDA plugin). By padding the begin address down to a multiple of 8 and
47  * extending the size of the allocated chuck accordingly, the chuck on the
48  * device will start at 0x200 with the padding (4 bytes), then &s1.b=0x204 and
49  * &s1.p=0x208, as they should be to satisfy the alignment requirements.
50  */
51 static const int64_t Alignment = 8;
52 
53 /// Map global data and execute pending ctors
54 static int InitLibrary(DeviceTy& Device) {
55   /*
56    * Map global data
57    */
58   int32_t device_id = Device.DeviceID;
59   int rc = OFFLOAD_SUCCESS;
60 
61   Device.PendingGlobalsMtx.lock();
62   TrlTblMtx->lock();
63   for (HostEntriesBeginToTransTableTy::iterator
64       ii = HostEntriesBeginToTransTable->begin();
65       ii != HostEntriesBeginToTransTable->end(); ++ii) {
66     TranslationTable *TransTable = &ii->second;
67     if (TransTable->HostTable.EntriesBegin ==
68         TransTable->HostTable.EntriesEnd) {
69       // No host entry so no need to proceed
70       continue;
71     }
72     if (TransTable->TargetsTable[device_id] != 0) {
73       // Library entries have already been processed
74       continue;
75     }
76 
77     // 1) get image.
78     assert(TransTable->TargetsImages.size() > (size_t)device_id &&
79            "Not expecting a device ID outside the table's bounds!");
80     __tgt_device_image *img = TransTable->TargetsImages[device_id];
81     if (!img) {
82       REPORT("No image loaded for device id %d.\n", device_id);
83       rc = OFFLOAD_FAIL;
84       break;
85     }
86     // 2) load image into the target table.
87     __tgt_target_table *TargetTable =
88         TransTable->TargetsTable[device_id] = Device.load_binary(img);
89     // Unable to get table for this image: invalidate image and fail.
90     if (!TargetTable) {
91       REPORT("Unable to generate entries table for device id %d.\n", device_id);
92       TransTable->TargetsImages[device_id] = 0;
93       rc = OFFLOAD_FAIL;
94       break;
95     }
96 
97     // Verify whether the two table sizes match.
98     size_t hsize =
99         TransTable->HostTable.EntriesEnd - TransTable->HostTable.EntriesBegin;
100     size_t tsize = TargetTable->EntriesEnd - TargetTable->EntriesBegin;
101 
102     // Invalid image for these host entries!
103     if (hsize != tsize) {
104       REPORT("Host and Target tables mismatch for device id %d [%zx != %zx].\n",
105              device_id, hsize, tsize);
106       TransTable->TargetsImages[device_id] = 0;
107       TransTable->TargetsTable[device_id] = 0;
108       rc = OFFLOAD_FAIL;
109       break;
110     }
111 
112     // process global data that needs to be mapped.
113     Device.DataMapMtx.lock();
114     __tgt_target_table *HostTable = &TransTable->HostTable;
115     for (__tgt_offload_entry *CurrDeviceEntry = TargetTable->EntriesBegin,
116                              *CurrHostEntry = HostTable->EntriesBegin,
117                              *EntryDeviceEnd = TargetTable->EntriesEnd;
118          CurrDeviceEntry != EntryDeviceEnd;
119          CurrDeviceEntry++, CurrHostEntry++) {
120       if (CurrDeviceEntry->size != 0) {
121         // has data.
122         assert(CurrDeviceEntry->size == CurrHostEntry->size &&
123                "data size mismatch");
124 
125         // Fortran may use multiple weak declarations for the same symbol,
126         // therefore we must allow for multiple weak symbols to be loaded from
127         // the fat binary. Treat these mappings as any other "regular" mapping.
128         // Add entry to map.
129         if (Device.getTgtPtrBegin(CurrHostEntry->addr, CurrHostEntry->size))
130           continue;
131         DP("Add mapping from host " DPxMOD " to device " DPxMOD " with size %zu"
132             "\n", DPxPTR(CurrHostEntry->addr), DPxPTR(CurrDeviceEntry->addr),
133             CurrDeviceEntry->size);
134         Device.HostDataToTargetMap.emplace(
135             (uintptr_t)CurrHostEntry->addr /*HstPtrBase*/,
136             (uintptr_t)CurrHostEntry->addr /*HstPtrBegin*/,
137             (uintptr_t)CurrHostEntry->addr + CurrHostEntry->size /*HstPtrEnd*/,
138             (uintptr_t)CurrDeviceEntry->addr /*TgtPtrBegin*/,
139             true /*IsRefCountINF*/);
140       }
141     }
142     Device.DataMapMtx.unlock();
143   }
144   TrlTblMtx->unlock();
145 
146   if (rc != OFFLOAD_SUCCESS) {
147     Device.PendingGlobalsMtx.unlock();
148     return rc;
149   }
150 
151   /*
152    * Run ctors for static objects
153    */
154   if (!Device.PendingCtorsDtors.empty()) {
155     // Call all ctors for all libraries registered so far
156     for (auto &lib : Device.PendingCtorsDtors) {
157       if (!lib.second.PendingCtors.empty()) {
158         DP("Has pending ctors... call now\n");
159         for (auto &entry : lib.second.PendingCtors) {
160           void *ctor = entry;
161           int rc = target(device_id, ctor, 0, NULL, NULL, NULL, NULL, NULL, 1,
162               1, true /*team*/);
163           if (rc != OFFLOAD_SUCCESS) {
164             REPORT("Running ctor " DPxMOD " failed.\n", DPxPTR(ctor));
165             Device.PendingGlobalsMtx.unlock();
166             return OFFLOAD_FAIL;
167           }
168         }
169         // Clear the list to indicate that this device has been used
170         lib.second.PendingCtors.clear();
171         DP("Done with pending ctors for lib " DPxMOD "\n", DPxPTR(lib.first));
172       }
173     }
174   }
175   Device.HasPendingGlobals = false;
176   Device.PendingGlobalsMtx.unlock();
177 
178   return OFFLOAD_SUCCESS;
179 }
180 
181 // Check whether a device has been initialized, global ctors have been
182 // executed and global data has been mapped; do so if not already done.
183 int CheckDeviceAndCtors(int64_t device_id) {
184   // Is device ready?
185   if (!device_is_ready(device_id)) {
186     REPORT("Device %" PRId64 " is not ready.\n", device_id);
187     return OFFLOAD_FAIL;
188   }
189 
190   // Get device info.
191   DeviceTy &Device = Devices[device_id];
192 
193   // Check whether global data has been mapped for this device
194   Device.PendingGlobalsMtx.lock();
195   bool hasPendingGlobals = Device.HasPendingGlobals;
196   Device.PendingGlobalsMtx.unlock();
197   if (hasPendingGlobals && InitLibrary(Device) != OFFLOAD_SUCCESS) {
198     REPORT("Failed to init globals on device %" PRId64 "\n", device_id);
199     return OFFLOAD_FAIL;
200   }
201 
202   return OFFLOAD_SUCCESS;
203 }
204 
205 static int32_t getParentIndex(int64_t type) {
206   return ((type & OMP_TGT_MAPTYPE_MEMBER_OF) >> 48) - 1;
207 }
208 
209 /// Call the user-defined mapper function followed by the appropriate
210 // target_data_* function (target_data_{begin,end,update}).
211 int targetDataMapper(DeviceTy &Device, void *arg_base, void *arg,
212                      int64_t arg_size, int64_t arg_type, void *arg_mapper,
213                      TargetDataFuncPtrTy target_data_function) {
214   DP("Calling the mapper function " DPxMOD "\n", DPxPTR(arg_mapper));
215 
216   // The mapper function fills up Components.
217   MapperComponentsTy MapperComponents;
218   MapperFuncPtrTy MapperFuncPtr = (MapperFuncPtrTy)(arg_mapper);
219   (*MapperFuncPtr)((void *)&MapperComponents, arg_base, arg, arg_size,
220       arg_type);
221 
222   // Construct new arrays for args_base, args, arg_sizes and arg_types
223   // using the information in MapperComponents and call the corresponding
224   // target_data_* function using these new arrays.
225   std::vector<void *> MapperArgsBase(MapperComponents.Components.size());
226   std::vector<void *> MapperArgs(MapperComponents.Components.size());
227   std::vector<int64_t> MapperArgSizes(MapperComponents.Components.size());
228   std::vector<int64_t> MapperArgTypes(MapperComponents.Components.size());
229 
230   for (unsigned I = 0, E = MapperComponents.Components.size(); I < E; ++I) {
231     auto &C =
232         MapperComponents
233             .Components[target_data_function == targetDataEnd ? I : E - I - 1];
234     MapperArgsBase[I] = C.Base;
235     MapperArgs[I] = C.Begin;
236     MapperArgSizes[I] = C.Size;
237     MapperArgTypes[I] = C.Type;
238   }
239 
240   int rc = target_data_function(Device, MapperComponents.Components.size(),
241                                 MapperArgsBase.data(), MapperArgs.data(),
242                                 MapperArgSizes.data(), MapperArgTypes.data(),
243                                 /*arg_mappers*/ nullptr,
244                                 /*__tgt_async_info*/ nullptr);
245 
246   return rc;
247 }
248 
249 /// Internal function to do the mapping and transfer the data to the device
250 int targetDataBegin(DeviceTy &Device, int32_t arg_num, void **args_base,
251                     void **args, int64_t *arg_sizes, int64_t *arg_types,
252                     void **arg_mappers, __tgt_async_info *async_info_ptr) {
253   // process each input.
254   for (int32_t i = 0; i < arg_num; ++i) {
255     // Ignore private variables and arrays - there is no mapping for them.
256     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
257         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
258       continue;
259 
260     if (arg_mappers && arg_mappers[i]) {
261       // Instead of executing the regular path of targetDataBegin, call the
262       // targetDataMapper variant which will call targetDataBegin again
263       // with new arguments.
264       DP("Calling targetDataMapper for the %dth argument\n", i);
265 
266       int rc = targetDataMapper(Device, args_base[i], args[i], arg_sizes[i],
267                                 arg_types[i], arg_mappers[i], targetDataBegin);
268 
269       if (rc != OFFLOAD_SUCCESS) {
270         REPORT("Call to targetDataBegin via targetDataMapper for custom mapper"
271                " failed.\n");
272         return OFFLOAD_FAIL;
273       }
274 
275       // Skip the rest of this function, continue to the next argument.
276       continue;
277     }
278 
279     void *HstPtrBegin = args[i];
280     void *HstPtrBase = args_base[i];
281     int64_t data_size = arg_sizes[i];
282 
283     // Adjust for proper alignment if this is a combined entry (for structs).
284     // Look at the next argument - if that is MEMBER_OF this one, then this one
285     // is a combined entry.
286     int64_t padding = 0;
287     const int next_i = i+1;
288     if (getParentIndex(arg_types[i]) < 0 && next_i < arg_num &&
289         getParentIndex(arg_types[next_i]) == i) {
290       padding = (int64_t)HstPtrBegin % Alignment;
291       if (padding) {
292         DP("Using a padding of %" PRId64 " bytes for begin address " DPxMOD
293             "\n", padding, DPxPTR(HstPtrBegin));
294         HstPtrBegin = (char *) HstPtrBegin - padding;
295         data_size += padding;
296       }
297     }
298 
299     // Address of pointer on the host and device, respectively.
300     void *Pointer_HstPtrBegin, *PointerTgtPtrBegin;
301     bool IsNew, Pointer_IsNew;
302     bool IsHostPtr = false;
303     bool IsImplicit = arg_types[i] & OMP_TGT_MAPTYPE_IMPLICIT;
304     // Force the creation of a device side copy of the data when:
305     // a close map modifier was associated with a map that contained a to.
306     bool HasCloseModifier = arg_types[i] & OMP_TGT_MAPTYPE_CLOSE;
307     bool HasPresentModifier = arg_types[i] & OMP_TGT_MAPTYPE_PRESENT;
308     // UpdateRef is based on MEMBER_OF instead of TARGET_PARAM because if we
309     // have reached this point via __tgt_target_data_begin and not __tgt_target
310     // then no argument is marked as TARGET_PARAM ("omp target data map" is not
311     // associated with a target region, so there are no target parameters). This
312     // may be considered a hack, we could revise the scheme in the future.
313     bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF);
314     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
315       DP("Has a pointer entry: \n");
316       // Base is address of pointer.
317       //
318       // Usually, the pointer is already allocated by this time.  For example:
319       //
320       //   #pragma omp target map(s.p[0:N])
321       //
322       // The map entry for s comes first, and the PTR_AND_OBJ entry comes
323       // afterward, so the pointer is already allocated by the time the
324       // PTR_AND_OBJ entry is handled below, and PointerTgtPtrBegin is thus
325       // non-null.  However, "declare target link" can produce a PTR_AND_OBJ
326       // entry for a global that might not already be allocated by the time the
327       // PTR_AND_OBJ entry is handled below, and so the allocation might fail
328       // when HasPresentModifier.
329       PointerTgtPtrBegin = Device.getOrAllocTgtPtr(
330           HstPtrBase, HstPtrBase, sizeof(void *), Pointer_IsNew, IsHostPtr,
331           IsImplicit, UpdateRef, HasCloseModifier, HasPresentModifier);
332       if (!PointerTgtPtrBegin) {
333         REPORT("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
334                HasPresentModifier ? "'present' map type modifier"
335                                   : "device failure or illegal mapping");
336         return OFFLOAD_FAIL;
337       }
338       DP("There are %zu bytes allocated at target address " DPxMOD " - is%s new"
339           "\n", sizeof(void *), DPxPTR(PointerTgtPtrBegin),
340           (Pointer_IsNew ? "" : " not"));
341       Pointer_HstPtrBegin = HstPtrBase;
342       // modify current entry.
343       HstPtrBase = *(void **)HstPtrBase;
344       UpdateRef = true; // subsequently update ref count of pointee
345     }
346 
347     void *TgtPtrBegin = Device.getOrAllocTgtPtr(
348         HstPtrBegin, HstPtrBase, data_size, IsNew, IsHostPtr, IsImplicit,
349         UpdateRef, HasCloseModifier, HasPresentModifier);
350     // If data_size==0, then the argument could be a zero-length pointer to
351     // NULL, so getOrAlloc() returning NULL is not an error.
352     if (!TgtPtrBegin && (data_size || HasPresentModifier)) {
353       REPORT("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
354              HasPresentModifier ? "'present' map type modifier"
355                                 : "device failure or illegal mapping");
356       return OFFLOAD_FAIL;
357     }
358     DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
359         " - is%s new\n", data_size, DPxPTR(TgtPtrBegin),
360         (IsNew ? "" : " not"));
361 
362     if (arg_types[i] & OMP_TGT_MAPTYPE_RETURN_PARAM) {
363       uintptr_t Delta = (uintptr_t)HstPtrBegin - (uintptr_t)HstPtrBase;
364       void *TgtPtrBase = (void *)((uintptr_t)TgtPtrBegin - Delta);
365       DP("Returning device pointer " DPxMOD "\n", DPxPTR(TgtPtrBase));
366       args_base[i] = TgtPtrBase;
367     }
368 
369     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
370       bool copy = false;
371       if (!(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
372           HasCloseModifier) {
373         if (IsNew || (arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS)) {
374           copy = true;
375         } else if (arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) {
376           // Copy data only if the "parent" struct has RefCount==1.
377           int32_t parent_idx = getParentIndex(arg_types[i]);
378           uint64_t parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
379           assert(parent_rc > 0 && "parent struct not found");
380           if (parent_rc == 1) {
381             copy = true;
382           }
383         }
384       }
385 
386       if (copy && !IsHostPtr) {
387         DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
388            data_size, DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
389         int rt = Device.submitData(TgtPtrBegin, HstPtrBegin, data_size,
390                                    async_info_ptr);
391         if (rt != OFFLOAD_SUCCESS) {
392           REPORT("Copying data to device failed.\n");
393           return OFFLOAD_FAIL;
394         }
395       }
396     }
397 
398     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ && !IsHostPtr) {
399       DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
400          DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
401       uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
402       void *TgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
403       int rt = Device.submitData(PointerTgtPtrBegin, &TgtPtrBase,
404                                  sizeof(void *), async_info_ptr);
405       if (rt != OFFLOAD_SUCCESS) {
406         REPORT("Copying data to device failed.\n");
407         return OFFLOAD_FAIL;
408       }
409       // create shadow pointers for this entry
410       Device.ShadowMtx.lock();
411       Device.ShadowPtrMap[Pointer_HstPtrBegin] = {
412           HstPtrBase, PointerTgtPtrBegin, TgtPtrBase};
413       Device.ShadowMtx.unlock();
414     }
415   }
416 
417   return OFFLOAD_SUCCESS;
418 }
419 
420 namespace {
421 /// This structure contains information to deallocate a target pointer, aka.
422 /// used to call the function \p DeviceTy::deallocTgtPtr.
423 struct DeallocTgtPtrInfo {
424   /// Host pointer used to look up into the map table
425   void *HstPtrBegin;
426   /// Size of the data
427   int64_t DataSize;
428   /// Whether it is forced to be removed from the map table
429   bool ForceDelete;
430   /// Whether it has \p close modifier
431   bool HasCloseModifier;
432 
433   DeallocTgtPtrInfo(void *HstPtr, int64_t Size, bool ForceDelete,
434                     bool HasCloseModifier)
435       : HstPtrBegin(HstPtr), DataSize(Size), ForceDelete(ForceDelete),
436         HasCloseModifier(HasCloseModifier) {}
437 };
438 } // namespace
439 
440 /// Internal function to undo the mapping and retrieve the data from the device.
441 int targetDataEnd(DeviceTy &Device, int32_t ArgNum, void **ArgBases,
442                   void **Args, int64_t *ArgSizes, int64_t *ArgTypes,
443                   void **ArgMappers, __tgt_async_info *AsyncInfo) {
444   int Ret;
445   std::vector<DeallocTgtPtrInfo> DeallocTgtPtrs;
446   // process each input.
447   for (int32_t I = ArgNum - 1; I >= 0; --I) {
448     // Ignore private variables and arrays - there is no mapping for them.
449     // Also, ignore the use_device_ptr directive, it has no effect here.
450     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) ||
451         (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE))
452       continue;
453 
454     if (ArgMappers && ArgMappers[I]) {
455       // Instead of executing the regular path of targetDataEnd, call the
456       // targetDataMapper variant which will call targetDataEnd again
457       // with new arguments.
458       DP("Calling targetDataMapper for the %dth argument\n", I);
459 
460       Ret = targetDataMapper(Device, ArgBases[I], Args[I], ArgSizes[I],
461                              ArgTypes[I], ArgMappers[I], targetDataEnd);
462 
463       if (Ret != OFFLOAD_SUCCESS) {
464         REPORT("Call to targetDataEnd via targetDataMapper for custom mapper"
465                " failed.\n");
466         return OFFLOAD_FAIL;
467       }
468 
469       // Skip the rest of this function, continue to the next argument.
470       continue;
471     }
472 
473     void *HstPtrBegin = Args[I];
474     int64_t DataSize = ArgSizes[I];
475     // Adjust for proper alignment if this is a combined entry (for structs).
476     // Look at the next argument - if that is MEMBER_OF this one, then this one
477     // is a combined entry.
478     const int NextI = I + 1;
479     if (getParentIndex(ArgTypes[I]) < 0 && NextI < ArgNum &&
480         getParentIndex(ArgTypes[NextI]) == I) {
481       int64_t Padding = (int64_t)HstPtrBegin % Alignment;
482       if (Padding) {
483         DP("Using a Padding of %" PRId64 " bytes for begin address " DPxMOD
484            "\n",
485            Padding, DPxPTR(HstPtrBegin));
486         HstPtrBegin = (char *)HstPtrBegin - Padding;
487         DataSize += Padding;
488       }
489     }
490 
491     bool IsLast, IsHostPtr;
492     bool IsImplicit = ArgTypes[I] & OMP_TGT_MAPTYPE_IMPLICIT;
493     bool UpdateRef = !(ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
494                      (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ);
495     bool ForceDelete = ArgTypes[I] & OMP_TGT_MAPTYPE_DELETE;
496     bool HasCloseModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_CLOSE;
497     bool HasPresentModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_PRESENT;
498 
499     // If PTR_AND_OBJ, HstPtrBegin is address of pointee
500     void *TgtPtrBegin = Device.getTgtPtrBegin(
501         HstPtrBegin, DataSize, IsLast, UpdateRef, IsHostPtr, !IsImplicit);
502     if (!TgtPtrBegin && (DataSize || HasPresentModifier)) {
503       DP("Mapping does not exist (%s)\n",
504          (HasPresentModifier ? "'present' map type modifier" : "ignored"));
505       if (HasPresentModifier) {
506         // This should be an error upon entering an "omp target exit data".  It
507         // should not be an error upon exiting an "omp target data" or "omp
508         // target".  For "omp target data", Clang thus doesn't include present
509         // modifiers for end calls.  For "omp target", we have not found a valid
510         // OpenMP program for which the error matters: it appears that, if a
511         // program can guarantee that data is present at the beginning of an
512         // "omp target" region so that there's no error there, that data is also
513         // guaranteed to be present at the end.
514         MESSAGE("device mapping required by 'present' map type modifier does "
515                 "not exist for host address " DPxMOD " (%" PRId64 " bytes)",
516                 DPxPTR(HstPtrBegin), DataSize);
517         return OFFLOAD_FAIL;
518       }
519     } else {
520       DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
521          " - is%s last\n",
522          DataSize, DPxPTR(TgtPtrBegin), (IsLast ? "" : " not"));
523     }
524 
525     bool DelEntry = IsLast || ForceDelete;
526 
527     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
528         !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
529       DelEntry = false; // protect parent struct from being deallocated
530     }
531 
532     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
533       // Move data back to the host
534       if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
535         bool Always = ArgTypes[I] & OMP_TGT_MAPTYPE_ALWAYS;
536         bool CopyMember = false;
537         if (!(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
538             HasCloseModifier) {
539           if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
540               !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
541             // Copy data only if the "parent" struct has RefCount==1.
542             int32_t ParentIdx = getParentIndex(ArgTypes[I]);
543             uint64_t ParentRC = Device.getMapEntryRefCnt(Args[ParentIdx]);
544             assert(ParentRC > 0 && "parent struct not found");
545             if (ParentRC == 1)
546               CopyMember = true;
547           }
548         }
549 
550         if ((DelEntry || Always || CopyMember) &&
551             !(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
552               TgtPtrBegin == HstPtrBegin)) {
553           DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
554              DataSize, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
555           Ret = Device.retrieveData(HstPtrBegin, TgtPtrBegin, DataSize,
556                                     AsyncInfo);
557           if (Ret != OFFLOAD_SUCCESS) {
558             REPORT("Copying data from device failed.\n");
559             return OFFLOAD_FAIL;
560           }
561         }
562       }
563 
564       // If we copied back to the host a struct/array containing pointers, we
565       // need to restore the original host pointer values from their shadow
566       // copies. If the struct is going to be deallocated, remove any remaining
567       // shadow pointer entries for this struct.
568       uintptr_t LB = (uintptr_t)HstPtrBegin;
569       uintptr_t UB = (uintptr_t)HstPtrBegin + DataSize;
570       Device.ShadowMtx.lock();
571       for (ShadowPtrListTy::iterator Itr = Device.ShadowPtrMap.begin();
572            Itr != Device.ShadowPtrMap.end();) {
573         void **ShadowHstPtrAddr = (void **)Itr->first;
574 
575         // An STL map is sorted on its keys; use this property
576         // to quickly determine when to break out of the loop.
577         if ((uintptr_t)ShadowHstPtrAddr < LB) {
578           ++Itr;
579           continue;
580         }
581         if ((uintptr_t)ShadowHstPtrAddr >= UB)
582           break;
583 
584         // If we copied the struct to the host, we need to restore the pointer.
585         if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
586           DP("Restoring original host pointer value " DPxMOD " for host "
587              "pointer " DPxMOD "\n",
588              DPxPTR(Itr->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
589           *ShadowHstPtrAddr = Itr->second.HstPtrVal;
590         }
591         // If the struct is to be deallocated, remove the shadow entry.
592         if (DelEntry) {
593           DP("Removing shadow pointer " DPxMOD "\n", DPxPTR(ShadowHstPtrAddr));
594           Itr = Device.ShadowPtrMap.erase(Itr);
595         } else {
596           ++Itr;
597         }
598       }
599       Device.ShadowMtx.unlock();
600 
601       // Add pointer to the buffer for later deallocation
602       if (DelEntry)
603         DeallocTgtPtrs.emplace_back(HstPtrBegin, DataSize, ForceDelete,
604                                     HasCloseModifier);
605     }
606   }
607 
608   // We need to synchronize before deallocating data.
609   // If AsyncInfo is nullptr, the previous data transfer (if has) will be
610   // synchronous, so we don't need to synchronize again. If AsyncInfo->Queue is
611   // nullptr, there is no data transfer happened because once there is,
612   // AsyncInfo->Queue will not be nullptr, so again, we don't need to
613   // synchronize.
614   if (AsyncInfo && AsyncInfo->Queue) {
615     Ret = Device.synchronize(AsyncInfo);
616     if (Ret != OFFLOAD_SUCCESS) {
617       REPORT("Failed to synchronize device.\n");
618       return OFFLOAD_FAIL;
619     }
620   }
621 
622   // Deallocate target pointer
623   for (DeallocTgtPtrInfo &Info : DeallocTgtPtrs) {
624     Ret = Device.deallocTgtPtr(Info.HstPtrBegin, Info.DataSize,
625                                Info.ForceDelete, Info.HasCloseModifier);
626     if (Ret != OFFLOAD_SUCCESS) {
627       REPORT("Deallocating data from device failed.\n");
628       return OFFLOAD_FAIL;
629     }
630   }
631 
632   return OFFLOAD_SUCCESS;
633 }
634 
635 /// Internal function to pass data to/from the target.
636 // async_info_ptr is currently unused, added here so target_data_update has the
637 // same signature as targetDataBegin and targetDataEnd.
638 int target_data_update(DeviceTy &Device, int32_t arg_num,
639     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
640     void **arg_mappers, __tgt_async_info *async_info_ptr) {
641   // process each input.
642   for (int32_t i = 0; i < arg_num; ++i) {
643     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
644         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
645       continue;
646 
647     if (arg_mappers && arg_mappers[i]) {
648       // Instead of executing the regular path of target_data_update, call the
649       // targetDataMapper variant which will call target_data_update again
650       // with new arguments.
651       DP("Calling targetDataMapper for the %dth argument\n", i);
652 
653       int rc =
654           targetDataMapper(Device, args_base[i], args[i], arg_sizes[i],
655                            arg_types[i], arg_mappers[i], target_data_update);
656 
657       if (rc != OFFLOAD_SUCCESS) {
658         REPORT(
659             "Call to target_data_update via targetDataMapper for custom mapper"
660             " failed.\n");
661         return OFFLOAD_FAIL;
662       }
663 
664       // Skip the rest of this function, continue to the next argument.
665       continue;
666     }
667 
668     void *HstPtrBegin = args[i];
669     int64_t MapSize = arg_sizes[i];
670     bool IsLast, IsHostPtr;
671     void *TgtPtrBegin = Device.getTgtPtrBegin(
672         HstPtrBegin, MapSize, IsLast, false, IsHostPtr, /*MustContain=*/true);
673     if (!TgtPtrBegin) {
674       DP("hst data:" DPxMOD " not found, becomes a noop\n", DPxPTR(HstPtrBegin));
675       if (arg_types[i] & OMP_TGT_MAPTYPE_PRESENT) {
676         MESSAGE("device mapping required by 'present' motion modifier does not "
677                 "exist for host address " DPxMOD " (%" PRId64 " bytes)",
678                 DPxPTR(HstPtrBegin), MapSize);
679         return OFFLOAD_FAIL;
680       }
681       continue;
682     }
683 
684     if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
685         TgtPtrBegin == HstPtrBegin) {
686       DP("hst data:" DPxMOD " unified and shared, becomes a noop\n",
687          DPxPTR(HstPtrBegin));
688       continue;
689     }
690 
691     if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
692       DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
693           arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
694       int rt = Device.retrieveData(HstPtrBegin, TgtPtrBegin, MapSize, nullptr);
695       if (rt != OFFLOAD_SUCCESS) {
696         REPORT("Copying data from device failed.\n");
697         return OFFLOAD_FAIL;
698       }
699 
700       uintptr_t lb = (uintptr_t) HstPtrBegin;
701       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
702       Device.ShadowMtx.lock();
703       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
704           it != Device.ShadowPtrMap.end(); ++it) {
705         void **ShadowHstPtrAddr = (void**) it->first;
706         if ((uintptr_t) ShadowHstPtrAddr < lb)
707           continue;
708         if ((uintptr_t) ShadowHstPtrAddr >= ub)
709           break;
710         DP("Restoring original host pointer value " DPxMOD " for host pointer "
711             DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
712             DPxPTR(ShadowHstPtrAddr));
713         *ShadowHstPtrAddr = it->second.HstPtrVal;
714       }
715       Device.ShadowMtx.unlock();
716     }
717 
718     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
719       DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
720           arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
721       int rt = Device.submitData(TgtPtrBegin, HstPtrBegin, MapSize, nullptr);
722       if (rt != OFFLOAD_SUCCESS) {
723         REPORT("Copying data to device failed.\n");
724         return OFFLOAD_FAIL;
725       }
726 
727       uintptr_t lb = (uintptr_t) HstPtrBegin;
728       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
729       Device.ShadowMtx.lock();
730       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
731           it != Device.ShadowPtrMap.end(); ++it) {
732         void **ShadowHstPtrAddr = (void **)it->first;
733         if ((uintptr_t)ShadowHstPtrAddr < lb)
734           continue;
735         if ((uintptr_t)ShadowHstPtrAddr >= ub)
736           break;
737         DP("Restoring original target pointer value " DPxMOD " for target "
738            "pointer " DPxMOD "\n",
739            DPxPTR(it->second.TgtPtrVal), DPxPTR(it->second.TgtPtrAddr));
740         rt = Device.submitData(it->second.TgtPtrAddr, &it->second.TgtPtrVal,
741                                sizeof(void *), nullptr);
742         if (rt != OFFLOAD_SUCCESS) {
743           REPORT("Copying data to device failed.\n");
744           Device.ShadowMtx.unlock();
745           return OFFLOAD_FAIL;
746         }
747       }
748       Device.ShadowMtx.unlock();
749     }
750   }
751   return OFFLOAD_SUCCESS;
752 }
753 
754 static const unsigned LambdaMapping = OMP_TGT_MAPTYPE_PTR_AND_OBJ |
755                                       OMP_TGT_MAPTYPE_LITERAL |
756                                       OMP_TGT_MAPTYPE_IMPLICIT;
757 static bool isLambdaMapping(int64_t Mapping) {
758   return (Mapping & LambdaMapping) == LambdaMapping;
759 }
760 
761 namespace {
762 /// Find the table information in the map or look it up in the translation
763 /// tables.
764 TableMap *getTableMap(void *HostPtr) {
765   std::lock_guard<std::mutex> TblMapLock(*TblMapMtx);
766   HostPtrToTableMapTy::iterator TableMapIt = HostPtrToTableMap->find(HostPtr);
767 
768   if (TableMapIt != HostPtrToTableMap->end())
769     return &TableMapIt->second;
770 
771   // We don't have a map. So search all the registered libraries.
772   TableMap *TM = nullptr;
773   std::lock_guard<std::mutex> TrlTblLock(*TrlTblMtx);
774   for (HostEntriesBeginToTransTableTy::iterator Itr =
775            HostEntriesBeginToTransTable->begin();
776        Itr != HostEntriesBeginToTransTable->end(); ++Itr) {
777     // get the translation table (which contains all the good info).
778     TranslationTable *TransTable = &Itr->second;
779     // iterate over all the host table entries to see if we can locate the
780     // host_ptr.
781     __tgt_offload_entry *Cur = TransTable->HostTable.EntriesBegin;
782     for (uint32_t I = 0; Cur < TransTable->HostTable.EntriesEnd; ++Cur, ++I) {
783       if (Cur->addr != HostPtr)
784         continue;
785       // we got a match, now fill the HostPtrToTableMap so that we
786       // may avoid this search next time.
787       TM = &(*HostPtrToTableMap)[HostPtr];
788       TM->Table = TransTable;
789       TM->Index = I;
790       return TM;
791     }
792   }
793 
794   return nullptr;
795 }
796 
797 /// Get loop trip count
798 /// FIXME: This function will not work right if calling
799 /// __kmpc_push_target_tripcount in one thread but doing offloading in another
800 /// thread, which might occur when we call task yield.
801 uint64_t getLoopTripCount(int64_t DeviceId) {
802   DeviceTy &Device = Devices[DeviceId];
803   uint64_t LoopTripCount = 0;
804 
805   {
806     std::lock_guard<std::mutex> TblMapLock(*TblMapMtx);
807     auto I = Device.LoopTripCnt.find(__kmpc_global_thread_num(NULL));
808     if (I != Device.LoopTripCnt.end()) {
809       LoopTripCount = I->second;
810       Device.LoopTripCnt.erase(I);
811       DP("loop trip count is %lu.\n", LoopTripCount);
812     }
813   }
814 
815   return LoopTripCount;
816 }
817 
818 /// A class manages private arguments in a target region.
819 class PrivateArgumentManagerTy {
820   /// A data structure for the information of first-private arguments. We can
821   /// use this information to optimize data transfer by packing all
822   /// first-private arguments and transfer them all at once.
823   struct FirstPrivateArgInfoTy {
824     /// The index of the element in \p TgtArgs corresponding to the argument
825     const int Index;
826     /// Host pointer begin
827     const char *HstPtrBegin;
828     /// Host pointer end
829     const char *HstPtrEnd;
830     /// Aligned size
831     const int64_t AlignedSize;
832 
833     FirstPrivateArgInfoTy(int Index, const void *HstPtr, int64_t Size)
834         : Index(Index), HstPtrBegin(reinterpret_cast<const char *>(HstPtr)),
835           HstPtrEnd(HstPtrBegin + Size), AlignedSize(Size + Size % Alignment) {}
836   };
837 
838   /// A vector of target pointers for all private arguments
839   std::vector<void *> TgtPtrs;
840 
841   /// A vector of information of all first-private arguments to be packed
842   std::vector<FirstPrivateArgInfoTy> FirstPrivateArgInfo;
843   /// Host buffer for all arguments to be packed
844   std::vector<char> FirstPrivateArgBuffer;
845   /// The total size of all arguments to be packed
846   int64_t FirstPrivateArgSize = 0;
847 
848   /// A reference to the \p DeviceTy object
849   DeviceTy &Device;
850   /// A pointer to a \p __tgt_async_info object
851   __tgt_async_info *AsyncInfo;
852 
853   // TODO: What would be the best value here? Should we make it configurable?
854   // If the size is larger than this threshold, we will allocate and transfer it
855   // immediately instead of packing it.
856   static constexpr const int64_t FirstPrivateArgSizeThreshold = 1024;
857 
858 public:
859   /// Constructor
860   PrivateArgumentManagerTy(DeviceTy &Dev, __tgt_async_info *AsyncInfo)
861       : Device(Dev), AsyncInfo(AsyncInfo) {}
862 
863   /// A a private argument
864   int addArg(void *HstPtr, int64_t ArgSize, int64_t ArgOffset,
865              bool IsFirstPrivate, void *&TgtPtr, int TgtArgsIndex) {
866     // If the argument is not first-private, or its size is greater than a
867     // predefined threshold, we will allocate memory and issue the transfer
868     // immediately.
869     if (ArgSize > FirstPrivateArgSizeThreshold || !IsFirstPrivate) {
870       TgtPtr = Device.allocData(ArgSize, HstPtr);
871       if (!TgtPtr) {
872         DP("Data allocation for %sprivate array " DPxMOD " failed.\n",
873            (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtr));
874         return OFFLOAD_FAIL;
875       }
876 #ifdef OMPTARGET_DEBUG
877       void *TgtPtrBase = (void *)((intptr_t)TgtPtr + ArgOffset);
878       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD
879          " for %sprivate array " DPxMOD " - pushing target argument " DPxMOD
880          "\n",
881          ArgSize, DPxPTR(TgtPtr), (IsFirstPrivate ? "first-" : ""),
882          DPxPTR(HstPtr), DPxPTR(TgtPtrBase));
883 #endif
884       // If first-private, copy data from host
885       if (IsFirstPrivate) {
886         int Ret = Device.submitData(TgtPtr, HstPtr, ArgSize, AsyncInfo);
887         if (Ret != OFFLOAD_SUCCESS) {
888           DP("Copying data to device failed, failed.\n");
889           return OFFLOAD_FAIL;
890         }
891       }
892       TgtPtrs.push_back(TgtPtr);
893     } else {
894       DP("Firstprivate array " DPxMOD " of size %" PRId64 " will be packed\n",
895          DPxPTR(HstPtr), ArgSize);
896       // When reach this point, the argument must meet all following
897       // requirements:
898       // 1. Its size does not exceed the threshold (see the comment for
899       // FirstPrivateArgSizeThreshold);
900       // 2. It must be first-private (needs to be mapped to target device).
901       // We will pack all this kind of arguments to transfer them all at once
902       // to reduce the number of data transfer. We will not take
903       // non-first-private arguments, aka. private arguments that doesn't need
904       // to be mapped to target device, into account because data allocation
905       // can be very efficient with memory manager.
906 
907       // Placeholder value
908       TgtPtr = nullptr;
909       FirstPrivateArgInfo.emplace_back(TgtArgsIndex, HstPtr, ArgSize);
910       FirstPrivateArgSize += FirstPrivateArgInfo.back().AlignedSize;
911     }
912 
913     return OFFLOAD_SUCCESS;
914   }
915 
916   /// Pack first-private arguments, replace place holder pointers in \p TgtArgs,
917   /// and start the transfer.
918   int packAndTransfer(std::vector<void *> &TgtArgs) {
919     if (!FirstPrivateArgInfo.empty()) {
920       assert(FirstPrivateArgSize != 0 &&
921              "FirstPrivateArgSize is 0 but FirstPrivateArgInfo is empty");
922       FirstPrivateArgBuffer.resize(FirstPrivateArgSize, 0);
923       auto Itr = FirstPrivateArgBuffer.begin();
924       // Copy all host data to this buffer
925       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
926         std::copy(Info.HstPtrBegin, Info.HstPtrEnd, Itr);
927         Itr = std::next(Itr, Info.AlignedSize);
928       }
929       // Allocate target memory
930       void *TgtPtr =
931           Device.allocData(FirstPrivateArgSize, FirstPrivateArgBuffer.data());
932       if (TgtPtr == nullptr) {
933         DP("Failed to allocate target memory for private arguments.\n");
934         return OFFLOAD_FAIL;
935       }
936       TgtPtrs.push_back(TgtPtr);
937       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD "\n",
938          FirstPrivateArgSize, DPxPTR(TgtPtr));
939       // Transfer data to target device
940       int Ret = Device.submitData(TgtPtr, FirstPrivateArgBuffer.data(),
941                                   FirstPrivateArgSize, AsyncInfo);
942       if (Ret != OFFLOAD_SUCCESS) {
943         DP("Failed to submit data of private arguments.\n");
944         return OFFLOAD_FAIL;
945       }
946       // Fill in all placeholder pointers
947       auto TP = reinterpret_cast<uintptr_t>(TgtPtr);
948       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
949         void *&Ptr = TgtArgs[Info.Index];
950         assert(Ptr == nullptr && "Target pointer is already set by mistaken");
951         Ptr = reinterpret_cast<void *>(TP);
952         TP += Info.AlignedSize;
953         DP("Firstprivate array " DPxMOD " of size %" PRId64 " mapped to " DPxMOD
954            "\n",
955            DPxPTR(Info.HstPtrBegin), Info.HstPtrEnd - Info.HstPtrBegin,
956            DPxPTR(Ptr));
957       }
958     }
959 
960     return OFFLOAD_SUCCESS;
961   }
962 
963   /// Free all target memory allocated for private arguments
964   int free() {
965     for (void *P : TgtPtrs) {
966       int Ret = Device.deleteData(P);
967       if (Ret != OFFLOAD_SUCCESS) {
968         DP("Deallocation of (first-)private arrays failed.\n");
969         return OFFLOAD_FAIL;
970       }
971     }
972 
973     TgtPtrs.clear();
974 
975     return OFFLOAD_SUCCESS;
976   }
977 };
978 
979 /// Process data before launching the kernel, including calling targetDataBegin
980 /// to map and transfer data to target device, transferring (first-)private
981 /// variables.
982 int processDataBefore(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
983                       void **ArgBases, void **Args, int64_t *ArgSizes,
984                       int64_t *ArgTypes, void **ArgMappers,
985                       std::vector<void *> &TgtArgs,
986                       std::vector<ptrdiff_t> &TgtOffsets,
987                       PrivateArgumentManagerTy &PrivateArgumentManager,
988                       __tgt_async_info *AsyncInfo) {
989   DeviceTy &Device = Devices[DeviceId];
990   int Ret = targetDataBegin(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
991                             ArgMappers, AsyncInfo);
992   if (Ret != OFFLOAD_SUCCESS) {
993     REPORT("Call to targetDataBegin failed, abort target.\n");
994     return OFFLOAD_FAIL;
995   }
996 
997   // List of (first-)private arrays allocated for this target region
998   std::vector<int> TgtArgsPositions(ArgNum, -1);
999 
1000   for (int32_t I = 0; I < ArgNum; ++I) {
1001     if (!(ArgTypes[I] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
1002       // This is not a target parameter, do not push it into TgtArgs.
1003       // Check for lambda mapping.
1004       if (isLambdaMapping(ArgTypes[I])) {
1005         assert((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1006                "PTR_AND_OBJ must be also MEMBER_OF.");
1007         unsigned Idx = getParentIndex(ArgTypes[I]);
1008         int TgtIdx = TgtArgsPositions[Idx];
1009         assert(TgtIdx != -1 && "Base address must be translated already.");
1010         // The parent lambda must be processed already and it must be the last
1011         // in TgtArgs and TgtOffsets arrays.
1012         void *HstPtrVal = Args[I];
1013         void *HstPtrBegin = ArgBases[I];
1014         void *HstPtrBase = Args[Idx];
1015         bool IsLast, IsHostPtr; // unused.
1016         void *TgtPtrBase =
1017             (void *)((intptr_t)TgtArgs[TgtIdx] + TgtOffsets[TgtIdx]);
1018         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
1019         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
1020         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
1021         void *PointerTgtPtrBegin = Device.getTgtPtrBegin(
1022             HstPtrVal, ArgSizes[I], IsLast, false, IsHostPtr);
1023         if (!PointerTgtPtrBegin) {
1024           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
1025              DPxPTR(HstPtrVal));
1026           continue;
1027         }
1028         if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
1029             TgtPtrBegin == HstPtrBegin) {
1030           DP("Unified memory is active, no need to map lambda captured"
1031              "variable (" DPxMOD ")\n",
1032              DPxPTR(HstPtrVal));
1033           continue;
1034         }
1035         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
1036            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
1037         Ret = Device.submitData(TgtPtrBegin, &PointerTgtPtrBegin,
1038                                 sizeof(void *), AsyncInfo);
1039         if (Ret != OFFLOAD_SUCCESS) {
1040           REPORT("Copying data to device failed.\n");
1041           return OFFLOAD_FAIL;
1042         }
1043       }
1044       continue;
1045     }
1046     void *HstPtrBegin = Args[I];
1047     void *HstPtrBase = ArgBases[I];
1048     void *TgtPtrBegin;
1049     ptrdiff_t TgtBaseOffset;
1050     bool IsLast, IsHostPtr; // unused.
1051     if (ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) {
1052       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
1053          DPxPTR(HstPtrBase));
1054       TgtPtrBegin = HstPtrBase;
1055       TgtBaseOffset = 0;
1056     } else if (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE) {
1057       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1058       // Can be marked for optimization if the next argument(s) do(es) not
1059       // depend on this one.
1060       const bool IsFirstPrivate =
1061           (I >= ArgNum - 1 || !(ArgTypes[I + 1] & OMP_TGT_MAPTYPE_MEMBER_OF));
1062       Ret = PrivateArgumentManager.addArg(HstPtrBegin, ArgSizes[I],
1063                                           TgtBaseOffset, IsFirstPrivate,
1064                                           TgtPtrBegin, TgtArgs.size());
1065       if (Ret != OFFLOAD_SUCCESS) {
1066         REPORT("Failed to process %sprivate argument " DPxMOD "\n",
1067                (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtrBegin));
1068         return OFFLOAD_FAIL;
1069       }
1070     } else {
1071       if (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
1072         HstPtrBase = *reinterpret_cast<void **>(HstPtrBase);
1073       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, ArgSizes[I], IsLast,
1074                                           false, IsHostPtr);
1075       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1076 #ifdef OMPTARGET_DEBUG
1077       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
1078       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
1079          DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
1080 #endif
1081     }
1082     TgtArgsPositions[I] = TgtArgs.size();
1083     TgtArgs.push_back(TgtPtrBegin);
1084     TgtOffsets.push_back(TgtBaseOffset);
1085   }
1086 
1087   assert(TgtArgs.size() == TgtOffsets.size() &&
1088          "Size mismatch in arguments and offsets");
1089 
1090   // Pack and transfer first-private arguments
1091   Ret = PrivateArgumentManager.packAndTransfer(TgtArgs);
1092   if (Ret != OFFLOAD_SUCCESS) {
1093     DP("Failed to pack and transfer first private arguments\n");
1094     return OFFLOAD_FAIL;
1095   }
1096 
1097   return OFFLOAD_SUCCESS;
1098 }
1099 
1100 /// Process data after launching the kernel, including transferring data back to
1101 /// host if needed and deallocating target memory of (first-)private variables.
1102 int processDataAfter(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
1103                      void **ArgBases, void **Args, int64_t *ArgSizes,
1104                      int64_t *ArgTypes, void **ArgMappers,
1105                      PrivateArgumentManagerTy &PrivateArgumentManager,
1106                      __tgt_async_info *AsyncInfo) {
1107   DeviceTy &Device = Devices[DeviceId];
1108 
1109   // Move data from device.
1110   int Ret = targetDataEnd(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
1111                           ArgMappers, AsyncInfo);
1112   if (Ret != OFFLOAD_SUCCESS) {
1113     REPORT("Call to targetDataEnd failed, abort target.\n");
1114     return OFFLOAD_FAIL;
1115   }
1116 
1117   // Free target memory for private arguments
1118   Ret = PrivateArgumentManager.free();
1119   if (Ret != OFFLOAD_SUCCESS) {
1120     REPORT("Failed to deallocate target memory for private args\n");
1121     return OFFLOAD_FAIL;
1122   }
1123 
1124   return OFFLOAD_SUCCESS;
1125 }
1126 } // namespace
1127 
1128 /// performs the same actions as data_begin in case arg_num is
1129 /// non-zero and initiates run of the offloaded region on the target platform;
1130 /// if arg_num is non-zero after the region execution is done it also
1131 /// performs the same action as data_update and data_end above. This function
1132 /// returns 0 if it was able to transfer the execution to a target and an
1133 /// integer different from zero otherwise.
1134 int target(int64_t DeviceId, void *HostPtr, int32_t ArgNum, void **ArgBases,
1135            void **Args, int64_t *ArgSizes, int64_t *ArgTypes, void **ArgMappers,
1136            int32_t TeamNum, int32_t ThreadLimit, int IsTeamConstruct) {
1137   DeviceTy &Device = Devices[DeviceId];
1138 
1139   TableMap *TM = getTableMap(HostPtr);
1140   // No map for this host pointer found!
1141   if (!TM) {
1142     REPORT("Host ptr " DPxMOD " does not have a matching target pointer.\n",
1143            DPxPTR(HostPtr));
1144     return OFFLOAD_FAIL;
1145   }
1146 
1147   // get target table.
1148   __tgt_target_table *TargetTable = nullptr;
1149   {
1150     std::lock_guard<std::mutex> TrlTblLock(*TrlTblMtx);
1151     assert(TM->Table->TargetsTable.size() > (size_t)DeviceId &&
1152            "Not expecting a device ID outside the table's bounds!");
1153     TargetTable = TM->Table->TargetsTable[DeviceId];
1154   }
1155   assert(TargetTable && "Global data has not been mapped\n");
1156 
1157   __tgt_async_info AsyncInfo;
1158 
1159   std::vector<void *> TgtArgs;
1160   std::vector<ptrdiff_t> TgtOffsets;
1161 
1162   PrivateArgumentManagerTy PrivateArgumentManager(Device, &AsyncInfo);
1163 
1164   // Process data, such as data mapping, before launching the kernel
1165   int Ret = processDataBefore(DeviceId, HostPtr, ArgNum, ArgBases, Args,
1166                               ArgSizes, ArgTypes, ArgMappers, TgtArgs,
1167                               TgtOffsets, PrivateArgumentManager, &AsyncInfo);
1168   if (Ret != OFFLOAD_SUCCESS) {
1169     REPORT("Failed to process data before launching the kernel.\n");
1170     return OFFLOAD_FAIL;
1171   }
1172 
1173   // Get loop trip count
1174   uint64_t LoopTripCount = getLoopTripCount(DeviceId);
1175 
1176   // Launch device execution.
1177   void *TgtEntryPtr = TargetTable->EntriesBegin[TM->Index].addr;
1178   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
1179      TargetTable->EntriesBegin[TM->Index].name, DPxPTR(TgtEntryPtr), TM->Index);
1180 
1181   if (IsTeamConstruct)
1182     Ret = Device.runTeamRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1183                                TgtArgs.size(), TeamNum, ThreadLimit,
1184                                LoopTripCount, &AsyncInfo);
1185   else
1186     Ret = Device.runRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1187                            TgtArgs.size(), &AsyncInfo);
1188 
1189   if (Ret != OFFLOAD_SUCCESS) {
1190     REPORT("Executing target region abort target.\n");
1191     return OFFLOAD_FAIL;
1192   }
1193 
1194   // Transfer data back and deallocate target memory for (first-)private
1195   // variables
1196   Ret = processDataAfter(DeviceId, HostPtr, ArgNum, ArgBases, Args, ArgSizes,
1197                          ArgTypes, ArgMappers, PrivateArgumentManager,
1198                          &AsyncInfo);
1199   if (Ret != OFFLOAD_SUCCESS) {
1200     REPORT("Failed to process data after launching the kernel.\n");
1201     return OFFLOAD_FAIL;
1202   }
1203 
1204   return OFFLOAD_SUCCESS;
1205 }
1206