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                    !(arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
377           // Copy data only if the "parent" struct has RefCount==1.
378           // If this is a PTR_AND_OBJ entry, the OBJ is not part of the struct,
379           // so exclude it from this check.
380           int32_t parent_idx = getParentIndex(arg_types[i]);
381           uint64_t parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
382           assert(parent_rc > 0 && "parent struct not found");
383           if (parent_rc == 1) {
384             copy = true;
385           }
386         }
387       }
388 
389       if (copy && !IsHostPtr) {
390         DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
391            data_size, DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
392         int rt = Device.submitData(TgtPtrBegin, HstPtrBegin, data_size,
393                                    async_info_ptr);
394         if (rt != OFFLOAD_SUCCESS) {
395           REPORT("Copying data to device failed.\n");
396           return OFFLOAD_FAIL;
397         }
398       }
399     }
400 
401     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ && !IsHostPtr) {
402       DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
403          DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
404       uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
405       void *TgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
406       int rt = Device.submitData(PointerTgtPtrBegin, &TgtPtrBase,
407                                  sizeof(void *), async_info_ptr);
408       if (rt != OFFLOAD_SUCCESS) {
409         REPORT("Copying data to device failed.\n");
410         return OFFLOAD_FAIL;
411       }
412       // create shadow pointers for this entry
413       Device.ShadowMtx.lock();
414       Device.ShadowPtrMap[Pointer_HstPtrBegin] = {
415           HstPtrBase, PointerTgtPtrBegin, TgtPtrBase};
416       Device.ShadowMtx.unlock();
417     }
418   }
419 
420   return OFFLOAD_SUCCESS;
421 }
422 
423 namespace {
424 /// This structure contains information to deallocate a target pointer, aka.
425 /// used to call the function \p DeviceTy::deallocTgtPtr.
426 struct DeallocTgtPtrInfo {
427   /// Host pointer used to look up into the map table
428   void *HstPtrBegin;
429   /// Size of the data
430   int64_t DataSize;
431   /// Whether it is forced to be removed from the map table
432   bool ForceDelete;
433   /// Whether it has \p close modifier
434   bool HasCloseModifier;
435 
436   DeallocTgtPtrInfo(void *HstPtr, int64_t Size, bool ForceDelete,
437                     bool HasCloseModifier)
438       : HstPtrBegin(HstPtr), DataSize(Size), ForceDelete(ForceDelete),
439         HasCloseModifier(HasCloseModifier) {}
440 };
441 } // namespace
442 
443 /// Internal function to undo the mapping and retrieve the data from the device.
444 int targetDataEnd(DeviceTy &Device, int32_t ArgNum, void **ArgBases,
445                   void **Args, int64_t *ArgSizes, int64_t *ArgTypes,
446                   void **ArgMappers, __tgt_async_info *AsyncInfo) {
447   int Ret;
448   std::vector<DeallocTgtPtrInfo> DeallocTgtPtrs;
449   // process each input.
450   for (int32_t I = ArgNum - 1; I >= 0; --I) {
451     // Ignore private variables and arrays - there is no mapping for them.
452     // Also, ignore the use_device_ptr directive, it has no effect here.
453     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) ||
454         (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE))
455       continue;
456 
457     if (ArgMappers && ArgMappers[I]) {
458       // Instead of executing the regular path of targetDataEnd, call the
459       // targetDataMapper variant which will call targetDataEnd again
460       // with new arguments.
461       DP("Calling targetDataMapper for the %dth argument\n", I);
462 
463       Ret = targetDataMapper(Device, ArgBases[I], Args[I], ArgSizes[I],
464                              ArgTypes[I], ArgMappers[I], targetDataEnd);
465 
466       if (Ret != OFFLOAD_SUCCESS) {
467         REPORT("Call to targetDataEnd via targetDataMapper for custom mapper"
468                " failed.\n");
469         return OFFLOAD_FAIL;
470       }
471 
472       // Skip the rest of this function, continue to the next argument.
473       continue;
474     }
475 
476     void *HstPtrBegin = Args[I];
477     int64_t DataSize = ArgSizes[I];
478     // Adjust for proper alignment if this is a combined entry (for structs).
479     // Look at the next argument - if that is MEMBER_OF this one, then this one
480     // is a combined entry.
481     const int NextI = I + 1;
482     if (getParentIndex(ArgTypes[I]) < 0 && NextI < ArgNum &&
483         getParentIndex(ArgTypes[NextI]) == I) {
484       int64_t Padding = (int64_t)HstPtrBegin % Alignment;
485       if (Padding) {
486         DP("Using a Padding of %" PRId64 " bytes for begin address " DPxMOD
487            "\n",
488            Padding, DPxPTR(HstPtrBegin));
489         HstPtrBegin = (char *)HstPtrBegin - Padding;
490         DataSize += Padding;
491       }
492     }
493 
494     bool IsLast, IsHostPtr;
495     bool IsImplicit = ArgTypes[I] & OMP_TGT_MAPTYPE_IMPLICIT;
496     bool UpdateRef = !(ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
497                      (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ);
498     bool ForceDelete = ArgTypes[I] & OMP_TGT_MAPTYPE_DELETE;
499     bool HasCloseModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_CLOSE;
500     bool HasPresentModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_PRESENT;
501 
502     // If PTR_AND_OBJ, HstPtrBegin is address of pointee
503     void *TgtPtrBegin = Device.getTgtPtrBegin(
504         HstPtrBegin, DataSize, IsLast, UpdateRef, IsHostPtr, !IsImplicit);
505     if (!TgtPtrBegin && (DataSize || HasPresentModifier)) {
506       DP("Mapping does not exist (%s)\n",
507          (HasPresentModifier ? "'present' map type modifier" : "ignored"));
508       if (HasPresentModifier) {
509         // This should be an error upon entering an "omp target exit data".  It
510         // should not be an error upon exiting an "omp target data" or "omp
511         // target".  For "omp target data", Clang thus doesn't include present
512         // modifiers for end calls.  For "omp target", we have not found a valid
513         // OpenMP program for which the error matters: it appears that, if a
514         // program can guarantee that data is present at the beginning of an
515         // "omp target" region so that there's no error there, that data is also
516         // guaranteed to be present at the end.
517         MESSAGE("device mapping required by 'present' map type modifier does "
518                 "not exist for host address " DPxMOD " (%" PRId64 " bytes)",
519                 DPxPTR(HstPtrBegin), DataSize);
520         return OFFLOAD_FAIL;
521       }
522     } else {
523       DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
524          " - is%s last\n",
525          DataSize, DPxPTR(TgtPtrBegin), (IsLast ? "" : " not"));
526     }
527 
528     bool DelEntry = IsLast || ForceDelete;
529 
530     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
531         !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
532       DelEntry = false; // protect parent struct from being deallocated
533     }
534 
535     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
536       // Move data back to the host
537       if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
538         bool Always = ArgTypes[I] & OMP_TGT_MAPTYPE_ALWAYS;
539         bool CopyMember = false;
540         if (!(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
541             HasCloseModifier) {
542           if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
543               !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
544             // Copy data only if the "parent" struct has RefCount==1.
545             int32_t ParentIdx = getParentIndex(ArgTypes[I]);
546             uint64_t ParentRC = Device.getMapEntryRefCnt(Args[ParentIdx]);
547             assert(ParentRC > 0 && "parent struct not found");
548             if (ParentRC == 1)
549               CopyMember = true;
550           }
551         }
552 
553         if ((DelEntry || Always || CopyMember) &&
554             !(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
555               TgtPtrBegin == HstPtrBegin)) {
556           DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
557              DataSize, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
558           Ret = Device.retrieveData(HstPtrBegin, TgtPtrBegin, DataSize,
559                                     AsyncInfo);
560           if (Ret != OFFLOAD_SUCCESS) {
561             REPORT("Copying data from device failed.\n");
562             return OFFLOAD_FAIL;
563           }
564         }
565       }
566 
567       // If we copied back to the host a struct/array containing pointers, we
568       // need to restore the original host pointer values from their shadow
569       // copies. If the struct is going to be deallocated, remove any remaining
570       // shadow pointer entries for this struct.
571       uintptr_t LB = (uintptr_t)HstPtrBegin;
572       uintptr_t UB = (uintptr_t)HstPtrBegin + DataSize;
573       Device.ShadowMtx.lock();
574       for (ShadowPtrListTy::iterator Itr = Device.ShadowPtrMap.begin();
575            Itr != Device.ShadowPtrMap.end();) {
576         void **ShadowHstPtrAddr = (void **)Itr->first;
577 
578         // An STL map is sorted on its keys; use this property
579         // to quickly determine when to break out of the loop.
580         if ((uintptr_t)ShadowHstPtrAddr < LB) {
581           ++Itr;
582           continue;
583         }
584         if ((uintptr_t)ShadowHstPtrAddr >= UB)
585           break;
586 
587         // If we copied the struct to the host, we need to restore the pointer.
588         if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
589           DP("Restoring original host pointer value " DPxMOD " for host "
590              "pointer " DPxMOD "\n",
591              DPxPTR(Itr->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
592           *ShadowHstPtrAddr = Itr->second.HstPtrVal;
593         }
594         // If the struct is to be deallocated, remove the shadow entry.
595         if (DelEntry) {
596           DP("Removing shadow pointer " DPxMOD "\n", DPxPTR(ShadowHstPtrAddr));
597           Itr = Device.ShadowPtrMap.erase(Itr);
598         } else {
599           ++Itr;
600         }
601       }
602       Device.ShadowMtx.unlock();
603 
604       // Add pointer to the buffer for later deallocation
605       if (DelEntry)
606         DeallocTgtPtrs.emplace_back(HstPtrBegin, DataSize, ForceDelete,
607                                     HasCloseModifier);
608     }
609   }
610 
611   // We need to synchronize before deallocating data.
612   // If AsyncInfo is nullptr, the previous data transfer (if has) will be
613   // synchronous, so we don't need to synchronize again. If AsyncInfo->Queue is
614   // nullptr, there is no data transfer happened because once there is,
615   // AsyncInfo->Queue will not be nullptr, so again, we don't need to
616   // synchronize.
617   if (AsyncInfo && AsyncInfo->Queue) {
618     Ret = Device.synchronize(AsyncInfo);
619     if (Ret != OFFLOAD_SUCCESS) {
620       REPORT("Failed to synchronize device.\n");
621       return OFFLOAD_FAIL;
622     }
623   }
624 
625   // Deallocate target pointer
626   for (DeallocTgtPtrInfo &Info : DeallocTgtPtrs) {
627     Ret = Device.deallocTgtPtr(Info.HstPtrBegin, Info.DataSize,
628                                Info.ForceDelete, Info.HasCloseModifier);
629     if (Ret != OFFLOAD_SUCCESS) {
630       REPORT("Deallocating data from device failed.\n");
631       return OFFLOAD_FAIL;
632     }
633   }
634 
635   return OFFLOAD_SUCCESS;
636 }
637 
638 /// Internal function to pass data to/from the target.
639 // async_info_ptr is currently unused, added here so target_data_update has the
640 // same signature as targetDataBegin and targetDataEnd.
641 int target_data_update(DeviceTy &Device, int32_t arg_num,
642     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
643     void **arg_mappers, __tgt_async_info *async_info_ptr) {
644   // process each input.
645   for (int32_t i = 0; i < arg_num; ++i) {
646     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
647         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
648       continue;
649 
650     if (arg_mappers && arg_mappers[i]) {
651       // Instead of executing the regular path of target_data_update, call the
652       // targetDataMapper variant which will call target_data_update again
653       // with new arguments.
654       DP("Calling targetDataMapper for the %dth argument\n", i);
655 
656       int rc =
657           targetDataMapper(Device, args_base[i], args[i], arg_sizes[i],
658                            arg_types[i], arg_mappers[i], target_data_update);
659 
660       if (rc != OFFLOAD_SUCCESS) {
661         REPORT(
662             "Call to target_data_update via targetDataMapper for custom mapper"
663             " failed.\n");
664         return OFFLOAD_FAIL;
665       }
666 
667       // Skip the rest of this function, continue to the next argument.
668       continue;
669     }
670 
671     void *HstPtrBegin = args[i];
672     int64_t MapSize = arg_sizes[i];
673     bool IsLast, IsHostPtr;
674     void *TgtPtrBegin = Device.getTgtPtrBegin(
675         HstPtrBegin, MapSize, IsLast, false, IsHostPtr, /*MustContain=*/true);
676     if (!TgtPtrBegin) {
677       DP("hst data:" DPxMOD " not found, becomes a noop\n", DPxPTR(HstPtrBegin));
678       if (arg_types[i] & OMP_TGT_MAPTYPE_PRESENT) {
679         MESSAGE("device mapping required by 'present' motion modifier does not "
680                 "exist for host address " DPxMOD " (%" PRId64 " bytes)",
681                 DPxPTR(HstPtrBegin), MapSize);
682         return OFFLOAD_FAIL;
683       }
684       continue;
685     }
686 
687     if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
688         TgtPtrBegin == HstPtrBegin) {
689       DP("hst data:" DPxMOD " unified and shared, becomes a noop\n",
690          DPxPTR(HstPtrBegin));
691       continue;
692     }
693 
694     if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
695       DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
696           arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
697       int rt = Device.retrieveData(HstPtrBegin, TgtPtrBegin, MapSize, nullptr);
698       if (rt != OFFLOAD_SUCCESS) {
699         REPORT("Copying data from device failed.\n");
700         return OFFLOAD_FAIL;
701       }
702 
703       uintptr_t lb = (uintptr_t) HstPtrBegin;
704       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
705       Device.ShadowMtx.lock();
706       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
707           it != Device.ShadowPtrMap.end(); ++it) {
708         void **ShadowHstPtrAddr = (void**) it->first;
709         if ((uintptr_t) ShadowHstPtrAddr < lb)
710           continue;
711         if ((uintptr_t) ShadowHstPtrAddr >= ub)
712           break;
713         DP("Restoring original host pointer value " DPxMOD " for host pointer "
714             DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
715             DPxPTR(ShadowHstPtrAddr));
716         *ShadowHstPtrAddr = it->second.HstPtrVal;
717       }
718       Device.ShadowMtx.unlock();
719     }
720 
721     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
722       DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
723           arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
724       int rt = Device.submitData(TgtPtrBegin, HstPtrBegin, MapSize, nullptr);
725       if (rt != OFFLOAD_SUCCESS) {
726         REPORT("Copying data to device failed.\n");
727         return OFFLOAD_FAIL;
728       }
729 
730       uintptr_t lb = (uintptr_t) HstPtrBegin;
731       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
732       Device.ShadowMtx.lock();
733       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
734           it != Device.ShadowPtrMap.end(); ++it) {
735         void **ShadowHstPtrAddr = (void **)it->first;
736         if ((uintptr_t)ShadowHstPtrAddr < lb)
737           continue;
738         if ((uintptr_t)ShadowHstPtrAddr >= ub)
739           break;
740         DP("Restoring original target pointer value " DPxMOD " for target "
741            "pointer " DPxMOD "\n",
742            DPxPTR(it->second.TgtPtrVal), DPxPTR(it->second.TgtPtrAddr));
743         rt = Device.submitData(it->second.TgtPtrAddr, &it->second.TgtPtrVal,
744                                sizeof(void *), nullptr);
745         if (rt != OFFLOAD_SUCCESS) {
746           REPORT("Copying data to device failed.\n");
747           Device.ShadowMtx.unlock();
748           return OFFLOAD_FAIL;
749         }
750       }
751       Device.ShadowMtx.unlock();
752     }
753   }
754   return OFFLOAD_SUCCESS;
755 }
756 
757 static const unsigned LambdaMapping = OMP_TGT_MAPTYPE_PTR_AND_OBJ |
758                                       OMP_TGT_MAPTYPE_LITERAL |
759                                       OMP_TGT_MAPTYPE_IMPLICIT;
760 static bool isLambdaMapping(int64_t Mapping) {
761   return (Mapping & LambdaMapping) == LambdaMapping;
762 }
763 
764 namespace {
765 /// Find the table information in the map or look it up in the translation
766 /// tables.
767 TableMap *getTableMap(void *HostPtr) {
768   std::lock_guard<std::mutex> TblMapLock(*TblMapMtx);
769   HostPtrToTableMapTy::iterator TableMapIt = HostPtrToTableMap->find(HostPtr);
770 
771   if (TableMapIt != HostPtrToTableMap->end())
772     return &TableMapIt->second;
773 
774   // We don't have a map. So search all the registered libraries.
775   TableMap *TM = nullptr;
776   std::lock_guard<std::mutex> TrlTblLock(*TrlTblMtx);
777   for (HostEntriesBeginToTransTableTy::iterator Itr =
778            HostEntriesBeginToTransTable->begin();
779        Itr != HostEntriesBeginToTransTable->end(); ++Itr) {
780     // get the translation table (which contains all the good info).
781     TranslationTable *TransTable = &Itr->second;
782     // iterate over all the host table entries to see if we can locate the
783     // host_ptr.
784     __tgt_offload_entry *Cur = TransTable->HostTable.EntriesBegin;
785     for (uint32_t I = 0; Cur < TransTable->HostTable.EntriesEnd; ++Cur, ++I) {
786       if (Cur->addr != HostPtr)
787         continue;
788       // we got a match, now fill the HostPtrToTableMap so that we
789       // may avoid this search next time.
790       TM = &(*HostPtrToTableMap)[HostPtr];
791       TM->Table = TransTable;
792       TM->Index = I;
793       return TM;
794     }
795   }
796 
797   return nullptr;
798 }
799 
800 /// Get loop trip count
801 /// FIXME: This function will not work right if calling
802 /// __kmpc_push_target_tripcount in one thread but doing offloading in another
803 /// thread, which might occur when we call task yield.
804 uint64_t getLoopTripCount(int64_t DeviceId) {
805   DeviceTy &Device = Devices[DeviceId];
806   uint64_t LoopTripCount = 0;
807 
808   {
809     std::lock_guard<std::mutex> TblMapLock(*TblMapMtx);
810     auto I = Device.LoopTripCnt.find(__kmpc_global_thread_num(NULL));
811     if (I != Device.LoopTripCnt.end()) {
812       LoopTripCount = I->second;
813       Device.LoopTripCnt.erase(I);
814       DP("loop trip count is %lu.\n", LoopTripCount);
815     }
816   }
817 
818   return LoopTripCount;
819 }
820 
821 /// A class manages private arguments in a target region.
822 class PrivateArgumentManagerTy {
823   /// A data structure for the information of first-private arguments. We can
824   /// use this information to optimize data transfer by packing all
825   /// first-private arguments and transfer them all at once.
826   struct FirstPrivateArgInfoTy {
827     /// The index of the element in \p TgtArgs corresponding to the argument
828     const int Index;
829     /// Host pointer begin
830     const char *HstPtrBegin;
831     /// Host pointer end
832     const char *HstPtrEnd;
833     /// Aligned size
834     const int64_t AlignedSize;
835 
836     FirstPrivateArgInfoTy(int Index, const void *HstPtr, int64_t Size)
837         : Index(Index), HstPtrBegin(reinterpret_cast<const char *>(HstPtr)),
838           HstPtrEnd(HstPtrBegin + Size), AlignedSize(Size + Size % Alignment) {}
839   };
840 
841   /// A vector of target pointers for all private arguments
842   std::vector<void *> TgtPtrs;
843 
844   /// A vector of information of all first-private arguments to be packed
845   std::vector<FirstPrivateArgInfoTy> FirstPrivateArgInfo;
846   /// Host buffer for all arguments to be packed
847   std::vector<char> FirstPrivateArgBuffer;
848   /// The total size of all arguments to be packed
849   int64_t FirstPrivateArgSize = 0;
850 
851   /// A reference to the \p DeviceTy object
852   DeviceTy &Device;
853   /// A pointer to a \p __tgt_async_info object
854   __tgt_async_info *AsyncInfo;
855 
856   // TODO: What would be the best value here? Should we make it configurable?
857   // If the size is larger than this threshold, we will allocate and transfer it
858   // immediately instead of packing it.
859   static constexpr const int64_t FirstPrivateArgSizeThreshold = 1024;
860 
861 public:
862   /// Constructor
863   PrivateArgumentManagerTy(DeviceTy &Dev, __tgt_async_info *AsyncInfo)
864       : Device(Dev), AsyncInfo(AsyncInfo) {}
865 
866   /// A a private argument
867   int addArg(void *HstPtr, int64_t ArgSize, int64_t ArgOffset,
868              bool IsFirstPrivate, void *&TgtPtr, int TgtArgsIndex) {
869     // If the argument is not first-private, or its size is greater than a
870     // predefined threshold, we will allocate memory and issue the transfer
871     // immediately.
872     if (ArgSize > FirstPrivateArgSizeThreshold || !IsFirstPrivate) {
873       TgtPtr = Device.allocData(ArgSize, HstPtr);
874       if (!TgtPtr) {
875         DP("Data allocation for %sprivate array " DPxMOD " failed.\n",
876            (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtr));
877         return OFFLOAD_FAIL;
878       }
879 #ifdef OMPTARGET_DEBUG
880       void *TgtPtrBase = (void *)((intptr_t)TgtPtr + ArgOffset);
881       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD
882          " for %sprivate array " DPxMOD " - pushing target argument " DPxMOD
883          "\n",
884          ArgSize, DPxPTR(TgtPtr), (IsFirstPrivate ? "first-" : ""),
885          DPxPTR(HstPtr), DPxPTR(TgtPtrBase));
886 #endif
887       // If first-private, copy data from host
888       if (IsFirstPrivate) {
889         int Ret = Device.submitData(TgtPtr, HstPtr, ArgSize, AsyncInfo);
890         if (Ret != OFFLOAD_SUCCESS) {
891           DP("Copying data to device failed, failed.\n");
892           return OFFLOAD_FAIL;
893         }
894       }
895       TgtPtrs.push_back(TgtPtr);
896     } else {
897       DP("Firstprivate array " DPxMOD " of size %" PRId64 " will be packed\n",
898          DPxPTR(HstPtr), ArgSize);
899       // When reach this point, the argument must meet all following
900       // requirements:
901       // 1. Its size does not exceed the threshold (see the comment for
902       // FirstPrivateArgSizeThreshold);
903       // 2. It must be first-private (needs to be mapped to target device).
904       // We will pack all this kind of arguments to transfer them all at once
905       // to reduce the number of data transfer. We will not take
906       // non-first-private arguments, aka. private arguments that doesn't need
907       // to be mapped to target device, into account because data allocation
908       // can be very efficient with memory manager.
909 
910       // Placeholder value
911       TgtPtr = nullptr;
912       FirstPrivateArgInfo.emplace_back(TgtArgsIndex, HstPtr, ArgSize);
913       FirstPrivateArgSize += FirstPrivateArgInfo.back().AlignedSize;
914     }
915 
916     return OFFLOAD_SUCCESS;
917   }
918 
919   /// Pack first-private arguments, replace place holder pointers in \p TgtArgs,
920   /// and start the transfer.
921   int packAndTransfer(std::vector<void *> &TgtArgs) {
922     if (!FirstPrivateArgInfo.empty()) {
923       assert(FirstPrivateArgSize != 0 &&
924              "FirstPrivateArgSize is 0 but FirstPrivateArgInfo is empty");
925       FirstPrivateArgBuffer.resize(FirstPrivateArgSize, 0);
926       auto Itr = FirstPrivateArgBuffer.begin();
927       // Copy all host data to this buffer
928       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
929         std::copy(Info.HstPtrBegin, Info.HstPtrEnd, Itr);
930         Itr = std::next(Itr, Info.AlignedSize);
931       }
932       // Allocate target memory
933       void *TgtPtr =
934           Device.allocData(FirstPrivateArgSize, FirstPrivateArgBuffer.data());
935       if (TgtPtr == nullptr) {
936         DP("Failed to allocate target memory for private arguments.\n");
937         return OFFLOAD_FAIL;
938       }
939       TgtPtrs.push_back(TgtPtr);
940       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD "\n",
941          FirstPrivateArgSize, DPxPTR(TgtPtr));
942       // Transfer data to target device
943       int Ret = Device.submitData(TgtPtr, FirstPrivateArgBuffer.data(),
944                                   FirstPrivateArgSize, AsyncInfo);
945       if (Ret != OFFLOAD_SUCCESS) {
946         DP("Failed to submit data of private arguments.\n");
947         return OFFLOAD_FAIL;
948       }
949       // Fill in all placeholder pointers
950       auto TP = reinterpret_cast<uintptr_t>(TgtPtr);
951       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
952         void *&Ptr = TgtArgs[Info.Index];
953         assert(Ptr == nullptr && "Target pointer is already set by mistaken");
954         Ptr = reinterpret_cast<void *>(TP);
955         TP += Info.AlignedSize;
956         DP("Firstprivate array " DPxMOD " of size %" PRId64 " mapped to " DPxMOD
957            "\n",
958            DPxPTR(Info.HstPtrBegin), Info.HstPtrEnd - Info.HstPtrBegin,
959            DPxPTR(Ptr));
960       }
961     }
962 
963     return OFFLOAD_SUCCESS;
964   }
965 
966   /// Free all target memory allocated for private arguments
967   int free() {
968     for (void *P : TgtPtrs) {
969       int Ret = Device.deleteData(P);
970       if (Ret != OFFLOAD_SUCCESS) {
971         DP("Deallocation of (first-)private arrays failed.\n");
972         return OFFLOAD_FAIL;
973       }
974     }
975 
976     TgtPtrs.clear();
977 
978     return OFFLOAD_SUCCESS;
979   }
980 };
981 
982 /// Process data before launching the kernel, including calling targetDataBegin
983 /// to map and transfer data to target device, transferring (first-)private
984 /// variables.
985 int processDataBefore(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
986                       void **ArgBases, void **Args, int64_t *ArgSizes,
987                       int64_t *ArgTypes, void **ArgMappers,
988                       std::vector<void *> &TgtArgs,
989                       std::vector<ptrdiff_t> &TgtOffsets,
990                       PrivateArgumentManagerTy &PrivateArgumentManager,
991                       __tgt_async_info *AsyncInfo) {
992   DeviceTy &Device = Devices[DeviceId];
993   int Ret = targetDataBegin(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
994                             ArgMappers, AsyncInfo);
995   if (Ret != OFFLOAD_SUCCESS) {
996     REPORT("Call to targetDataBegin failed, abort target.\n");
997     return OFFLOAD_FAIL;
998   }
999 
1000   // List of (first-)private arrays allocated for this target region
1001   std::vector<int> TgtArgsPositions(ArgNum, -1);
1002 
1003   for (int32_t I = 0; I < ArgNum; ++I) {
1004     if (!(ArgTypes[I] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
1005       // This is not a target parameter, do not push it into TgtArgs.
1006       // Check for lambda mapping.
1007       if (isLambdaMapping(ArgTypes[I])) {
1008         assert((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1009                "PTR_AND_OBJ must be also MEMBER_OF.");
1010         unsigned Idx = getParentIndex(ArgTypes[I]);
1011         int TgtIdx = TgtArgsPositions[Idx];
1012         assert(TgtIdx != -1 && "Base address must be translated already.");
1013         // The parent lambda must be processed already and it must be the last
1014         // in TgtArgs and TgtOffsets arrays.
1015         void *HstPtrVal = Args[I];
1016         void *HstPtrBegin = ArgBases[I];
1017         void *HstPtrBase = Args[Idx];
1018         bool IsLast, IsHostPtr; // unused.
1019         void *TgtPtrBase =
1020             (void *)((intptr_t)TgtArgs[TgtIdx] + TgtOffsets[TgtIdx]);
1021         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
1022         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
1023         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
1024         void *PointerTgtPtrBegin = Device.getTgtPtrBegin(
1025             HstPtrVal, ArgSizes[I], IsLast, false, IsHostPtr);
1026         if (!PointerTgtPtrBegin) {
1027           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
1028              DPxPTR(HstPtrVal));
1029           continue;
1030         }
1031         if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
1032             TgtPtrBegin == HstPtrBegin) {
1033           DP("Unified memory is active, no need to map lambda captured"
1034              "variable (" DPxMOD ")\n",
1035              DPxPTR(HstPtrVal));
1036           continue;
1037         }
1038         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
1039            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
1040         Ret = Device.submitData(TgtPtrBegin, &PointerTgtPtrBegin,
1041                                 sizeof(void *), AsyncInfo);
1042         if (Ret != OFFLOAD_SUCCESS) {
1043           REPORT("Copying data to device failed.\n");
1044           return OFFLOAD_FAIL;
1045         }
1046       }
1047       continue;
1048     }
1049     void *HstPtrBegin = Args[I];
1050     void *HstPtrBase = ArgBases[I];
1051     void *TgtPtrBegin;
1052     ptrdiff_t TgtBaseOffset;
1053     bool IsLast, IsHostPtr; // unused.
1054     if (ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) {
1055       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
1056          DPxPTR(HstPtrBase));
1057       TgtPtrBegin = HstPtrBase;
1058       TgtBaseOffset = 0;
1059     } else if (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE) {
1060       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1061       // Can be marked for optimization if the next argument(s) do(es) not
1062       // depend on this one.
1063       const bool IsFirstPrivate =
1064           (I >= ArgNum - 1 || !(ArgTypes[I + 1] & OMP_TGT_MAPTYPE_MEMBER_OF));
1065       Ret = PrivateArgumentManager.addArg(HstPtrBegin, ArgSizes[I],
1066                                           TgtBaseOffset, IsFirstPrivate,
1067                                           TgtPtrBegin, TgtArgs.size());
1068       if (Ret != OFFLOAD_SUCCESS) {
1069         REPORT("Failed to process %sprivate argument " DPxMOD "\n",
1070                (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtrBegin));
1071         return OFFLOAD_FAIL;
1072       }
1073     } else {
1074       if (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
1075         HstPtrBase = *reinterpret_cast<void **>(HstPtrBase);
1076       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, ArgSizes[I], IsLast,
1077                                           false, IsHostPtr);
1078       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1079 #ifdef OMPTARGET_DEBUG
1080       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
1081       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
1082          DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
1083 #endif
1084     }
1085     TgtArgsPositions[I] = TgtArgs.size();
1086     TgtArgs.push_back(TgtPtrBegin);
1087     TgtOffsets.push_back(TgtBaseOffset);
1088   }
1089 
1090   assert(TgtArgs.size() == TgtOffsets.size() &&
1091          "Size mismatch in arguments and offsets");
1092 
1093   // Pack and transfer first-private arguments
1094   Ret = PrivateArgumentManager.packAndTransfer(TgtArgs);
1095   if (Ret != OFFLOAD_SUCCESS) {
1096     DP("Failed to pack and transfer first private arguments\n");
1097     return OFFLOAD_FAIL;
1098   }
1099 
1100   return OFFLOAD_SUCCESS;
1101 }
1102 
1103 /// Process data after launching the kernel, including transferring data back to
1104 /// host if needed and deallocating target memory of (first-)private variables.
1105 int processDataAfter(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
1106                      void **ArgBases, void **Args, int64_t *ArgSizes,
1107                      int64_t *ArgTypes, void **ArgMappers,
1108                      PrivateArgumentManagerTy &PrivateArgumentManager,
1109                      __tgt_async_info *AsyncInfo) {
1110   DeviceTy &Device = Devices[DeviceId];
1111 
1112   // Move data from device.
1113   int Ret = targetDataEnd(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
1114                           ArgMappers, AsyncInfo);
1115   if (Ret != OFFLOAD_SUCCESS) {
1116     REPORT("Call to targetDataEnd failed, abort target.\n");
1117     return OFFLOAD_FAIL;
1118   }
1119 
1120   // Free target memory for private arguments
1121   Ret = PrivateArgumentManager.free();
1122   if (Ret != OFFLOAD_SUCCESS) {
1123     REPORT("Failed to deallocate target memory for private args\n");
1124     return OFFLOAD_FAIL;
1125   }
1126 
1127   return OFFLOAD_SUCCESS;
1128 }
1129 } // namespace
1130 
1131 /// performs the same actions as data_begin in case arg_num is
1132 /// non-zero and initiates run of the offloaded region on the target platform;
1133 /// if arg_num is non-zero after the region execution is done it also
1134 /// performs the same action as data_update and data_end above. This function
1135 /// returns 0 if it was able to transfer the execution to a target and an
1136 /// integer different from zero otherwise.
1137 int target(int64_t DeviceId, void *HostPtr, int32_t ArgNum, void **ArgBases,
1138            void **Args, int64_t *ArgSizes, int64_t *ArgTypes, void **ArgMappers,
1139            int32_t TeamNum, int32_t ThreadLimit, int IsTeamConstruct) {
1140   DeviceTy &Device = Devices[DeviceId];
1141 
1142   TableMap *TM = getTableMap(HostPtr);
1143   // No map for this host pointer found!
1144   if (!TM) {
1145     REPORT("Host ptr " DPxMOD " does not have a matching target pointer.\n",
1146            DPxPTR(HostPtr));
1147     return OFFLOAD_FAIL;
1148   }
1149 
1150   // get target table.
1151   __tgt_target_table *TargetTable = nullptr;
1152   {
1153     std::lock_guard<std::mutex> TrlTblLock(*TrlTblMtx);
1154     assert(TM->Table->TargetsTable.size() > (size_t)DeviceId &&
1155            "Not expecting a device ID outside the table's bounds!");
1156     TargetTable = TM->Table->TargetsTable[DeviceId];
1157   }
1158   assert(TargetTable && "Global data has not been mapped\n");
1159 
1160   __tgt_async_info AsyncInfo;
1161 
1162   std::vector<void *> TgtArgs;
1163   std::vector<ptrdiff_t> TgtOffsets;
1164 
1165   PrivateArgumentManagerTy PrivateArgumentManager(Device, &AsyncInfo);
1166 
1167   // Process data, such as data mapping, before launching the kernel
1168   int Ret = processDataBefore(DeviceId, HostPtr, ArgNum, ArgBases, Args,
1169                               ArgSizes, ArgTypes, ArgMappers, TgtArgs,
1170                               TgtOffsets, PrivateArgumentManager, &AsyncInfo);
1171   if (Ret != OFFLOAD_SUCCESS) {
1172     REPORT("Failed to process data before launching the kernel.\n");
1173     return OFFLOAD_FAIL;
1174   }
1175 
1176   // Get loop trip count
1177   uint64_t LoopTripCount = getLoopTripCount(DeviceId);
1178 
1179   // Launch device execution.
1180   void *TgtEntryPtr = TargetTable->EntriesBegin[TM->Index].addr;
1181   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
1182      TargetTable->EntriesBegin[TM->Index].name, DPxPTR(TgtEntryPtr), TM->Index);
1183 
1184   if (IsTeamConstruct)
1185     Ret = Device.runTeamRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1186                                TgtArgs.size(), TeamNum, ThreadLimit,
1187                                LoopTripCount, &AsyncInfo);
1188   else
1189     Ret = Device.runRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1190                            TgtArgs.size(), &AsyncInfo);
1191 
1192   if (Ret != OFFLOAD_SUCCESS) {
1193     REPORT("Executing target region abort target.\n");
1194     return OFFLOAD_FAIL;
1195   }
1196 
1197   // Transfer data back and deallocate target memory for (first-)private
1198   // variables
1199   Ret = processDataAfter(DeviceId, HostPtr, ArgNum, ArgBases, Args, ArgSizes,
1200                          ArgTypes, ArgMappers, PrivateArgumentManager,
1201                          &AsyncInfo);
1202   if (Ret != OFFLOAD_SUCCESS) {
1203     REPORT("Failed to process data after launching the kernel.\n");
1204     return OFFLOAD_FAIL;
1205   }
1206 
1207   return OFFLOAD_SUCCESS;
1208 }
1209