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 /// Process data before launching the kernel, including calling targetDataBegin
826 /// to map and transfer data to target device, transferring (first-)private
827 /// variables.
828 int processDataBefore(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
829                       void **ArgBases, void **Args, int64_t *ArgSizes,
830                       int64_t *ArgTypes, void **ArgMappers,
831                       std::vector<void *> &TgtArgs,
832                       std::vector<ptrdiff_t> &TgtOffsets,
833                       std::vector<void *> &FPArrays,
834                       __tgt_async_info *AsyncInfo) {
835   DeviceTy &Device = Devices[DeviceId];
836   int Ret = targetDataBegin(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
837                             ArgMappers, AsyncInfo);
838   if (Ret != OFFLOAD_SUCCESS) {
839     DP("Call to targetDataBegin failed, abort target.\n");
840     return OFFLOAD_FAIL;
841   }
842 
843   // List of (first-)private arrays allocated for this target region
844   std::vector<int> TgtArgsPositions(ArgNum, -1);
845 
846   for (int32_t I = 0; I < ArgNum; ++I) {
847     if (!(ArgTypes[I] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
848       // This is not a target parameter, do not push it into TgtArgs.
849       // Check for lambda mapping.
850       if (isLambdaMapping(ArgTypes[I])) {
851         assert((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
852                "PTR_AND_OBJ must be also MEMBER_OF.");
853         unsigned Idx = getParentIndex(ArgTypes[I]);
854         int TgtIdx = TgtArgsPositions[Idx];
855         assert(TgtIdx != -1 && "Base address must be translated already.");
856         // The parent lambda must be processed already and it must be the last
857         // in TgtArgs and TgtOffsets arrays.
858         void *HstPtrVal = Args[I];
859         void *HstPtrBegin = ArgBases[I];
860         void *HstPtrBase = Args[Idx];
861         bool IsLast, IsHostPtr; // unused.
862         void *TgtPtrBase =
863             (void *)((intptr_t)TgtArgs[TgtIdx] + TgtOffsets[TgtIdx]);
864         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
865         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
866         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
867         void *PointerTgtPtrBegin = Device.getTgtPtrBegin(
868             HstPtrVal, ArgSizes[I], IsLast, false, IsHostPtr);
869         if (!PointerTgtPtrBegin) {
870           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
871              DPxPTR(HstPtrVal));
872           continue;
873         }
874         if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
875             TgtPtrBegin == HstPtrBegin) {
876           DP("Unified memory is active, no need to map lambda captured"
877              "variable (" DPxMOD ")\n",
878              DPxPTR(HstPtrVal));
879           continue;
880         }
881         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
882            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
883         Ret = Device.submitData(TgtPtrBegin, &PointerTgtPtrBegin,
884                                 sizeof(void *), AsyncInfo);
885         if (Ret != OFFLOAD_SUCCESS) {
886           DP("Copying data to device failed.\n");
887           return OFFLOAD_FAIL;
888         }
889       }
890       continue;
891     }
892     void *HstPtrBegin = Args[I];
893     void *HstPtrBase = ArgBases[I];
894     void *TgtPtrBegin;
895     ptrdiff_t TgtBaseOffset;
896     bool IsLast, IsHostPtr; // unused.
897     if (ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) {
898       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
899          DPxPTR(HstPtrBase));
900       TgtPtrBegin = HstPtrBase;
901       TgtBaseOffset = 0;
902     } else if (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE) {
903       // Allocate memory for (first-)private array
904       TgtPtrBegin = Device.allocData(ArgSizes[I], HstPtrBegin);
905       if (!TgtPtrBegin) {
906         DP("Data allocation for %sprivate array " DPxMOD " failed, "
907            "abort target.\n",
908            (ArgTypes[I] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
909            DPxPTR(HstPtrBegin));
910         return OFFLOAD_FAIL;
911       }
912       FPArrays.push_back(TgtPtrBegin);
913       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
914 #ifdef OMPTARGET_DEBUG
915       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
916       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD " for "
917          "%sprivate array " DPxMOD " - pushing target argument " DPxMOD "\n",
918          ArgSizes[I], DPxPTR(TgtPtrBegin),
919          (ArgTypes[I] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
920          DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBase));
921 #endif
922       // If first-private, copy data from host
923       if (ArgTypes[I] & OMP_TGT_MAPTYPE_TO) {
924         Ret =
925             Device.submitData(TgtPtrBegin, HstPtrBegin, ArgSizes[I], AsyncInfo);
926         if (Ret != OFFLOAD_SUCCESS) {
927           DP("Copying data to device failed, failed.\n");
928           return OFFLOAD_FAIL;
929         }
930       }
931     } else {
932       if (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
933         HstPtrBase = *reinterpret_cast<void **>(HstPtrBase);
934       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, ArgSizes[I], IsLast,
935                                           false, IsHostPtr);
936       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
937 #ifdef OMPTARGET_DEBUG
938       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
939       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
940          DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
941 #endif
942     }
943     TgtArgsPositions[I] = TgtArgs.size();
944     TgtArgs.push_back(TgtPtrBegin);
945     TgtOffsets.push_back(TgtBaseOffset);
946   }
947 
948   assert(TgtArgs.size() == TgtOffsets.size() &&
949          "Size mismatch in arguments and offsets");
950 
951   return OFFLOAD_SUCCESS;
952 }
953 
954 /// Process data after launching the kernel, including transferring data back to
955 /// host if needed and deallocating target memory of (first-)private variables.
956 /// FIXME: This function has correctness issue that target memory might be
957 /// deallocated when they're being used.
958 int processDataAfter(int64_t DeviceId, void *HostPtr, int32_t ArgNum,
959                      void **ArgBases, void **Args, int64_t *ArgSizes,
960                      int64_t *ArgTypes, void **ArgMappers,
961                      std::vector<void *> &FPArrays,
962                      __tgt_async_info *AsyncInfo) {
963   DeviceTy &Device = Devices[DeviceId];
964 
965   // Move data from device.
966   int Ret = targetDataEnd(Device, ArgNum, ArgBases, Args, ArgSizes, ArgTypes,
967                           ArgMappers, AsyncInfo);
968   if (Ret != OFFLOAD_SUCCESS) {
969     DP("Call to targetDataEnd failed, abort targe.\n");
970     return OFFLOAD_FAIL;
971   }
972 
973   // Deallocate (first-)private arrays
974   for (void *P : FPArrays) {
975     Ret = Device.deleteData(P);
976     if (Ret != OFFLOAD_SUCCESS) {
977       DP("Deallocation of (first-)private arrays failed.\n");
978       return OFFLOAD_FAIL;
979     }
980   }
981 
982   return OFFLOAD_SUCCESS;
983 }
984 } // namespace
985 
986 /// performs the same actions as data_begin in case arg_num is
987 /// non-zero and initiates run of the offloaded region on the target platform;
988 /// if arg_num is non-zero after the region execution is done it also
989 /// performs the same action as data_update and data_end above. This function
990 /// returns 0 if it was able to transfer the execution to a target and an
991 /// integer different from zero otherwise.
992 int target(int64_t DeviceId, void *HostPtr, int32_t ArgNum, void **ArgBases,
993            void **Args, int64_t *ArgSizes, int64_t *ArgTypes, void **ArgMappers,
994            int32_t TeamNum, int32_t ThreadLimit, int IsTeamConstruct) {
995   DeviceTy &Device = Devices[DeviceId];
996 
997   TableMap *TM = getTableMap(HostPtr);
998   // No map for this host pointer found!
999   if (!TM) {
1000     DP("Host ptr " DPxMOD " does not have a matching target pointer.\n",
1001        DPxPTR(HostPtr));
1002     return OFFLOAD_FAIL;
1003   }
1004 
1005   // get target table.
1006   __tgt_target_table *TargetTable = nullptr;
1007   {
1008     std::lock_guard<std::mutex> TrlTblLock(*TrlTblMtx);
1009     assert(TM->Table->TargetsTable.size() > (size_t)DeviceId &&
1010            "Not expecting a device ID outside the table's bounds!");
1011     TargetTable = TM->Table->TargetsTable[DeviceId];
1012   }
1013   assert(TargetTable && "Global data has not been mapped\n");
1014 
1015   __tgt_async_info AsyncInfo;
1016 
1017   std::vector<void *> TgtArgs;
1018   std::vector<ptrdiff_t> TgtOffsets;
1019   std::vector<void *> FPArrays;
1020 
1021   // Process data, such as data mapping, before launching the kernel
1022   int Ret = processDataBefore(DeviceId, HostPtr, ArgNum, ArgBases, Args,
1023                               ArgSizes, ArgTypes, ArgMappers, TgtArgs,
1024                               TgtOffsets, FPArrays, &AsyncInfo);
1025   if (Ret != OFFLOAD_SUCCESS) {
1026     DP("Failed to process data before launching the kernel.\n");
1027     return OFFLOAD_FAIL;
1028   }
1029 
1030   // Get loop trip count
1031   uint64_t LoopTripCount = getLoopTripCount(DeviceId);
1032 
1033   // Launch device execution.
1034   void *TgtEntryPtr = TargetTable->EntriesBegin[TM->Index].addr;
1035   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
1036      TargetTable->EntriesBegin[TM->Index].name, DPxPTR(TgtEntryPtr), TM->Index);
1037 
1038   if (IsTeamConstruct)
1039     Ret = Device.runTeamRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1040                                TgtArgs.size(), TeamNum, ThreadLimit,
1041                                LoopTripCount, &AsyncInfo);
1042   else
1043     Ret = Device.runRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1044                            TgtArgs.size(), &AsyncInfo);
1045 
1046   if (Ret != OFFLOAD_SUCCESS) {
1047     DP("Executing target region abort target.\n");
1048     return OFFLOAD_FAIL;
1049   }
1050 
1051   // Transfer data back and deallocate target memory for (first-)private
1052   // variables
1053   Ret = processDataAfter(DeviceId, HostPtr, ArgNum, ArgBases, Args, ArgSizes,
1054                          ArgTypes, ArgMappers, FPArrays, &AsyncInfo);
1055   if (Ret != OFFLOAD_SUCCESS) {
1056     DP("Failed to process data after launching the kernel.\n");
1057     return OFFLOAD_FAIL;
1058   }
1059 
1060   return OFFLOAD_SUCCESS;
1061 }
1062