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     TargetPointerResultTy Pointer_TPR;
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       Pointer_TPR = Device.getOrAllocTgtPtr(
491           HstPtrBase, HstPtrBase, sizeof(void *), nullptr, IsImplicit,
492           UpdateRef, HasCloseModifier, HasPresentModifier);
493       PointerTgtPtrBegin = Pointer_TPR.TargetPointer;
494       IsHostPtr = Pointer_TPR.Flags.IsHostPointer;
495       if (!PointerTgtPtrBegin) {
496         REPORT("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
497                HasPresentModifier ? "'present' map type modifier"
498                                   : "device failure or illegal mapping");
499         return OFFLOAD_FAIL;
500       }
501       DP("There are %zu bytes allocated at target address " DPxMOD " - is%s new"
502          "\n",
503          sizeof(void *), DPxPTR(PointerTgtPtrBegin),
504          (Pointer_TPR.Flags.IsNewEntry ? "" : " not"));
505       Pointer_HstPtrBegin = HstPtrBase;
506       // modify current entry.
507       HstPtrBase = *(void **)HstPtrBase;
508       // No need to update pointee ref count for the first element of the
509       // subelement that comes from mapper.
510       UpdateRef =
511           (!FromMapper || i != 0); // subsequently update ref count of pointee
512     }
513 
514     auto TPR = Device.getOrAllocTgtPtr(HstPtrBegin, HstPtrBase, data_size,
515                                        HstPtrName, IsImplicit, UpdateRef,
516                                        HasCloseModifier, HasPresentModifier);
517     void *TgtPtrBegin = TPR.TargetPointer;
518     IsHostPtr = TPR.Flags.IsHostPointer;
519     // If data_size==0, then the argument could be a zero-length pointer to
520     // NULL, so getOrAlloc() returning NULL is not an error.
521     if (!TgtPtrBegin && (data_size || HasPresentModifier)) {
522       REPORT("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
523              HasPresentModifier ? "'present' map type modifier"
524                                 : "device failure or illegal mapping");
525       return OFFLOAD_FAIL;
526     }
527     DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
528        " - is%s new\n",
529        data_size, DPxPTR(TgtPtrBegin), (TPR.Flags.IsNewEntry ? "" : " not"));
530 
531     if (arg_types[i] & OMP_TGT_MAPTYPE_RETURN_PARAM) {
532       uintptr_t Delta = (uintptr_t)HstPtrBegin - (uintptr_t)HstPtrBase;
533       void *TgtPtrBase = (void *)((uintptr_t)TgtPtrBegin - Delta);
534       DP("Returning device pointer " DPxMOD "\n", DPxPTR(TgtPtrBase));
535       args_base[i] = TgtPtrBase;
536     }
537 
538     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
539       bool copy = false;
540       if (!(PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
541           HasCloseModifier) {
542         if (TPR.Flags.IsNewEntry || (arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS))
543           copy = true;
544       }
545 
546       if (copy && !IsHostPtr) {
547         DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
548            data_size, DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
549         int rt =
550             Device.submitData(TgtPtrBegin, HstPtrBegin, data_size, AsyncInfo);
551         if (rt != OFFLOAD_SUCCESS) {
552           REPORT("Copying data to device failed.\n");
553           return OFFLOAD_FAIL;
554         }
555       }
556     }
557 
558     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ && !IsHostPtr) {
559       // Check whether we need to update the pointer on the device
560       bool UpdateDevPtr = false;
561 
562       uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
563       void *ExpectedTgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
564 
565       Device.ShadowMtx.lock();
566       auto Entry = Device.ShadowPtrMap.find(Pointer_HstPtrBegin);
567       // If this pointer is not in the map we need to insert it. If the map
568       // contains a stale entry, we need to update it (e.g. if the pointee was
569       // deallocated and later on is reallocated at another device address). The
570       // latter scenario is the subject of LIT test env/base_ptr_ref_count.c. An
571       // entry is removed from ShadowPtrMap only when the PTR of a PTR_AND_OBJ
572       // pair is deallocated, not when the OBJ is deallocated. In
573       // env/base_ptr_ref_count.c the PTR is a global "declare target" pointer,
574       // so it stays in the map for the lifetime of the application. When the
575       // OBJ is deallocated and later on allocated again (at a different device
576       // address), ShadowPtrMap still contains an entry for Pointer_HstPtrBegin
577       // which is stale, pointing to the old ExpectedTgtPtrBase of the OBJ.
578       if (Entry == Device.ShadowPtrMap.end() ||
579           Entry->second.TgtPtrVal != ExpectedTgtPtrBase) {
580         // create or update shadow pointers for this entry
581         Device.ShadowPtrMap[Pointer_HstPtrBegin] = {
582             HstPtrBase, PointerTgtPtrBegin, ExpectedTgtPtrBase};
583         UpdateDevPtr = true;
584       }
585       Device.ShadowMtx.unlock();
586 
587       if (UpdateDevPtr) {
588         DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
589            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
590         void *&TgtPtrBase = AsyncInfo.getVoidPtrLocation();
591         TgtPtrBase = ExpectedTgtPtrBase;
592         int rt = Device.submitData(PointerTgtPtrBegin, &TgtPtrBase,
593                                    sizeof(void *), AsyncInfo);
594         if (rt != OFFLOAD_SUCCESS) {
595           REPORT("Copying data to device failed.\n");
596           return OFFLOAD_FAIL;
597         }
598       }
599     }
600   }
601 
602   return OFFLOAD_SUCCESS;
603 }
604 
605 namespace {
606 /// This structure contains information to deallocate a target pointer, aka.
607 /// used to call the function \p DeviceTy::deallocTgtPtr.
608 struct DeallocTgtPtrInfo {
609   /// Host pointer used to look up into the map table
610   void *HstPtrBegin;
611   /// Size of the data
612   int64_t DataSize;
613   /// Whether it has \p close modifier
614   bool HasCloseModifier;
615 
616   DeallocTgtPtrInfo(void *HstPtr, int64_t Size, bool HasCloseModifier)
617       : HstPtrBegin(HstPtr), DataSize(Size),
618         HasCloseModifier(HasCloseModifier) {}
619 };
620 } // namespace
621 
622 /// Internal function to undo the mapping and retrieve the data from the device.
623 int targetDataEnd(ident_t *loc, DeviceTy &Device, int32_t ArgNum,
624                   void **ArgBases, void **Args, int64_t *ArgSizes,
625                   int64_t *ArgTypes, map_var_info_t *ArgNames,
626                   void **ArgMappers, AsyncInfoTy &AsyncInfo, bool FromMapper) {
627   int Ret;
628   std::vector<DeallocTgtPtrInfo> DeallocTgtPtrs;
629   void *FromMapperBase = nullptr;
630   // process each input.
631   for (int32_t I = ArgNum - 1; I >= 0; --I) {
632     // Ignore private variables and arrays - there is no mapping for them.
633     // Also, ignore the use_device_ptr directive, it has no effect here.
634     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) ||
635         (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE))
636       continue;
637 
638     if (ArgMappers && ArgMappers[I]) {
639       // Instead of executing the regular path of targetDataEnd, call the
640       // targetDataMapper variant which will call targetDataEnd again
641       // with new arguments.
642       DP("Calling targetDataMapper for the %dth argument\n", I);
643 
644       map_var_info_t ArgName = (!ArgNames) ? nullptr : ArgNames[I];
645       Ret = targetDataMapper(loc, Device, ArgBases[I], Args[I], ArgSizes[I],
646                              ArgTypes[I], ArgName, ArgMappers[I], AsyncInfo,
647                              targetDataEnd);
648 
649       if (Ret != OFFLOAD_SUCCESS) {
650         REPORT("Call to targetDataEnd via targetDataMapper for custom mapper"
651                " failed.\n");
652         return OFFLOAD_FAIL;
653       }
654 
655       // Skip the rest of this function, continue to the next argument.
656       continue;
657     }
658 
659     void *HstPtrBegin = Args[I];
660     int64_t DataSize = ArgSizes[I];
661     // Adjust for proper alignment if this is a combined entry (for structs).
662     // Look at the next argument - if that is MEMBER_OF this one, then this one
663     // is a combined entry.
664     const int NextI = I + 1;
665     if (getParentIndex(ArgTypes[I]) < 0 && NextI < ArgNum &&
666         getParentIndex(ArgTypes[NextI]) == I) {
667       int64_t Padding = (int64_t)HstPtrBegin % Alignment;
668       if (Padding) {
669         DP("Using a Padding of %" PRId64 " bytes for begin address " DPxMOD
670            "\n",
671            Padding, DPxPTR(HstPtrBegin));
672         HstPtrBegin = (char *)HstPtrBegin - Padding;
673         DataSize += Padding;
674       }
675     }
676 
677     bool IsLast, IsHostPtr;
678     bool IsImplicit = ArgTypes[I] & OMP_TGT_MAPTYPE_IMPLICIT;
679     bool UpdateRef = (!(ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
680                       (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) &&
681                      !(FromMapper && I == 0);
682     bool ForceDelete = ArgTypes[I] & OMP_TGT_MAPTYPE_DELETE;
683     bool HasCloseModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_CLOSE;
684     bool HasPresentModifier = ArgTypes[I] & OMP_TGT_MAPTYPE_PRESENT;
685 
686     // If PTR_AND_OBJ, HstPtrBegin is address of pointee
687     void *TgtPtrBegin =
688         Device.getTgtPtrBegin(HstPtrBegin, DataSize, IsLast, UpdateRef,
689                               IsHostPtr, !IsImplicit, ForceDelete);
690     if (!TgtPtrBegin && (DataSize || HasPresentModifier)) {
691       DP("Mapping does not exist (%s)\n",
692          (HasPresentModifier ? "'present' map type modifier" : "ignored"));
693       if (HasPresentModifier) {
694         // OpenMP 5.1, sec. 2.21.7.1 "map Clause", p. 350 L10-13:
695         // "If a map clause appears on a target, target data, target enter data
696         // or target exit data construct with a present map-type-modifier then
697         // on entry to the region if the corresponding list item does not appear
698         // in the device data environment then an error occurs and the program
699         // terminates."
700         //
701         // This should be an error upon entering an "omp target exit data".  It
702         // should not be an error upon exiting an "omp target data" or "omp
703         // target".  For "omp target data", Clang thus doesn't include present
704         // modifiers for end calls.  For "omp target", we have not found a valid
705         // OpenMP program for which the error matters: it appears that, if a
706         // program can guarantee that data is present at the beginning of an
707         // "omp target" region so that there's no error there, that data is also
708         // guaranteed to be present at the end.
709         MESSAGE("device mapping required by 'present' map type modifier does "
710                 "not exist for host address " DPxMOD " (%" PRId64 " bytes)",
711                 DPxPTR(HstPtrBegin), DataSize);
712         return OFFLOAD_FAIL;
713       }
714     } else {
715       DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
716          " - is%s last\n",
717          DataSize, DPxPTR(TgtPtrBegin), (IsLast ? "" : " not"));
718     }
719 
720     // OpenMP 5.1, sec. 2.21.7.1 "map Clause", p. 351 L14-16:
721     // "If the map clause appears on a target, target data, or target exit data
722     // construct and a corresponding list item of the original list item is not
723     // present in the device data environment on exit from the region then the
724     // list item is ignored."
725     if (!TgtPtrBegin)
726       continue;
727 
728     bool DelEntry = IsLast;
729 
730     // If the last element from the mapper (for end transfer args comes in
731     // reverse order), do not remove the partial entry, the parent struct still
732     // exists.
733     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
734         !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
735       DelEntry = false; // protect parent struct from being deallocated
736     }
737 
738     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
739       // Move data back to the host
740       if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
741         bool Always = ArgTypes[I] & OMP_TGT_MAPTYPE_ALWAYS;
742         bool CopyMember = false;
743         if (!(PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
744             HasCloseModifier) {
745           if ((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
746               !(ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ))
747             CopyMember = IsLast;
748         }
749 
750         if ((DelEntry || Always || CopyMember) &&
751             !(PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
752               TgtPtrBegin == HstPtrBegin)) {
753           DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
754              DataSize, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
755           Ret = Device.retrieveData(HstPtrBegin, TgtPtrBegin, DataSize,
756                                     AsyncInfo);
757           if (Ret != OFFLOAD_SUCCESS) {
758             REPORT("Copying data from device failed.\n");
759             return OFFLOAD_FAIL;
760           }
761         }
762       }
763       if (DelEntry && FromMapper && I == 0) {
764         DelEntry = false;
765         FromMapperBase = HstPtrBegin;
766       }
767 
768       // If we copied back to the host a struct/array containing pointers, we
769       // need to restore the original host pointer values from their shadow
770       // copies. If the struct is going to be deallocated, remove any remaining
771       // shadow pointer entries for this struct.
772       uintptr_t LB = (uintptr_t)HstPtrBegin;
773       uintptr_t UB = (uintptr_t)HstPtrBegin + DataSize;
774       Device.ShadowMtx.lock();
775       for (ShadowPtrListTy::iterator Itr = Device.ShadowPtrMap.begin();
776            Itr != Device.ShadowPtrMap.end();) {
777         void **ShadowHstPtrAddr = (void **)Itr->first;
778 
779         // An STL map is sorted on its keys; use this property
780         // to quickly determine when to break out of the loop.
781         if ((uintptr_t)ShadowHstPtrAddr < LB) {
782           ++Itr;
783           continue;
784         }
785         if ((uintptr_t)ShadowHstPtrAddr >= UB)
786           break;
787 
788         // If we copied the struct to the host, we need to restore the pointer.
789         if (ArgTypes[I] & OMP_TGT_MAPTYPE_FROM) {
790           DP("Restoring original host pointer value " DPxMOD " for host "
791              "pointer " DPxMOD "\n",
792              DPxPTR(Itr->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
793           *ShadowHstPtrAddr = Itr->second.HstPtrVal;
794         }
795         // If the struct is to be deallocated, remove the shadow entry.
796         if (DelEntry) {
797           DP("Removing shadow pointer " DPxMOD "\n", DPxPTR(ShadowHstPtrAddr));
798           Itr = Device.ShadowPtrMap.erase(Itr);
799         } else {
800           ++Itr;
801         }
802       }
803       Device.ShadowMtx.unlock();
804 
805       // Add pointer to the buffer for later deallocation
806       if (DelEntry)
807         DeallocTgtPtrs.emplace_back(HstPtrBegin, DataSize, HasCloseModifier);
808     }
809   }
810 
811   // TODO: We should not synchronize here but pass the AsyncInfo object to the
812   //       allocate/deallocate device APIs.
813   //
814   // We need to synchronize before deallocating data.
815   Ret = AsyncInfo.synchronize();
816   if (Ret != OFFLOAD_SUCCESS)
817     return OFFLOAD_FAIL;
818 
819   // Deallocate target pointer
820   for (DeallocTgtPtrInfo &Info : DeallocTgtPtrs) {
821     if (FromMapperBase && FromMapperBase == Info.HstPtrBegin)
822       continue;
823     Ret = Device.deallocTgtPtr(Info.HstPtrBegin, Info.DataSize,
824                                Info.HasCloseModifier);
825     if (Ret != OFFLOAD_SUCCESS) {
826       REPORT("Deallocating data from device failed.\n");
827       return OFFLOAD_FAIL;
828     }
829   }
830 
831   return OFFLOAD_SUCCESS;
832 }
833 
834 static int targetDataContiguous(ident_t *loc, DeviceTy &Device, void *ArgsBase,
835                                 void *HstPtrBegin, int64_t ArgSize,
836                                 int64_t ArgType, AsyncInfoTy &AsyncInfo) {
837   TIMESCOPE_WITH_IDENT(loc);
838   bool IsLast, IsHostPtr;
839   void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, ArgSize, IsLast, false,
840                                             IsHostPtr, /*MustContain=*/true);
841   if (!TgtPtrBegin) {
842     DP("hst data:" DPxMOD " not found, becomes a noop\n", DPxPTR(HstPtrBegin));
843     if (ArgType & OMP_TGT_MAPTYPE_PRESENT) {
844       MESSAGE("device mapping required by 'present' motion modifier does not "
845               "exist for host address " DPxMOD " (%" PRId64 " bytes)",
846               DPxPTR(HstPtrBegin), ArgSize);
847       return OFFLOAD_FAIL;
848     }
849     return OFFLOAD_SUCCESS;
850   }
851 
852   if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
853       TgtPtrBegin == HstPtrBegin) {
854     DP("hst data:" DPxMOD " unified and shared, becomes a noop\n",
855        DPxPTR(HstPtrBegin));
856     return OFFLOAD_SUCCESS;
857   }
858 
859   if (ArgType & OMP_TGT_MAPTYPE_FROM) {
860     DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
861        ArgSize, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
862     int Ret = Device.retrieveData(HstPtrBegin, TgtPtrBegin, ArgSize, AsyncInfo);
863     if (Ret != OFFLOAD_SUCCESS) {
864       REPORT("Copying data from device failed.\n");
865       return OFFLOAD_FAIL;
866     }
867 
868     uintptr_t LB = (uintptr_t)HstPtrBegin;
869     uintptr_t UB = (uintptr_t)HstPtrBegin + ArgSize;
870     Device.ShadowMtx.lock();
871     for (ShadowPtrListTy::iterator IT = Device.ShadowPtrMap.begin();
872          IT != Device.ShadowPtrMap.end(); ++IT) {
873       void **ShadowHstPtrAddr = (void **)IT->first;
874       if ((uintptr_t)ShadowHstPtrAddr < LB)
875         continue;
876       if ((uintptr_t)ShadowHstPtrAddr >= UB)
877         break;
878       DP("Restoring original host pointer value " DPxMOD
879          " for host pointer " DPxMOD "\n",
880          DPxPTR(IT->second.HstPtrVal), DPxPTR(ShadowHstPtrAddr));
881       *ShadowHstPtrAddr = IT->second.HstPtrVal;
882     }
883     Device.ShadowMtx.unlock();
884   }
885 
886   if (ArgType & OMP_TGT_MAPTYPE_TO) {
887     DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
888        ArgSize, DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
889     int Ret = Device.submitData(TgtPtrBegin, HstPtrBegin, ArgSize, AsyncInfo);
890     if (Ret != OFFLOAD_SUCCESS) {
891       REPORT("Copying data to device failed.\n");
892       return OFFLOAD_FAIL;
893     }
894 
895     uintptr_t LB = (uintptr_t)HstPtrBegin;
896     uintptr_t UB = (uintptr_t)HstPtrBegin + ArgSize;
897     Device.ShadowMtx.lock();
898     for (ShadowPtrListTy::iterator IT = Device.ShadowPtrMap.begin();
899          IT != Device.ShadowPtrMap.end(); ++IT) {
900       void **ShadowHstPtrAddr = (void **)IT->first;
901       if ((uintptr_t)ShadowHstPtrAddr < LB)
902         continue;
903       if ((uintptr_t)ShadowHstPtrAddr >= UB)
904         break;
905       DP("Restoring original target pointer value " DPxMOD " for target "
906          "pointer " DPxMOD "\n",
907          DPxPTR(IT->second.TgtPtrVal), DPxPTR(IT->second.TgtPtrAddr));
908       Ret = Device.submitData(IT->second.TgtPtrAddr, &IT->second.TgtPtrVal,
909                               sizeof(void *), AsyncInfo);
910       if (Ret != OFFLOAD_SUCCESS) {
911         REPORT("Copying data to device failed.\n");
912         Device.ShadowMtx.unlock();
913         return OFFLOAD_FAIL;
914       }
915     }
916     Device.ShadowMtx.unlock();
917   }
918   return OFFLOAD_SUCCESS;
919 }
920 
921 static int targetDataNonContiguous(ident_t *loc, DeviceTy &Device,
922                                    void *ArgsBase,
923                                    __tgt_target_non_contig *NonContig,
924                                    uint64_t Size, int64_t ArgType,
925                                    int CurrentDim, int DimSize, uint64_t Offset,
926                                    AsyncInfoTy &AsyncInfo) {
927   TIMESCOPE_WITH_IDENT(loc);
928   int Ret = OFFLOAD_SUCCESS;
929   if (CurrentDim < DimSize) {
930     for (unsigned int I = 0; I < NonContig[CurrentDim].Count; ++I) {
931       uint64_t CurOffset =
932           (NonContig[CurrentDim].Offset + I) * NonContig[CurrentDim].Stride;
933       // we only need to transfer the first element for the last dimension
934       // since we've already got a contiguous piece.
935       if (CurrentDim != DimSize - 1 || I == 0) {
936         Ret = targetDataNonContiguous(loc, Device, ArgsBase, NonContig, Size,
937                                       ArgType, CurrentDim + 1, DimSize,
938                                       Offset + CurOffset, AsyncInfo);
939         // Stop the whole process if any contiguous piece returns anything
940         // other than OFFLOAD_SUCCESS.
941         if (Ret != OFFLOAD_SUCCESS)
942           return Ret;
943       }
944     }
945   } else {
946     char *Ptr = (char *)ArgsBase + Offset;
947     DP("Transfer of non-contiguous : host ptr " DPxMOD " offset %" PRIu64
948        " len %" PRIu64 "\n",
949        DPxPTR(Ptr), Offset, Size);
950     Ret = targetDataContiguous(loc, Device, ArgsBase, Ptr, Size, ArgType,
951                                AsyncInfo);
952   }
953   return Ret;
954 }
955 
956 static int getNonContigMergedDimension(__tgt_target_non_contig *NonContig,
957                                        int32_t DimSize) {
958   int RemovedDim = 0;
959   for (int I = DimSize - 1; I > 0; --I) {
960     if (NonContig[I].Count * NonContig[I].Stride == NonContig[I - 1].Stride)
961       RemovedDim++;
962   }
963   return RemovedDim;
964 }
965 
966 /// Internal function to pass data to/from the target.
967 int targetDataUpdate(ident_t *loc, DeviceTy &Device, int32_t ArgNum,
968                      void **ArgsBase, void **Args, int64_t *ArgSizes,
969                      int64_t *ArgTypes, map_var_info_t *ArgNames,
970                      void **ArgMappers, AsyncInfoTy &AsyncInfo, bool) {
971   // process each input.
972   for (int32_t I = 0; I < ArgNum; ++I) {
973     if ((ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) ||
974         (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE))
975       continue;
976 
977     if (ArgMappers && ArgMappers[I]) {
978       // Instead of executing the regular path of targetDataUpdate, call the
979       // targetDataMapper variant which will call targetDataUpdate again
980       // with new arguments.
981       DP("Calling targetDataMapper for the %dth argument\n", I);
982 
983       map_var_info_t ArgName = (!ArgNames) ? nullptr : ArgNames[I];
984       int Ret = targetDataMapper(loc, Device, ArgsBase[I], Args[I], ArgSizes[I],
985                                  ArgTypes[I], ArgName, ArgMappers[I], AsyncInfo,
986                                  targetDataUpdate);
987 
988       if (Ret != OFFLOAD_SUCCESS) {
989         REPORT("Call to targetDataUpdate via targetDataMapper for custom mapper"
990                " failed.\n");
991         return OFFLOAD_FAIL;
992       }
993 
994       // Skip the rest of this function, continue to the next argument.
995       continue;
996     }
997 
998     int Ret = OFFLOAD_SUCCESS;
999 
1000     if (ArgTypes[I] & OMP_TGT_MAPTYPE_NON_CONTIG) {
1001       __tgt_target_non_contig *NonContig = (__tgt_target_non_contig *)Args[I];
1002       int32_t DimSize = ArgSizes[I];
1003       uint64_t Size =
1004           NonContig[DimSize - 1].Count * NonContig[DimSize - 1].Stride;
1005       int32_t MergedDim = getNonContigMergedDimension(NonContig, DimSize);
1006       Ret = targetDataNonContiguous(
1007           loc, Device, ArgsBase[I], NonContig, Size, ArgTypes[I],
1008           /*current_dim=*/0, DimSize - MergedDim, /*offset=*/0, AsyncInfo);
1009     } else {
1010       Ret = targetDataContiguous(loc, Device, ArgsBase[I], Args[I], ArgSizes[I],
1011                                  ArgTypes[I], AsyncInfo);
1012     }
1013     if (Ret == OFFLOAD_FAIL)
1014       return OFFLOAD_FAIL;
1015   }
1016   return OFFLOAD_SUCCESS;
1017 }
1018 
1019 static const unsigned LambdaMapping = OMP_TGT_MAPTYPE_PTR_AND_OBJ |
1020                                       OMP_TGT_MAPTYPE_LITERAL |
1021                                       OMP_TGT_MAPTYPE_IMPLICIT;
1022 static bool isLambdaMapping(int64_t Mapping) {
1023   return (Mapping & LambdaMapping) == LambdaMapping;
1024 }
1025 
1026 namespace {
1027 /// Find the table information in the map or look it up in the translation
1028 /// tables.
1029 TableMap *getTableMap(void *HostPtr) {
1030   std::lock_guard<std::mutex> TblMapLock(PM->TblMapMtx);
1031   HostPtrToTableMapTy::iterator TableMapIt =
1032       PM->HostPtrToTableMap.find(HostPtr);
1033 
1034   if (TableMapIt != PM->HostPtrToTableMap.end())
1035     return &TableMapIt->second;
1036 
1037   // We don't have a map. So search all the registered libraries.
1038   TableMap *TM = nullptr;
1039   std::lock_guard<std::mutex> TrlTblLock(PM->TrlTblMtx);
1040   for (HostEntriesBeginToTransTableTy::iterator Itr =
1041            PM->HostEntriesBeginToTransTable.begin();
1042        Itr != PM->HostEntriesBeginToTransTable.end(); ++Itr) {
1043     // get the translation table (which contains all the good info).
1044     TranslationTable *TransTable = &Itr->second;
1045     // iterate over all the host table entries to see if we can locate the
1046     // host_ptr.
1047     __tgt_offload_entry *Cur = TransTable->HostTable.EntriesBegin;
1048     for (uint32_t I = 0; Cur < TransTable->HostTable.EntriesEnd; ++Cur, ++I) {
1049       if (Cur->addr != HostPtr)
1050         continue;
1051       // we got a match, now fill the HostPtrToTableMap so that we
1052       // may avoid this search next time.
1053       TM = &(PM->HostPtrToTableMap)[HostPtr];
1054       TM->Table = TransTable;
1055       TM->Index = I;
1056       return TM;
1057     }
1058   }
1059 
1060   return nullptr;
1061 }
1062 
1063 /// Get loop trip count
1064 /// FIXME: This function will not work right if calling
1065 /// __kmpc_push_target_tripcount_mapper in one thread but doing offloading in
1066 /// another thread, which might occur when we call task yield.
1067 uint64_t getLoopTripCount(int64_t DeviceId) {
1068   DeviceTy &Device = PM->Devices[DeviceId];
1069   uint64_t LoopTripCount = 0;
1070 
1071   {
1072     std::lock_guard<std::mutex> TblMapLock(PM->TblMapMtx);
1073     auto I = Device.LoopTripCnt.find(__kmpc_global_thread_num(NULL));
1074     if (I != Device.LoopTripCnt.end()) {
1075       LoopTripCount = I->second;
1076       Device.LoopTripCnt.erase(I);
1077       DP("loop trip count is %" PRIu64 ".\n", LoopTripCount);
1078     }
1079   }
1080 
1081   return LoopTripCount;
1082 }
1083 
1084 /// A class manages private arguments in a target region.
1085 class PrivateArgumentManagerTy {
1086   /// A data structure for the information of first-private arguments. We can
1087   /// use this information to optimize data transfer by packing all
1088   /// first-private arguments and transfer them all at once.
1089   struct FirstPrivateArgInfoTy {
1090     /// The index of the element in \p TgtArgs corresponding to the argument
1091     const int Index;
1092     /// Host pointer begin
1093     const char *HstPtrBegin;
1094     /// Host pointer end
1095     const char *HstPtrEnd;
1096     /// Aligned size
1097     const int64_t AlignedSize;
1098     /// Host pointer name
1099     const map_var_info_t HstPtrName = nullptr;
1100 
1101     FirstPrivateArgInfoTy(int Index, const void *HstPtr, int64_t Size,
1102                           const map_var_info_t HstPtrName = nullptr)
1103         : Index(Index), HstPtrBegin(reinterpret_cast<const char *>(HstPtr)),
1104           HstPtrEnd(HstPtrBegin + Size), AlignedSize(Size + Size % Alignment),
1105           HstPtrName(HstPtrName) {}
1106   };
1107 
1108   /// A vector of target pointers for all private arguments
1109   std::vector<void *> TgtPtrs;
1110 
1111   /// A vector of information of all first-private arguments to be packed
1112   std::vector<FirstPrivateArgInfoTy> FirstPrivateArgInfo;
1113   /// Host buffer for all arguments to be packed
1114   std::vector<char> FirstPrivateArgBuffer;
1115   /// The total size of all arguments to be packed
1116   int64_t FirstPrivateArgSize = 0;
1117 
1118   /// A reference to the \p DeviceTy object
1119   DeviceTy &Device;
1120   /// A pointer to a \p AsyncInfoTy object
1121   AsyncInfoTy &AsyncInfo;
1122 
1123   // TODO: What would be the best value here? Should we make it configurable?
1124   // If the size is larger than this threshold, we will allocate and transfer it
1125   // immediately instead of packing it.
1126   static constexpr const int64_t FirstPrivateArgSizeThreshold = 1024;
1127 
1128 public:
1129   /// Constructor
1130   PrivateArgumentManagerTy(DeviceTy &Dev, AsyncInfoTy &AsyncInfo)
1131       : Device(Dev), AsyncInfo(AsyncInfo) {}
1132 
1133   /// Add a private argument
1134   int addArg(void *HstPtr, int64_t ArgSize, int64_t ArgOffset,
1135              bool IsFirstPrivate, void *&TgtPtr, int TgtArgsIndex,
1136              const map_var_info_t HstPtrName = nullptr,
1137              const bool AllocImmediately = false) {
1138     // If the argument is not first-private, or its size is greater than a
1139     // predefined threshold, we will allocate memory and issue the transfer
1140     // immediately.
1141     if (ArgSize > FirstPrivateArgSizeThreshold || !IsFirstPrivate ||
1142         AllocImmediately) {
1143       TgtPtr = Device.allocData(ArgSize, HstPtr);
1144       if (!TgtPtr) {
1145         DP("Data allocation for %sprivate array " DPxMOD " failed.\n",
1146            (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtr));
1147         return OFFLOAD_FAIL;
1148       }
1149 #ifdef OMPTARGET_DEBUG
1150       void *TgtPtrBase = (void *)((intptr_t)TgtPtr + ArgOffset);
1151       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD
1152          " for %sprivate array " DPxMOD " - pushing target argument " DPxMOD
1153          "\n",
1154          ArgSize, DPxPTR(TgtPtr), (IsFirstPrivate ? "first-" : ""),
1155          DPxPTR(HstPtr), DPxPTR(TgtPtrBase));
1156 #endif
1157       // If first-private, copy data from host
1158       if (IsFirstPrivate) {
1159         DP("Submitting firstprivate data to the device.\n");
1160         int Ret = Device.submitData(TgtPtr, HstPtr, ArgSize, AsyncInfo);
1161         if (Ret != OFFLOAD_SUCCESS) {
1162           DP("Copying data to device failed, failed.\n");
1163           return OFFLOAD_FAIL;
1164         }
1165       }
1166       TgtPtrs.push_back(TgtPtr);
1167     } else {
1168       DP("Firstprivate array " DPxMOD " of size %" PRId64 " will be packed\n",
1169          DPxPTR(HstPtr), ArgSize);
1170       // When reach this point, the argument must meet all following
1171       // requirements:
1172       // 1. Its size does not exceed the threshold (see the comment for
1173       // FirstPrivateArgSizeThreshold);
1174       // 2. It must be first-private (needs to be mapped to target device).
1175       // We will pack all this kind of arguments to transfer them all at once
1176       // to reduce the number of data transfer. We will not take
1177       // non-first-private arguments, aka. private arguments that doesn't need
1178       // to be mapped to target device, into account because data allocation
1179       // can be very efficient with memory manager.
1180 
1181       // Placeholder value
1182       TgtPtr = nullptr;
1183       FirstPrivateArgInfo.emplace_back(TgtArgsIndex, HstPtr, ArgSize,
1184                                        HstPtrName);
1185       FirstPrivateArgSize += FirstPrivateArgInfo.back().AlignedSize;
1186     }
1187 
1188     return OFFLOAD_SUCCESS;
1189   }
1190 
1191   /// Pack first-private arguments, replace place holder pointers in \p TgtArgs,
1192   /// and start the transfer.
1193   int packAndTransfer(std::vector<void *> &TgtArgs) {
1194     if (!FirstPrivateArgInfo.empty()) {
1195       assert(FirstPrivateArgSize != 0 &&
1196              "FirstPrivateArgSize is 0 but FirstPrivateArgInfo is empty");
1197       FirstPrivateArgBuffer.resize(FirstPrivateArgSize, 0);
1198       auto Itr = FirstPrivateArgBuffer.begin();
1199       // Copy all host data to this buffer
1200       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
1201         std::copy(Info.HstPtrBegin, Info.HstPtrEnd, Itr);
1202         Itr = std::next(Itr, Info.AlignedSize);
1203       }
1204       // Allocate target memory
1205       void *TgtPtr =
1206           Device.allocData(FirstPrivateArgSize, FirstPrivateArgBuffer.data());
1207       if (TgtPtr == nullptr) {
1208         DP("Failed to allocate target memory for private arguments.\n");
1209         return OFFLOAD_FAIL;
1210       }
1211       TgtPtrs.push_back(TgtPtr);
1212       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD "\n",
1213          FirstPrivateArgSize, DPxPTR(TgtPtr));
1214       // Transfer data to target device
1215       int Ret = Device.submitData(TgtPtr, FirstPrivateArgBuffer.data(),
1216                                   FirstPrivateArgSize, AsyncInfo);
1217       if (Ret != OFFLOAD_SUCCESS) {
1218         DP("Failed to submit data of private arguments.\n");
1219         return OFFLOAD_FAIL;
1220       }
1221       // Fill in all placeholder pointers
1222       auto TP = reinterpret_cast<uintptr_t>(TgtPtr);
1223       for (FirstPrivateArgInfoTy &Info : FirstPrivateArgInfo) {
1224         void *&Ptr = TgtArgs[Info.Index];
1225         assert(Ptr == nullptr && "Target pointer is already set by mistaken");
1226         Ptr = reinterpret_cast<void *>(TP);
1227         TP += Info.AlignedSize;
1228         DP("Firstprivate array " DPxMOD " of size %" PRId64 " mapped to " DPxMOD
1229            "\n",
1230            DPxPTR(Info.HstPtrBegin), Info.HstPtrEnd - Info.HstPtrBegin,
1231            DPxPTR(Ptr));
1232       }
1233     }
1234 
1235     return OFFLOAD_SUCCESS;
1236   }
1237 
1238   /// Free all target memory allocated for private arguments
1239   int free() {
1240     for (void *P : TgtPtrs) {
1241       int Ret = Device.deleteData(P);
1242       if (Ret != OFFLOAD_SUCCESS) {
1243         DP("Deallocation of (first-)private arrays failed.\n");
1244         return OFFLOAD_FAIL;
1245       }
1246     }
1247 
1248     TgtPtrs.clear();
1249 
1250     return OFFLOAD_SUCCESS;
1251   }
1252 };
1253 
1254 /// Process data before launching the kernel, including calling targetDataBegin
1255 /// to map and transfer data to target device, transferring (first-)private
1256 /// variables.
1257 static int processDataBefore(ident_t *loc, int64_t DeviceId, void *HostPtr,
1258                              int32_t ArgNum, void **ArgBases, void **Args,
1259                              int64_t *ArgSizes, int64_t *ArgTypes,
1260                              map_var_info_t *ArgNames, void **ArgMappers,
1261                              std::vector<void *> &TgtArgs,
1262                              std::vector<ptrdiff_t> &TgtOffsets,
1263                              PrivateArgumentManagerTy &PrivateArgumentManager,
1264                              AsyncInfoTy &AsyncInfo) {
1265   TIMESCOPE_WITH_NAME_AND_IDENT("mappingBeforeTargetRegion", loc);
1266   DeviceTy &Device = PM->Devices[DeviceId];
1267   int Ret = targetDataBegin(loc, Device, ArgNum, ArgBases, Args, ArgSizes,
1268                             ArgTypes, ArgNames, ArgMappers, AsyncInfo);
1269   if (Ret != OFFLOAD_SUCCESS) {
1270     REPORT("Call to targetDataBegin failed, abort target.\n");
1271     return OFFLOAD_FAIL;
1272   }
1273 
1274   // List of (first-)private arrays allocated for this target region
1275   std::vector<int> TgtArgsPositions(ArgNum, -1);
1276 
1277   for (int32_t I = 0; I < ArgNum; ++I) {
1278     if (!(ArgTypes[I] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
1279       // This is not a target parameter, do not push it into TgtArgs.
1280       // Check for lambda mapping.
1281       if (isLambdaMapping(ArgTypes[I])) {
1282         assert((ArgTypes[I] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1283                "PTR_AND_OBJ must be also MEMBER_OF.");
1284         unsigned Idx = getParentIndex(ArgTypes[I]);
1285         int TgtIdx = TgtArgsPositions[Idx];
1286         assert(TgtIdx != -1 && "Base address must be translated already.");
1287         // The parent lambda must be processed already and it must be the last
1288         // in TgtArgs and TgtOffsets arrays.
1289         void *HstPtrVal = Args[I];
1290         void *HstPtrBegin = ArgBases[I];
1291         void *HstPtrBase = Args[Idx];
1292         bool IsLast, IsHostPtr; // unused.
1293         void *TgtPtrBase =
1294             (void *)((intptr_t)TgtArgs[TgtIdx] + TgtOffsets[TgtIdx]);
1295         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
1296         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
1297         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
1298         void *&PointerTgtPtrBegin = AsyncInfo.getVoidPtrLocation();
1299         PointerTgtPtrBegin = Device.getTgtPtrBegin(HstPtrVal, ArgSizes[I],
1300                                                    IsLast, false, IsHostPtr);
1301         if (!PointerTgtPtrBegin) {
1302           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
1303              DPxPTR(HstPtrVal));
1304           continue;
1305         }
1306         if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
1307             TgtPtrBegin == HstPtrBegin) {
1308           DP("Unified memory is active, no need to map lambda captured"
1309              "variable (" DPxMOD ")\n",
1310              DPxPTR(HstPtrVal));
1311           continue;
1312         }
1313         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
1314            DPxPTR(PointerTgtPtrBegin), DPxPTR(TgtPtrBegin));
1315         Ret = Device.submitData(TgtPtrBegin, &PointerTgtPtrBegin,
1316                                 sizeof(void *), AsyncInfo);
1317         if (Ret != OFFLOAD_SUCCESS) {
1318           REPORT("Copying data to device failed.\n");
1319           return OFFLOAD_FAIL;
1320         }
1321       }
1322       continue;
1323     }
1324     void *HstPtrBegin = Args[I];
1325     void *HstPtrBase = ArgBases[I];
1326     void *TgtPtrBegin;
1327     map_var_info_t HstPtrName = (!ArgNames) ? nullptr : ArgNames[I];
1328     ptrdiff_t TgtBaseOffset;
1329     bool IsLast, IsHostPtr; // unused.
1330     if (ArgTypes[I] & OMP_TGT_MAPTYPE_LITERAL) {
1331       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
1332          DPxPTR(HstPtrBase));
1333       TgtPtrBegin = HstPtrBase;
1334       TgtBaseOffset = 0;
1335     } else if (ArgTypes[I] & OMP_TGT_MAPTYPE_PRIVATE) {
1336       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1337       const bool IsFirstPrivate = (ArgTypes[I] & OMP_TGT_MAPTYPE_TO);
1338       // If there is a next argument and it depends on the current one, we need
1339       // to allocate the private memory immediately. If this is not the case,
1340       // then the argument can be marked for optimization and packed with the
1341       // other privates.
1342       const bool AllocImmediately =
1343           (I < ArgNum - 1 && (ArgTypes[I + 1] & OMP_TGT_MAPTYPE_MEMBER_OF));
1344       Ret = PrivateArgumentManager.addArg(
1345           HstPtrBegin, ArgSizes[I], TgtBaseOffset, IsFirstPrivate, TgtPtrBegin,
1346           TgtArgs.size(), HstPtrName, AllocImmediately);
1347       if (Ret != OFFLOAD_SUCCESS) {
1348         REPORT("Failed to process %sprivate argument " DPxMOD "\n",
1349                (IsFirstPrivate ? "first-" : ""), DPxPTR(HstPtrBegin));
1350         return OFFLOAD_FAIL;
1351       }
1352     } else {
1353       if (ArgTypes[I] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
1354         HstPtrBase = *reinterpret_cast<void **>(HstPtrBase);
1355       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, ArgSizes[I], IsLast,
1356                                           false, IsHostPtr);
1357       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
1358 #ifdef OMPTARGET_DEBUG
1359       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
1360       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
1361          DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
1362 #endif
1363     }
1364     TgtArgsPositions[I] = TgtArgs.size();
1365     TgtArgs.push_back(TgtPtrBegin);
1366     TgtOffsets.push_back(TgtBaseOffset);
1367   }
1368 
1369   assert(TgtArgs.size() == TgtOffsets.size() &&
1370          "Size mismatch in arguments and offsets");
1371 
1372   // Pack and transfer first-private arguments
1373   Ret = PrivateArgumentManager.packAndTransfer(TgtArgs);
1374   if (Ret != OFFLOAD_SUCCESS) {
1375     DP("Failed to pack and transfer first private arguments\n");
1376     return OFFLOAD_FAIL;
1377   }
1378 
1379   return OFFLOAD_SUCCESS;
1380 }
1381 
1382 /// Process data after launching the kernel, including transferring data back to
1383 /// host if needed and deallocating target memory of (first-)private variables.
1384 static int processDataAfter(ident_t *loc, int64_t DeviceId, void *HostPtr,
1385                             int32_t ArgNum, void **ArgBases, void **Args,
1386                             int64_t *ArgSizes, int64_t *ArgTypes,
1387                             map_var_info_t *ArgNames, void **ArgMappers,
1388                             PrivateArgumentManagerTy &PrivateArgumentManager,
1389                             AsyncInfoTy &AsyncInfo) {
1390   TIMESCOPE_WITH_NAME_AND_IDENT("mappingAfterTargetRegion", loc);
1391   DeviceTy &Device = PM->Devices[DeviceId];
1392 
1393   // Move data from device.
1394   int Ret = targetDataEnd(loc, Device, ArgNum, ArgBases, Args, ArgSizes,
1395                           ArgTypes, ArgNames, ArgMappers, AsyncInfo);
1396   if (Ret != OFFLOAD_SUCCESS) {
1397     REPORT("Call to targetDataEnd failed, abort target.\n");
1398     return OFFLOAD_FAIL;
1399   }
1400 
1401   // Free target memory for private arguments
1402   Ret = PrivateArgumentManager.free();
1403   if (Ret != OFFLOAD_SUCCESS) {
1404     REPORT("Failed to deallocate target memory for private args\n");
1405     return OFFLOAD_FAIL;
1406   }
1407 
1408   return OFFLOAD_SUCCESS;
1409 }
1410 } // namespace
1411 
1412 /// performs the same actions as data_begin in case arg_num is
1413 /// non-zero and initiates run of the offloaded region on the target platform;
1414 /// if arg_num is non-zero after the region execution is done it also
1415 /// performs the same action as data_update and data_end above. This function
1416 /// returns 0 if it was able to transfer the execution to a target and an
1417 /// integer different from zero otherwise.
1418 int target(ident_t *loc, DeviceTy &Device, void *HostPtr, int32_t ArgNum,
1419            void **ArgBases, void **Args, int64_t *ArgSizes, int64_t *ArgTypes,
1420            map_var_info_t *ArgNames, void **ArgMappers, int32_t TeamNum,
1421            int32_t ThreadLimit, int IsTeamConstruct, AsyncInfoTy &AsyncInfo) {
1422   int32_t DeviceId = Device.DeviceID;
1423 
1424   TableMap *TM = getTableMap(HostPtr);
1425   // No map for this host pointer found!
1426   if (!TM) {
1427     REPORT("Host ptr " DPxMOD " does not have a matching target pointer.\n",
1428            DPxPTR(HostPtr));
1429     return OFFLOAD_FAIL;
1430   }
1431 
1432   // get target table.
1433   __tgt_target_table *TargetTable = nullptr;
1434   {
1435     std::lock_guard<std::mutex> TrlTblLock(PM->TrlTblMtx);
1436     assert(TM->Table->TargetsTable.size() > (size_t)DeviceId &&
1437            "Not expecting a device ID outside the table's bounds!");
1438     TargetTable = TM->Table->TargetsTable[DeviceId];
1439   }
1440   assert(TargetTable && "Global data has not been mapped\n");
1441 
1442   std::vector<void *> TgtArgs;
1443   std::vector<ptrdiff_t> TgtOffsets;
1444 
1445   PrivateArgumentManagerTy PrivateArgumentManager(Device, AsyncInfo);
1446 
1447   int Ret;
1448   if (ArgNum) {
1449     // Process data, such as data mapping, before launching the kernel
1450     Ret = processDataBefore(loc, DeviceId, HostPtr, ArgNum, ArgBases, Args,
1451                             ArgSizes, ArgTypes, ArgNames, ArgMappers, TgtArgs,
1452                             TgtOffsets, PrivateArgumentManager, AsyncInfo);
1453     if (Ret != OFFLOAD_SUCCESS) {
1454       REPORT("Failed to process data before launching the kernel.\n");
1455       return OFFLOAD_FAIL;
1456     }
1457   }
1458 
1459   // Get loop trip count
1460   uint64_t LoopTripCount = getLoopTripCount(DeviceId);
1461 
1462   // Launch device execution.
1463   void *TgtEntryPtr = TargetTable->EntriesBegin[TM->Index].addr;
1464   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
1465      TargetTable->EntriesBegin[TM->Index].name, DPxPTR(TgtEntryPtr), TM->Index);
1466 
1467   {
1468     TIMESCOPE_WITH_NAME_AND_IDENT(
1469         IsTeamConstruct ? "runTargetTeamRegion" : "runTargetRegion", loc);
1470     if (IsTeamConstruct)
1471       Ret = Device.runTeamRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1472                                  TgtArgs.size(), TeamNum, ThreadLimit,
1473                                  LoopTripCount, AsyncInfo);
1474     else
1475       Ret = Device.runRegion(TgtEntryPtr, &TgtArgs[0], &TgtOffsets[0],
1476                              TgtArgs.size(), AsyncInfo);
1477   }
1478 
1479   if (Ret != OFFLOAD_SUCCESS) {
1480     REPORT("Executing target region abort target.\n");
1481     return OFFLOAD_FAIL;
1482   }
1483 
1484   if (ArgNum) {
1485     // Transfer data back and deallocate target memory for (first-)private
1486     // variables
1487     Ret = processDataAfter(loc, DeviceId, HostPtr, ArgNum, ArgBases, Args,
1488                            ArgSizes, ArgTypes, ArgNames, ArgMappers,
1489                            PrivateArgumentManager, AsyncInfo);
1490     if (Ret != OFFLOAD_SUCCESS) {
1491       REPORT("Failed to process data after launching the kernel.\n");
1492       return OFFLOAD_FAIL;
1493     }
1494   }
1495 
1496   return OFFLOAD_SUCCESS;
1497 }
1498