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   PM->TrlTblMtx.lock();
63   for (HostEntriesBeginToTransTableTy::iterator entry_it =
64            PM->HostEntriesBeginToTransTable.begin();
65        entry_it != PM->HostEntriesBeginToTransTable.end(); ++entry_it) {
66     TranslationTable *TransTable = &entry_it->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   PM->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 = PM->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 (!(PM->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 (!(PM->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             !(PM->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 static int target_data_contiguous(DeviceTy &Device, void *args_base,
639                                   void *HstPtrBegin, int64_t MapSize,
640                                   int64_t arg_type) {
641   bool IsLast, IsHostPtr;
642   void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, MapSize, IsLast, false,
643                                             IsHostPtr, /*MustContain=*/true);
644   if (!TgtPtrBegin) {
645     DP("hst data:" DPxMOD " not found, becomes a noop\n", DPxPTR(HstPtrBegin));
646     if (arg_type & OMP_TGT_MAPTYPE_PRESENT) {
647       MESSAGE("device mapping required by 'present' motion modifier does not "
648               "exist for host address " DPxMOD " (%" PRId64 " bytes)",
649               DPxPTR(HstPtrBegin), MapSize);
650       return OFFLOAD_FAIL;
651     }
652     return OFFLOAD_SUCCESS;
653   }
654 
655   if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
656       TgtPtrBegin == HstPtrBegin) {
657     DP("hst data:" DPxMOD " unified and shared, becomes a noop\n",
658        DPxPTR(HstPtrBegin));
659     return OFFLOAD_SUCCESS;
660   }
661 
662   if (arg_type & OMP_TGT_MAPTYPE_FROM) {
663     DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
664        arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
665     int rt = Device.retrieveData(HstPtrBegin, TgtPtrBegin, MapSize, nullptr);
666     if (rt != OFFLOAD_SUCCESS) {
667       REPORT("Copying data from device failed.\n");
668       return OFFLOAD_FAIL;
669     }
670 
671     uintptr_t lb = (uintptr_t)HstPtrBegin;
672     uintptr_t ub = (uintptr_t)HstPtrBegin + MapSize;
673     Device.ShadowMtx.lock();
674     for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
675          it != Device.ShadowPtrMap.end(); ++it) {
676       void **ShadowHstPtrAddr = (void **)it->first;
677       if ((uintptr_t)ShadowHstPtrAddr < lb)
678         continue;
679       if ((uintptr_t)ShadowHstPtrAddr >= ub)
680         break;
681       DP("Restoring original host pointer value " DPxMOD
682          " for host pointer " DPxMOD "\n",
683          DPxPTR(it->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
684       *ShadowHstPtrAddr = it->second.HstPtrVal;
685     }
686     Device.ShadowMtx.unlock();
687   }
688 
689   if (arg_type & OMP_TGT_MAPTYPE_TO) {
690     DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
691        arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
692     int rt = Device.submitData(TgtPtrBegin, HstPtrBegin, MapSize, nullptr);
693     if (rt != OFFLOAD_SUCCESS) {
694       REPORT("Copying data to device failed.\n");
695       return OFFLOAD_FAIL;
696     }
697 
698     uintptr_t lb = (uintptr_t)HstPtrBegin;
699     uintptr_t ub = (uintptr_t)HstPtrBegin + MapSize;
700     Device.ShadowMtx.lock();
701     for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
702          it != Device.ShadowPtrMap.end(); ++it) {
703       void **ShadowHstPtrAddr = (void **)it->first;
704       if ((uintptr_t)ShadowHstPtrAddr < lb)
705         continue;
706       if ((uintptr_t)ShadowHstPtrAddr >= ub)
707         break;
708       DP("Restoring original target pointer value " DPxMOD " for target "
709          "pointer " DPxMOD "\n",
710          DPxPTR(it->second.TgtPtrVal), DPxPTR(it->second.TgtPtrAddr));
711       rt = Device.submitData(it->second.TgtPtrAddr, &it->second.TgtPtrVal,
712                              sizeof(void *), nullptr);
713       if (rt != OFFLOAD_SUCCESS) {
714         REPORT("Copying data to device failed.\n");
715         Device.ShadowMtx.unlock();
716         return OFFLOAD_FAIL;
717       }
718     }
719     Device.ShadowMtx.unlock();
720   }
721   return OFFLOAD_SUCCESS;
722 }
723 
724 static int target_data_non_contiguous(DeviceTy &Device, void *arg_base,
725                                       __tgt_target_non_contig *non_contig,
726                                       uint64_t size, int64_t arg_type,
727                                       int current_dim, int dim_size,
728                                       uint64_t offset) {
729   int rt = OFFLOAD_SUCCESS;
730   if (current_dim < dim_size) {
731     for (unsigned int i = 0; i < non_contig[current_dim].count; ++i) {
732       uint64_t cur_offset =
733           (non_contig[current_dim].offset + i) * non_contig[current_dim].stride;
734       // we only need to transfer the first element for the last dimension
735       // since we've already got a contiguous piece.
736       if (current_dim != dim_size - 1 || i == 0) {
737         rt = target_data_non_contiguous(Device, arg_base, non_contig, size,
738                                         arg_type, current_dim + 1, dim_size,
739                                         offset + cur_offset);
740         // Stop the whole process if any contiguous piece returns anything
741         // other than OFFLOAD_SUCCESS.
742         if (rt != OFFLOAD_SUCCESS)
743           return rt;
744       }
745     }
746   } else {
747     char *ptr = (char *)arg_base + offset;
748     DP("Transfer of non-contiguous : host ptr %lx offset %ld len %ld\n",
749        (uint64_t)ptr, offset, size);
750     rt = target_data_contiguous(Device, arg_base, ptr, size, arg_type);
751   }
752   return rt;
753 }
754 
755 static int get_non_contig_merged_dimension(__tgt_target_non_contig *non_contig,
756                                            int32_t dim_size) {
757   int removed_dim = 0;
758   for (int i = dim_size - 1; i > 0; --i) {
759     if (non_contig[i].count * non_contig[i].stride == non_contig[i - 1].stride)
760       removed_dim++;
761   }
762   return removed_dim;
763 }
764 
765 /// Internal function to pass data to/from the target.
766 // async_info_ptr is currently unused, added here so target_data_update has the
767 // same signature as targetDataBegin and targetDataEnd.
768 int target_data_update(DeviceTy &Device, int32_t arg_num,
769     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
770     void **arg_mappers, __tgt_async_info *async_info_ptr) {
771   // process each input.
772   for (int32_t i = 0; i < arg_num; ++i) {
773     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
774         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
775       continue;
776 
777     if (arg_mappers && arg_mappers[i]) {
778       // Instead of executing the regular path of target_data_update, call the
779       // targetDataMapper variant which will call target_data_update again
780       // with new arguments.
781       DP("Calling targetDataMapper for the %dth argument\n", i);
782 
783       int rc =
784           targetDataMapper(Device, args_base[i], args[i], arg_sizes[i],
785                            arg_types[i], arg_mappers[i], target_data_update);
786 
787       if (rc != OFFLOAD_SUCCESS) {
788         REPORT(
789             "Call to target_data_update via targetDataMapper for custom mapper"
790             " failed.\n");
791         return OFFLOAD_FAIL;
792       }
793 
794       // Skip the rest of this function, continue to the next argument.
795       continue;
796     }
797 
798     int rt = OFFLOAD_SUCCESS;
799 
800     if (arg_types[i] & OMP_TGT_MAPTYPE_NON_CONTIG) {
801       __tgt_target_non_contig *non_contig = (__tgt_target_non_contig *)args[i];
802       int32_t dim_size = arg_sizes[i];
803       uint64_t size =
804           non_contig[dim_size - 1].count * non_contig[dim_size - 1].stride;
805       int32_t merged_dim =
806           get_non_contig_merged_dimension(non_contig, dim_size);
807       rt = target_data_non_contiguous(
808           Device, args_base[i], non_contig, size, arg_types[i],
809           /*current_dim=*/0, dim_size - merged_dim, /*offset=*/0);
810     } else {
811       rt = target_data_contiguous(Device, args_base[i], args[i], arg_sizes[i],
812                                   arg_types[i]);
813     }
814     if (rt == OFFLOAD_FAIL)
815       return OFFLOAD_FAIL;
816   }
817   return OFFLOAD_SUCCESS;
818 }
819 
820 static const unsigned LambdaMapping = OMP_TGT_MAPTYPE_PTR_AND_OBJ |
821                                       OMP_TGT_MAPTYPE_LITERAL |
822                                       OMP_TGT_MAPTYPE_IMPLICIT;
823 static bool isLambdaMapping(int64_t Mapping) {
824   return (Mapping & LambdaMapping) == LambdaMapping;
825 }
826 
827 namespace {
828 /// Find the table information in the map or look it up in the translation
829 /// tables.
830 TableMap *getTableMap(void *HostPtr) {
831   std::lock_guard<std::mutex> TblMapLock(PM->TblMapMtx);
832   HostPtrToTableMapTy::iterator TableMapIt =
833       PM->HostPtrToTableMap.find(HostPtr);
834 
835   if (TableMapIt != PM->HostPtrToTableMap.end())
836     return &TableMapIt->second;
837 
838   // We don't have a map. So search all the registered libraries.
839   TableMap *TM = nullptr;
840   std::lock_guard<std::mutex> TrlTblLock(PM->TrlTblMtx);
841   for (HostEntriesBeginToTransTableTy::iterator Itr =
842            PM->HostEntriesBeginToTransTable.begin();
843        Itr != PM->HostEntriesBeginToTransTable.end(); ++Itr) {
844     // get the translation table (which contains all the good info).
845     TranslationTable *TransTable = &Itr->second;
846     // iterate over all the host table entries to see if we can locate the
847     // host_ptr.
848     __tgt_offload_entry *Cur = TransTable->HostTable.EntriesBegin;
849     for (uint32_t I = 0; Cur < TransTable->HostTable.EntriesEnd; ++Cur, ++I) {
850       if (Cur->addr != HostPtr)
851         continue;
852       // we got a match, now fill the HostPtrToTableMap so that we
853       // may avoid this search next time.
854       TM = &(PM->HostPtrToTableMap)[HostPtr];
855       TM->Table = TransTable;
856       TM->Index = I;
857       return TM;
858     }
859   }
860 
861   return nullptr;
862 }
863 
864 /// Get loop trip count
865 /// FIXME: This function will not work right if calling
866 /// __kmpc_push_target_tripcount in one thread but doing offloading in another
867 /// thread, which might occur when we call task yield.
868 uint64_t getLoopTripCount(int64_t DeviceId) {
869   DeviceTy &Device = PM->Devices[DeviceId];
870   uint64_t LoopTripCount = 0;
871 
872   {
873     std::lock_guard<std::mutex> TblMapLock(PM->TblMapMtx);
874     auto I = Device.LoopTripCnt.find(__kmpc_global_thread_num(NULL));
875     if (I != Device.LoopTripCnt.end()) {
876       LoopTripCount = I->second;
877       Device.LoopTripCnt.erase(I);
878       DP("loop trip count is %lu.\n", LoopTripCount);
879     }
880   }
881 
882   return LoopTripCount;
883 }
884 
885 /// A class manages private arguments in a target region.
886 class PrivateArgumentManagerTy {
887   /// A data structure for the information of first-private arguments. We can
888   /// use this information to optimize data transfer by packing all
889   /// first-private arguments and transfer them all at once.
890   struct FirstPrivateArgInfoTy {
891     /// The index of the element in \p TgtArgs corresponding to the argument
892     const int Index;
893     /// Host pointer begin
894     const char *HstPtrBegin;
895     /// Host pointer end
896     const char *HstPtrEnd;
897     /// Aligned size
898     const int64_t AlignedSize;
899 
900     FirstPrivateArgInfoTy(int Index, const void *HstPtr, int64_t Size)
901         : Index(Index), HstPtrBegin(reinterpret_cast<const char *>(HstPtr)),
902           HstPtrEnd(HstPtrBegin + Size), AlignedSize(Size + Size % Alignment) {}
903   };
904 
905   /// A vector of target pointers for all private arguments
906   std::vector<void *> TgtPtrs;
907 
908   /// A vector of information of all first-private arguments to be packed
909   std::vector<FirstPrivateArgInfoTy> FirstPrivateArgInfo;
910   /// Host buffer for all arguments to be packed
911   std::vector<char> FirstPrivateArgBuffer;
912   /// The total size of all arguments to be packed
913   int64_t FirstPrivateArgSize = 0;
914 
915   /// A reference to the \p DeviceTy object
916   DeviceTy &Device;
917   /// A pointer to a \p __tgt_async_info object
918   __tgt_async_info *AsyncInfo;
919 
920   // TODO: What would be the best value here? Should we make it configurable?
921   // If the size is larger than this threshold, we will allocate and transfer it
922   // immediately instead of packing it.
923   static constexpr const int64_t FirstPrivateArgSizeThreshold = 1024;
924 
925 public:
926   /// Constructor
927   PrivateArgumentManagerTy(DeviceTy &Dev, __tgt_async_info *AsyncInfo)
928       : Device(Dev), AsyncInfo(AsyncInfo) {}
929 
930   /// A a private argument
931   int addArg(void *HstPtr, int64_t ArgSize, int64_t ArgOffset,
932              bool IsFirstPrivate, void *&TgtPtr, int TgtArgsIndex) {
933     // If the argument is not first-private, or its size is greater than a
934     // predefined threshold, we will allocate memory and issue the transfer
935     // immediately.
936     if (ArgSize > FirstPrivateArgSizeThreshold || !IsFirstPrivate) {
937       TgtPtr = Device.allocData(ArgSize, HstPtr);
938       if (!TgtPtr) {
939         DP("Data allocation for %sprivate array " DPxMOD " failed.\n",
940            (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtr));
941         return OFFLOAD_FAIL;
942       }
943 #ifdef OMPTARGET_DEBUG
944       void *TgtPtrBase = (void *)((intptr_t)TgtPtr + ArgOffset);
945       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD
946          " for %sprivate array " DPxMOD " - pushing target argument " DPxMOD
947          "\n",
948          ArgSize, DPxPTR(TgtPtr), (IsFirstPrivate ? "first-" : ""),
949          DPxPTR(HstPtr), DPxPTR(TgtPtrBase));
950 #endif
951       // If first-private, copy data from host
952       if (IsFirstPrivate) {
953         int Ret = Device.submitData(TgtPtr, HstPtr, ArgSize, AsyncInfo);
954         if (Ret != OFFLOAD_SUCCESS) {
955           DP("Copying data to device failed, failed.\n");
956           return OFFLOAD_FAIL;
957         }
958       }
959       TgtPtrs.push_back(TgtPtr);
960     } else {
961       DP("Firstprivate array " DPxMOD " of size %" PRId64 " will be packed\n",
962          DPxPTR(HstPtr), ArgSize);
963       // When reach this point, the argument must meet all following
964       // requirements:
965       // 1. Its size does not exceed the threshold (see the comment for
966       // FirstPrivateArgSizeThreshold);
967       // 2. It must be first-private (needs to be mapped to target device).
968       // We will pack all this kind of arguments to transfer them all at once
969       // to reduce the number of data transfer. We will not take
970       // non-first-private arguments, aka. private arguments that doesn't need
971       // to be mapped to target device, into account because data allocation
972       // can be very efficient with memory manager.
973 
974       // Placeholder value
975       TgtPtr = nullptr;
976       FirstPrivateArgInfo.emplace_back(TgtArgsIndex, HstPtr, ArgSize);
977       FirstPrivateArgSize += FirstPrivateArgInfo.back().AlignedSize;
978     }
979 
980     return OFFLOAD_SUCCESS;
981   }
982 
983   /// Pack first-private arguments, replace place holder pointers in \p TgtArgs,
984   /// and start the transfer.
985   int packAndTransfer(std::vector<void *> &TgtArgs) {
986     if (!FirstPrivateArgInfo.empty()) {
987       assert(FirstPrivateArgSize != 0 &&
988              "FirstPrivateArgSize is 0 but FirstPrivateArgInfo is empty");
989       FirstPrivateArgBuffer.resize(FirstPrivateArgSize, 0);
990       auto Itr = FirstPrivateArgBuffer.begin();
991       // Copy all host data to this buffer
992       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
993         std::copy(Info.HstPtrBegin, Info.HstPtrEnd, Itr);
994         Itr = std::next(Itr, Info.AlignedSize);
995       }
996       // Allocate target memory
997       void *TgtPtr =
998           Device.allocData(FirstPrivateArgSize, FirstPrivateArgBuffer.data());
999       if (TgtPtr == nullptr) {
1000         DP("Failed to allocate target memory for private arguments.\n");
1001         return OFFLOAD_FAIL;
1002       }
1003       TgtPtrs.push_back(TgtPtr);
1004       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD "\n",
1005          FirstPrivateArgSize, DPxPTR(TgtPtr));
1006       // Transfer data to target device
1007       int Ret = Device.submitData(TgtPtr, FirstPrivateArgBuffer.data(),
1008                                   FirstPrivateArgSize, AsyncInfo);
1009       if (Ret != OFFLOAD_SUCCESS) {
1010         DP("Failed to submit data of private arguments.\n");
1011         return OFFLOAD_FAIL;
1012       }
1013       // Fill in all placeholder pointers
1014       auto TP = reinterpret_cast<uintptr_t>(TgtPtr);
1015       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
1016         void *&Ptr = TgtArgs[Info.Index];
1017         assert(Ptr == nullptr && "Target pointer is already set by mistaken");
1018         Ptr = reinterpret_cast<void *>(TP);
1019         TP += Info.AlignedSize;
1020         DP("Firstprivate array " DPxMOD " of size %" PRId64 " mapped to " DPxMOD
1021            "\n",
1022            DPxPTR(Info.HstPtrBegin), Info.HstPtrEnd - Info.HstPtrBegin,
1023            DPxPTR(Ptr));
1024       }
1025     }
1026 
1027     return OFFLOAD_SUCCESS;
1028   }
1029 
1030   /// Free all target memory allocated for private arguments
1031   int free() {
1032     for (void *P : TgtPtrs) {
1033       int Ret = Device.deleteData(P);
1034       if (Ret != OFFLOAD_SUCCESS) {
1035         DP("Deallocation of (first-)private arrays failed.\n");
1036         return OFFLOAD_FAIL;
1037       }
1038     }
1039 
1040     TgtPtrs.clear();
1041 
1042     return OFFLOAD_SUCCESS;
1043   }
1044 };
1045 
1046 /// Process data before launching the kernel, including calling targetDataBegin
1047 /// to map and transfer data to target device, transferring (first-)private
1048 /// variables.
1049 int processDataBefore(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
1050                       void **ArgBases, void **Args, int64_t *ArgSizes,
1051                       int64_t *ArgTypes, void **ArgMappers,
1052                       std::vector<void *> &TgtArgs,
1053                       std::vector<ptrdiff_t> &TgtOffsets,
1054                       PrivateArgumentManagerTy &PrivateArgumentManager,
1055                       __tgt_async_info *AsyncInfo) {
1056   DeviceTy &Device = PM->Devices[DeviceId];
1057   int Ret = targetDataBegin(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
1058                             ArgMappers, AsyncInfo);
1059   if (Ret != OFFLOAD_SUCCESS) {
1060     REPORT("Call to targetDataBegin failed, abort target.\n");
1061     return OFFLOAD_FAIL;
1062   }
1063 
1064   // List of (first-)private arrays allocated for this target region
1065   std::vector<int> TgtArgsPositions(ArgNum, -1);
1066 
1067   for (int32_t I = 0; I < ArgNum; ++I) {
1068     if (!(ArgTypes[I] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
1069       // This is not a target parameter, do not push it into TgtArgs.
1070       // Check for lambda mapping.
1071       if (isLambdaMapping(ArgTypes[I])) {
1072         assert((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1073                "PTR_AND_OBJ must be also MEMBER_OF.");
1074         unsigned Idx = getParentIndex(ArgTypes[I]);
1075         int TgtIdx = TgtArgsPositions[Idx];
1076         assert(TgtIdx != -1 && "Base address must be translated already.");
1077         // The parent lambda must be processed already and it must be the last
1078         // in TgtArgs and TgtOffsets arrays.
1079         void *HstPtrVal = Args[I];
1080         void *HstPtrBegin = ArgBases[I];
1081         void *HstPtrBase = Args[Idx];
1082         bool IsLast, IsHostPtr; // unused.
1083         void *TgtPtrBase =
1084             (void *)((intptr_t)TgtArgs[TgtIdx] + TgtOffsets[TgtIdx]);
1085         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
1086         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
1087         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
1088         void *PointerTgtPtrBegin = Device.getTgtPtrBegin(
1089             HstPtrVal, ArgSizes[I], IsLast, false, IsHostPtr);
1090         if (!PointerTgtPtrBegin) {
1091           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
1092              DPxPTR(HstPtrVal));
1093           continue;
1094         }
1095         if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
1096             TgtPtrBegin == HstPtrBegin) {
1097           DP("Unified memory is active, no need to map lambda captured"
1098              "variable (" DPxMOD ")\n",
1099              DPxPTR(HstPtrVal));
1100           continue;
1101         }
1102         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
1103            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
1104         Ret = Device.submitData(TgtPtrBegin, &PointerTgtPtrBegin,
1105                                 sizeof(void *), AsyncInfo);
1106         if (Ret != OFFLOAD_SUCCESS) {
1107           REPORT("Copying data to device failed.\n");
1108           return OFFLOAD_FAIL;
1109         }
1110       }
1111       continue;
1112     }
1113     void *HstPtrBegin = Args[I];
1114     void *HstPtrBase = ArgBases[I];
1115     void *TgtPtrBegin;
1116     ptrdiff_t TgtBaseOffset;
1117     bool IsLast, IsHostPtr; // unused.
1118     if (ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) {
1119       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
1120          DPxPTR(HstPtrBase));
1121       TgtPtrBegin = HstPtrBase;
1122       TgtBaseOffset = 0;
1123     } else if (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE) {
1124       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1125       // Can be marked for optimization if the next argument(s) do(es) not
1126       // depend on this one.
1127       const bool IsFirstPrivate =
1128           (I >= ArgNum - 1 || !(ArgTypes[I + 1] & OMP_TGT_MAPTYPE_MEMBER_OF));
1129       Ret = PrivateArgumentManager.addArg(HstPtrBegin, ArgSizes[I],
1130                                           TgtBaseOffset, IsFirstPrivate,
1131                                           TgtPtrBegin, TgtArgs.size());
1132       if (Ret != OFFLOAD_SUCCESS) {
1133         REPORT("Failed to process %sprivate argument " DPxMOD "\n",
1134                (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtrBegin));
1135         return OFFLOAD_FAIL;
1136       }
1137     } else {
1138       if (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
1139         HstPtrBase = *reinterpret_cast<void **>(HstPtrBase);
1140       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, ArgSizes[I], IsLast,
1141                                           false, IsHostPtr);
1142       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1143 #ifdef OMPTARGET_DEBUG
1144       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
1145       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
1146          DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
1147 #endif
1148     }
1149     TgtArgsPositions[I] = TgtArgs.size();
1150     TgtArgs.push_back(TgtPtrBegin);
1151     TgtOffsets.push_back(TgtBaseOffset);
1152   }
1153 
1154   assert(TgtArgs.size() == TgtOffsets.size() &&
1155          "Size mismatch in arguments and offsets");
1156 
1157   // Pack and transfer first-private arguments
1158   Ret = PrivateArgumentManager.packAndTransfer(TgtArgs);
1159   if (Ret != OFFLOAD_SUCCESS) {
1160     DP("Failed to pack and transfer first private arguments\n");
1161     return OFFLOAD_FAIL;
1162   }
1163 
1164   return OFFLOAD_SUCCESS;
1165 }
1166 
1167 /// Process data after launching the kernel, including transferring data back to
1168 /// host if needed and deallocating target memory of (first-)private variables.
1169 int processDataAfter(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
1170                      void **ArgBases, void **Args, int64_t *ArgSizes,
1171                      int64_t *ArgTypes, void **ArgMappers,
1172                      PrivateArgumentManagerTy &PrivateArgumentManager,
1173                      __tgt_async_info *AsyncInfo) {
1174   DeviceTy &Device = PM->Devices[DeviceId];
1175 
1176   // Move data from device.
1177   int Ret = targetDataEnd(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
1178                           ArgMappers, AsyncInfo);
1179   if (Ret != OFFLOAD_SUCCESS) {
1180     REPORT("Call to targetDataEnd failed, abort target.\n");
1181     return OFFLOAD_FAIL;
1182   }
1183 
1184   // Free target memory for private arguments
1185   Ret = PrivateArgumentManager.free();
1186   if (Ret != OFFLOAD_SUCCESS) {
1187     REPORT("Failed to deallocate target memory for private args\n");
1188     return OFFLOAD_FAIL;
1189   }
1190 
1191   return OFFLOAD_SUCCESS;
1192 }
1193 } // namespace
1194 
1195 /// performs the same actions as data_begin in case arg_num is
1196 /// non-zero and initiates run of the offloaded region on the target platform;
1197 /// if arg_num is non-zero after the region execution is done it also
1198 /// performs the same action as data_update and data_end above. This function
1199 /// returns 0 if it was able to transfer the execution to a target and an
1200 /// integer different from zero otherwise.
1201 int target(int64_t DeviceId, void *HostPtr, int32_t ArgNum, void **ArgBases,
1202            void **Args, int64_t *ArgSizes, int64_t *ArgTypes, void **ArgMappers,
1203            int32_t TeamNum, int32_t ThreadLimit, int IsTeamConstruct) {
1204   DeviceTy &Device = PM->Devices[DeviceId];
1205 
1206   TableMap *TM = getTableMap(HostPtr);
1207   // No map for this host pointer found!
1208   if (!TM) {
1209     REPORT("Host ptr " DPxMOD " does not have a matching target pointer.\n",
1210            DPxPTR(HostPtr));
1211     return OFFLOAD_FAIL;
1212   }
1213 
1214   // get target table.
1215   __tgt_target_table *TargetTable = nullptr;
1216   {
1217     std::lock_guard<std::mutex> TrlTblLock(PM->TrlTblMtx);
1218     assert(TM->Table->TargetsTable.size() > (size_t)DeviceId &&
1219            "Not expecting a device ID outside the table's bounds!");
1220     TargetTable = TM->Table->TargetsTable[DeviceId];
1221   }
1222   assert(TargetTable && "Global data has not been mapped\n");
1223 
1224   __tgt_async_info AsyncInfo;
1225 
1226   std::vector<void *> TgtArgs;
1227   std::vector<ptrdiff_t> TgtOffsets;
1228 
1229   PrivateArgumentManagerTy PrivateArgumentManager(Device, &AsyncInfo);
1230 
1231   // Process data, such as data mapping, before launching the kernel
1232   int Ret = processDataBefore(DeviceId, HostPtr, ArgNum, ArgBases, Args,
1233                               ArgSizes, ArgTypes, ArgMappers, TgtArgs,
1234                               TgtOffsets, PrivateArgumentManager, &AsyncInfo);
1235   if (Ret != OFFLOAD_SUCCESS) {
1236     REPORT("Failed to process data before launching the kernel.\n");
1237     return OFFLOAD_FAIL;
1238   }
1239 
1240   // Get loop trip count
1241   uint64_t LoopTripCount = getLoopTripCount(DeviceId);
1242 
1243   // Launch device execution.
1244   void *TgtEntryPtr = TargetTable->EntriesBegin[TM->Index].addr;
1245   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
1246      TargetTable->EntriesBegin[TM->Index].name, DPxPTR(TgtEntryPtr), TM->Index);
1247 
1248   if (IsTeamConstruct)
1249     Ret = Device.runTeamRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1250                                TgtArgs.size(), TeamNum, ThreadLimit,
1251                                LoopTripCount, &AsyncInfo);
1252   else
1253     Ret = Device.runRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1254                            TgtArgs.size(), &AsyncInfo);
1255 
1256   if (Ret != OFFLOAD_SUCCESS) {
1257     REPORT("Executing target region abort target.\n");
1258     return OFFLOAD_FAIL;
1259   }
1260 
1261   // Transfer data back and deallocate target memory for (first-)private
1262   // variables
1263   Ret = processDataAfter(DeviceId, HostPtr, ArgNum, ArgBases, Args, ArgSizes,
1264                          ArgTypes, ArgMappers, PrivateArgumentManager,
1265                          &AsyncInfo);
1266   if (Ret != OFFLOAD_SUCCESS) {
1267     REPORT("Failed to process data after launching the kernel.\n");
1268     return OFFLOAD_FAIL;
1269   }
1270 
1271   return OFFLOAD_SUCCESS;
1272 }
1273