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