1 //===------ omptarget.cpp - Target independent OpenMP target RTL -- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implementation of the interface to be used by Clang during the codegen of a
10 // target region.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include <omptarget.h>
15 
16 #include "device.h"
17 #include "private.h"
18 #include "rtl.h"
19 
20 #include <cassert>
21 #include <vector>
22 
23 #ifdef OMPTARGET_DEBUG
24 int DebugLevel = 0;
25 #endif // OMPTARGET_DEBUG
26 
27 
28 
29 /* All begin addresses for partially mapped structs must be 8-aligned in order
30  * to ensure proper alignment of members. E.g.
31  *
32  * struct S {
33  *   int a;   // 4-aligned
34  *   int b;   // 4-aligned
35  *   int *p;  // 8-aligned
36  * } s1;
37  * ...
38  * #pragma omp target map(tofrom: s1.b, s1.p[0:N])
39  * {
40  *   s1.b = 5;
41  *   for (int i...) s1.p[i] = ...;
42  * }
43  *
44  * Here we are mapping s1 starting from member b, so BaseAddress=&s1=&s1.a and
45  * BeginAddress=&s1.b. Let's assume that the struct begins at address 0x100,
46  * then &s1.a=0x100, &s1.b=0x104, &s1.p=0x108. Each member obeys the alignment
47  * requirements for its type. Now, when we allocate memory on the device, in
48  * CUDA's case cuMemAlloc() returns an address which is at least 256-aligned.
49  * This means that the chunk of the struct on the device will start at a
50  * 256-aligned address, let's say 0x200. Then the address of b will be 0x200 and
51  * address of p will be a misaligned 0x204 (on the host there was no need to add
52  * padding between b and p, so p comes exactly 4 bytes after b). If the device
53  * kernel tries to access s1.p, a misaligned address error occurs (as reported
54  * by the CUDA plugin). By padding the begin address down to a multiple of 8 and
55  * extending the size of the allocated chuck accordingly, the chuck on the
56  * device will start at 0x200 with the padding (4 bytes), then &s1.b=0x204 and
57  * &s1.p=0x208, as they should be to satisfy the alignment requirements.
58  */
59 static const int64_t alignment = 8;
60 
61 /// Map global data and execute pending ctors
62 static int InitLibrary(DeviceTy& Device) {
63   /*
64    * Map global data
65    */
66   int32_t device_id = Device.DeviceID;
67   int rc = OFFLOAD_SUCCESS;
68 
69   Device.PendingGlobalsMtx.lock();
70   TrlTblMtx->lock();
71   for (HostEntriesBeginToTransTableTy::iterator
72       ii = HostEntriesBeginToTransTable->begin();
73       ii != HostEntriesBeginToTransTable->end(); ++ii) {
74     TranslationTable *TransTable = &ii->second;
75     if (TransTable->HostTable.EntriesBegin ==
76         TransTable->HostTable.EntriesEnd) {
77       // No host entry so no need to proceed
78       continue;
79     }
80     if (TransTable->TargetsTable[device_id] != 0) {
81       // Library entries have already been processed
82       continue;
83     }
84 
85     // 1) get image.
86     assert(TransTable->TargetsImages.size() > (size_t)device_id &&
87            "Not expecting a device ID outside the table's bounds!");
88     __tgt_device_image *img = TransTable->TargetsImages[device_id];
89     if (!img) {
90       DP("No image loaded for device id %d.\n", device_id);
91       rc = OFFLOAD_FAIL;
92       break;
93     }
94     // 2) load image into the target table.
95     __tgt_target_table *TargetTable =
96         TransTable->TargetsTable[device_id] = Device.load_binary(img);
97     // Unable to get table for this image: invalidate image and fail.
98     if (!TargetTable) {
99       DP("Unable to generate entries table for device id %d.\n", device_id);
100       TransTable->TargetsImages[device_id] = 0;
101       rc = OFFLOAD_FAIL;
102       break;
103     }
104 
105     // Verify whether the two table sizes match.
106     size_t hsize =
107         TransTable->HostTable.EntriesEnd - TransTable->HostTable.EntriesBegin;
108     size_t tsize = TargetTable->EntriesEnd - TargetTable->EntriesBegin;
109 
110     // Invalid image for these host entries!
111     if (hsize != tsize) {
112       DP("Host and Target tables mismatch for device id %d [%zx != %zx].\n",
113          device_id, hsize, tsize);
114       TransTable->TargetsImages[device_id] = 0;
115       TransTable->TargetsTable[device_id] = 0;
116       rc = OFFLOAD_FAIL;
117       break;
118     }
119 
120     // process global data that needs to be mapped.
121     Device.DataMapMtx.lock();
122     __tgt_target_table *HostTable = &TransTable->HostTable;
123     for (__tgt_offload_entry *CurrDeviceEntry = TargetTable->EntriesBegin,
124                              *CurrHostEntry = HostTable->EntriesBegin,
125                              *EntryDeviceEnd = TargetTable->EntriesEnd;
126          CurrDeviceEntry != EntryDeviceEnd;
127          CurrDeviceEntry++, CurrHostEntry++) {
128       if (CurrDeviceEntry->size != 0) {
129         // has data.
130         assert(CurrDeviceEntry->size == CurrHostEntry->size &&
131                "data size mismatch");
132 
133         // Fortran may use multiple weak declarations for the same symbol,
134         // therefore we must allow for multiple weak symbols to be loaded from
135         // the fat binary. Treat these mappings as any other "regular" mapping.
136         // Add entry to map.
137         if (Device.getTgtPtrBegin(CurrHostEntry->addr, CurrHostEntry->size))
138           continue;
139         DP("Add mapping from host " DPxMOD " to device " DPxMOD " with size %zu"
140             "\n", DPxPTR(CurrHostEntry->addr), DPxPTR(CurrDeviceEntry->addr),
141             CurrDeviceEntry->size);
142         Device.HostDataToTargetMap.emplace(
143             (uintptr_t)CurrHostEntry->addr /*HstPtrBase*/,
144             (uintptr_t)CurrHostEntry->addr /*HstPtrBegin*/,
145             (uintptr_t)CurrHostEntry->addr + CurrHostEntry->size /*HstPtrEnd*/,
146             (uintptr_t)CurrDeviceEntry->addr /*TgtPtrBegin*/,
147             true /*IsRefCountINF*/);
148       }
149     }
150     Device.DataMapMtx.unlock();
151   }
152   TrlTblMtx->unlock();
153 
154   if (rc != OFFLOAD_SUCCESS) {
155     Device.PendingGlobalsMtx.unlock();
156     return rc;
157   }
158 
159   /*
160    * Run ctors for static objects
161    */
162   if (!Device.PendingCtorsDtors.empty()) {
163     // Call all ctors for all libraries registered so far
164     for (auto &lib : Device.PendingCtorsDtors) {
165       if (!lib.second.PendingCtors.empty()) {
166         DP("Has pending ctors... call now\n");
167         for (auto &entry : lib.second.PendingCtors) {
168           void *ctor = entry;
169           int rc = target(device_id, ctor, 0, NULL, NULL, NULL, NULL, NULL, 1,
170               1, true /*team*/);
171           if (rc != OFFLOAD_SUCCESS) {
172             DP("Running ctor " DPxMOD " failed.\n", DPxPTR(ctor));
173             Device.PendingGlobalsMtx.unlock();
174             return OFFLOAD_FAIL;
175           }
176         }
177         // Clear the list to indicate that this device has been used
178         lib.second.PendingCtors.clear();
179         DP("Done with pending ctors for lib " DPxMOD "\n", DPxPTR(lib.first));
180       }
181     }
182   }
183   Device.HasPendingGlobals = false;
184   Device.PendingGlobalsMtx.unlock();
185 
186   return OFFLOAD_SUCCESS;
187 }
188 
189 // Check whether a device has been initialized, global ctors have been
190 // executed and global data has been mapped; do so if not already done.
191 int CheckDeviceAndCtors(int64_t device_id) {
192   // Is device ready?
193   if (!device_is_ready(device_id)) {
194     DP("Device %" PRId64 " is not ready.\n", device_id);
195     return OFFLOAD_FAIL;
196   }
197 
198   // Get device info.
199   DeviceTy &Device = Devices[device_id];
200 
201   // Check whether global data has been mapped for this device
202   Device.PendingGlobalsMtx.lock();
203   bool hasPendingGlobals = Device.HasPendingGlobals;
204   Device.PendingGlobalsMtx.unlock();
205   if (hasPendingGlobals && InitLibrary(Device) != OFFLOAD_SUCCESS) {
206     DP("Failed to init globals on device %" PRId64 "\n", device_id);
207     return OFFLOAD_FAIL;
208   }
209 
210   return OFFLOAD_SUCCESS;
211 }
212 
213 static int32_t member_of(int64_t type) {
214   return ((type & OMP_TGT_MAPTYPE_MEMBER_OF) >> 48) - 1;
215 }
216 
217 /// Call the user-defined mapper function followed by the appropriate
218 // target_data_* function (target_data_{begin,end,update}).
219 int target_data_mapper(DeviceTy &Device, void *arg_base,
220     void *arg, int64_t arg_size, int64_t arg_type, void *arg_mapper,
221     TargetDataFuncPtrTy target_data_function) {
222   DP("Calling the mapper function " DPxMOD "\n", DPxPTR(arg_mapper));
223 
224   // The mapper function fills up Components.
225   MapperComponentsTy MapperComponents;
226   MapperFuncPtrTy MapperFuncPtr = (MapperFuncPtrTy)(arg_mapper);
227   (*MapperFuncPtr)((void *)&MapperComponents, arg_base, arg, arg_size,
228       arg_type);
229 
230   // Construct new arrays for args_base, args, arg_sizes and arg_types
231   // using the information in MapperComponents and call the corresponding
232   // target_data_* function using these new arrays.
233   std::vector<void *> mapper_args_base;
234   std::vector<void *> mapper_args;
235   std::vector<int64_t> mapper_arg_sizes;
236   std::vector<int64_t> mapper_arg_types;
237 
238   for (auto& C : MapperComponents.Components) {
239     mapper_args_base.push_back(C.Base);
240     mapper_args.push_back(C.Begin);
241     mapper_arg_sizes.push_back(C.Size);
242     mapper_arg_types.push_back(C.Type);
243   }
244 
245   int rc = target_data_function(Device, MapperComponents.Components.size(),
246       mapper_args_base.data(), mapper_args.data(), mapper_arg_sizes.data(),
247       mapper_arg_types.data(), /*arg_mappers*/ nullptr,
248       /*__tgt_async_info*/ nullptr);
249 
250   return rc;
251 }
252 
253 /// Internal function to do the mapping and transfer the data to the device
254 int target_data_begin(DeviceTy &Device, int32_t arg_num, void **args_base,
255                       void **args, int64_t *arg_sizes, int64_t *arg_types,
256                       void **arg_mappers, __tgt_async_info *async_info_ptr) {
257   // process each input.
258   for (int32_t i = 0; i < arg_num; ++i) {
259     // Ignore private variables and arrays - there is no mapping for them.
260     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
261         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
262       continue;
263 
264     if (arg_mappers && arg_mappers[i]) {
265       // Instead of executing the regular path of target_data_begin, call the
266       // target_data_mapper variant which will call target_data_begin again
267       // with new arguments.
268       DP("Calling target_data_mapper for the %dth argument\n", i);
269 
270       int rc = target_data_mapper(Device, args_base[i], args[i], arg_sizes[i],
271           arg_types[i], arg_mappers[i], target_data_begin);
272 
273       if (rc != OFFLOAD_SUCCESS) {
274         DP("Call to target_data_begin via target_data_mapper for custom mapper"
275             " failed.\n");
276         return OFFLOAD_FAIL;
277       }
278 
279       // Skip the rest of this function, continue to the next argument.
280       continue;
281     }
282 
283     void *HstPtrBegin = args[i];
284     void *HstPtrBase = args_base[i];
285     int64_t data_size = arg_sizes[i];
286 
287     // Adjust for proper alignment if this is a combined entry (for structs).
288     // Look at the next argument - if that is MEMBER_OF this one, then this one
289     // is a combined entry.
290     int64_t padding = 0;
291     const int next_i = i+1;
292     if (member_of(arg_types[i]) < 0 && next_i < arg_num &&
293         member_of(arg_types[next_i]) == i) {
294       padding = (int64_t)HstPtrBegin % alignment;
295       if (padding) {
296         DP("Using a padding of %" PRId64 " bytes for begin address " DPxMOD
297             "\n", padding, DPxPTR(HstPtrBegin));
298         HstPtrBegin = (char *) HstPtrBegin - padding;
299         data_size += padding;
300       }
301     }
302 
303     // Address of pointer on the host and device, respectively.
304     void *Pointer_HstPtrBegin, *Pointer_TgtPtrBegin;
305     bool IsNew, Pointer_IsNew;
306     bool IsHostPtr = false;
307     bool IsImplicit = arg_types[i] & OMP_TGT_MAPTYPE_IMPLICIT;
308     // Force the creation of a device side copy of the data when:
309     // a close map modifier was associated with a map that contained a to.
310     bool HasCloseModifier = arg_types[i] & OMP_TGT_MAPTYPE_CLOSE;
311     bool HasPresentModifier = arg_types[i] & OMP_TGT_MAPTYPE_PRESENT;
312     // UpdateRef is based on MEMBER_OF instead of TARGET_PARAM because if we
313     // have reached this point via __tgt_target_data_begin and not __tgt_target
314     // then no argument is marked as TARGET_PARAM ("omp target data map" is not
315     // associated with a target region, so there are no target parameters). This
316     // may be considered a hack, we could revise the scheme in the future.
317     bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF);
318     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
319       DP("Has a pointer entry: \n");
320       // Base is address of pointer.
321       //
322       // Usually, the pointer is already allocated by this time.  For example:
323       //
324       //   #pragma omp target map(s.p[0:N])
325       //
326       // The map entry for s comes first, and the PTR_AND_OBJ entry comes
327       // afterward, so the pointer is already allocated by the time the
328       // PTR_AND_OBJ entry is handled below, and Pointer_TgtPtrBegin is thus
329       // non-null.  However, "declare target link" can produce a PTR_AND_OBJ
330       // entry for a global that might not already be allocated by the time the
331       // PTR_AND_OBJ entry is handled below, and so the allocation might fail
332       // when HasPresentModifier.
333       Pointer_TgtPtrBegin = Device.getOrAllocTgtPtr(
334           HstPtrBase, HstPtrBase, sizeof(void *), Pointer_IsNew, IsHostPtr,
335           IsImplicit, UpdateRef, HasCloseModifier, HasPresentModifier);
336       if (!Pointer_TgtPtrBegin) {
337         DP("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
338            HasPresentModifier ? "'present' map type modifier"
339                               : "device failure or illegal mapping");
340         return OFFLOAD_FAIL;
341       }
342       DP("There are %zu bytes allocated at target address " DPxMOD " - is%s new"
343           "\n", sizeof(void *), DPxPTR(Pointer_TgtPtrBegin),
344           (Pointer_IsNew ? "" : " not"));
345       Pointer_HstPtrBegin = HstPtrBase;
346       // modify current entry.
347       HstPtrBase = *(void **)HstPtrBase;
348       UpdateRef = true; // subsequently update ref count of pointee
349     }
350 
351     void *TgtPtrBegin = Device.getOrAllocTgtPtr(
352         HstPtrBegin, HstPtrBase, data_size, IsNew, IsHostPtr, IsImplicit,
353         UpdateRef, HasCloseModifier, HasPresentModifier);
354     // If data_size==0, then the argument could be a zero-length pointer to
355     // NULL, so getOrAlloc() returning NULL is not an error.
356     if (!TgtPtrBegin && (data_size || HasPresentModifier)) {
357       DP("Call to getOrAllocTgtPtr returned null pointer (%s).\n",
358          HasPresentModifier ? "'present' map type modifier"
359                             : "device failure or illegal mapping");
360       return OFFLOAD_FAIL;
361     }
362     DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
363         " - is%s new\n", data_size, DPxPTR(TgtPtrBegin),
364         (IsNew ? "" : " not"));
365 
366     if (arg_types[i] & OMP_TGT_MAPTYPE_RETURN_PARAM) {
367       uintptr_t Delta = (uintptr_t)HstPtrBegin - (uintptr_t)HstPtrBase;
368       void *TgtPtrBase = (void *)((uintptr_t)TgtPtrBegin - Delta);
369       DP("Returning device pointer " DPxMOD "\n", DPxPTR(TgtPtrBase));
370       args_base[i] = TgtPtrBase;
371     }
372 
373     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
374       bool copy = false;
375       if (!(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
376           HasCloseModifier) {
377         if (IsNew || (arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS)) {
378           copy = true;
379         } else if (arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) {
380           // Copy data only if the "parent" struct has RefCount==1.
381           int32_t parent_idx = member_of(arg_types[i]);
382           uint64_t parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
383           assert(parent_rc > 0 && "parent struct not found");
384           if (parent_rc == 1) {
385             copy = true;
386           }
387         }
388       }
389 
390       if (copy && !IsHostPtr) {
391         DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
392            data_size, DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
393         int rt = Device.data_submit(TgtPtrBegin, HstPtrBegin, data_size,
394                                     async_info_ptr);
395         if (rt != OFFLOAD_SUCCESS) {
396           DP("Copying data to device failed.\n");
397           return OFFLOAD_FAIL;
398         }
399       }
400     }
401 
402     if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ && !IsHostPtr) {
403       DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
404           DPxPTR(Pointer_TgtPtrBegin), DPxPTR(TgtPtrBegin));
405       uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
406       void *TgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
407       int rt = Device.data_submit(Pointer_TgtPtrBegin, &TgtPtrBase,
408                                   sizeof(void *), async_info_ptr);
409       if (rt != OFFLOAD_SUCCESS) {
410         DP("Copying data to device failed.\n");
411         return OFFLOAD_FAIL;
412       }
413       // create shadow pointers for this entry
414       Device.ShadowMtx.lock();
415       Device.ShadowPtrMap[Pointer_HstPtrBegin] = {HstPtrBase,
416           Pointer_TgtPtrBegin, TgtPtrBase};
417       Device.ShadowMtx.unlock();
418     }
419   }
420 
421   return OFFLOAD_SUCCESS;
422 }
423 
424 /// Internal function to undo the mapping and retrieve the data from the device.
425 int target_data_end(DeviceTy &Device, int32_t arg_num, void **args_base,
426                     void **args, int64_t *arg_sizes, int64_t *arg_types,
427                     void **arg_mappers, __tgt_async_info *async_info_ptr) {
428   // process each input.
429   for (int32_t i = arg_num - 1; i >= 0; --i) {
430     // Ignore private variables and arrays - there is no mapping for them.
431     // Also, ignore the use_device_ptr directive, it has no effect here.
432     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
433         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
434       continue;
435 
436     if (arg_mappers && arg_mappers[i]) {
437       // Instead of executing the regular path of target_data_end, call the
438       // target_data_mapper variant which will call target_data_end again
439       // with new arguments.
440       DP("Calling target_data_mapper for the %dth argument\n", i);
441 
442       int rc = target_data_mapper(Device, args_base[i], args[i], arg_sizes[i],
443           arg_types[i], arg_mappers[i], target_data_end);
444 
445       if (rc != OFFLOAD_SUCCESS) {
446         DP("Call to target_data_end via target_data_mapper for custom mapper"
447             " failed.\n");
448         return OFFLOAD_FAIL;
449       }
450 
451       // Skip the rest of this function, continue to the next argument.
452       continue;
453     }
454 
455     void *HstPtrBegin = args[i];
456     int64_t data_size = arg_sizes[i];
457     // Adjust for proper alignment if this is a combined entry (for structs).
458     // Look at the next argument - if that is MEMBER_OF this one, then this one
459     // is a combined entry.
460     int64_t padding = 0;
461     const int next_i = i+1;
462     if (member_of(arg_types[i]) < 0 && next_i < arg_num &&
463         member_of(arg_types[next_i]) == i) {
464       padding = (int64_t)HstPtrBegin % alignment;
465       if (padding) {
466         DP("Using a padding of %" PRId64 " bytes for begin address " DPxMOD
467             "\n", padding, DPxPTR(HstPtrBegin));
468         HstPtrBegin = (char *) HstPtrBegin - padding;
469         data_size += padding;
470       }
471     }
472 
473     bool IsLast, IsHostPtr;
474     bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
475         (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ);
476     bool ForceDelete = arg_types[i] & OMP_TGT_MAPTYPE_DELETE;
477     bool HasCloseModifier = arg_types[i] & OMP_TGT_MAPTYPE_CLOSE;
478     bool HasPresentModifier = arg_types[i] & OMP_TGT_MAPTYPE_PRESENT;
479 
480     // If PTR_AND_OBJ, HstPtrBegin is address of pointee
481     void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, data_size, IsLast,
482         UpdateRef, IsHostPtr);
483     if (!TgtPtrBegin && (data_size || HasPresentModifier)) {
484       DP("Mapping does not exist (%s)\n",
485          (HasPresentModifier ? "'present' map type modifier" : "ignored"));
486       if (HasPresentModifier) {
487         // FIXME: This should not be an error on exit from "omp target data",
488         // but it should be an error upon entering an "omp target exit data".
489         MESSAGE("device mapping required by 'present' map type modifier does "
490                 "not exist for host address " DPxMOD " (%ld bytes)",
491                 DPxPTR(HstPtrBegin), data_size);
492         return OFFLOAD_FAIL;
493       }
494     } else {
495       DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
496          " - is%s last\n",
497          data_size, DPxPTR(TgtPtrBegin), (IsLast ? "" : " not"));
498     }
499 
500     bool DelEntry = IsLast || ForceDelete;
501 
502     if ((arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
503         !(arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
504       DelEntry = false; // protect parent struct from being deallocated
505     }
506 
507     if ((arg_types[i] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
508       // Move data back to the host
509       if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
510         bool Always = arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS;
511         bool CopyMember = false;
512         if (!(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) ||
513             HasCloseModifier) {
514           if ((arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
515               !(arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
516             // Copy data only if the "parent" struct has RefCount==1.
517             int32_t parent_idx = member_of(arg_types[i]);
518             uint64_t parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
519             assert(parent_rc > 0 && "parent struct not found");
520             if (parent_rc == 1) {
521               CopyMember = true;
522             }
523           }
524         }
525 
526         if ((DelEntry || Always || CopyMember) &&
527             !(RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
528               TgtPtrBegin == HstPtrBegin)) {
529           DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
530              data_size, DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
531           int rt = Device.data_retrieve(HstPtrBegin, TgtPtrBegin, data_size,
532                                         async_info_ptr);
533           if (rt != OFFLOAD_SUCCESS) {
534             DP("Copying data from device failed.\n");
535             return OFFLOAD_FAIL;
536           }
537         }
538       }
539 
540       // If we copied back to the host a struct/array containing pointers, we
541       // need to restore the original host pointer values from their shadow
542       // copies. If the struct is going to be deallocated, remove any remaining
543       // shadow pointer entries for this struct.
544       uintptr_t lb = (uintptr_t) HstPtrBegin;
545       uintptr_t ub = (uintptr_t) HstPtrBegin + data_size;
546       Device.ShadowMtx.lock();
547       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
548            it != Device.ShadowPtrMap.end();) {
549         void **ShadowHstPtrAddr = (void**) it->first;
550 
551         // An STL map is sorted on its keys; use this property
552         // to quickly determine when to break out of the loop.
553         if ((uintptr_t) ShadowHstPtrAddr < lb) {
554           ++it;
555           continue;
556         }
557         if ((uintptr_t) ShadowHstPtrAddr >= ub)
558           break;
559 
560         // If we copied the struct to the host, we need to restore the pointer.
561         if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
562           DP("Restoring original host pointer value " DPxMOD " for host "
563               "pointer " DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
564               DPxPTR(ShadowHstPtrAddr));
565           *ShadowHstPtrAddr = it->second.HstPtrVal;
566         }
567         // If the struct is to be deallocated, remove the shadow entry.
568         if (DelEntry) {
569           DP("Removing shadow pointer " DPxMOD "\n", DPxPTR(ShadowHstPtrAddr));
570           it = Device.ShadowPtrMap.erase(it);
571         } else {
572           ++it;
573         }
574       }
575       Device.ShadowMtx.unlock();
576 
577       // Deallocate map
578       if (DelEntry) {
579         int rt = Device.deallocTgtPtr(HstPtrBegin, data_size, ForceDelete,
580                                       HasCloseModifier);
581         if (rt != OFFLOAD_SUCCESS) {
582           DP("Deallocating data from device failed.\n");
583           return OFFLOAD_FAIL;
584         }
585       }
586     }
587   }
588 
589   return OFFLOAD_SUCCESS;
590 }
591 
592 /// Internal function to pass data to/from the target.
593 // async_info_ptr is currently unused, added here so target_data_update has the
594 // same signature as target_data_begin and target_data_end.
595 int target_data_update(DeviceTy &Device, int32_t arg_num,
596     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
597     void **arg_mappers, __tgt_async_info *async_info_ptr) {
598   // process each input.
599   for (int32_t i = 0; i < arg_num; ++i) {
600     if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
601         (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
602       continue;
603 
604     if (arg_mappers && arg_mappers[i]) {
605       // Instead of executing the regular path of target_data_update, call the
606       // target_data_mapper variant which will call target_data_update again
607       // with new arguments.
608       DP("Calling target_data_mapper for the %dth argument\n", i);
609 
610       int rc = target_data_mapper(Device, args_base[i], args[i], arg_sizes[i],
611           arg_types[i], arg_mappers[i], target_data_update);
612 
613       if (rc != OFFLOAD_SUCCESS) {
614         DP("Call to target_data_update via target_data_mapper for custom mapper"
615             " failed.\n");
616         return OFFLOAD_FAIL;
617       }
618 
619       // Skip the rest of this function, continue to the next argument.
620       continue;
621     }
622 
623     void *HstPtrBegin = args[i];
624     int64_t MapSize = arg_sizes[i];
625     bool IsLast, IsHostPtr;
626     void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, MapSize, IsLast,
627         false, IsHostPtr);
628     if (!TgtPtrBegin) {
629       DP("hst data:" DPxMOD " not found, becomes a noop\n", DPxPTR(HstPtrBegin));
630       continue;
631     }
632 
633     if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
634         TgtPtrBegin == HstPtrBegin) {
635       DP("hst data:" DPxMOD " unified and shared, becomes a noop\n",
636          DPxPTR(HstPtrBegin));
637       continue;
638     }
639 
640     if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
641       DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
642           arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
643       int rt = Device.data_retrieve(HstPtrBegin, TgtPtrBegin, MapSize, nullptr);
644       if (rt != OFFLOAD_SUCCESS) {
645         DP("Copying data from device failed.\n");
646         return OFFLOAD_FAIL;
647       }
648 
649       uintptr_t lb = (uintptr_t) HstPtrBegin;
650       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
651       Device.ShadowMtx.lock();
652       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
653           it != Device.ShadowPtrMap.end(); ++it) {
654         void **ShadowHstPtrAddr = (void**) it->first;
655         if ((uintptr_t) ShadowHstPtrAddr < lb)
656           continue;
657         if ((uintptr_t) ShadowHstPtrAddr >= ub)
658           break;
659         DP("Restoring original host pointer value " DPxMOD " for host pointer "
660             DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
661             DPxPTR(ShadowHstPtrAddr));
662         *ShadowHstPtrAddr = it->second.HstPtrVal;
663       }
664       Device.ShadowMtx.unlock();
665     }
666 
667     if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
668       DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
669           arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
670       int rt = Device.data_submit(TgtPtrBegin, HstPtrBegin, MapSize, nullptr);
671       if (rt != OFFLOAD_SUCCESS) {
672         DP("Copying data to device failed.\n");
673         return OFFLOAD_FAIL;
674       }
675 
676       uintptr_t lb = (uintptr_t) HstPtrBegin;
677       uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
678       Device.ShadowMtx.lock();
679       for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
680           it != Device.ShadowPtrMap.end(); ++it) {
681         void **ShadowHstPtrAddr = (void**) it->first;
682         if ((uintptr_t) ShadowHstPtrAddr < lb)
683           continue;
684         if ((uintptr_t) ShadowHstPtrAddr >= ub)
685           break;
686         DP("Restoring original target pointer value " DPxMOD " for target "
687             "pointer " DPxMOD "\n", DPxPTR(it->second.TgtPtrVal),
688             DPxPTR(it->second.TgtPtrAddr));
689         rt = Device.data_submit(it->second.TgtPtrAddr,
690             &it->second.TgtPtrVal, sizeof(void *), nullptr);
691         if (rt != OFFLOAD_SUCCESS) {
692           DP("Copying data to device failed.\n");
693           Device.ShadowMtx.unlock();
694           return OFFLOAD_FAIL;
695         }
696       }
697       Device.ShadowMtx.unlock();
698     }
699   }
700   return OFFLOAD_SUCCESS;
701 }
702 
703 static const unsigned LambdaMapping = OMP_TGT_MAPTYPE_PTR_AND_OBJ |
704                                       OMP_TGT_MAPTYPE_LITERAL |
705                                       OMP_TGT_MAPTYPE_IMPLICIT;
706 static bool isLambdaMapping(int64_t Mapping) {
707   return (Mapping & LambdaMapping) == LambdaMapping;
708 }
709 
710 /// performs the same actions as data_begin in case arg_num is
711 /// non-zero and initiates run of the offloaded region on the target platform;
712 /// if arg_num is non-zero after the region execution is done it also
713 /// performs the same action as data_update and data_end above. This function
714 /// returns 0 if it was able to transfer the execution to a target and an
715 /// integer different from zero otherwise.
716 int target(int64_t device_id, void *host_ptr, int32_t arg_num,
717     void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
718     void **arg_mappers, int32_t team_num, int32_t thread_limit,
719     int IsTeamConstruct) {
720   DeviceTy &Device = Devices[device_id];
721 
722   // Find the table information in the map or look it up in the translation
723   // tables.
724   TableMap *TM = 0;
725   TblMapMtx->lock();
726   HostPtrToTableMapTy::iterator TableMapIt = HostPtrToTableMap->find(host_ptr);
727   if (TableMapIt == HostPtrToTableMap->end()) {
728     // We don't have a map. So search all the registered libraries.
729     TrlTblMtx->lock();
730     for (HostEntriesBeginToTransTableTy::iterator
731              ii = HostEntriesBeginToTransTable->begin(),
732              ie = HostEntriesBeginToTransTable->end();
733          !TM && ii != ie; ++ii) {
734       // get the translation table (which contains all the good info).
735       TranslationTable *TransTable = &ii->second;
736       // iterate over all the host table entries to see if we can locate the
737       // host_ptr.
738       __tgt_offload_entry *begin = TransTable->HostTable.EntriesBegin;
739       __tgt_offload_entry *end = TransTable->HostTable.EntriesEnd;
740       __tgt_offload_entry *cur = begin;
741       for (uint32_t i = 0; cur < end; ++cur, ++i) {
742         if (cur->addr != host_ptr)
743           continue;
744         // we got a match, now fill the HostPtrToTableMap so that we
745         // may avoid this search next time.
746         TM = &(*HostPtrToTableMap)[host_ptr];
747         TM->Table = TransTable;
748         TM->Index = i;
749         break;
750       }
751     }
752     TrlTblMtx->unlock();
753   } else {
754     TM = &TableMapIt->second;
755   }
756   TblMapMtx->unlock();
757 
758   // No map for this host pointer found!
759   if (!TM) {
760     DP("Host ptr " DPxMOD " does not have a matching target pointer.\n",
761        DPxPTR(host_ptr));
762     return OFFLOAD_FAIL;
763   }
764 
765   // get target table.
766   TrlTblMtx->lock();
767   assert(TM->Table->TargetsTable.size() > (size_t)device_id &&
768          "Not expecting a device ID outside the table's bounds!");
769   __tgt_target_table *TargetTable = TM->Table->TargetsTable[device_id];
770   TrlTblMtx->unlock();
771   assert(TargetTable && "Global data has not been mapped\n");
772 
773   __tgt_async_info AsyncInfo;
774 
775   // Move data to device.
776   int rc = target_data_begin(Device, arg_num, args_base, args, arg_sizes,
777                              arg_types, arg_mappers, &AsyncInfo);
778   if (rc != OFFLOAD_SUCCESS) {
779     DP("Call to target_data_begin failed, abort target.\n");
780     return OFFLOAD_FAIL;
781   }
782 
783   std::vector<void *> tgt_args;
784   std::vector<ptrdiff_t> tgt_offsets;
785 
786   // List of (first-)private arrays allocated for this target region
787   std::vector<void *> fpArrays;
788   std::vector<int> tgtArgsPositions(arg_num, -1);
789 
790   for (int32_t i = 0; i < arg_num; ++i) {
791     if (!(arg_types[i] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
792       // This is not a target parameter, do not push it into tgt_args.
793       // Check for lambda mapping.
794       if (isLambdaMapping(arg_types[i])) {
795         assert((arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
796                "PTR_AND_OBJ must be also MEMBER_OF.");
797         unsigned idx = member_of(arg_types[i]);
798         int tgtIdx = tgtArgsPositions[idx];
799         assert(tgtIdx != -1 && "Base address must be translated already.");
800         // The parent lambda must be processed already and it must be the last
801         // in tgt_args and tgt_offsets arrays.
802         void *HstPtrVal = args[i];
803         void *HstPtrBegin = args_base[i];
804         void *HstPtrBase = args[idx];
805         bool IsLast, IsHostPtr; // unused.
806         void *TgtPtrBase =
807             (void *)((intptr_t)tgt_args[tgtIdx] + tgt_offsets[tgtIdx]);
808         DP("Parent lambda base " DPxMOD "\n", DPxPTR(TgtPtrBase));
809         uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
810         void *TgtPtrBegin = (void *)((uintptr_t)TgtPtrBase + Delta);
811         void *Pointer_TgtPtrBegin =
812             Device.getTgtPtrBegin(HstPtrVal, arg_sizes[i], IsLast, false,
813                                   IsHostPtr);
814         if (!Pointer_TgtPtrBegin) {
815           DP("No lambda captured variable mapped (" DPxMOD ") - ignored\n",
816              DPxPTR(HstPtrVal));
817           continue;
818         }
819         if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
820             TgtPtrBegin == HstPtrBegin) {
821           DP("Unified memory is active, no need to map lambda captured"
822              "variable (" DPxMOD ")\n", DPxPTR(HstPtrVal));
823           continue;
824         }
825         DP("Update lambda reference (" DPxMOD ") -> [" DPxMOD "]\n",
826            DPxPTR(Pointer_TgtPtrBegin), DPxPTR(TgtPtrBegin));
827         int rt = Device.data_submit(TgtPtrBegin, &Pointer_TgtPtrBegin,
828                                     sizeof(void *), &AsyncInfo);
829         if (rt != OFFLOAD_SUCCESS) {
830           DP("Copying data to device failed.\n");
831           return OFFLOAD_FAIL;
832         }
833       }
834       continue;
835     }
836     void *HstPtrBegin = args[i];
837     void *HstPtrBase = args_base[i];
838     void *TgtPtrBegin;
839     ptrdiff_t TgtBaseOffset;
840     bool IsLast, IsHostPtr; // unused.
841     if (arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) {
842       DP("Forwarding first-private value " DPxMOD " to the target construct\n",
843           DPxPTR(HstPtrBase));
844       TgtPtrBegin = HstPtrBase;
845       TgtBaseOffset = 0;
846     } else if (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE) {
847       // Allocate memory for (first-)private array
848       TgtPtrBegin = Device.RTL->data_alloc(Device.RTLDeviceID,
849           arg_sizes[i], HstPtrBegin);
850       if (!TgtPtrBegin) {
851         DP ("Data allocation for %sprivate array " DPxMOD " failed, "
852             "abort target.\n",
853             (arg_types[i] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
854             DPxPTR(HstPtrBegin));
855         return OFFLOAD_FAIL;
856       }
857       fpArrays.push_back(TgtPtrBegin);
858       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
859 #ifdef OMPTARGET_DEBUG
860       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
861       DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD " for "
862           "%sprivate array " DPxMOD " - pushing target argument " DPxMOD "\n",
863           arg_sizes[i], DPxPTR(TgtPtrBegin),
864           (arg_types[i] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
865           DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBase));
866 #endif
867       // If first-private, copy data from host
868       if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
869         int rt = Device.data_submit(TgtPtrBegin, HstPtrBegin, arg_sizes[i],
870                                     &AsyncInfo);
871         if (rt != OFFLOAD_SUCCESS) {
872           DP("Copying data to device failed, failed.\n");
873           return OFFLOAD_FAIL;
874         }
875       }
876     } else if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
877       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBase, sizeof(void *), IsLast,
878           false, IsHostPtr);
879       TgtBaseOffset = 0; // no offset for ptrs.
880       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD " to "
881          "object " DPxMOD "\n", DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBase),
882          DPxPTR(HstPtrBase));
883     } else {
884       TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, arg_sizes[i], IsLast,
885           false, IsHostPtr);
886       TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
887 #ifdef OMPTARGET_DEBUG
888       void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
889       DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
890           DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
891 #endif
892     }
893     tgtArgsPositions[i] = tgt_args.size();
894     tgt_args.push_back(TgtPtrBegin);
895     tgt_offsets.push_back(TgtBaseOffset);
896   }
897 
898   assert(tgt_args.size() == tgt_offsets.size() &&
899       "Size mismatch in arguments and offsets");
900 
901   // Pop loop trip count
902   uint64_t ltc = 0;
903   TblMapMtx->lock();
904   auto I = Device.LoopTripCnt.find(__kmpc_global_thread_num(NULL));
905   if (I != Device.LoopTripCnt.end()) {
906     ltc = I->second;
907     Device.LoopTripCnt.erase(I);
908     DP("loop trip count is %lu.\n", ltc);
909   }
910   TblMapMtx->unlock();
911 
912   // Launch device execution.
913   DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
914       TargetTable->EntriesBegin[TM->Index].name,
915       DPxPTR(TargetTable->EntriesBegin[TM->Index].addr), TM->Index);
916   if (IsTeamConstruct) {
917     rc = Device.run_team_region(TargetTable->EntriesBegin[TM->Index].addr,
918                                 &tgt_args[0], &tgt_offsets[0], tgt_args.size(),
919                                 team_num, thread_limit, ltc, &AsyncInfo);
920   } else {
921     rc = Device.run_region(TargetTable->EntriesBegin[TM->Index].addr,
922                            &tgt_args[0], &tgt_offsets[0], tgt_args.size(),
923                            &AsyncInfo);
924   }
925   if (rc != OFFLOAD_SUCCESS) {
926     DP ("Executing target region abort target.\n");
927     return OFFLOAD_FAIL;
928   }
929 
930   // Deallocate (first-)private arrays
931   for (auto it : fpArrays) {
932     int rt = Device.RTL->data_delete(Device.RTLDeviceID, it);
933     if (rt != OFFLOAD_SUCCESS) {
934       DP("Deallocation of (first-)private arrays failed.\n");
935       return OFFLOAD_FAIL;
936     }
937   }
938 
939   // Move data from device.
940   int rt = target_data_end(Device, arg_num, args_base, args, arg_sizes,
941                            arg_types, arg_mappers, &AsyncInfo);
942   if (rt != OFFLOAD_SUCCESS) {
943     DP("Call to target_data_end failed, abort targe.\n");
944     return OFFLOAD_FAIL;
945   }
946 
947   if (Device.RTL->synchronize)
948     return Device.RTL->synchronize(device_id, &AsyncInfo);
949 
950   return OFFLOAD_SUCCESS;
951 }
952