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