blob: 9fa2b08106882bd326737f01a4dbac776ff1ed0d [file] [log] [blame]
George Rokos2467df62017-01-25 21:27:24 +00001//===------ omptarget.cpp - Target independent OpenMP target RTL -- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.txt for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implementation of the interface to be used by Clang during the codegen of a
11// target region.
12//
13//===----------------------------------------------------------------------===//
14
Jonas Hahnfeld43322802017-12-06 21:59:07 +000015#include <omptarget.h>
16
17#include "device.h"
18#include "private.h"
19#include "rtl.h"
20
George Rokos2467df62017-01-25 21:27:24 +000021#include <cassert>
22#include <climits>
George Rokos2467df62017-01-25 21:27:24 +000023#include <cstring>
George Rokos2467df62017-01-25 21:27:24 +000024#include <string>
25#include <vector>
26
Sergey Dmitrievb305d262017-08-14 15:09:59 +000027#ifdef OMPTARGET_DEBUG
Jonas Hahnfeld43322802017-12-06 21:59:07 +000028int DebugLevel = 0;
Sergey Dmitrievb305d262017-08-14 15:09:59 +000029#endif // OMPTARGET_DEBUG
30
George Rokos2467df62017-01-25 21:27:24 +000031#define INF_REF_CNT (LONG_MAX>>1) // leave room for additions/subtractions
32#define CONSIDERED_INF(x) (x > (INF_REF_CNT>>1))
33
George Rokos2467df62017-01-25 21:27:24 +000034/// Map between Device ID (i.e. openmp device id) and its DeviceTy.
Jonas Hahnfeld43322802017-12-06 21:59:07 +000035DevicesTy Devices;
George Rokos2467df62017-01-25 21:27:24 +000036
37/// Check whether a device has an associated RTL and initialize it if it's not
38/// already initialized.
39static bool device_is_ready(int device_num) {
40 DP("Checking whether device %d is ready.\n", device_num);
41 // Devices.size() can only change while registering a new
42 // library, so try to acquire the lock of RTLs' mutex.
43 RTLsMtx.lock();
44 size_t Devices_size = Devices.size();
45 RTLsMtx.unlock();
46 if (Devices_size <= (size_t)device_num) {
47 DP("Device ID %d does not have a matching RTL\n", device_num);
48 return false;
49 }
50
51 // Get device info
52 DeviceTy &Device = Devices[device_num];
53
54 DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
55 Device.RTLDeviceID, Device.IsInit);
56
57 // Init the device if not done before
58 if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
59 DP("Failed to init device %d\n", device_num);
60 return false;
61 }
62
63 DP("Device %d is ready to use.\n", device_num);
64
65 return true;
66}
67
68////////////////////////////////////////////////////////////////////////////////
69// Target API functions
70//
71EXTERN int omp_get_num_devices(void) {
72 RTLsMtx.lock();
73 size_t Devices_size = Devices.size();
74 RTLsMtx.unlock();
75
76 DP("Call to omp_get_num_devices returning %zd\n", Devices_size);
77
78 return Devices_size;
79}
80
81EXTERN int omp_get_initial_device(void) {
82 DP("Call to omp_get_initial_device returning %d\n", HOST_DEVICE);
83 return HOST_DEVICE;
84}
85
86EXTERN void *omp_target_alloc(size_t size, int device_num) {
87 DP("Call to omp_target_alloc for device %d requesting %zu bytes\n",
88 device_num, size);
89
90 if (size <= 0) {
91 DP("Call to omp_target_alloc with non-positive length\n");
92 return NULL;
93 }
94
95 void *rc = NULL;
96
97 if (device_num == omp_get_initial_device()) {
98 rc = malloc(size);
99 DP("omp_target_alloc returns host ptr " DPxMOD "\n", DPxPTR(rc));
100 return rc;
101 }
102
103 if (!device_is_ready(device_num)) {
104 DP("omp_target_alloc returns NULL ptr\n");
105 return NULL;
106 }
107
108 DeviceTy &Device = Devices[device_num];
George Rokos1546d312017-05-10 14:12:36 +0000109 rc = Device.RTL->data_alloc(Device.RTLDeviceID, size, NULL);
George Rokos2467df62017-01-25 21:27:24 +0000110 DP("omp_target_alloc returns device ptr " DPxMOD "\n", DPxPTR(rc));
111 return rc;
112}
113
114EXTERN void omp_target_free(void *device_ptr, int device_num) {
115 DP("Call to omp_target_free for device %d and address " DPxMOD "\n",
116 device_num, DPxPTR(device_ptr));
117
118 if (!device_ptr) {
119 DP("Call to omp_target_free with NULL ptr\n");
120 return;
121 }
122
123 if (device_num == omp_get_initial_device()) {
124 free(device_ptr);
125 DP("omp_target_free deallocated host ptr\n");
126 return;
127 }
128
129 if (!device_is_ready(device_num)) {
130 DP("omp_target_free returns, nothing to do\n");
131 return;
132 }
133
134 DeviceTy &Device = Devices[device_num];
135 Device.RTL->data_delete(Device.RTLDeviceID, (void *)device_ptr);
136 DP("omp_target_free deallocated device ptr\n");
137}
138
139EXTERN int omp_target_is_present(void *ptr, int device_num) {
140 DP("Call to omp_target_is_present for device %d and address " DPxMOD "\n",
141 device_num, DPxPTR(ptr));
142
143 if (!ptr) {
144 DP("Call to omp_target_is_present with NULL ptr, returning false\n");
145 return false;
146 }
147
148 if (device_num == omp_get_initial_device()) {
149 DP("Call to omp_target_is_present on host, returning true\n");
150 return true;
151 }
152
153 RTLsMtx.lock();
154 size_t Devices_size = Devices.size();
155 RTLsMtx.unlock();
156 if (Devices_size <= (size_t)device_num) {
157 DP("Call to omp_target_is_present with invalid device ID, returning "
158 "false\n");
159 return false;
160 }
161
162 DeviceTy& Device = Devices[device_num];
163 bool IsLast; // not used
164 int rc = (Device.getTgtPtrBegin(ptr, 0, IsLast, false) != NULL);
165 DP("Call to omp_target_is_present returns %d\n", rc);
166 return rc;
167}
168
169EXTERN int omp_target_memcpy(void *dst, void *src, size_t length,
170 size_t dst_offset, size_t src_offset, int dst_device, int src_device) {
171 DP("Call to omp_target_memcpy, dst device %d, src device %d, "
172 "dst addr " DPxMOD ", src addr " DPxMOD ", dst offset %zu, "
173 "src offset %zu, length %zu\n", dst_device, src_device, DPxPTR(dst),
174 DPxPTR(src), dst_offset, src_offset, length);
175
176 if (!dst || !src || length <= 0) {
177 DP("Call to omp_target_memcpy with invalid arguments\n");
178 return OFFLOAD_FAIL;
179 }
180
181 if (src_device != omp_get_initial_device() && !device_is_ready(src_device)) {
182 DP("omp_target_memcpy returns OFFLOAD_FAIL\n");
183 return OFFLOAD_FAIL;
184 }
185
186 if (dst_device != omp_get_initial_device() && !device_is_ready(dst_device)) {
187 DP("omp_target_memcpy returns OFFLOAD_FAIL\n");
188 return OFFLOAD_FAIL;
189 }
190
191 int rc = OFFLOAD_SUCCESS;
192 void *srcAddr = (char *)src + src_offset;
193 void *dstAddr = (char *)dst + dst_offset;
194
195 if (src_device == omp_get_initial_device() &&
196 dst_device == omp_get_initial_device()) {
197 DP("copy from host to host\n");
198 const void *p = memcpy(dstAddr, srcAddr, length);
199 if (p == NULL)
200 rc = OFFLOAD_FAIL;
201 } else if (src_device == omp_get_initial_device()) {
202 DP("copy from host to device\n");
203 DeviceTy& DstDev = Devices[dst_device];
204 rc = DstDev.data_submit(dstAddr, srcAddr, length);
205 } else if (dst_device == omp_get_initial_device()) {
206 DP("copy from device to host\n");
207 DeviceTy& SrcDev = Devices[src_device];
208 rc = SrcDev.data_retrieve(dstAddr, srcAddr, length);
209 } else {
210 DP("copy from device to device\n");
211 void *buffer = malloc(length);
212 DeviceTy& SrcDev = Devices[src_device];
213 DeviceTy& DstDev = Devices[dst_device];
214 rc = SrcDev.data_retrieve(buffer, srcAddr, length);
215 if (rc == OFFLOAD_SUCCESS)
216 rc = DstDev.data_submit(dstAddr, buffer, length);
217 }
218
219 DP("omp_target_memcpy returns %d\n", rc);
220 return rc;
221}
222
223EXTERN int omp_target_memcpy_rect(void *dst, void *src, size_t element_size,
224 int num_dims, const size_t *volume, const size_t *dst_offsets,
225 const size_t *src_offsets, const size_t *dst_dimensions,
226 const size_t *src_dimensions, int dst_device, int src_device) {
227 DP("Call to omp_target_memcpy_rect, dst device %d, src device %d, "
228 "dst addr " DPxMOD ", src addr " DPxMOD ", dst offsets " DPxMOD ", "
229 "src offsets " DPxMOD ", dst dims " DPxMOD ", src dims " DPxMOD ", "
230 "volume " DPxMOD ", element size %zu, num_dims %d\n", dst_device,
231 src_device, DPxPTR(dst), DPxPTR(src), DPxPTR(dst_offsets),
232 DPxPTR(src_offsets), DPxPTR(dst_dimensions), DPxPTR(src_dimensions),
233 DPxPTR(volume), element_size, num_dims);
234
235 if (!(dst || src)) {
236 DP("Call to omp_target_memcpy_rect returns max supported dimensions %d\n",
237 INT_MAX);
238 return INT_MAX;
239 }
240
241 if (!dst || !src || element_size < 1 || num_dims < 1 || !volume ||
242 !dst_offsets || !src_offsets || !dst_dimensions || !src_dimensions) {
243 DP("Call to omp_target_memcpy_rect with invalid arguments\n");
244 return OFFLOAD_FAIL;
245 }
246
247 int rc;
248 if (num_dims == 1) {
249 rc = omp_target_memcpy(dst, src, element_size * volume[0],
250 element_size * dst_offsets[0], element_size * src_offsets[0],
251 dst_device, src_device);
252 } else {
253 size_t dst_slice_size = element_size;
254 size_t src_slice_size = element_size;
255 for (int i=1; i<num_dims; ++i) {
256 dst_slice_size *= dst_dimensions[i];
257 src_slice_size *= src_dimensions[i];
258 }
259
260 size_t dst_off = dst_offsets[0] * dst_slice_size;
261 size_t src_off = src_offsets[0] * src_slice_size;
262 for (size_t i=0; i<volume[0]; ++i) {
263 rc = omp_target_memcpy_rect((char *) dst + dst_off + dst_slice_size * i,
264 (char *) src + src_off + src_slice_size * i, element_size,
265 num_dims - 1, volume + 1, dst_offsets + 1, src_offsets + 1,
266 dst_dimensions + 1, src_dimensions + 1, dst_device, src_device);
267
268 if (rc) {
269 DP("Recursive call to omp_target_memcpy_rect returns unsuccessfully\n");
270 return rc;
271 }
272 }
273 }
274
275 DP("omp_target_memcpy_rect returns %d\n", rc);
276 return rc;
277}
278
279EXTERN int omp_target_associate_ptr(void *host_ptr, void *device_ptr,
280 size_t size, size_t device_offset, int device_num) {
281 DP("Call to omp_target_associate_ptr with host_ptr " DPxMOD ", "
282 "device_ptr " DPxMOD ", size %zu, device_offset %zu, device_num %d\n",
283 DPxPTR(host_ptr), DPxPTR(device_ptr), size, device_offset, device_num);
284
285 if (!host_ptr || !device_ptr || size <= 0) {
286 DP("Call to omp_target_associate_ptr with invalid arguments\n");
287 return OFFLOAD_FAIL;
288 }
289
290 if (device_num == omp_get_initial_device()) {
291 DP("omp_target_associate_ptr: no association possible on the host\n");
292 return OFFLOAD_FAIL;
293 }
294
295 if (!device_is_ready(device_num)) {
296 DP("omp_target_associate_ptr returns OFFLOAD_FAIL\n");
297 return OFFLOAD_FAIL;
298 }
299
300 DeviceTy& Device = Devices[device_num];
301 void *device_addr = (void *)((uint64_t)device_ptr + (uint64_t)device_offset);
302 int rc = Device.associatePtr(host_ptr, device_addr, size);
303 DP("omp_target_associate_ptr returns %d\n", rc);
304 return rc;
305}
306
307EXTERN int omp_target_disassociate_ptr(void *host_ptr, int device_num) {
308 DP("Call to omp_target_disassociate_ptr with host_ptr " DPxMOD ", "
309 "device_num %d\n", DPxPTR(host_ptr), device_num);
310
311 if (!host_ptr) {
312 DP("Call to omp_target_associate_ptr with invalid host_ptr\n");
313 return OFFLOAD_FAIL;
314 }
315
316 if (device_num == omp_get_initial_device()) {
317 DP("omp_target_disassociate_ptr: no association possible on the host\n");
318 return OFFLOAD_FAIL;
319 }
320
321 if (!device_is_ready(device_num)) {
322 DP("omp_target_disassociate_ptr returns OFFLOAD_FAIL\n");
323 return OFFLOAD_FAIL;
324 }
325
326 DeviceTy& Device = Devices[device_num];
327 int rc = Device.disassociatePtr(host_ptr);
328 DP("omp_target_disassociate_ptr returns %d\n", rc);
329 return rc;
330}
331
332////////////////////////////////////////////////////////////////////////////////
333// functionality for device
334
335int DeviceTy::associatePtr(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size) {
336 DataMapMtx.lock();
337
338 // Check if entry exists
339 for (auto &HT : HostDataToTargetMap) {
340 if ((uintptr_t)HstPtrBegin == HT.HstPtrBegin) {
341 // Mapping already exists
342 bool isValid = HT.HstPtrBegin == (uintptr_t) HstPtrBegin &&
343 HT.HstPtrEnd == (uintptr_t) HstPtrBegin + Size &&
344 HT.TgtPtrBegin == (uintptr_t) TgtPtrBegin;
345 DataMapMtx.unlock();
346 if (isValid) {
347 DP("Attempt to re-associate the same device ptr+offset with the same "
348 "host ptr, nothing to do\n");
349 return OFFLOAD_SUCCESS;
350 } else {
351 DP("Not allowed to re-associate a different device ptr+offset with the "
352 "same host ptr\n");
353 return OFFLOAD_FAIL;
354 }
355 }
356 }
357
358 // Mapping does not exist, allocate it
359 HostDataToTargetTy newEntry;
360
361 // Set up missing fields
362 newEntry.HstPtrBase = (uintptr_t) HstPtrBegin;
363 newEntry.HstPtrBegin = (uintptr_t) HstPtrBegin;
364 newEntry.HstPtrEnd = (uintptr_t) HstPtrBegin + Size;
365 newEntry.TgtPtrBegin = (uintptr_t) TgtPtrBegin;
366 // refCount must be infinite
367 newEntry.RefCount = INF_REF_CNT;
368
369 DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", HstEnd="
370 DPxMOD ", TgtBegin=" DPxMOD "\n", DPxPTR(newEntry.HstPtrBase),
371 DPxPTR(newEntry.HstPtrBegin), DPxPTR(newEntry.HstPtrEnd),
372 DPxPTR(newEntry.TgtPtrBegin));
373 HostDataToTargetMap.push_front(newEntry);
374
375 DataMapMtx.unlock();
376
377 return OFFLOAD_SUCCESS;
378}
379
380int DeviceTy::disassociatePtr(void *HstPtrBegin) {
381 DataMapMtx.lock();
382
383 // Check if entry exists
384 for (HostDataToTargetListTy::iterator ii = HostDataToTargetMap.begin();
385 ii != HostDataToTargetMap.end(); ++ii) {
386 if ((uintptr_t)HstPtrBegin == ii->HstPtrBegin) {
387 // Mapping exists
388 if (CONSIDERED_INF(ii->RefCount)) {
389 DP("Association found, removing it\n");
390 HostDataToTargetMap.erase(ii);
391 DataMapMtx.unlock();
392 return OFFLOAD_SUCCESS;
393 } else {
394 DP("Trying to disassociate a pointer which was not mapped via "
395 "omp_target_associate_ptr\n");
396 break;
397 }
398 }
399 }
400
401 // Mapping not found
402 DataMapMtx.unlock();
403 DP("Association not found\n");
404 return OFFLOAD_FAIL;
405}
406
407// Get ref count of map entry containing HstPtrBegin
408long DeviceTy::getMapEntryRefCnt(void *HstPtrBegin) {
409 uintptr_t hp = (uintptr_t)HstPtrBegin;
410 long RefCnt = -1;
411
412 DataMapMtx.lock();
413 for (auto &HT : HostDataToTargetMap) {
414 if (hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd) {
415 DP("DeviceTy::getMapEntry: requested entry found\n");
416 RefCnt = HT.RefCount;
417 break;
418 }
419 }
420 DataMapMtx.unlock();
421
422 if (RefCnt < 0) {
423 DP("DeviceTy::getMapEntry: requested entry not found\n");
424 }
425
426 return RefCnt;
427}
428
429LookupResult DeviceTy::lookupMapping(void *HstPtrBegin, int64_t Size) {
430 uintptr_t hp = (uintptr_t)HstPtrBegin;
431 LookupResult lr;
432
433 DP("Looking up mapping(HstPtrBegin=" DPxMOD ", Size=%ld)...\n", DPxPTR(hp),
434 Size);
435 for (lr.Entry = HostDataToTargetMap.begin();
436 lr.Entry != HostDataToTargetMap.end(); ++lr.Entry) {
437 auto &HT = *lr.Entry;
438 // Is it contained?
439 lr.Flags.IsContained = hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd &&
440 (hp+Size) <= HT.HstPtrEnd;
441 // Does it extend into an already mapped region?
442 lr.Flags.ExtendsBefore = hp < HT.HstPtrBegin && (hp+Size) > HT.HstPtrBegin;
443 // Does it extend beyond the mapped region?
444 lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp+Size) > HT.HstPtrEnd;
445
446 if (lr.Flags.IsContained || lr.Flags.ExtendsBefore ||
447 lr.Flags.ExtendsAfter) {
448 break;
449 }
450 }
451
452 if (lr.Flags.ExtendsBefore) {
453 DP("WARNING: Pointer is not mapped but section extends into already "
454 "mapped data\n");
455 }
456 if (lr.Flags.ExtendsAfter) {
457 DP("WARNING: Pointer is already mapped but section extends beyond mapped "
458 "region\n");
459 }
460
461 return lr;
462}
463
464// Used by target_data_begin
465// Return the target pointer begin (where the data will be moved).
466// Allocate memory if this is the first occurrence if this mapping.
467// Increment the reference counter.
468// If NULL is returned, then either data allocation failed or the user tried
469// to do an illegal mapping.
470void *DeviceTy::getOrAllocTgtPtr(void *HstPtrBegin, void *HstPtrBase,
471 int64_t Size, bool &IsNew, bool IsImplicit, bool UpdateRefCount) {
472 void *rc = NULL;
473 DataMapMtx.lock();
474 LookupResult lr = lookupMapping(HstPtrBegin, Size);
475
476 // Check if the pointer is contained.
477 if (lr.Flags.IsContained ||
478 ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && IsImplicit)) {
479 auto &HT = *lr.Entry;
480 IsNew = false;
481
482 if (UpdateRefCount)
483 ++HT.RefCount;
484
485 uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
486 DP("Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
487 "Size=%ld,%s RefCount=%s\n", (IsImplicit ? " (implicit)" : ""),
488 DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
489 (UpdateRefCount ? " updated" : ""),
490 (CONSIDERED_INF(HT.RefCount)) ? "INF" :
491 std::to_string(HT.RefCount).c_str());
492 rc = (void *)tp;
493 } else if ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && !IsImplicit) {
494 // Explicit extension of mapped data - not allowed.
495 DP("Explicit extension of mapping is not allowed.\n");
496 } else if (Size) {
497 // If it is not contained and Size > 0 we should create a new entry for it.
498 IsNew = true;
George Rokos1546d312017-05-10 14:12:36 +0000499 uintptr_t tp = (uintptr_t)RTL->data_alloc(RTLDeviceID, Size, HstPtrBegin);
George Rokos2467df62017-01-25 21:27:24 +0000500 DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", "
501 "HstEnd=" DPxMOD ", TgtBegin=" DPxMOD "\n", DPxPTR(HstPtrBase),
502 DPxPTR(HstPtrBegin), DPxPTR((uintptr_t)HstPtrBegin + Size), DPxPTR(tp));
503 HostDataToTargetMap.push_front(HostDataToTargetTy((uintptr_t)HstPtrBase,
504 (uintptr_t)HstPtrBegin, (uintptr_t)HstPtrBegin + Size, tp));
505 rc = (void *)tp;
506 }
507
508 DataMapMtx.unlock();
509 return rc;
510}
511
512// Used by target_data_begin, target_data_end, target_data_update and target.
513// Return the target pointer begin (where the data will be moved).
514// Decrement the reference counter if called from target_data_end.
515void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
516 bool UpdateRefCount) {
517 void *rc = NULL;
518 DataMapMtx.lock();
519 LookupResult lr = lookupMapping(HstPtrBegin, Size);
520
521 if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
522 auto &HT = *lr.Entry;
523 IsLast = !(HT.RefCount > 1);
524
525 if (HT.RefCount > 1 && UpdateRefCount)
526 --HT.RefCount;
527
528 uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
529 DP("Mapping exists with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
530 "Size=%ld,%s RefCount=%s\n", DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
531 (UpdateRefCount ? " updated" : ""),
532 (CONSIDERED_INF(HT.RefCount)) ? "INF" :
533 std::to_string(HT.RefCount).c_str());
534 rc = (void *)tp;
535 } else {
536 IsLast = false;
537 }
538
539 DataMapMtx.unlock();
540 return rc;
541}
542
543// Return the target pointer begin (where the data will be moved).
George Rokosd57681b2017-04-22 11:45:03 +0000544// Lock-free version called when loading global symbols from the fat binary.
George Rokos2467df62017-01-25 21:27:24 +0000545void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
546 uintptr_t hp = (uintptr_t)HstPtrBegin;
547 LookupResult lr = lookupMapping(HstPtrBegin, Size);
548 if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
549 auto &HT = *lr.Entry;
550 uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
551 return (void *)tp;
552 }
553
554 return NULL;
555}
556
557int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size, bool ForceDelete) {
558 // Check if the pointer is contained in any sub-nodes.
559 int rc;
560 DataMapMtx.lock();
561 LookupResult lr = lookupMapping(HstPtrBegin, Size);
562 if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
563 auto &HT = *lr.Entry;
564 if (ForceDelete)
565 HT.RefCount = 1;
566 if (--HT.RefCount <= 0) {
567 assert(HT.RefCount == 0 && "did not expect a negative ref count");
568 DP("Deleting tgt data " DPxMOD " of size %ld\n",
569 DPxPTR(HT.TgtPtrBegin), Size);
570 RTL->data_delete(RTLDeviceID, (void *)HT.TgtPtrBegin);
571 DP("Removing%s mapping with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
572 ", Size=%ld\n", (ForceDelete ? " (forced)" : ""),
573 DPxPTR(HT.HstPtrBegin), DPxPTR(HT.TgtPtrBegin), Size);
574 HostDataToTargetMap.erase(lr.Entry);
575 }
576 rc = OFFLOAD_SUCCESS;
577 } else {
578 DP("Section to delete (hst addr " DPxMOD ") does not exist in the allocated"
579 " memory\n", DPxPTR(HstPtrBegin));
580 rc = OFFLOAD_FAIL;
581 }
582
583 DataMapMtx.unlock();
584 return rc;
585}
586
587/// Init device, should not be called directly.
588void DeviceTy::init() {
589 int32_t rc = RTL->init_device(RTLDeviceID);
590 if (rc == OFFLOAD_SUCCESS) {
591 IsInit = true;
592 }
593}
594
595/// Thread-safe method to initialize the device only once.
596int32_t DeviceTy::initOnce() {
597 std::call_once(InitFlag, &DeviceTy::init, this);
598
599 // At this point, if IsInit is true, then either this thread or some other
600 // thread in the past successfully initialized the device, so we can return
601 // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
602 // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
603 // that some other thread already attempted to execute init() and if IsInit
604 // is still false, return OFFLOAD_FAIL.
605 if (IsInit)
606 return OFFLOAD_SUCCESS;
607 else
608 return OFFLOAD_FAIL;
609}
610
611// Load binary to device.
612__tgt_target_table *DeviceTy::load_binary(void *Img) {
613 RTL->Mtx.lock();
614 __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
615 RTL->Mtx.unlock();
616 return rc;
617}
618
619// Submit data to device.
620int32_t DeviceTy::data_submit(void *TgtPtrBegin, void *HstPtrBegin,
621 int64_t Size) {
622 return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
623}
624
625// Retrieve data from device.
626int32_t DeviceTy::data_retrieve(void *HstPtrBegin, void *TgtPtrBegin,
627 int64_t Size) {
628 return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
629}
630
631// Run region on device
632int32_t DeviceTy::run_region(void *TgtEntryPtr, void **TgtVarsPtr,
George Rokos1546d312017-05-10 14:12:36 +0000633 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize) {
634 return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
635 TgtVarsSize);
George Rokos2467df62017-01-25 21:27:24 +0000636}
637
638// Run team region on device.
639int32_t DeviceTy::run_team_region(void *TgtEntryPtr, void **TgtVarsPtr,
George Rokos1546d312017-05-10 14:12:36 +0000640 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize, int32_t NumTeams,
641 int32_t ThreadLimit, uint64_t LoopTripCount) {
642 return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
643 TgtVarsSize, NumTeams, ThreadLimit, LoopTripCount);
George Rokos2467df62017-01-25 21:27:24 +0000644}
645
646////////////////////////////////////////////////////////////////////////////////
George Rokos2467df62017-01-25 21:27:24 +0000647/// adds a target shared library to the target execution image
648EXTERN void __tgt_register_lib(__tgt_bin_desc *desc) {
Jonas Hahnfeld43322802017-12-06 21:59:07 +0000649 RTLs.RegisterLib(desc);
George Rokos2467df62017-01-25 21:27:24 +0000650}
651
652////////////////////////////////////////////////////////////////////////////////
653/// unloads a target shared library
654EXTERN void __tgt_unregister_lib(__tgt_bin_desc *desc) {
Jonas Hahnfeld43322802017-12-06 21:59:07 +0000655 RTLs.UnregisterLib(desc);
George Rokos2467df62017-01-25 21:27:24 +0000656}
657
658/// Map global data and execute pending ctors
659static int InitLibrary(DeviceTy& Device) {
660 /*
661 * Map global data
662 */
663 int32_t device_id = Device.DeviceID;
664 int rc = OFFLOAD_SUCCESS;
665
666 Device.PendingGlobalsMtx.lock();
667 TrlTblMtx.lock();
668 for (HostEntriesBeginToTransTableTy::iterator
669 ii = HostEntriesBeginToTransTable.begin();
670 ii != HostEntriesBeginToTransTable.end(); ++ii) {
671 TranslationTable *TransTable = &ii->second;
672 if (TransTable->TargetsTable[device_id] != 0) {
673 // Library entries have already been processed
674 continue;
675 }
676
677 // 1) get image.
678 assert(TransTable->TargetsImages.size() > (size_t)device_id &&
679 "Not expecting a device ID outside the table's bounds!");
680 __tgt_device_image *img = TransTable->TargetsImages[device_id];
681 if (!img) {
682 DP("No image loaded for device id %d.\n", device_id);
683 rc = OFFLOAD_FAIL;
684 break;
685 }
686 // 2) load image into the target table.
687 __tgt_target_table *TargetTable =
688 TransTable->TargetsTable[device_id] = Device.load_binary(img);
689 // Unable to get table for this image: invalidate image and fail.
690 if (!TargetTable) {
691 DP("Unable to generate entries table for device id %d.\n", device_id);
692 TransTable->TargetsImages[device_id] = 0;
693 rc = OFFLOAD_FAIL;
694 break;
695 }
696
697 // Verify whether the two table sizes match.
698 size_t hsize =
699 TransTable->HostTable.EntriesEnd - TransTable->HostTable.EntriesBegin;
700 size_t tsize = TargetTable->EntriesEnd - TargetTable->EntriesBegin;
701
702 // Invalid image for these host entries!
703 if (hsize != tsize) {
704 DP("Host and Target tables mismatch for device id %d [%zx != %zx].\n",
705 device_id, hsize, tsize);
706 TransTable->TargetsImages[device_id] = 0;
707 TransTable->TargetsTable[device_id] = 0;
708 rc = OFFLOAD_FAIL;
709 break;
710 }
711
712 // process global data that needs to be mapped.
George Rokosd57681b2017-04-22 11:45:03 +0000713 Device.DataMapMtx.lock();
George Rokos2467df62017-01-25 21:27:24 +0000714 __tgt_target_table *HostTable = &TransTable->HostTable;
715 for (__tgt_offload_entry *CurrDeviceEntry = TargetTable->EntriesBegin,
716 *CurrHostEntry = HostTable->EntriesBegin,
717 *EntryDeviceEnd = TargetTable->EntriesEnd;
718 CurrDeviceEntry != EntryDeviceEnd;
719 CurrDeviceEntry++, CurrHostEntry++) {
720 if (CurrDeviceEntry->size != 0) {
721 // has data.
722 assert(CurrDeviceEntry->size == CurrHostEntry->size &&
723 "data size mismatch");
George Rokosba7380b2017-03-22 16:43:40 +0000724
725 // Fortran may use multiple weak declarations for the same symbol,
726 // therefore we must allow for multiple weak symbols to be loaded from
727 // the fat binary. Treat these mappings as any other "regular" mapping.
728 // Add entry to map.
George Rokosd57681b2017-04-22 11:45:03 +0000729 if (Device.getTgtPtrBegin(CurrHostEntry->addr, CurrHostEntry->size))
730 continue;
George Rokos2467df62017-01-25 21:27:24 +0000731 DP("Add mapping from host " DPxMOD " to device " DPxMOD " with size %zu"
732 "\n", DPxPTR(CurrHostEntry->addr), DPxPTR(CurrDeviceEntry->addr),
733 CurrDeviceEntry->size);
George Rokosd57681b2017-04-22 11:45:03 +0000734 Device.HostDataToTargetMap.push_front(HostDataToTargetTy(
735 (uintptr_t)CurrHostEntry->addr /*HstPtrBase*/,
736 (uintptr_t)CurrHostEntry->addr /*HstPtrBegin*/,
737 (uintptr_t)CurrHostEntry->addr + CurrHostEntry->size /*HstPtrEnd*/,
738 (uintptr_t)CurrDeviceEntry->addr /*TgtPtrBegin*/,
739 INF_REF_CNT /*RefCount*/));
George Rokos2467df62017-01-25 21:27:24 +0000740 }
741 }
George Rokosd57681b2017-04-22 11:45:03 +0000742 Device.DataMapMtx.unlock();
George Rokos2467df62017-01-25 21:27:24 +0000743 }
744 TrlTblMtx.unlock();
745
746 if (rc != OFFLOAD_SUCCESS) {
747 Device.PendingGlobalsMtx.unlock();
748 return rc;
749 }
750
751 /*
752 * Run ctors for static objects
753 */
754 if (!Device.PendingCtorsDtors.empty()) {
755 // Call all ctors for all libraries registered so far
756 for (auto &lib : Device.PendingCtorsDtors) {
757 if (!lib.second.PendingCtors.empty()) {
758 DP("Has pending ctors... call now\n");
759 for (auto &entry : lib.second.PendingCtors) {
760 void *ctor = entry;
761 int rc = target(device_id, ctor, 0, NULL, NULL, NULL,
762 NULL, 1, 1, true /*team*/);
763 if (rc != OFFLOAD_SUCCESS) {
764 DP("Running ctor " DPxMOD " failed.\n", DPxPTR(ctor));
765 Device.PendingGlobalsMtx.unlock();
766 return OFFLOAD_FAIL;
767 }
768 }
769 // Clear the list to indicate that this device has been used
770 lib.second.PendingCtors.clear();
771 DP("Done with pending ctors for lib " DPxMOD "\n", DPxPTR(lib.first));
772 }
773 }
774 }
775 Device.HasPendingGlobals = false;
776 Device.PendingGlobalsMtx.unlock();
777
778 return OFFLOAD_SUCCESS;
779}
780
781// Check whether a device has been initialized, global ctors have been
782// executed and global data has been mapped; do so if not already done.
783static int CheckDevice(int32_t device_id) {
784 // Is device ready?
785 if (!device_is_ready(device_id)) {
786 DP("Device %d is not ready.\n", device_id);
787 return OFFLOAD_FAIL;
788 }
789
790 // Get device info.
791 DeviceTy &Device = Devices[device_id];
792
793 // Check whether global data has been mapped for this device
794 Device.PendingGlobalsMtx.lock();
795 bool hasPendingGlobals = Device.HasPendingGlobals;
796 Device.PendingGlobalsMtx.unlock();
797 if (hasPendingGlobals && InitLibrary(Device) != OFFLOAD_SUCCESS) {
798 DP("Failed to init globals on device %d\n", device_id);
799 return OFFLOAD_FAIL;
800 }
801
802 return OFFLOAD_SUCCESS;
803}
804
805// Following datatypes and functions (tgt_oldmap_type, combined_entry_t,
806// translate_map, cleanup_map) will be removed once the compiler starts using
807// the new map types.
808
809// Old map types
810enum tgt_oldmap_type {
811 OMP_TGT_OLDMAPTYPE_TO = 0x001, // copy data from host to device
812 OMP_TGT_OLDMAPTYPE_FROM = 0x002, // copy data from device to host
813 OMP_TGT_OLDMAPTYPE_ALWAYS = 0x004, // copy regardless of the ref. count
814 OMP_TGT_OLDMAPTYPE_DELETE = 0x008, // force unmapping of data
815 OMP_TGT_OLDMAPTYPE_MAP_PTR = 0x010, // map pointer as well as pointee
816 OMP_TGT_OLDMAPTYPE_FIRST_MAP = 0x020, // first occurrence of mapped variable
817 OMP_TGT_OLDMAPTYPE_RETURN_PTR = 0x040, // return TgtBase addr of mapped data
818 OMP_TGT_OLDMAPTYPE_PRIVATE_PTR = 0x080, // private variable - not mapped
819 OMP_TGT_OLDMAPTYPE_PRIVATE_VAL = 0x100 // copy by value - not mapped
820};
821
822// Temporary functions for map translation and cleanup
823struct combined_entry_t {
824 int num_members; // number of members in combined entry
825 void *base_addr; // base address of combined entry
826 void *begin_addr; // begin address of combined entry
827 void *end_addr; // size of combined entry
828};
829
830static void translate_map(int32_t arg_num, void **args_base, void **args,
George Rokosb92dbb42017-11-21 18:26:41 +0000831 int64_t *arg_sizes, int64_t *arg_types, int32_t &new_arg_num,
George Rokos2467df62017-01-25 21:27:24 +0000832 void **&new_args_base, void **&new_args, int64_t *&new_arg_sizes,
833 int64_t *&new_arg_types, bool is_target_construct) {
834 if (arg_num <= 0) {
835 DP("Nothing to translate\n");
836 new_arg_num = 0;
837 return;
838 }
839
840 // array of combined entries
841 combined_entry_t *cmb_entries =
842 (combined_entry_t *) alloca(arg_num * sizeof(combined_entry_t));
843 // number of combined entries
844 long num_combined = 0;
845 // old entry is MAP_PTR?
846 bool *is_ptr_old = (bool *) alloca(arg_num * sizeof(bool));
847 // old entry is member of member_of[old] cmb_entry
848 int *member_of = (int *) alloca(arg_num * sizeof(int));
George Rokos15a6e7d2017-02-15 20:45:37 +0000849 // temporary storage for modifications of the original arg_types
George Rokosb92dbb42017-11-21 18:26:41 +0000850 int64_t *mod_arg_types = (int64_t *) alloca(arg_num *sizeof(int64_t));
George Rokos2467df62017-01-25 21:27:24 +0000851
852 DP("Translating %d map entries\n", arg_num);
853 for (int i = 0; i < arg_num; ++i) {
854 member_of[i] = -1;
855 is_ptr_old[i] = false;
George Rokos15a6e7d2017-02-15 20:45:37 +0000856 mod_arg_types[i] = arg_types[i];
George Rokos2467df62017-01-25 21:27:24 +0000857 // Scan previous entries to see whether this entry shares the same base
858 for (int j = 0; j < i; ++j) {
859 void *new_begin_addr = NULL;
860 void *new_end_addr = NULL;
861
George Rokos15a6e7d2017-02-15 20:45:37 +0000862 if (mod_arg_types[i] & OMP_TGT_OLDMAPTYPE_MAP_PTR) {
George Rokos2467df62017-01-25 21:27:24 +0000863 if (args_base[i] == args[j]) {
George Rokos15a6e7d2017-02-15 20:45:37 +0000864 if (!(mod_arg_types[j] & OMP_TGT_OLDMAPTYPE_MAP_PTR)) {
George Rokos2467df62017-01-25 21:27:24 +0000865 DP("Entry %d has the same base as entry %d's begin address\n", i,
866 j);
867 new_begin_addr = args_base[i];
868 new_end_addr = (char *)args_base[i] + sizeof(void *);
869 assert(arg_sizes[j] == sizeof(void *));
870 is_ptr_old[j] = true;
871 } else {
872 DP("Entry %d has the same base as entry %d's begin address, but "
873 "%d's base was a MAP_PTR too\n", i, j, j);
George Rokos15a6e7d2017-02-15 20:45:37 +0000874 int32_t to_from_always_delete =
875 OMP_TGT_OLDMAPTYPE_TO | OMP_TGT_OLDMAPTYPE_FROM |
876 OMP_TGT_OLDMAPTYPE_ALWAYS | OMP_TGT_OLDMAPTYPE_DELETE;
877 if (mod_arg_types[j] & to_from_always_delete) {
878 DP("Resetting to/from/always/delete flags for entry %d because "
879 "it is only a pointer to pointer\n", j);
880 mod_arg_types[j] &= ~to_from_always_delete;
881 }
George Rokos2467df62017-01-25 21:27:24 +0000882 }
883 }
884 } else {
George Rokos15a6e7d2017-02-15 20:45:37 +0000885 if (!(mod_arg_types[i] & OMP_TGT_OLDMAPTYPE_FIRST_MAP) &&
George Rokos2467df62017-01-25 21:27:24 +0000886 args_base[i] == args_base[j]) {
887 DP("Entry %d has the same base address as entry %d\n", i, j);
888 new_begin_addr = args[i];
889 new_end_addr = (char *)args[i] + arg_sizes[i];
890 }
891 }
892
893 // If we have combined the entry with a previous one
894 if (new_begin_addr) {
895 int id;
896 if(member_of[j] == -1) {
897 // We have a new entry
898 id = num_combined++;
899 DP("Creating new combined entry %d for old entry %d\n", id, j);
900 // Initialize new entry
901 cmb_entries[id].num_members = 1;
902 cmb_entries[id].base_addr = args_base[j];
George Rokos15a6e7d2017-02-15 20:45:37 +0000903 if (mod_arg_types[j] & OMP_TGT_OLDMAPTYPE_MAP_PTR) {
George Rokos2467df62017-01-25 21:27:24 +0000904 cmb_entries[id].begin_addr = args_base[j];
905 cmb_entries[id].end_addr = (char *)args_base[j] + arg_sizes[j];
906 } else {
907 cmb_entries[id].begin_addr = args[j];
908 cmb_entries[id].end_addr = (char *)args[j] + arg_sizes[j];
909 }
910 member_of[j] = id;
911 } else {
912 // Reuse existing combined entry
913 DP("Reusing existing combined entry %d\n", member_of[j]);
914 id = member_of[j];
915 }
916
917 // Update combined entry
918 DP("Adding entry %d to combined entry %d\n", i, id);
919 cmb_entries[id].num_members++;
920 // base_addr stays the same
921 cmb_entries[id].begin_addr =
922 std::min(cmb_entries[id].begin_addr, new_begin_addr);
923 cmb_entries[id].end_addr =
924 std::max(cmb_entries[id].end_addr, new_end_addr);
925 member_of[i] = id;
926 break;
927 }
928 }
929 }
930
931 DP("New entries: %ld combined + %d original\n", num_combined, arg_num);
932 new_arg_num = arg_num + num_combined;
933 new_args_base = (void **) malloc(new_arg_num * sizeof(void *));
934 new_args = (void **) malloc(new_arg_num * sizeof(void *));
935 new_arg_sizes = (int64_t *) malloc(new_arg_num * sizeof(int64_t));
936 new_arg_types = (int64_t *) malloc(new_arg_num * sizeof(int64_t));
937
938 const int64_t alignment = 8;
939
940 int next_id = 0; // next ID
941 int next_cid = 0; // next combined ID
942 int *combined_to_new_id = (int *) alloca(num_combined * sizeof(int));
943 for (int i = 0; i < arg_num; ++i) {
944 // It is member_of
945 if (member_of[i] == next_cid) {
946 int cid = next_cid++; // ID of this combined entry
947 int nid = next_id++; // ID of the new (global) entry
948 combined_to_new_id[cid] = nid;
949 DP("Combined entry %3d will become new entry %3d\n", cid, nid);
950
951 int64_t padding = (int64_t)cmb_entries[cid].begin_addr % alignment;
952 if (padding) {
953 DP("Using a padding of %" PRId64 " for begin address " DPxMOD "\n",
954 padding, DPxPTR(cmb_entries[cid].begin_addr));
955 cmb_entries[cid].begin_addr =
956 (char *)cmb_entries[cid].begin_addr - padding;
957 }
958
959 new_args_base[nid] = cmb_entries[cid].base_addr;
960 new_args[nid] = cmb_entries[cid].begin_addr;
961 new_arg_sizes[nid] = (int64_t) ((char *)cmb_entries[cid].end_addr -
962 (char *)cmb_entries[cid].begin_addr);
963 new_arg_types[nid] = OMP_TGT_MAPTYPE_TARGET_PARAM;
964 DP("Entry %3d: base_addr " DPxMOD ", begin_addr " DPxMOD ", "
965 "size %" PRId64 ", type 0x%" PRIx64 "\n", nid,
966 DPxPTR(new_args_base[nid]), DPxPTR(new_args[nid]), new_arg_sizes[nid],
967 new_arg_types[nid]);
968 } else if (member_of[i] != -1) {
969 DP("Combined entry %3d has been encountered before, do nothing\n",
970 member_of[i]);
971 }
972
973 // Now that the combined entry (the one the old entry was a member of) has
974 // been inserted into the new arguments list, proceed with the old entry.
975 int nid = next_id++;
976 DP("Old entry %3d will become new entry %3d\n", i, nid);
977
978 new_args_base[nid] = args_base[i];
979 new_args[nid] = args[i];
980 new_arg_sizes[nid] = arg_sizes[i];
George Rokos15a6e7d2017-02-15 20:45:37 +0000981 int64_t old_type = mod_arg_types[i];
George Rokos2467df62017-01-25 21:27:24 +0000982
983 if (is_ptr_old[i]) {
984 // Reset TO and FROM flags
985 old_type &= ~(OMP_TGT_OLDMAPTYPE_TO | OMP_TGT_OLDMAPTYPE_FROM);
986 }
987
988 if (member_of[i] == -1) {
989 if (!is_target_construct)
990 old_type &= ~OMP_TGT_MAPTYPE_TARGET_PARAM;
991 new_arg_types[nid] = old_type;
992 DP("Entry %3d: base_addr " DPxMOD ", begin_addr " DPxMOD ", size %" PRId64
993 ", type 0x%" PRIx64 " (old entry %d not MEMBER_OF)\n", nid,
994 DPxPTR(new_args_base[nid]), DPxPTR(new_args[nid]), new_arg_sizes[nid],
995 new_arg_types[nid], i);
996 } else {
997 // Old entry is not FIRST_MAP
998 old_type &= ~OMP_TGT_OLDMAPTYPE_FIRST_MAP;
999 // Add MEMBER_OF
1000 int new_member_of = combined_to_new_id[member_of[i]];
1001 old_type |= ((int64_t)new_member_of + 1) << 48;
1002 new_arg_types[nid] = old_type;
1003 DP("Entry %3d: base_addr " DPxMOD ", begin_addr " DPxMOD ", size %" PRId64
1004 ", type 0x%" PRIx64 " (old entry %d MEMBER_OF %d)\n", nid,
1005 DPxPTR(new_args_base[nid]), DPxPTR(new_args[nid]), new_arg_sizes[nid],
1006 new_arg_types[nid], i, new_member_of);
1007 }
1008 }
1009}
1010
1011static void cleanup_map(int32_t new_arg_num, void **new_args_base,
1012 void **new_args, int64_t *new_arg_sizes, int64_t *new_arg_types,
1013 int32_t arg_num, void **args_base) {
1014 if (new_arg_num > 0) {
1015 int offset = new_arg_num - arg_num;
1016 for (int32_t i = 0; i < arg_num; ++i) {
1017 // Restore old base address
1018 args_base[i] = new_args_base[i+offset];
1019 }
1020 free(new_args_base);
1021 free(new_args);
1022 free(new_arg_sizes);
1023 free(new_arg_types);
1024 }
1025}
1026
1027static short member_of(int64_t type) {
1028 return ((type & OMP_TGT_MAPTYPE_MEMBER_OF) >> 48) - 1;
1029}
1030
1031/// Internal function to do the mapping and transfer the data to the device
1032static int target_data_begin(DeviceTy &Device, int32_t arg_num,
1033 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types) {
1034 // process each input.
1035 int rc = OFFLOAD_SUCCESS;
1036 for (int32_t i = 0; i < arg_num; ++i) {
1037 // Ignore private variables and arrays - there is no mapping for them.
1038 if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
1039 (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
1040 continue;
1041
1042 void *HstPtrBegin = args[i];
1043 void *HstPtrBase = args_base[i];
1044 // Address of pointer on the host and device, respectively.
1045 void *Pointer_HstPtrBegin, *Pointer_TgtPtrBegin;
1046 bool IsNew, Pointer_IsNew;
1047 bool IsImplicit = arg_types[i] & OMP_TGT_MAPTYPE_IMPLICIT;
1048 bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF);
1049 if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
1050 DP("Has a pointer entry: \n");
1051 // base is address of pointer.
1052 Pointer_TgtPtrBegin = Device.getOrAllocTgtPtr(HstPtrBase, HstPtrBase,
1053 sizeof(void *), Pointer_IsNew, IsImplicit, UpdateRef);
1054 if (!Pointer_TgtPtrBegin) {
1055 DP("Call to getOrAllocTgtPtr returned null pointer (device failure or "
1056 "illegal mapping).\n");
1057 }
1058 DP("There are %zu bytes allocated at target address " DPxMOD " - is%s new"
1059 "\n", sizeof(void *), DPxPTR(Pointer_TgtPtrBegin),
1060 (Pointer_IsNew ? "" : " not"));
1061 Pointer_HstPtrBegin = HstPtrBase;
1062 // modify current entry.
1063 HstPtrBase = *(void **)HstPtrBase;
1064 UpdateRef = true; // subsequently update ref count of pointee
1065 }
1066
1067 void *TgtPtrBegin = Device.getOrAllocTgtPtr(HstPtrBegin, HstPtrBase,
1068 arg_sizes[i], IsNew, IsImplicit, UpdateRef);
1069 if (!TgtPtrBegin && arg_sizes[i]) {
1070 // If arg_sizes[i]==0, then the argument is a pointer to NULL, so
1071 // getOrAlloc() returning NULL is not an error.
1072 DP("Call to getOrAllocTgtPtr returned null pointer (device failure or "
1073 "illegal mapping).\n");
1074 }
1075 DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
1076 " - is%s new\n", arg_sizes[i], DPxPTR(TgtPtrBegin),
1077 (IsNew ? "" : " not"));
1078
1079 if (arg_types[i] & OMP_TGT_MAPTYPE_RETURN_PARAM) {
1080 void *ret_ptr;
1081 if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)
1082 ret_ptr = Pointer_TgtPtrBegin;
1083 else {
1084 bool IsLast; // not used
1085 ret_ptr = Device.getTgtPtrBegin(HstPtrBegin, 0, IsLast, false);
1086 }
1087
1088 DP("Returning device pointer " DPxMOD "\n", DPxPTR(ret_ptr));
1089 args_base[i] = ret_ptr;
1090 }
1091
1092 if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
1093 bool copy = false;
1094 if (IsNew || (arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS)) {
1095 copy = true;
1096 } else if (arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) {
1097 // Copy data only if the "parent" struct has RefCount==1.
1098 short parent_idx = member_of(arg_types[i]);
1099 long parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
1100 assert(parent_rc > 0 && "parent struct not found");
1101 if (parent_rc == 1) {
1102 copy = true;
1103 }
1104 }
1105
1106 if (copy) {
1107 DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
1108 arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
1109 int rt = Device.data_submit(TgtPtrBegin, HstPtrBegin, arg_sizes[i]);
1110 if (rt != OFFLOAD_SUCCESS) {
1111 DP("Copying data to device failed.\n");
1112 rc = OFFLOAD_FAIL;
1113 }
1114 }
1115 }
1116
1117 if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
1118 DP("Update pointer (" DPxMOD ") -> [" DPxMOD "]\n",
1119 DPxPTR(Pointer_TgtPtrBegin), DPxPTR(TgtPtrBegin));
1120 uint64_t Delta = (uint64_t)HstPtrBegin - (uint64_t)HstPtrBase;
1121 void *TgtPtrBase = (void *)((uint64_t)TgtPtrBegin - Delta);
1122 int rt = Device.data_submit(Pointer_TgtPtrBegin, &TgtPtrBase,
1123 sizeof(void *));
1124 if (rt != OFFLOAD_SUCCESS) {
1125 DP("Copying data to device failed.\n");
1126 rc = OFFLOAD_FAIL;
1127 }
1128 // create shadow pointers for this entry
1129 Device.ShadowMtx.lock();
1130 Device.ShadowPtrMap[Pointer_HstPtrBegin] = {HstPtrBase,
1131 Pointer_TgtPtrBegin, TgtPtrBase};
1132 Device.ShadowMtx.unlock();
1133 }
1134 }
1135
1136 return rc;
1137}
1138
George Rokosb92dbb42017-11-21 18:26:41 +00001139EXTERN void __tgt_target_data_begin_nowait(int64_t device_id, int32_t arg_num,
1140 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
George Rokos2467df62017-01-25 21:27:24 +00001141 int32_t depNum, void *depList, int32_t noAliasDepNum,
1142 void *noAliasDepList) {
1143 if (depNum + noAliasDepNum > 0)
1144 __kmpc_omp_taskwait(NULL, 0);
1145
1146 __tgt_target_data_begin(device_id, arg_num, args_base, args, arg_sizes,
1147 arg_types);
1148}
1149
1150/// creates host-to-target data mapping, stores it in the
1151/// libomptarget.so internal structure (an entry in a stack of data maps)
1152/// and passes the data to the device.
George Rokosb92dbb42017-11-21 18:26:41 +00001153EXTERN void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
1154 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types) {
1155 DP("Entering data begin region for device %ld with %d mappings\n", device_id,
George Rokos2467df62017-01-25 21:27:24 +00001156 arg_num);
1157
1158 // No devices available?
1159 if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1160 device_id = omp_get_default_device();
George Rokosb92dbb42017-11-21 18:26:41 +00001161 DP("Use default device id %ld\n", device_id);
George Rokos2467df62017-01-25 21:27:24 +00001162 }
1163
1164 if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
George Rokosb92dbb42017-11-21 18:26:41 +00001165 DP("Failed to get device %ld ready\n", device_id);
George Rokos2467df62017-01-25 21:27:24 +00001166 return;
1167 }
1168
1169 DeviceTy& Device = Devices[device_id];
1170
1171 // Translate maps
1172 int32_t new_arg_num;
1173 void **new_args_base;
1174 void **new_args;
1175 int64_t *new_arg_sizes;
1176 int64_t *new_arg_types;
1177 translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
1178 new_args_base, new_args, new_arg_sizes, new_arg_types, false);
1179
1180 //target_data_begin(Device, arg_num, args_base, args, arg_sizes, arg_types);
1181 target_data_begin(Device, new_arg_num, new_args_base, new_args, new_arg_sizes,
1182 new_arg_types);
1183
1184 // Cleanup translation memory
1185 cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
1186 new_arg_types, arg_num, args_base);
1187}
1188
1189/// Internal function to undo the mapping and retrieve the data from the device.
1190static int target_data_end(DeviceTy &Device, int32_t arg_num, void **args_base,
1191 void **args, int64_t *arg_sizes, int64_t *arg_types) {
1192 int rc = OFFLOAD_SUCCESS;
1193 // process each input.
1194 for (int32_t i = arg_num - 1; i >= 0; --i) {
1195 // Ignore private variables and arrays - there is no mapping for them.
1196 // Also, ignore the use_device_ptr directive, it has no effect here.
1197 if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
1198 (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
1199 continue;
1200
1201 void *HstPtrBegin = args[i];
1202 bool IsLast;
1203 bool UpdateRef = !(arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) ||
1204 (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ);
1205 bool ForceDelete = arg_types[i] & OMP_TGT_MAPTYPE_DELETE;
1206
1207 // If PTR_AND_OBJ, HstPtrBegin is address of pointee
1208 void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, arg_sizes[i], IsLast,
1209 UpdateRef);
1210 DP("There are %" PRId64 " bytes allocated at target address " DPxMOD
1211 " - is%s last\n", arg_sizes[i], DPxPTR(TgtPtrBegin),
1212 (IsLast ? "" : " not"));
1213
George Rokos15a6e7d2017-02-15 20:45:37 +00001214 bool DelEntry = IsLast || ForceDelete;
1215
George Rokos2467df62017-01-25 21:27:24 +00001216 if ((arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1217 !(arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
George Rokos15a6e7d2017-02-15 20:45:37 +00001218 DelEntry = false; // protect parent struct from being deallocated
George Rokos2467df62017-01-25 21:27:24 +00001219 }
1220
George Rokos2467df62017-01-25 21:27:24 +00001221 if ((arg_types[i] & OMP_TGT_MAPTYPE_FROM) || DelEntry) {
1222 // Move data back to the host
1223 if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
1224 bool Always = arg_types[i] & OMP_TGT_MAPTYPE_ALWAYS;
1225 bool CopyMember = false;
1226 if ((arg_types[i] & OMP_TGT_MAPTYPE_MEMBER_OF) &&
1227 !(arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ)) {
1228 // Copy data only if the "parent" struct has RefCount==1.
1229 short parent_idx = member_of(arg_types[i]);
1230 long parent_rc = Device.getMapEntryRefCnt(args[parent_idx]);
1231 assert(parent_rc > 0 && "parent struct not found");
1232 if (parent_rc == 1) {
1233 CopyMember = true;
1234 }
1235 }
1236
1237 if (DelEntry || Always || CopyMember) {
1238 DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
1239 arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
1240 int rt = Device.data_retrieve(HstPtrBegin, TgtPtrBegin, arg_sizes[i]);
1241 if (rt != OFFLOAD_SUCCESS) {
1242 DP("Copying data from device failed.\n");
1243 rc = OFFLOAD_FAIL;
1244 }
1245 }
1246 }
1247
1248 // If we copied back to the host a struct/array containing pointers, we
1249 // need to restore the original host pointer values from their shadow
1250 // copies. If the struct is going to be deallocated, remove any remaining
1251 // shadow pointer entries for this struct.
1252 uintptr_t lb = (uintptr_t) HstPtrBegin;
1253 uintptr_t ub = (uintptr_t) HstPtrBegin + arg_sizes[i];
1254 Device.ShadowMtx.lock();
1255 for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
1256 it != Device.ShadowPtrMap.end(); ++it) {
1257 void **ShadowHstPtrAddr = (void**) it->first;
1258
1259 // An STL map is sorted on its keys; use this property
1260 // to quickly determine when to break out of the loop.
1261 if ((uintptr_t) ShadowHstPtrAddr < lb)
1262 continue;
1263 if ((uintptr_t) ShadowHstPtrAddr >= ub)
1264 break;
1265
1266 // If we copied the struct to the host, we need to restore the pointer.
1267 if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
1268 DP("Restoring original host pointer value " DPxMOD " for host "
1269 "pointer " DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
1270 DPxPTR(ShadowHstPtrAddr));
1271 *ShadowHstPtrAddr = it->second.HstPtrVal;
1272 }
1273 // If the struct is to be deallocated, remove the shadow entry.
1274 if (DelEntry) {
1275 DP("Removing shadow pointer " DPxMOD "\n", DPxPTR(ShadowHstPtrAddr));
1276 Device.ShadowPtrMap.erase(it);
1277 }
1278 }
1279 Device.ShadowMtx.unlock();
1280
1281 // Deallocate map
1282 if (DelEntry) {
1283 int rt = Device.deallocTgtPtr(HstPtrBegin, arg_sizes[i], ForceDelete);
1284 if (rt != OFFLOAD_SUCCESS) {
1285 DP("Deallocating data from device failed.\n");
1286 rc = OFFLOAD_FAIL;
1287 }
1288 }
1289 }
1290 }
1291
1292 return rc;
1293}
1294
1295/// passes data from the target, releases target memory and destroys
1296/// the host-target mapping (top entry from the stack of data maps)
1297/// created by the last __tgt_target_data_begin.
George Rokosb92dbb42017-11-21 18:26:41 +00001298EXTERN void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
1299 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types) {
George Rokos2467df62017-01-25 21:27:24 +00001300 DP("Entering data end region with %d mappings\n", arg_num);
1301
1302 // No devices available?
1303 if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1304 device_id = omp_get_default_device();
1305 }
1306
1307 RTLsMtx.lock();
1308 size_t Devices_size = Devices.size();
1309 RTLsMtx.unlock();
1310 if (Devices_size <= (size_t)device_id) {
George Rokosb92dbb42017-11-21 18:26:41 +00001311 DP("Device ID %ld does not have a matching RTL.\n", device_id);
George Rokos2467df62017-01-25 21:27:24 +00001312 return;
1313 }
1314
1315 DeviceTy &Device = Devices[device_id];
1316 if (!Device.IsInit) {
1317 DP("uninit device: ignore");
1318 return;
1319 }
1320
1321 // Translate maps
1322 int32_t new_arg_num;
1323 void **new_args_base;
1324 void **new_args;
1325 int64_t *new_arg_sizes;
1326 int64_t *new_arg_types;
1327 translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
1328 new_args_base, new_args, new_arg_sizes, new_arg_types, false);
1329
1330 //target_data_end(Device, arg_num, args_base, args, arg_sizes, arg_types);
1331 target_data_end(Device, new_arg_num, new_args_base, new_args, new_arg_sizes,
1332 new_arg_types);
1333
1334 // Cleanup translation memory
1335 cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
1336 new_arg_types, arg_num, args_base);
1337}
1338
George Rokosb92dbb42017-11-21 18:26:41 +00001339EXTERN void __tgt_target_data_end_nowait(int64_t device_id, int32_t arg_num,
1340 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
George Rokos2467df62017-01-25 21:27:24 +00001341 int32_t depNum, void *depList, int32_t noAliasDepNum,
1342 void *noAliasDepList) {
1343 if (depNum + noAliasDepNum > 0)
1344 __kmpc_omp_taskwait(NULL, 0);
1345
1346 __tgt_target_data_end(device_id, arg_num, args_base, args, arg_sizes,
1347 arg_types);
1348}
1349
1350/// passes data to/from the target.
George Rokosb92dbb42017-11-21 18:26:41 +00001351EXTERN void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
1352 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types) {
George Rokos2467df62017-01-25 21:27:24 +00001353 DP("Entering data update with %d mappings\n", arg_num);
1354
1355 // No devices available?
1356 if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1357 device_id = omp_get_default_device();
1358 }
1359
1360 if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
George Rokosb92dbb42017-11-21 18:26:41 +00001361 DP("Failed to get device %ld ready\n", device_id);
George Rokos2467df62017-01-25 21:27:24 +00001362 return;
1363 }
1364
1365 DeviceTy& Device = Devices[device_id];
1366
1367 // process each input.
1368 for (int32_t i = 0; i < arg_num; ++i) {
1369 if ((arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) ||
1370 (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE))
1371 continue;
1372
1373 void *HstPtrBegin = args[i];
1374 int64_t MapSize = arg_sizes[i];
1375 bool IsLast;
1376 void *TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, MapSize, IsLast,
1377 false);
1378
1379 if (arg_types[i] & OMP_TGT_MAPTYPE_FROM) {
1380 DP("Moving %" PRId64 " bytes (tgt:" DPxMOD ") -> (hst:" DPxMOD ")\n",
1381 arg_sizes[i], DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBegin));
1382 Device.data_retrieve(HstPtrBegin, TgtPtrBegin, MapSize);
1383
1384 uintptr_t lb = (uintptr_t) HstPtrBegin;
1385 uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
1386 Device.ShadowMtx.lock();
1387 for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
1388 it != Device.ShadowPtrMap.end(); ++it) {
1389 void **ShadowHstPtrAddr = (void**) it->first;
1390 if ((uintptr_t) ShadowHstPtrAddr < lb)
1391 continue;
1392 if ((uintptr_t) ShadowHstPtrAddr >= ub)
1393 break;
1394 DP("Restoring original host pointer value " DPxMOD " for host pointer "
1395 DPxMOD "\n", DPxPTR(it->second.HstPtrVal),
1396 DPxPTR(ShadowHstPtrAddr));
1397 *ShadowHstPtrAddr = it->second.HstPtrVal;
1398 }
1399 Device.ShadowMtx.unlock();
1400 }
1401
1402 if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
1403 DP("Moving %" PRId64 " bytes (hst:" DPxMOD ") -> (tgt:" DPxMOD ")\n",
1404 arg_sizes[i], DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBegin));
1405 Device.data_submit(TgtPtrBegin, HstPtrBegin, MapSize);
1406
1407 uintptr_t lb = (uintptr_t) HstPtrBegin;
1408 uintptr_t ub = (uintptr_t) HstPtrBegin + MapSize;
1409 Device.ShadowMtx.lock();
1410 for (ShadowPtrListTy::iterator it = Device.ShadowPtrMap.begin();
1411 it != Device.ShadowPtrMap.end(); ++it) {
1412 void **ShadowHstPtrAddr = (void**) it->first;
1413 if ((uintptr_t) ShadowHstPtrAddr < lb)
1414 continue;
1415 if ((uintptr_t) ShadowHstPtrAddr >= ub)
1416 break;
1417 DP("Restoring original target pointer value " DPxMOD " for target "
1418 "pointer " DPxMOD "\n", DPxPTR(it->second.TgtPtrVal),
1419 DPxPTR(it->second.TgtPtrAddr));
1420 Device.data_submit(it->second.TgtPtrAddr,
1421 &it->second.TgtPtrVal, sizeof(void *));
1422 }
1423 Device.ShadowMtx.unlock();
1424 }
1425 }
1426}
1427
1428EXTERN void __tgt_target_data_update_nowait(
George Rokosb92dbb42017-11-21 18:26:41 +00001429 int64_t device_id, int32_t arg_num, void **args_base, void **args,
1430 int64_t *arg_sizes, int64_t *arg_types, int32_t depNum, void *depList,
George Rokos2467df62017-01-25 21:27:24 +00001431 int32_t noAliasDepNum, void *noAliasDepList) {
1432 if (depNum + noAliasDepNum > 0)
1433 __kmpc_omp_taskwait(NULL, 0);
1434
1435 __tgt_target_data_update(device_id, arg_num, args_base, args, arg_sizes,
1436 arg_types);
1437}
1438
1439/// performs the same actions as data_begin in case arg_num is
1440/// non-zero and initiates run of the offloaded region on the target platform;
1441/// if arg_num is non-zero after the region execution is done it also
1442/// performs the same action as data_update and data_end above. This function
1443/// returns 0 if it was able to transfer the execution to a target and an
1444/// integer different from zero otherwise.
Jonas Hahnfeld43322802017-12-06 21:59:07 +00001445int target(int64_t device_id, void *host_ptr, int32_t arg_num,
George Rokos2467df62017-01-25 21:27:24 +00001446 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types,
1447 int32_t team_num, int32_t thread_limit, int IsTeamConstruct) {
1448 DeviceTy &Device = Devices[device_id];
1449
1450 // Find the table information in the map or look it up in the translation
1451 // tables.
1452 TableMap *TM = 0;
1453 TblMapMtx.lock();
1454 HostPtrToTableMapTy::iterator TableMapIt = HostPtrToTableMap.find(host_ptr);
1455 if (TableMapIt == HostPtrToTableMap.end()) {
1456 // We don't have a map. So search all the registered libraries.
1457 TrlTblMtx.lock();
1458 for (HostEntriesBeginToTransTableTy::iterator
1459 ii = HostEntriesBeginToTransTable.begin(),
1460 ie = HostEntriesBeginToTransTable.end();
1461 !TM && ii != ie; ++ii) {
1462 // get the translation table (which contains all the good info).
1463 TranslationTable *TransTable = &ii->second;
1464 // iterate over all the host table entries to see if we can locate the
1465 // host_ptr.
1466 __tgt_offload_entry *begin = TransTable->HostTable.EntriesBegin;
1467 __tgt_offload_entry *end = TransTable->HostTable.EntriesEnd;
1468 __tgt_offload_entry *cur = begin;
1469 for (uint32_t i = 0; cur < end; ++cur, ++i) {
1470 if (cur->addr != host_ptr)
1471 continue;
1472 // we got a match, now fill the HostPtrToTableMap so that we
1473 // may avoid this search next time.
1474 TM = &HostPtrToTableMap[host_ptr];
1475 TM->Table = TransTable;
1476 TM->Index = i;
1477 break;
1478 }
1479 }
1480 TrlTblMtx.unlock();
1481 } else {
1482 TM = &TableMapIt->second;
1483 }
1484 TblMapMtx.unlock();
1485
1486 // No map for this host pointer found!
1487 if (!TM) {
1488 DP("Host ptr " DPxMOD " does not have a matching target pointer.\n",
1489 DPxPTR(host_ptr));
1490 return OFFLOAD_FAIL;
1491 }
1492
1493 // get target table.
1494 TrlTblMtx.lock();
1495 assert(TM->Table->TargetsTable.size() > (size_t)device_id &&
1496 "Not expecting a device ID outside the table's bounds!");
1497 __tgt_target_table *TargetTable = TM->Table->TargetsTable[device_id];
1498 TrlTblMtx.unlock();
1499 assert(TargetTable && "Global data has not been mapped\n");
1500
1501 // Move data to device.
1502 int rc = target_data_begin(Device, arg_num, args_base, args, arg_sizes,
1503 arg_types);
1504
1505 if (rc != OFFLOAD_SUCCESS) {
1506 DP("Call to target_data_begin failed, skipping target execution.\n");
1507 // Call target_data_end to dealloc whatever target_data_begin allocated
1508 // and return OFFLOAD_FAIL.
1509 target_data_end(Device, arg_num, args_base, args, arg_sizes, arg_types);
1510 return OFFLOAD_FAIL;
1511 }
1512
1513 std::vector<void *> tgt_args;
George Rokos1546d312017-05-10 14:12:36 +00001514 std::vector<ptrdiff_t> tgt_offsets;
George Rokos2467df62017-01-25 21:27:24 +00001515
1516 // List of (first-)private arrays allocated for this target region
1517 std::vector<void *> fpArrays;
1518
1519 for (int32_t i = 0; i < arg_num; ++i) {
1520 if (!(arg_types[i] & OMP_TGT_MAPTYPE_TARGET_PARAM)) {
1521 // This is not a target parameter, do not push it into tgt_args.
1522 continue;
1523 }
1524 void *HstPtrBegin = args[i];
1525 void *HstPtrBase = args_base[i];
George Rokos1546d312017-05-10 14:12:36 +00001526 void *TgtPtrBegin;
1527 ptrdiff_t TgtBaseOffset;
George Rokos2467df62017-01-25 21:27:24 +00001528 bool IsLast; // unused.
1529 if (arg_types[i] & OMP_TGT_MAPTYPE_LITERAL) {
1530 DP("Forwarding first-private value " DPxMOD " to the target construct\n",
1531 DPxPTR(HstPtrBase));
George Rokos1546d312017-05-10 14:12:36 +00001532 TgtPtrBegin = HstPtrBase;
1533 TgtBaseOffset = 0;
George Rokos2467df62017-01-25 21:27:24 +00001534 } else if (arg_types[i] & OMP_TGT_MAPTYPE_PRIVATE) {
1535 // Allocate memory for (first-)private array
George Rokos1546d312017-05-10 14:12:36 +00001536 TgtPtrBegin = Device.RTL->data_alloc(Device.RTLDeviceID,
1537 arg_sizes[i], HstPtrBegin);
George Rokos2467df62017-01-25 21:27:24 +00001538 if (!TgtPtrBegin) {
1539 DP ("Data allocation for %sprivate array " DPxMOD " failed\n",
1540 (arg_types[i] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
1541 DPxPTR(HstPtrBegin));
1542 rc = OFFLOAD_FAIL;
1543 break;
1544 } else {
1545 fpArrays.push_back(TgtPtrBegin);
George Rokos1546d312017-05-10 14:12:36 +00001546 TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
Samuel Antao8933ffb2017-06-09 16:46:07 +00001547#ifdef OMPTARGET_DEBUG
George Rokos1546d312017-05-10 14:12:36 +00001548 void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
George Rokos2467df62017-01-25 21:27:24 +00001549 DP("Allocated %" PRId64 " bytes of target memory at " DPxMOD " for "
1550 "%sprivate array " DPxMOD " - pushing target argument " DPxMOD "\n",
1551 arg_sizes[i], DPxPTR(TgtPtrBegin),
1552 (arg_types[i] & OMP_TGT_MAPTYPE_TO ? "first-" : ""),
1553 DPxPTR(HstPtrBegin), DPxPTR(TgtPtrBase));
Samuel Antao8933ffb2017-06-09 16:46:07 +00001554#endif
George Rokos2467df62017-01-25 21:27:24 +00001555 // If first-private, copy data from host
1556 if (arg_types[i] & OMP_TGT_MAPTYPE_TO) {
1557 int rt = Device.data_submit(TgtPtrBegin, HstPtrBegin, arg_sizes[i]);
1558 if (rt != OFFLOAD_SUCCESS) {
1559 DP ("Copying data to device failed.\n");
1560 rc = OFFLOAD_FAIL;
1561 break;
1562 }
1563 }
1564 }
1565 } else if (arg_types[i] & OMP_TGT_MAPTYPE_PTR_AND_OBJ) {
George Rokos1546d312017-05-10 14:12:36 +00001566 TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBase, sizeof(void *), IsLast,
1567 false);
1568 TgtBaseOffset = 0; // no offset for ptrs.
George Rokos2467df62017-01-25 21:27:24 +00001569 DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD " to "
1570 "object " DPxMOD "\n", DPxPTR(TgtPtrBegin), DPxPTR(HstPtrBase),
1571 DPxPTR(HstPtrBase));
1572 } else {
George Rokos1546d312017-05-10 14:12:36 +00001573 TgtPtrBegin = Device.getTgtPtrBegin(HstPtrBegin, arg_sizes[i], IsLast,
1574 false);
1575 TgtBaseOffset = (intptr_t)HstPtrBase - (intptr_t)HstPtrBegin;
Samuel Antao8933ffb2017-06-09 16:46:07 +00001576#ifdef OMPTARGET_DEBUG
George Rokos1546d312017-05-10 14:12:36 +00001577 void *TgtPtrBase = (void *)((intptr_t)TgtPtrBegin + TgtBaseOffset);
George Rokos2467df62017-01-25 21:27:24 +00001578 DP("Obtained target argument " DPxMOD " from host pointer " DPxMOD "\n",
1579 DPxPTR(TgtPtrBase), DPxPTR(HstPtrBegin));
Samuel Antao8933ffb2017-06-09 16:46:07 +00001580#endif
George Rokos2467df62017-01-25 21:27:24 +00001581 }
George Rokos1546d312017-05-10 14:12:36 +00001582 tgt_args.push_back(TgtPtrBegin);
1583 tgt_offsets.push_back(TgtBaseOffset);
George Rokos2467df62017-01-25 21:27:24 +00001584 }
George Rokos1546d312017-05-10 14:12:36 +00001585
1586 assert(tgt_args.size() == tgt_offsets.size() &&
1587 "Size mismatch in arguments and offsets");
George Rokos2467df62017-01-25 21:27:24 +00001588
1589 // Pop loop trip count
1590 uint64_t ltc = Device.loopTripCnt;
1591 Device.loopTripCnt = 0;
1592
1593 // Launch device execution.
1594 if (rc == OFFLOAD_SUCCESS) {
1595 DP("Launching target execution %s with pointer " DPxMOD " (index=%d).\n",
1596 TargetTable->EntriesBegin[TM->Index].name,
1597 DPxPTR(TargetTable->EntriesBegin[TM->Index].addr), TM->Index);
1598 if (IsTeamConstruct) {
1599 rc = Device.run_team_region(TargetTable->EntriesBegin[TM->Index].addr,
George Rokos1546d312017-05-10 14:12:36 +00001600 &tgt_args[0], &tgt_offsets[0], tgt_args.size(), team_num,
1601 thread_limit, ltc);
George Rokos2467df62017-01-25 21:27:24 +00001602 } else {
1603 rc = Device.run_region(TargetTable->EntriesBegin[TM->Index].addr,
George Rokos1546d312017-05-10 14:12:36 +00001604 &tgt_args[0], &tgt_offsets[0], tgt_args.size());
George Rokos2467df62017-01-25 21:27:24 +00001605 }
1606 } else {
1607 DP("Errors occurred while obtaining target arguments, skipping kernel "
1608 "execution\n");
1609 }
1610
1611 // Deallocate (first-)private arrays
1612 for (auto it : fpArrays) {
1613 int rt = Device.RTL->data_delete(Device.RTLDeviceID, it);
1614 if (rt != OFFLOAD_SUCCESS) {
1615 DP("Deallocation of (first-)private arrays failed.\n");
1616 rc = OFFLOAD_FAIL;
1617 }
1618 }
1619
1620 // Move data from device.
1621 int rt = target_data_end(Device, arg_num, args_base, args, arg_sizes,
1622 arg_types);
1623
1624 if (rt != OFFLOAD_SUCCESS) {
1625 DP("Call to target_data_end failed.\n");
1626 rc = OFFLOAD_FAIL;
1627 }
1628
1629 return rc;
1630}
1631
George Rokosb92dbb42017-11-21 18:26:41 +00001632EXTERN int __tgt_target(int64_t device_id, void *host_ptr, int32_t arg_num,
1633 void **args_base, void **args, int64_t *arg_sizes, int64_t *arg_types) {
1634 DP("Entering target region with entry point " DPxMOD " and device Id %ld\n",
George Rokos2467df62017-01-25 21:27:24 +00001635 DPxPTR(host_ptr), device_id);
1636
1637 if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1638 device_id = omp_get_default_device();
1639 }
1640
1641 if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
George Rokosb92dbb42017-11-21 18:26:41 +00001642 DP("Failed to get device %ld ready\n", device_id);
George Rokos2467df62017-01-25 21:27:24 +00001643 return OFFLOAD_FAIL;
1644 }
1645
1646 // Translate maps
1647 int32_t new_arg_num;
1648 void **new_args_base;
1649 void **new_args;
1650 int64_t *new_arg_sizes;
1651 int64_t *new_arg_types;
1652 translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
1653 new_args_base, new_args, new_arg_sizes, new_arg_types, true);
1654
1655 //return target(device_id, host_ptr, arg_num, args_base, args, arg_sizes,
1656 // arg_types, 0, 0, false /*team*/, false /*recursive*/);
1657 int rc = target(device_id, host_ptr, new_arg_num, new_args_base, new_args,
1658 new_arg_sizes, new_arg_types, 0, 0, false /*team*/);
1659
1660 // Cleanup translation memory
1661 cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
1662 new_arg_types, arg_num, args_base);
1663
1664 return rc;
1665}
1666
George Rokosb92dbb42017-11-21 18:26:41 +00001667EXTERN int __tgt_target_nowait(int64_t device_id, void *host_ptr,
George Rokos2467df62017-01-25 21:27:24 +00001668 int32_t arg_num, void **args_base, void **args, int64_t *arg_sizes,
George Rokosb92dbb42017-11-21 18:26:41 +00001669 int64_t *arg_types, int32_t depNum, void *depList, int32_t noAliasDepNum,
George Rokos2467df62017-01-25 21:27:24 +00001670 void *noAliasDepList) {
1671 if (depNum + noAliasDepNum > 0)
1672 __kmpc_omp_taskwait(NULL, 0);
1673
1674 return __tgt_target(device_id, host_ptr, arg_num, args_base, args, arg_sizes,
1675 arg_types);
1676}
1677
George Rokosb92dbb42017-11-21 18:26:41 +00001678EXTERN int __tgt_target_teams(int64_t device_id, void *host_ptr,
George Rokos2467df62017-01-25 21:27:24 +00001679 int32_t arg_num, void **args_base, void **args, int64_t *arg_sizes,
George Rokosb92dbb42017-11-21 18:26:41 +00001680 int64_t *arg_types, int32_t team_num, int32_t thread_limit) {
1681 DP("Entering target region with entry point " DPxMOD " and device Id %ld\n",
George Rokos2467df62017-01-25 21:27:24 +00001682 DPxPTR(host_ptr), device_id);
1683
1684 if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1685 device_id = omp_get_default_device();
1686 }
1687
1688 if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
George Rokosb92dbb42017-11-21 18:26:41 +00001689 DP("Failed to get device %ld ready\n", device_id);
George Rokos2467df62017-01-25 21:27:24 +00001690 return OFFLOAD_FAIL;
1691 }
1692
1693 // Translate maps
1694 int32_t new_arg_num;
1695 void **new_args_base;
1696 void **new_args;
1697 int64_t *new_arg_sizes;
1698 int64_t *new_arg_types;
1699 translate_map(arg_num, args_base, args, arg_sizes, arg_types, new_arg_num,
1700 new_args_base, new_args, new_arg_sizes, new_arg_types, true);
1701
1702 //return target(device_id, host_ptr, arg_num, args_base, args, arg_sizes,
1703 // arg_types, team_num, thread_limit, true /*team*/,
1704 // false /*recursive*/);
1705 int rc = target(device_id, host_ptr, new_arg_num, new_args_base, new_args,
1706 new_arg_sizes, new_arg_types, team_num, thread_limit, true /*team*/);
1707
1708 // Cleanup translation memory
1709 cleanup_map(new_arg_num, new_args_base, new_args, new_arg_sizes,
1710 new_arg_types, arg_num, args_base);
1711
1712 return rc;
1713}
1714
George Rokosb92dbb42017-11-21 18:26:41 +00001715EXTERN int __tgt_target_teams_nowait(int64_t device_id, void *host_ptr,
George Rokos2467df62017-01-25 21:27:24 +00001716 int32_t arg_num, void **args_base, void **args, int64_t *arg_sizes,
George Rokosb92dbb42017-11-21 18:26:41 +00001717 int64_t *arg_types, int32_t team_num, int32_t thread_limit, int32_t depNum,
George Rokos2467df62017-01-25 21:27:24 +00001718 void *depList, int32_t noAliasDepNum, void *noAliasDepList) {
1719 if (depNum + noAliasDepNum > 0)
1720 __kmpc_omp_taskwait(NULL, 0);
1721
1722 return __tgt_target_teams(device_id, host_ptr, arg_num, args_base, args,
1723 arg_sizes, arg_types, team_num, thread_limit);
1724}
1725
1726
1727// The trip count mechanism will be revised - this scheme is not thread-safe.
George Rokosb92dbb42017-11-21 18:26:41 +00001728EXTERN void __kmpc_push_target_tripcount(int64_t device_id,
George Rokos2467df62017-01-25 21:27:24 +00001729 uint64_t loop_tripcount) {
1730 if (device_id == OFFLOAD_DEVICE_DEFAULT) {
1731 device_id = omp_get_default_device();
1732 }
1733
1734 if (CheckDevice(device_id) != OFFLOAD_SUCCESS) {
George Rokosb92dbb42017-11-21 18:26:41 +00001735 DP("Failed to get device %ld ready\n", device_id);
George Rokos2467df62017-01-25 21:27:24 +00001736 return;
1737 }
1738
George Rokosb92dbb42017-11-21 18:26:41 +00001739 DP("__kmpc_push_target_tripcount(%ld, %" PRIu64 ")\n", device_id,
George Rokos2467df62017-01-25 21:27:24 +00001740 loop_tripcount);
1741 Devices[device_id].loopTripCnt = loop_tripcount;
1742}
1743