1 //===--- amdgpu/src/rtl.cpp --------------------------------------- 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 // RTL for AMD hsa machine
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <algorithm>
14 #include <assert.h>
15 #include <cstdio>
16 #include <cstdlib>
17 #include <cstring>
18 #include <functional>
19 #include <libelf.h>
20 #include <list>
21 #include <memory>
22 #include <mutex>
23 #include <shared_mutex>
24 #include <unordered_map>
25 #include <vector>
26 
27 #include "interop_hsa.h"
28 #include "impl_runtime.h"
29 
30 #include "internal.h"
31 #include "rt.h"
32 
33 #include "DeviceEnvironment.h"
34 #include "get_elf_mach_gfx_name.h"
35 #include "omptargetplugin.h"
36 #include "print_tracing.h"
37 
38 #include "llvm/Frontend/OpenMP/OMPConstants.h"
39 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
40 
41 // hostrpc interface, FIXME: consider moving to its own include these are
42 // statically linked into amdgpu/plugin if present from hostrpc_services.a,
43 // linked as --whole-archive to override the weak symbols that are used to
44 // implement a fallback for toolchains that do not yet have a hostrpc library.
45 extern "C" {
46 uint64_t hostrpc_assign_buffer(hsa_agent_t agent, hsa_queue_t *this_Q,
47                                uint32_t device_id);
48 hsa_status_t hostrpc_init();
49 hsa_status_t hostrpc_terminate();
50 
51 __attribute__((weak)) hsa_status_t hostrpc_init() { return HSA_STATUS_SUCCESS; }
52 __attribute__((weak)) hsa_status_t hostrpc_terminate() {
53   return HSA_STATUS_SUCCESS;
54 }
55 __attribute__((weak)) uint64_t hostrpc_assign_buffer(hsa_agent_t, hsa_queue_t *,
56                                                      uint32_t device_id) {
57   DP("Warning: Attempting to assign hostrpc to device %u, but hostrpc library "
58      "missing\n",
59      device_id);
60   return 0;
61 }
62 }
63 
64 // Heuristic parameters used for kernel launch
65 // Number of teams per CU to allow scheduling flexibility
66 static const unsigned DefaultTeamsPerCU = 4;
67 
68 int print_kernel_trace;
69 
70 #ifdef OMPTARGET_DEBUG
71 #define check(msg, status)                                                     \
72   if (status != HSA_STATUS_SUCCESS) {                                          \
73     DP(#msg " failed\n");                                                      \
74   } else {                                                                     \
75     DP(#msg " succeeded\n");                                                   \
76   }
77 #else
78 #define check(msg, status)                                                     \
79   {}
80 #endif
81 
82 #include "elf_common.h"
83 
84 namespace hsa {
85 template <typename C> hsa_status_t iterate_agents(C cb) {
86   auto L = [](hsa_agent_t agent, void *data) -> hsa_status_t {
87     C *unwrapped = static_cast<C *>(data);
88     return (*unwrapped)(agent);
89   };
90   return hsa_iterate_agents(L, static_cast<void *>(&cb));
91 }
92 
93 template <typename C>
94 hsa_status_t amd_agent_iterate_memory_pools(hsa_agent_t Agent, C cb) {
95   auto L = [](hsa_amd_memory_pool_t MemoryPool, void *data) -> hsa_status_t {
96     C *unwrapped = static_cast<C *>(data);
97     return (*unwrapped)(MemoryPool);
98   };
99 
100   return hsa_amd_agent_iterate_memory_pools(Agent, L, static_cast<void *>(&cb));
101 }
102 
103 } // namespace hsa
104 
105 /// Keep entries table per device
106 struct FuncOrGblEntryTy {
107   __tgt_target_table Table;
108   std::vector<__tgt_offload_entry> Entries;
109 };
110 
111 struct KernelArgPool {
112 private:
113   static pthread_mutex_t mutex;
114 
115 public:
116   uint32_t kernarg_segment_size;
117   void *kernarg_region = nullptr;
118   std::queue<int> free_kernarg_segments;
119 
120   uint32_t kernarg_size_including_implicit() {
121     return kernarg_segment_size + sizeof(impl_implicit_args_t);
122   }
123 
124   ~KernelArgPool() {
125     if (kernarg_region) {
126       auto r = hsa_amd_memory_pool_free(kernarg_region);
127       if (r != HSA_STATUS_SUCCESS) {
128         DP("hsa_amd_memory_pool_free failed: %s\n", get_error_string(r));
129       }
130     }
131   }
132 
133   // Can't really copy or move a mutex
134   KernelArgPool() = default;
135   KernelArgPool(const KernelArgPool &) = delete;
136   KernelArgPool(KernelArgPool &&) = delete;
137 
138   KernelArgPool(uint32_t kernarg_segment_size,
139                 hsa_amd_memory_pool_t &memory_pool)
140       : kernarg_segment_size(kernarg_segment_size) {
141 
142     // impl uses one pool per kernel for all gpus, with a fixed upper size
143     // preserving that exact scheme here, including the queue<int>
144 
145     hsa_status_t err = hsa_amd_memory_pool_allocate(
146         memory_pool, kernarg_size_including_implicit() * MAX_NUM_KERNELS, 0,
147         &kernarg_region);
148 
149     if (err != HSA_STATUS_SUCCESS) {
150       DP("hsa_amd_memory_pool_allocate failed: %s\n", get_error_string(err));
151       kernarg_region = nullptr; // paranoid
152       return;
153     }
154 
155     err = core::allow_access_to_all_gpu_agents(kernarg_region);
156     if (err != HSA_STATUS_SUCCESS) {
157       DP("hsa allow_access_to_all_gpu_agents failed: %s\n",
158          get_error_string(err));
159       auto r = hsa_amd_memory_pool_free(kernarg_region);
160       if (r != HSA_STATUS_SUCCESS) {
161         // if free failed, can't do anything more to resolve it
162         DP("hsa memory poll free failed: %s\n", get_error_string(err));
163       }
164       kernarg_region = nullptr;
165       return;
166     }
167 
168     for (int i = 0; i < MAX_NUM_KERNELS; i++) {
169       free_kernarg_segments.push(i);
170     }
171   }
172 
173   void *allocate(uint64_t arg_num) {
174     assert((arg_num * sizeof(void *)) == kernarg_segment_size);
175     lock l(&mutex);
176     void *res = nullptr;
177     if (!free_kernarg_segments.empty()) {
178 
179       int free_idx = free_kernarg_segments.front();
180       res = static_cast<void *>(static_cast<char *>(kernarg_region) +
181                                 (free_idx * kernarg_size_including_implicit()));
182       assert(free_idx == pointer_to_index(res));
183       free_kernarg_segments.pop();
184     }
185     return res;
186   }
187 
188   void deallocate(void *ptr) {
189     lock l(&mutex);
190     int idx = pointer_to_index(ptr);
191     free_kernarg_segments.push(idx);
192   }
193 
194 private:
195   int pointer_to_index(void *ptr) {
196     ptrdiff_t bytes =
197         static_cast<char *>(ptr) - static_cast<char *>(kernarg_region);
198     assert(bytes >= 0);
199     assert(bytes % kernarg_size_including_implicit() == 0);
200     return bytes / kernarg_size_including_implicit();
201   }
202   struct lock {
203     lock(pthread_mutex_t *m) : m(m) { pthread_mutex_lock(m); }
204     ~lock() { pthread_mutex_unlock(m); }
205     pthread_mutex_t *m;
206   };
207 };
208 pthread_mutex_t KernelArgPool::mutex = PTHREAD_MUTEX_INITIALIZER;
209 
210 std::unordered_map<std::string /*kernel*/, std::unique_ptr<KernelArgPool>>
211     KernelArgPoolMap;
212 
213 /// Use a single entity to encode a kernel and a set of flags
214 struct KernelTy {
215   llvm::omp::OMPTgtExecModeFlags ExecutionMode;
216   int16_t ConstWGSize;
217   int32_t device_id;
218   void *CallStackAddr = nullptr;
219   const char *Name;
220 
221   KernelTy(llvm::omp::OMPTgtExecModeFlags _ExecutionMode, int16_t _ConstWGSize,
222            int32_t _device_id, void *_CallStackAddr, const char *_Name,
223            uint32_t _kernarg_segment_size,
224            hsa_amd_memory_pool_t &KernArgMemoryPool)
225       : ExecutionMode(_ExecutionMode), ConstWGSize(_ConstWGSize),
226         device_id(_device_id), CallStackAddr(_CallStackAddr), Name(_Name) {
227     DP("Construct kernelinfo: ExecMode %d\n", ExecutionMode);
228 
229     std::string N(_Name);
230     if (KernelArgPoolMap.find(N) == KernelArgPoolMap.end()) {
231       KernelArgPoolMap.insert(
232           std::make_pair(N, std::unique_ptr<KernelArgPool>(new KernelArgPool(
233                                 _kernarg_segment_size, KernArgMemoryPool))));
234     }
235   }
236 };
237 
238 /// List that contains all the kernels.
239 /// FIXME: we may need this to be per device and per library.
240 std::list<KernelTy> KernelsList;
241 
242 template <typename Callback> static hsa_status_t FindAgents(Callback CB) {
243 
244   hsa_status_t err =
245       hsa::iterate_agents([&](hsa_agent_t agent) -> hsa_status_t {
246         hsa_device_type_t device_type;
247         // get_info fails iff HSA runtime not yet initialized
248         hsa_status_t err =
249             hsa_agent_get_info(agent, HSA_AGENT_INFO_DEVICE, &device_type);
250 
251         if (err != HSA_STATUS_SUCCESS) {
252           if (print_kernel_trace > 0)
253             DP("rtl.cpp: err %s\n", get_error_string(err));
254 
255           return err;
256         }
257 
258         CB(device_type, agent);
259         return HSA_STATUS_SUCCESS;
260       });
261 
262   // iterate_agents fails iff HSA runtime not yet initialized
263   if (print_kernel_trace > 0 && err != HSA_STATUS_SUCCESS) {
264     DP("rtl.cpp: err %s\n", get_error_string(err));
265   }
266 
267   return err;
268 }
269 
270 static void callbackQueue(hsa_status_t status, hsa_queue_t *source,
271                           void *data) {
272   if (status != HSA_STATUS_SUCCESS) {
273     const char *status_string;
274     if (hsa_status_string(status, &status_string) != HSA_STATUS_SUCCESS) {
275       status_string = "unavailable";
276     }
277     DP("[%s:%d] GPU error in queue %p %d (%s)\n", __FILE__, __LINE__, source,
278        status, status_string);
279     abort();
280   }
281 }
282 
283 namespace core {
284 namespace {
285 void packet_store_release(uint32_t *packet, uint16_t header, uint16_t rest) {
286   __atomic_store_n(packet, header | (rest << 16), __ATOMIC_RELEASE);
287 }
288 
289 uint16_t create_header() {
290   uint16_t header = HSA_PACKET_TYPE_KERNEL_DISPATCH << HSA_PACKET_HEADER_TYPE;
291   header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE;
292   header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE;
293   return header;
294 }
295 
296 hsa_status_t isValidMemoryPool(hsa_amd_memory_pool_t MemoryPool) {
297   bool AllocAllowed = false;
298   hsa_status_t Err = hsa_amd_memory_pool_get_info(
299       MemoryPool, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED,
300       &AllocAllowed);
301   if (Err != HSA_STATUS_SUCCESS) {
302     DP("Alloc allowed in memory pool check failed: %s\n",
303        get_error_string(Err));
304     return Err;
305   }
306 
307   size_t Size = 0;
308   Err = hsa_amd_memory_pool_get_info(MemoryPool, HSA_AMD_MEMORY_POOL_INFO_SIZE,
309                                      &Size);
310   if (Err != HSA_STATUS_SUCCESS) {
311     DP("Get memory pool size failed: %s\n", get_error_string(Err));
312     return Err;
313   }
314 
315   return (AllocAllowed && Size > 0) ? HSA_STATUS_SUCCESS : HSA_STATUS_ERROR;
316 }
317 
318 hsa_status_t addMemoryPool(hsa_amd_memory_pool_t MemoryPool, void *Data) {
319   std::vector<hsa_amd_memory_pool_t> *Result =
320       static_cast<std::vector<hsa_amd_memory_pool_t> *>(Data);
321 
322   hsa_status_t err;
323   if ((err = isValidMemoryPool(MemoryPool)) != HSA_STATUS_SUCCESS) {
324     return err;
325   }
326 
327   Result->push_back(MemoryPool);
328   return HSA_STATUS_SUCCESS;
329 }
330 
331 } // namespace
332 } // namespace core
333 
334 struct EnvironmentVariables {
335   int NumTeams;
336   int TeamLimit;
337   int TeamThreadLimit;
338   int MaxTeamsDefault;
339   int DynamicMemSize;
340 };
341 
342 template <uint32_t wavesize>
343 static constexpr const llvm::omp::GV &getGridValue() {
344   return llvm::omp::getAMDGPUGridValues<wavesize>();
345 }
346 
347 struct HSALifetime {
348   // Wrapper around HSA used to ensure it is constructed before other types
349   // and destructed after, which means said other types can use raii for
350   // cleanup without risking running outside of the lifetime of HSA
351   const hsa_status_t S;
352 
353   bool HSAInitSuccess() { return S == HSA_STATUS_SUCCESS; }
354   HSALifetime() : S(hsa_init()) {}
355 
356   ~HSALifetime() {
357     if (S == HSA_STATUS_SUCCESS) {
358       hsa_status_t Err = hsa_shut_down();
359       if (Err != HSA_STATUS_SUCCESS) {
360         // Can't call into HSA to get a string from the integer
361         DP("Shutting down HSA failed: %d\n", Err);
362       }
363     }
364   }
365 };
366 
367 // Handle scheduling of multiple hsa_queue's per device to
368 // multiple threads (one scheduler per device)
369 class HSAQueueScheduler {
370 public:
371   HSAQueueScheduler() : current(0) {}
372 
373   HSAQueueScheduler(const HSAQueueScheduler &) = delete;
374 
375   HSAQueueScheduler(HSAQueueScheduler &&q) {
376     current = q.current.load();
377     for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) {
378       HSAQueues[i] = q.HSAQueues[i];
379       q.HSAQueues[i] = nullptr;
380     }
381   }
382 
383   // \return false if any HSA queue creation fails
384   bool CreateQueues(hsa_agent_t HSAAgent, uint32_t queue_size) {
385     for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) {
386       hsa_queue_t *Q = nullptr;
387       hsa_status_t rc =
388           hsa_queue_create(HSAAgent, queue_size, HSA_QUEUE_TYPE_MULTI,
389                            callbackQueue, NULL, UINT32_MAX, UINT32_MAX, &Q);
390       if (rc != HSA_STATUS_SUCCESS) {
391         DP("Failed to create HSA queue %d\n", i);
392         return false;
393       }
394       HSAQueues[i] = Q;
395     }
396     return true;
397   }
398 
399   ~HSAQueueScheduler() {
400     for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) {
401       if (HSAQueues[i]) {
402         hsa_status_t err = hsa_queue_destroy(HSAQueues[i]);
403         if (err != HSA_STATUS_SUCCESS)
404           DP("Error destroying HSA queue");
405       }
406     }
407   }
408 
409   // \return next queue to use for device
410   hsa_queue_t *Next() {
411     return HSAQueues[(current.fetch_add(1, std::memory_order_relaxed)) %
412                      NUM_QUEUES_PER_DEVICE];
413   }
414 
415 private:
416   // Number of queues per device
417   enum : uint8_t { NUM_QUEUES_PER_DEVICE = 4 };
418   hsa_queue_t *HSAQueues[NUM_QUEUES_PER_DEVICE] = {};
419   std::atomic<uint8_t> current;
420 };
421 
422 /// Class containing all the device information
423 class RTLDeviceInfoTy : HSALifetime {
424   std::vector<std::list<FuncOrGblEntryTy>> FuncGblEntries;
425 
426   struct QueueDeleter {
427     void operator()(hsa_queue_t *Q) {
428       if (Q) {
429         hsa_status_t Err = hsa_queue_destroy(Q);
430         if (Err != HSA_STATUS_SUCCESS) {
431           DP("Error destroying hsa queue: %s\n", get_error_string(Err));
432         }
433       }
434     }
435   };
436 
437 public:
438   bool ConstructionSucceeded = false;
439 
440   // load binary populates symbol tables and mutates various global state
441   // run uses those symbol tables
442   std::shared_timed_mutex load_run_lock;
443 
444   int NumberOfDevices = 0;
445 
446   // GPU devices
447   std::vector<hsa_agent_t> HSAAgents;
448   std::vector<HSAQueueScheduler> HSAQueueSchedulers; // one per gpu
449 
450   // CPUs
451   std::vector<hsa_agent_t> CPUAgents;
452 
453   // Device properties
454   std::vector<int> ComputeUnits;
455   std::vector<int> GroupsPerDevice;
456   std::vector<int> ThreadsPerGroup;
457   std::vector<int> WarpSize;
458   std::vector<std::string> GPUName;
459 
460   // OpenMP properties
461   std::vector<int> NumTeams;
462   std::vector<int> NumThreads;
463 
464   // OpenMP Environment properties
465   EnvironmentVariables Env;
466 
467   // OpenMP Requires Flags
468   int64_t RequiresFlags;
469 
470   // Resource pools
471   SignalPoolT FreeSignalPool;
472 
473   bool hostcall_required = false;
474 
475   std::vector<hsa_executable_t> HSAExecutables;
476 
477   std::vector<std::map<std::string, atl_kernel_info_t>> KernelInfoTable;
478   std::vector<std::map<std::string, atl_symbol_info_t>> SymbolInfoTable;
479 
480   hsa_amd_memory_pool_t KernArgPool;
481 
482   // fine grained memory pool for host allocations
483   hsa_amd_memory_pool_t HostFineGrainedMemoryPool;
484 
485   // fine and coarse-grained memory pools per offloading device
486   std::vector<hsa_amd_memory_pool_t> DeviceFineGrainedMemoryPools;
487   std::vector<hsa_amd_memory_pool_t> DeviceCoarseGrainedMemoryPools;
488 
489   struct implFreePtrDeletor {
490     void operator()(void *p) {
491       core::Runtime::Memfree(p); // ignore failure to free
492     }
493   };
494 
495   // device_State shared across loaded binaries, error if inconsistent size
496   std::vector<std::pair<std::unique_ptr<void, implFreePtrDeletor>, uint64_t>>
497       deviceStateStore;
498 
499   static const unsigned HardTeamLimit =
500       (1 << 16) - 1; // 64K needed to fit in uint16
501   static const int DefaultNumTeams = 128;
502 
503   // These need to be per-device since different devices can have different
504   // wave sizes, but are currently the same number for each so that refactor
505   // can be postponed.
506   static_assert(getGridValue<32>().GV_Max_Teams ==
507                     getGridValue<64>().GV_Max_Teams,
508                 "");
509   static const int Max_Teams = getGridValue<64>().GV_Max_Teams;
510 
511   static_assert(getGridValue<32>().GV_Max_WG_Size ==
512                     getGridValue<64>().GV_Max_WG_Size,
513                 "");
514   static const int Max_WG_Size = getGridValue<64>().GV_Max_WG_Size;
515 
516   static_assert(getGridValue<32>().GV_Default_WG_Size ==
517                     getGridValue<64>().GV_Default_WG_Size,
518                 "");
519   static const int Default_WG_Size = getGridValue<64>().GV_Default_WG_Size;
520 
521   using MemcpyFunc = hsa_status_t (*)(hsa_signal_t, void *, void *, size_t size,
522                                       hsa_agent_t, hsa_amd_memory_pool_t);
523   hsa_status_t freesignalpool_memcpy(void *dest, void *src, size_t size,
524                                      MemcpyFunc Func, int32_t deviceId) {
525     hsa_agent_t agent = HSAAgents[deviceId];
526     hsa_signal_t s = FreeSignalPool.pop();
527     if (s.handle == 0) {
528       return HSA_STATUS_ERROR;
529     }
530     hsa_status_t r = Func(s, dest, src, size, agent, HostFineGrainedMemoryPool);
531     FreeSignalPool.push(s);
532     return r;
533   }
534 
535   hsa_status_t freesignalpool_memcpy_d2h(void *dest, void *src, size_t size,
536                                          int32_t deviceId) {
537     return freesignalpool_memcpy(dest, src, size, impl_memcpy_d2h, deviceId);
538   }
539 
540   hsa_status_t freesignalpool_memcpy_h2d(void *dest, void *src, size_t size,
541                                          int32_t deviceId) {
542     return freesignalpool_memcpy(dest, src, size, impl_memcpy_h2d, deviceId);
543   }
544 
545   // Record entry point associated with device
546   void addOffloadEntry(int32_t device_id, __tgt_offload_entry entry) {
547     assert(device_id < (int32_t)FuncGblEntries.size() &&
548            "Unexpected device id!");
549     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
550 
551     E.Entries.push_back(entry);
552   }
553 
554   // Return true if the entry is associated with device
555   bool findOffloadEntry(int32_t device_id, void *addr) {
556     assert(device_id < (int32_t)FuncGblEntries.size() &&
557            "Unexpected device id!");
558     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
559 
560     for (auto &it : E.Entries) {
561       if (it.addr == addr)
562         return true;
563     }
564 
565     return false;
566   }
567 
568   // Return the pointer to the target entries table
569   __tgt_target_table *getOffloadEntriesTable(int32_t device_id) {
570     assert(device_id < (int32_t)FuncGblEntries.size() &&
571            "Unexpected device id!");
572     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
573 
574     int32_t size = E.Entries.size();
575 
576     // Table is empty
577     if (!size)
578       return 0;
579 
580     __tgt_offload_entry *begin = &E.Entries[0];
581     __tgt_offload_entry *end = &E.Entries[size - 1];
582 
583     // Update table info according to the entries and return the pointer
584     E.Table.EntriesBegin = begin;
585     E.Table.EntriesEnd = ++end;
586 
587     return &E.Table;
588   }
589 
590   // Clear entries table for a device
591   void clearOffloadEntriesTable(int device_id) {
592     assert(device_id < (int32_t)FuncGblEntries.size() &&
593            "Unexpected device id!");
594     FuncGblEntries[device_id].emplace_back();
595     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
596     // KernelArgPoolMap.clear();
597     E.Entries.clear();
598     E.Table.EntriesBegin = E.Table.EntriesEnd = 0;
599   }
600 
601   hsa_status_t addDeviceMemoryPool(hsa_amd_memory_pool_t MemoryPool,
602                                    int DeviceId) {
603     assert(DeviceId < DeviceFineGrainedMemoryPools.size() && "Error here.");
604     uint32_t GlobalFlags = 0;
605     hsa_status_t Err = hsa_amd_memory_pool_get_info(
606         MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags);
607 
608     if (Err != HSA_STATUS_SUCCESS) {
609       return Err;
610     }
611 
612     if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) {
613       DeviceFineGrainedMemoryPools[DeviceId] = MemoryPool;
614     } else if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED) {
615       DeviceCoarseGrainedMemoryPools[DeviceId] = MemoryPool;
616     }
617 
618     return HSA_STATUS_SUCCESS;
619   }
620 
621   hsa_status_t setupDevicePools(const std::vector<hsa_agent_t> &Agents) {
622     for (int DeviceId = 0; DeviceId < Agents.size(); DeviceId++) {
623       hsa_status_t Err = hsa::amd_agent_iterate_memory_pools(
624           Agents[DeviceId], [&](hsa_amd_memory_pool_t MemoryPool) {
625             hsa_status_t ValidStatus = core::isValidMemoryPool(MemoryPool);
626             if (ValidStatus != HSA_STATUS_SUCCESS) {
627               DP("Alloc allowed in memory pool check failed: %s\n",
628                  get_error_string(ValidStatus));
629               return HSA_STATUS_SUCCESS;
630             }
631             return addDeviceMemoryPool(MemoryPool, DeviceId);
632           });
633 
634       if (Err != HSA_STATUS_SUCCESS) {
635         DP("[%s:%d] %s failed: %s\n", __FILE__, __LINE__,
636            "Iterate all memory pools", get_error_string(Err));
637         return Err;
638       }
639     }
640     return HSA_STATUS_SUCCESS;
641   }
642 
643   hsa_status_t setupHostMemoryPools(std::vector<hsa_agent_t> &Agents) {
644     std::vector<hsa_amd_memory_pool_t> HostPools;
645 
646     // collect all the "valid" pools for all the given agents.
647     for (const auto &Agent : Agents) {
648       hsa_status_t Err = hsa_amd_agent_iterate_memory_pools(
649           Agent, core::addMemoryPool, static_cast<void *>(&HostPools));
650       if (Err != HSA_STATUS_SUCCESS) {
651         DP("addMemoryPool returned %s, continuing\n", get_error_string(Err));
652       }
653     }
654 
655     // We need two fine-grained pools.
656     //  1. One with kernarg flag set for storing kernel arguments
657     //  2. Second for host allocations
658     bool FineGrainedMemoryPoolSet = false;
659     bool KernArgPoolSet = false;
660     for (const auto &MemoryPool : HostPools) {
661       hsa_status_t Err = HSA_STATUS_SUCCESS;
662       uint32_t GlobalFlags = 0;
663       Err = hsa_amd_memory_pool_get_info(
664           MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags);
665       if (Err != HSA_STATUS_SUCCESS) {
666         DP("Get memory pool info failed: %s\n", get_error_string(Err));
667         return Err;
668       }
669 
670       if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) {
671         if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_KERNARG_INIT) {
672           KernArgPool = MemoryPool;
673           KernArgPoolSet = true;
674         }
675         HostFineGrainedMemoryPool = MemoryPool;
676         FineGrainedMemoryPoolSet = true;
677       }
678     }
679 
680     if (FineGrainedMemoryPoolSet && KernArgPoolSet)
681       return HSA_STATUS_SUCCESS;
682 
683     return HSA_STATUS_ERROR;
684   }
685 
686   hsa_amd_memory_pool_t getDeviceMemoryPool(int DeviceId) {
687     assert(DeviceId >= 0 && DeviceId < DeviceCoarseGrainedMemoryPools.size() &&
688            "Invalid device Id");
689     return DeviceCoarseGrainedMemoryPools[DeviceId];
690   }
691 
692   hsa_amd_memory_pool_t getHostMemoryPool() {
693     return HostFineGrainedMemoryPool;
694   }
695 
696   static int readEnv(const char *Env, int Default = -1) {
697     const char *envStr = getenv(Env);
698     int res = Default;
699     if (envStr) {
700       res = std::stoi(envStr);
701       DP("Parsed %s=%d\n", Env, res);
702     }
703     return res;
704   }
705 
706   RTLDeviceInfoTy() {
707     DP("Start initializing " GETNAME(TARGET_NAME) "\n");
708 
709     // LIBOMPTARGET_KERNEL_TRACE provides a kernel launch trace to stderr
710     // anytime. You do not need a debug library build.
711     //  0 => no tracing
712     //  1 => tracing dispatch only
713     // >1 => verbosity increase
714 
715     if (!HSAInitSuccess()) {
716       DP("Error when initializing HSA in " GETNAME(TARGET_NAME) "\n");
717       return;
718     }
719 
720     if (char *envStr = getenv("LIBOMPTARGET_KERNEL_TRACE"))
721       print_kernel_trace = atoi(envStr);
722     else
723       print_kernel_trace = 0;
724 
725     hsa_status_t err = core::atl_init_gpu_context();
726     if (err != HSA_STATUS_SUCCESS) {
727       DP("Error when initializing " GETNAME(TARGET_NAME) "\n");
728       return;
729     }
730 
731     // Init hostcall soon after initializing hsa
732     hostrpc_init();
733 
734     err = FindAgents([&](hsa_device_type_t DeviceType, hsa_agent_t Agent) {
735       if (DeviceType == HSA_DEVICE_TYPE_CPU) {
736         CPUAgents.push_back(Agent);
737       } else {
738         HSAAgents.push_back(Agent);
739       }
740     });
741     if (err != HSA_STATUS_SUCCESS)
742       return;
743 
744     NumberOfDevices = (int)HSAAgents.size();
745 
746     if (NumberOfDevices == 0) {
747       DP("There are no devices supporting HSA.\n");
748       return;
749     } else {
750       DP("There are %d devices supporting HSA.\n", NumberOfDevices);
751     }
752 
753     // Init the device info
754     HSAQueueSchedulers.reserve(NumberOfDevices);
755     FuncGblEntries.resize(NumberOfDevices);
756     ThreadsPerGroup.resize(NumberOfDevices);
757     ComputeUnits.resize(NumberOfDevices);
758     GPUName.resize(NumberOfDevices);
759     GroupsPerDevice.resize(NumberOfDevices);
760     WarpSize.resize(NumberOfDevices);
761     NumTeams.resize(NumberOfDevices);
762     NumThreads.resize(NumberOfDevices);
763     deviceStateStore.resize(NumberOfDevices);
764     KernelInfoTable.resize(NumberOfDevices);
765     SymbolInfoTable.resize(NumberOfDevices);
766     DeviceCoarseGrainedMemoryPools.resize(NumberOfDevices);
767     DeviceFineGrainedMemoryPools.resize(NumberOfDevices);
768 
769     err = setupDevicePools(HSAAgents);
770     if (err != HSA_STATUS_SUCCESS) {
771       DP("Setup for Device Memory Pools failed\n");
772       return;
773     }
774 
775     err = setupHostMemoryPools(CPUAgents);
776     if (err != HSA_STATUS_SUCCESS) {
777       DP("Setup for Host Memory Pools failed\n");
778       return;
779     }
780 
781     for (int i = 0; i < NumberOfDevices; i++) {
782       uint32_t queue_size = 0;
783       {
784         hsa_status_t err = hsa_agent_get_info(
785             HSAAgents[i], HSA_AGENT_INFO_QUEUE_MAX_SIZE, &queue_size);
786         if (err != HSA_STATUS_SUCCESS) {
787           DP("HSA query QUEUE_MAX_SIZE failed for agent %d\n", i);
788           return;
789         }
790         enum { MaxQueueSize = 4096 };
791         if (queue_size > MaxQueueSize) {
792           queue_size = MaxQueueSize;
793         }
794       }
795 
796       {
797         HSAQueueScheduler QSched;
798         if (!QSched.CreateQueues(HSAAgents[i], queue_size))
799           return;
800         HSAQueueSchedulers.emplace_back(std::move(QSched));
801       }
802 
803       deviceStateStore[i] = {nullptr, 0};
804     }
805 
806     for (int i = 0; i < NumberOfDevices; i++) {
807       ThreadsPerGroup[i] = RTLDeviceInfoTy::Default_WG_Size;
808       GroupsPerDevice[i] = RTLDeviceInfoTy::DefaultNumTeams;
809       ComputeUnits[i] = 1;
810       DP("Device %d: Initial groupsPerDevice %d & threadsPerGroup %d\n", i,
811          GroupsPerDevice[i], ThreadsPerGroup[i]);
812     }
813 
814     // Get environment variables regarding teams
815     Env.TeamLimit = readEnv("OMP_TEAM_LIMIT");
816     Env.NumTeams = readEnv("OMP_NUM_TEAMS");
817     Env.MaxTeamsDefault = readEnv("OMP_MAX_TEAMS_DEFAULT");
818     Env.TeamThreadLimit = readEnv("OMP_TEAMS_THREAD_LIMIT");
819     Env.DynamicMemSize = readEnv("LIBOMPTARGET_SHARED_MEMORY_SIZE", 0);
820 
821     // Default state.
822     RequiresFlags = OMP_REQ_UNDEFINED;
823 
824     ConstructionSucceeded = true;
825   }
826 
827   ~RTLDeviceInfoTy() {
828     DP("Finalizing the " GETNAME(TARGET_NAME) " DeviceInfo.\n");
829     if (!HSAInitSuccess()) {
830       // Then none of these can have been set up and they can't be torn down
831       return;
832     }
833     // Run destructors on types that use HSA before
834     // impl_finalize removes access to it
835     deviceStateStore.clear();
836     KernelArgPoolMap.clear();
837     // Terminate hostrpc before finalizing hsa
838     hostrpc_terminate();
839 
840     hsa_status_t Err;
841     for (uint32_t I = 0; I < HSAExecutables.size(); I++) {
842       Err = hsa_executable_destroy(HSAExecutables[I]);
843       if (Err != HSA_STATUS_SUCCESS) {
844         DP("[%s:%d] %s failed: %s\n", __FILE__, __LINE__,
845            "Destroying executable", get_error_string(Err));
846       }
847     }
848   }
849 };
850 
851 pthread_mutex_t SignalPoolT::mutex = PTHREAD_MUTEX_INITIALIZER;
852 
853 static RTLDeviceInfoTy DeviceInfo;
854 
855 namespace {
856 
857 int32_t dataRetrieve(int32_t DeviceId, void *HstPtr, void *TgtPtr, int64_t Size,
858                      __tgt_async_info *AsyncInfo) {
859   assert(AsyncInfo && "AsyncInfo is nullptr");
860   assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large");
861   // Return success if we are not copying back to host from target.
862   if (!HstPtr)
863     return OFFLOAD_SUCCESS;
864   hsa_status_t err;
865   DP("Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size,
866      (long long unsigned)(Elf64_Addr)TgtPtr,
867      (long long unsigned)(Elf64_Addr)HstPtr);
868 
869   err = DeviceInfo.freesignalpool_memcpy_d2h(HstPtr, TgtPtr, (size_t)Size,
870                                              DeviceId);
871 
872   if (err != HSA_STATUS_SUCCESS) {
873     DP("Error when copying data from device to host. Pointers: "
874        "host = 0x%016lx, device = 0x%016lx, size = %lld\n",
875        (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size);
876     return OFFLOAD_FAIL;
877   }
878   DP("DONE Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size,
879      (long long unsigned)(Elf64_Addr)TgtPtr,
880      (long long unsigned)(Elf64_Addr)HstPtr);
881   return OFFLOAD_SUCCESS;
882 }
883 
884 int32_t dataSubmit(int32_t DeviceId, void *TgtPtr, void *HstPtr, int64_t Size,
885                    __tgt_async_info *AsyncInfo) {
886   assert(AsyncInfo && "AsyncInfo is nullptr");
887   hsa_status_t err;
888   assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large");
889   // Return success if we are not doing host to target.
890   if (!HstPtr)
891     return OFFLOAD_SUCCESS;
892 
893   DP("Submit data %ld bytes, (hst:%016llx) -> (tgt:%016llx).\n", Size,
894      (long long unsigned)(Elf64_Addr)HstPtr,
895      (long long unsigned)(Elf64_Addr)TgtPtr);
896   err = DeviceInfo.freesignalpool_memcpy_h2d(TgtPtr, HstPtr, (size_t)Size,
897                                              DeviceId);
898   if (err != HSA_STATUS_SUCCESS) {
899     DP("Error when copying data from host to device. Pointers: "
900        "host = 0x%016lx, device = 0x%016lx, size = %lld\n",
901        (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size);
902     return OFFLOAD_FAIL;
903   }
904   return OFFLOAD_SUCCESS;
905 }
906 
907 // Async.
908 // The implementation was written with cuda streams in mind. The semantics of
909 // that are to execute kernels on a queue in order of insertion. A synchronise
910 // call then makes writes visible between host and device. This means a series
911 // of N data_submit_async calls are expected to execute serially. HSA offers
912 // various options to run the data copies concurrently. This may require changes
913 // to libomptarget.
914 
915 // __tgt_async_info* contains a void * Queue. Queue = 0 is used to indicate that
916 // there are no outstanding kernels that need to be synchronized. Any async call
917 // may be passed a Queue==0, at which point the cuda implementation will set it
918 // to non-null (see getStream). The cuda streams are per-device. Upstream may
919 // change this interface to explicitly initialize the AsyncInfo_pointer, but
920 // until then hsa lazily initializes it as well.
921 
922 void initAsyncInfo(__tgt_async_info *AsyncInfo) {
923   // set non-null while using async calls, return to null to indicate completion
924   assert(AsyncInfo);
925   if (!AsyncInfo->Queue) {
926     AsyncInfo->Queue = reinterpret_cast<void *>(UINT64_MAX);
927   }
928 }
929 void finiAsyncInfo(__tgt_async_info *AsyncInfo) {
930   assert(AsyncInfo);
931   assert(AsyncInfo->Queue);
932   AsyncInfo->Queue = 0;
933 }
934 
935 // Determine launch values for kernel.
936 struct launchVals {
937   int WorkgroupSize;
938   int GridSize;
939 };
940 launchVals getLaunchVals(int WarpSize, EnvironmentVariables Env,
941                          int ConstWGSize,
942                          llvm::omp::OMPTgtExecModeFlags ExecutionMode,
943                          int num_teams, int thread_limit,
944                          uint64_t loop_tripcount, int DeviceNumTeams) {
945 
946   int threadsPerGroup = RTLDeviceInfoTy::Default_WG_Size;
947   int num_groups = 0;
948 
949   int Max_Teams =
950       Env.MaxTeamsDefault > 0 ? Env.MaxTeamsDefault : DeviceNumTeams;
951   if (Max_Teams > RTLDeviceInfoTy::HardTeamLimit)
952     Max_Teams = RTLDeviceInfoTy::HardTeamLimit;
953 
954   if (print_kernel_trace & STARTUP_DETAILS) {
955     DP("RTLDeviceInfoTy::Max_Teams: %d\n", RTLDeviceInfoTy::Max_Teams);
956     DP("Max_Teams: %d\n", Max_Teams);
957     DP("RTLDeviceInfoTy::Warp_Size: %d\n", WarpSize);
958     DP("RTLDeviceInfoTy::Max_WG_Size: %d\n", RTLDeviceInfoTy::Max_WG_Size);
959     DP("RTLDeviceInfoTy::Default_WG_Size: %d\n",
960        RTLDeviceInfoTy::Default_WG_Size);
961     DP("thread_limit: %d\n", thread_limit);
962     DP("threadsPerGroup: %d\n", threadsPerGroup);
963     DP("ConstWGSize: %d\n", ConstWGSize);
964   }
965   // check for thread_limit() clause
966   if (thread_limit > 0) {
967     threadsPerGroup = thread_limit;
968     DP("Setting threads per block to requested %d\n", thread_limit);
969     // Add master warp for GENERIC
970     if (ExecutionMode ==
971         llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC) {
972       threadsPerGroup += WarpSize;
973       DP("Adding master wavefront: +%d threads\n", WarpSize);
974     }
975     if (threadsPerGroup > RTLDeviceInfoTy::Max_WG_Size) { // limit to max
976       threadsPerGroup = RTLDeviceInfoTy::Max_WG_Size;
977       DP("Setting threads per block to maximum %d\n", threadsPerGroup);
978     }
979   }
980   // check flat_max_work_group_size attr here
981   if (threadsPerGroup > ConstWGSize) {
982     threadsPerGroup = ConstWGSize;
983     DP("Reduced threadsPerGroup to flat-attr-group-size limit %d\n",
984        threadsPerGroup);
985   }
986   if (print_kernel_trace & STARTUP_DETAILS)
987     DP("threadsPerGroup: %d\n", threadsPerGroup);
988   DP("Preparing %d threads\n", threadsPerGroup);
989 
990   // Set default num_groups (teams)
991   if (Env.TeamLimit > 0)
992     num_groups = (Max_Teams < Env.TeamLimit) ? Max_Teams : Env.TeamLimit;
993   else
994     num_groups = Max_Teams;
995   DP("Set default num of groups %d\n", num_groups);
996 
997   if (print_kernel_trace & STARTUP_DETAILS) {
998     DP("num_groups: %d\n", num_groups);
999     DP("num_teams: %d\n", num_teams);
1000   }
1001 
1002   // Reduce num_groups if threadsPerGroup exceeds RTLDeviceInfoTy::Max_WG_Size
1003   // This reduction is typical for default case (no thread_limit clause).
1004   // or when user goes crazy with num_teams clause.
1005   // FIXME: We cant distinguish between a constant or variable thread limit.
1006   // So we only handle constant thread_limits.
1007   if (threadsPerGroup >
1008       RTLDeviceInfoTy::Default_WG_Size) //  256 < threadsPerGroup <= 1024
1009     // Should we round threadsPerGroup up to nearest WarpSize
1010     // here?
1011     num_groups = (Max_Teams * RTLDeviceInfoTy::Max_WG_Size) / threadsPerGroup;
1012 
1013   // check for num_teams() clause
1014   if (num_teams > 0) {
1015     num_groups = (num_teams < num_groups) ? num_teams : num_groups;
1016   }
1017   if (print_kernel_trace & STARTUP_DETAILS) {
1018     DP("num_groups: %d\n", num_groups);
1019     DP("Env.NumTeams %d\n", Env.NumTeams);
1020     DP("Env.TeamLimit %d\n", Env.TeamLimit);
1021   }
1022 
1023   if (Env.NumTeams > 0) {
1024     num_groups = (Env.NumTeams < num_groups) ? Env.NumTeams : num_groups;
1025     DP("Modifying teams based on Env.NumTeams %d\n", Env.NumTeams);
1026   } else if (Env.TeamLimit > 0) {
1027     num_groups = (Env.TeamLimit < num_groups) ? Env.TeamLimit : num_groups;
1028     DP("Modifying teams based on Env.TeamLimit%d\n", Env.TeamLimit);
1029   } else {
1030     if (num_teams <= 0) {
1031       if (loop_tripcount > 0) {
1032         if (ExecutionMode ==
1033             llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_SPMD) {
1034           // round up to the nearest integer
1035           num_groups = ((loop_tripcount - 1) / threadsPerGroup) + 1;
1036         } else if (ExecutionMode ==
1037                    llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC) {
1038           num_groups = loop_tripcount;
1039         } else /* OMP_TGT_EXEC_MODE_GENERIC_SPMD */ {
1040           // This is a generic kernel that was transformed to use SPMD-mode
1041           // execution but uses Generic-mode semantics for scheduling.
1042           num_groups = loop_tripcount;
1043         }
1044         DP("Using %d teams due to loop trip count %" PRIu64 " and number of "
1045            "threads per block %d\n",
1046            num_groups, loop_tripcount, threadsPerGroup);
1047       }
1048     } else {
1049       num_groups = num_teams;
1050     }
1051     if (num_groups > Max_Teams) {
1052       num_groups = Max_Teams;
1053       if (print_kernel_trace & STARTUP_DETAILS)
1054         DP("Limiting num_groups %d to Max_Teams %d \n", num_groups, Max_Teams);
1055     }
1056     if (num_groups > num_teams && num_teams > 0) {
1057       num_groups = num_teams;
1058       if (print_kernel_trace & STARTUP_DETAILS)
1059         DP("Limiting num_groups %d to clause num_teams %d \n", num_groups,
1060            num_teams);
1061     }
1062   }
1063 
1064   // num_teams clause always honored, no matter what, unless DEFAULT is active.
1065   if (num_teams > 0) {
1066     num_groups = num_teams;
1067     // Cap num_groups to EnvMaxTeamsDefault if set.
1068     if (Env.MaxTeamsDefault > 0 && num_groups > Env.MaxTeamsDefault)
1069       num_groups = Env.MaxTeamsDefault;
1070   }
1071   if (print_kernel_trace & STARTUP_DETAILS) {
1072     DP("threadsPerGroup: %d\n", threadsPerGroup);
1073     DP("num_groups: %d\n", num_groups);
1074     DP("loop_tripcount: %ld\n", loop_tripcount);
1075   }
1076   DP("Final %d num_groups and %d threadsPerGroup\n", num_groups,
1077      threadsPerGroup);
1078 
1079   launchVals res;
1080   res.WorkgroupSize = threadsPerGroup;
1081   res.GridSize = threadsPerGroup * num_groups;
1082   return res;
1083 }
1084 
1085 static uint64_t acquire_available_packet_id(hsa_queue_t *queue) {
1086   uint64_t packet_id = hsa_queue_add_write_index_relaxed(queue, 1);
1087   bool full = true;
1088   while (full) {
1089     full =
1090         packet_id >= (queue->size + hsa_queue_load_read_index_scacquire(queue));
1091   }
1092   return packet_id;
1093 }
1094 
1095 int32_t runRegionLocked(int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
1096                         ptrdiff_t *tgt_offsets, int32_t arg_num,
1097                         int32_t num_teams, int32_t thread_limit,
1098                         uint64_t loop_tripcount) {
1099   // Set the context we are using
1100   // update thread limit content in gpu memory if un-initialized or specified
1101   // from host
1102 
1103   DP("Run target team region thread_limit %d\n", thread_limit);
1104 
1105   // All args are references.
1106   std::vector<void *> args(arg_num);
1107   std::vector<void *> ptrs(arg_num);
1108 
1109   DP("Arg_num: %d\n", arg_num);
1110   for (int32_t i = 0; i < arg_num; ++i) {
1111     ptrs[i] = (void *)((intptr_t)tgt_args[i] + tgt_offsets[i]);
1112     args[i] = &ptrs[i];
1113     DP("Offseted base: arg[%d]:" DPxMOD "\n", i, DPxPTR(ptrs[i]));
1114   }
1115 
1116   KernelTy *KernelInfo = (KernelTy *)tgt_entry_ptr;
1117 
1118   std::string kernel_name = std::string(KernelInfo->Name);
1119   auto &KernelInfoTable = DeviceInfo.KernelInfoTable;
1120   if (KernelInfoTable[device_id].find(kernel_name) ==
1121       KernelInfoTable[device_id].end()) {
1122     DP("Kernel %s not found\n", kernel_name.c_str());
1123     return OFFLOAD_FAIL;
1124   }
1125 
1126   const atl_kernel_info_t KernelInfoEntry =
1127       KernelInfoTable[device_id][kernel_name];
1128   const uint32_t group_segment_size =
1129       KernelInfoEntry.group_segment_size + DeviceInfo.Env.DynamicMemSize;
1130   const uint32_t sgpr_count = KernelInfoEntry.sgpr_count;
1131   const uint32_t vgpr_count = KernelInfoEntry.vgpr_count;
1132   const uint32_t sgpr_spill_count = KernelInfoEntry.sgpr_spill_count;
1133   const uint32_t vgpr_spill_count = KernelInfoEntry.vgpr_spill_count;
1134 
1135   assert(arg_num == (int)KernelInfoEntry.explicit_argument_count);
1136 
1137   /*
1138    * Set limit based on ThreadsPerGroup and GroupsPerDevice
1139    */
1140   launchVals LV =
1141       getLaunchVals(DeviceInfo.WarpSize[device_id], DeviceInfo.Env,
1142                     KernelInfo->ConstWGSize, KernelInfo->ExecutionMode,
1143                     num_teams,      // From run_region arg
1144                     thread_limit,   // From run_region arg
1145                     loop_tripcount, // From run_region arg
1146                     DeviceInfo.NumTeams[KernelInfo->device_id]);
1147   const int GridSize = LV.GridSize;
1148   const int WorkgroupSize = LV.WorkgroupSize;
1149 
1150   if (print_kernel_trace >= LAUNCH) {
1151     int num_groups = GridSize / WorkgroupSize;
1152     // enum modes are SPMD, GENERIC, NONE 0,1,2
1153     // if doing rtl timing, print to stderr, unless stdout requested.
1154     bool traceToStdout = print_kernel_trace & (RTL_TO_STDOUT | RTL_TIMING);
1155     fprintf(traceToStdout ? stdout : stderr,
1156             "DEVID:%2d SGN:%1d ConstWGSize:%-4d args:%2d teamsXthrds:(%4dX%4d) "
1157             "reqd:(%4dX%4d) lds_usage:%uB sgpr_count:%u vgpr_count:%u "
1158             "sgpr_spill_count:%u vgpr_spill_count:%u tripcount:%lu n:%s\n",
1159             device_id, KernelInfo->ExecutionMode, KernelInfo->ConstWGSize,
1160             arg_num, num_groups, WorkgroupSize, num_teams, thread_limit,
1161             group_segment_size, sgpr_count, vgpr_count, sgpr_spill_count,
1162             vgpr_spill_count, loop_tripcount, KernelInfo->Name);
1163   }
1164 
1165   // Run on the device.
1166   {
1167     hsa_queue_t *queue = DeviceInfo.HSAQueueSchedulers[device_id].Next();
1168     if (!queue) {
1169       return OFFLOAD_FAIL;
1170     }
1171     uint64_t packet_id = acquire_available_packet_id(queue);
1172 
1173     const uint32_t mask = queue->size - 1; // size is a power of 2
1174     hsa_kernel_dispatch_packet_t *packet =
1175         (hsa_kernel_dispatch_packet_t *)queue->base_address +
1176         (packet_id & mask);
1177 
1178     // packet->header is written last
1179     packet->setup = UINT16_C(1) << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS;
1180     packet->workgroup_size_x = WorkgroupSize;
1181     packet->workgroup_size_y = 1;
1182     packet->workgroup_size_z = 1;
1183     packet->reserved0 = 0;
1184     packet->grid_size_x = GridSize;
1185     packet->grid_size_y = 1;
1186     packet->grid_size_z = 1;
1187     packet->private_segment_size = KernelInfoEntry.private_segment_size;
1188     packet->group_segment_size = group_segment_size;
1189     packet->kernel_object = KernelInfoEntry.kernel_object;
1190     packet->kernarg_address = 0;     // use the block allocator
1191     packet->reserved2 = 0;           // impl writes id_ here
1192     packet->completion_signal = {0}; // may want a pool of signals
1193 
1194     KernelArgPool *ArgPool = nullptr;
1195     void *kernarg = nullptr;
1196     {
1197       auto it = KernelArgPoolMap.find(std::string(KernelInfo->Name));
1198       if (it != KernelArgPoolMap.end()) {
1199         ArgPool = (it->second).get();
1200       }
1201     }
1202     if (!ArgPool) {
1203       DP("Warning: No ArgPool for %s on device %d\n", KernelInfo->Name,
1204          device_id);
1205     }
1206     {
1207       if (ArgPool) {
1208         assert(ArgPool->kernarg_segment_size == (arg_num * sizeof(void *)));
1209         kernarg = ArgPool->allocate(arg_num);
1210       }
1211       if (!kernarg) {
1212         DP("Allocate kernarg failed\n");
1213         return OFFLOAD_FAIL;
1214       }
1215 
1216       // Copy explicit arguments
1217       for (int i = 0; i < arg_num; i++) {
1218         memcpy((char *)kernarg + sizeof(void *) * i, args[i], sizeof(void *));
1219       }
1220 
1221       // Initialize implicit arguments. TODO: Which of these can be dropped
1222       impl_implicit_args_t *impl_args =
1223           reinterpret_cast<impl_implicit_args_t *>(
1224               static_cast<char *>(kernarg) + ArgPool->kernarg_segment_size);
1225       memset(impl_args, 0,
1226              sizeof(impl_implicit_args_t)); // may not be necessary
1227       impl_args->offset_x = 0;
1228       impl_args->offset_y = 0;
1229       impl_args->offset_z = 0;
1230 
1231       // assign a hostcall buffer for the selected Q
1232       if (__atomic_load_n(&DeviceInfo.hostcall_required, __ATOMIC_ACQUIRE)) {
1233         // hostrpc_assign_buffer is not thread safe, and this function is
1234         // under a multiple reader lock, not a writer lock.
1235         static pthread_mutex_t hostcall_init_lock = PTHREAD_MUTEX_INITIALIZER;
1236         pthread_mutex_lock(&hostcall_init_lock);
1237         uint64_t buffer = hostrpc_assign_buffer(DeviceInfo.HSAAgents[device_id],
1238                                                 queue, device_id);
1239         pthread_mutex_unlock(&hostcall_init_lock);
1240         if (!buffer) {
1241           DP("hostrpc_assign_buffer failed, gpu would dereference null and "
1242              "error\n");
1243           return OFFLOAD_FAIL;
1244         }
1245 
1246         DP("Implicit argument count: %d\n",
1247            KernelInfoEntry.implicit_argument_count);
1248         if (KernelInfoEntry.implicit_argument_count >= 4) {
1249           // Initialise pointer for implicit_argument_count != 0 ABI
1250           // Guess that the right implicit argument is at offset 24 after
1251           // the explicit arguments. In the future, should be able to read
1252           // the offset from msgpack. Clang is not annotating it at present.
1253           uint64_t Offset =
1254               sizeof(void *) * (KernelInfoEntry.explicit_argument_count + 3);
1255           if ((Offset + 8) > ArgPool->kernarg_size_including_implicit()) {
1256             DP("Bad offset of hostcall: %lu, exceeds kernarg size w/ implicit "
1257                "args: %d\n",
1258                Offset + 8, ArgPool->kernarg_size_including_implicit());
1259           } else {
1260             memcpy(static_cast<char *>(kernarg) + Offset, &buffer, 8);
1261           }
1262         }
1263 
1264         // initialise pointer for implicit_argument_count == 0 ABI
1265         impl_args->hostcall_ptr = buffer;
1266       }
1267 
1268       packet->kernarg_address = kernarg;
1269     }
1270 
1271     hsa_signal_t s = DeviceInfo.FreeSignalPool.pop();
1272     if (s.handle == 0) {
1273       DP("Failed to get signal instance\n");
1274       return OFFLOAD_FAIL;
1275     }
1276     packet->completion_signal = s;
1277     hsa_signal_store_relaxed(packet->completion_signal, 1);
1278 
1279     // Publish the packet indicating it is ready to be processed
1280     core::packet_store_release(reinterpret_cast<uint32_t *>(packet),
1281                                core::create_header(), packet->setup);
1282 
1283     // Since the packet is already published, its contents must not be
1284     // accessed any more
1285     hsa_signal_store_relaxed(queue->doorbell_signal, packet_id);
1286 
1287     while (hsa_signal_wait_scacquire(s, HSA_SIGNAL_CONDITION_EQ, 0, UINT64_MAX,
1288                                      HSA_WAIT_STATE_BLOCKED) != 0)
1289       ;
1290 
1291     assert(ArgPool);
1292     ArgPool->deallocate(kernarg);
1293     DeviceInfo.FreeSignalPool.push(s);
1294   }
1295 
1296   DP("Kernel completed\n");
1297   return OFFLOAD_SUCCESS;
1298 }
1299 
1300 bool elf_machine_id_is_amdgcn(__tgt_device_image *image) {
1301   const uint16_t amdgcnMachineID = 224; // EM_AMDGPU may not be in system elf.h
1302   int32_t r = elf_check_machine(image, amdgcnMachineID);
1303   if (!r) {
1304     DP("Supported machine ID not found\n");
1305   }
1306   return r;
1307 }
1308 
1309 uint32_t elf_e_flags(__tgt_device_image *image) {
1310   char *img_begin = (char *)image->ImageStart;
1311   size_t img_size = (char *)image->ImageEnd - img_begin;
1312 
1313   Elf *e = elf_memory(img_begin, img_size);
1314   if (!e) {
1315     DP("Unable to get ELF handle: %s!\n", elf_errmsg(-1));
1316     return 0;
1317   }
1318 
1319   Elf64_Ehdr *eh64 = elf64_getehdr(e);
1320 
1321   if (!eh64) {
1322     DP("Unable to get machine ID from ELF file!\n");
1323     elf_end(e);
1324     return 0;
1325   }
1326 
1327   uint32_t Flags = eh64->e_flags;
1328 
1329   elf_end(e);
1330   DP("ELF Flags: 0x%x\n", Flags);
1331   return Flags;
1332 }
1333 
1334 template <typename T> bool enforce_upper_bound(T *value, T upper) {
1335   bool changed = *value > upper;
1336   if (changed) {
1337     *value = upper;
1338   }
1339   return changed;
1340 }
1341 
1342 Elf64_Shdr *find_only_SHT_HASH(Elf *elf) {
1343   size_t N;
1344   int rc = elf_getshdrnum(elf, &N);
1345   if (rc != 0) {
1346     return nullptr;
1347   }
1348 
1349   Elf64_Shdr *result = nullptr;
1350   for (size_t i = 0; i < N; i++) {
1351     Elf_Scn *scn = elf_getscn(elf, i);
1352     if (scn) {
1353       Elf64_Shdr *shdr = elf64_getshdr(scn);
1354       if (shdr) {
1355         if (shdr->sh_type == SHT_HASH) {
1356           if (result == nullptr) {
1357             result = shdr;
1358           } else {
1359             // multiple SHT_HASH sections not handled
1360             return nullptr;
1361           }
1362         }
1363       }
1364     }
1365   }
1366   return result;
1367 }
1368 
1369 const Elf64_Sym *elf_lookup(Elf *elf, char *base, Elf64_Shdr *section_hash,
1370                             const char *symname) {
1371 
1372   assert(section_hash);
1373   size_t section_symtab_index = section_hash->sh_link;
1374   Elf64_Shdr *section_symtab =
1375       elf64_getshdr(elf_getscn(elf, section_symtab_index));
1376   size_t section_strtab_index = section_symtab->sh_link;
1377 
1378   const Elf64_Sym *symtab =
1379       reinterpret_cast<const Elf64_Sym *>(base + section_symtab->sh_offset);
1380 
1381   const uint32_t *hashtab =
1382       reinterpret_cast<const uint32_t *>(base + section_hash->sh_offset);
1383 
1384   // Layout:
1385   // nbucket
1386   // nchain
1387   // bucket[nbucket]
1388   // chain[nchain]
1389   uint32_t nbucket = hashtab[0];
1390   const uint32_t *bucket = &hashtab[2];
1391   const uint32_t *chain = &hashtab[nbucket + 2];
1392 
1393   const size_t max = strlen(symname) + 1;
1394   const uint32_t hash = elf_hash(symname);
1395   for (uint32_t i = bucket[hash % nbucket]; i != 0; i = chain[i]) {
1396     char *n = elf_strptr(elf, section_strtab_index, symtab[i].st_name);
1397     if (strncmp(symname, n, max) == 0) {
1398       return &symtab[i];
1399     }
1400   }
1401 
1402   return nullptr;
1403 }
1404 
1405 struct symbol_info {
1406   void *addr = nullptr;
1407   uint32_t size = UINT32_MAX;
1408   uint32_t sh_type = SHT_NULL;
1409 };
1410 
1411 int get_symbol_info_without_loading(Elf *elf, char *base, const char *symname,
1412                                     symbol_info *res) {
1413   if (elf_kind(elf) != ELF_K_ELF) {
1414     return 1;
1415   }
1416 
1417   Elf64_Shdr *section_hash = find_only_SHT_HASH(elf);
1418   if (!section_hash) {
1419     return 1;
1420   }
1421 
1422   const Elf64_Sym *sym = elf_lookup(elf, base, section_hash, symname);
1423   if (!sym) {
1424     return 1;
1425   }
1426 
1427   if (sym->st_size > UINT32_MAX) {
1428     return 1;
1429   }
1430 
1431   if (sym->st_shndx == SHN_UNDEF) {
1432     return 1;
1433   }
1434 
1435   Elf_Scn *section = elf_getscn(elf, sym->st_shndx);
1436   if (!section) {
1437     return 1;
1438   }
1439 
1440   Elf64_Shdr *header = elf64_getshdr(section);
1441   if (!header) {
1442     return 1;
1443   }
1444 
1445   res->addr = sym->st_value + base;
1446   res->size = static_cast<uint32_t>(sym->st_size);
1447   res->sh_type = header->sh_type;
1448   return 0;
1449 }
1450 
1451 int get_symbol_info_without_loading(char *base, size_t img_size,
1452                                     const char *symname, symbol_info *res) {
1453   Elf *elf = elf_memory(base, img_size);
1454   if (elf) {
1455     int rc = get_symbol_info_without_loading(elf, base, symname, res);
1456     elf_end(elf);
1457     return rc;
1458   }
1459   return 1;
1460 }
1461 
1462 hsa_status_t interop_get_symbol_info(char *base, size_t img_size,
1463                                      const char *symname, void **var_addr,
1464                                      uint32_t *var_size) {
1465   symbol_info si;
1466   int rc = get_symbol_info_without_loading(base, img_size, symname, &si);
1467   if (rc == 0) {
1468     *var_addr = si.addr;
1469     *var_size = si.size;
1470     return HSA_STATUS_SUCCESS;
1471   } else {
1472     return HSA_STATUS_ERROR;
1473   }
1474 }
1475 
1476 template <typename C>
1477 hsa_status_t module_register_from_memory_to_place(
1478     std::map<std::string, atl_kernel_info_t> &KernelInfoTable,
1479     std::map<std::string, atl_symbol_info_t> &SymbolInfoTable,
1480     void *module_bytes, size_t module_size, int DeviceId, C cb,
1481     std::vector<hsa_executable_t> &HSAExecutables) {
1482   auto L = [](void *data, size_t size, void *cb_state) -> hsa_status_t {
1483     C *unwrapped = static_cast<C *>(cb_state);
1484     return (*unwrapped)(data, size);
1485   };
1486   return core::RegisterModuleFromMemory(
1487       KernelInfoTable, SymbolInfoTable, module_bytes, module_size,
1488       DeviceInfo.HSAAgents[DeviceId], L, static_cast<void *>(&cb),
1489       HSAExecutables);
1490 }
1491 
1492 uint64_t get_device_State_bytes(char *ImageStart, size_t img_size) {
1493   uint64_t device_State_bytes = 0;
1494   {
1495     // If this is the deviceRTL, get the state variable size
1496     symbol_info size_si;
1497     int rc = get_symbol_info_without_loading(
1498         ImageStart, img_size, "omptarget_nvptx_device_State_size", &size_si);
1499 
1500     if (rc == 0) {
1501       if (size_si.size != sizeof(uint64_t)) {
1502         DP("Found device_State_size variable with wrong size\n");
1503         return 0;
1504       }
1505 
1506       // Read number of bytes directly from the elf
1507       memcpy(&device_State_bytes, size_si.addr, sizeof(uint64_t));
1508     }
1509   }
1510   return device_State_bytes;
1511 }
1512 
1513 struct device_environment {
1514   // initialise an DeviceEnvironmentTy in the deviceRTL
1515   // patches around differences in the deviceRTL between trunk, aomp,
1516   // rocmcc. Over time these differences will tend to zero and this class
1517   // simplified.
1518   // Symbol may be in .data or .bss, and may be missing fields, todo:
1519   // review aomp/trunk/rocm and simplify the following
1520 
1521   // The symbol may also have been deadstripped because the device side
1522   // accessors were unused.
1523 
1524   // If the symbol is in .data (aomp, rocm) it can be written directly.
1525   // If it is in .bss, we must wait for it to be allocated space on the
1526   // gpu (trunk) and initialize after loading.
1527   const char *sym() { return "omptarget_device_environment"; }
1528 
1529   DeviceEnvironmentTy host_device_env;
1530   symbol_info si;
1531   bool valid = false;
1532 
1533   __tgt_device_image *image;
1534   const size_t img_size;
1535 
1536   device_environment(int device_id, int number_devices, int dynamic_mem_size,
1537                      __tgt_device_image *image, const size_t img_size)
1538       : image(image), img_size(img_size) {
1539 
1540     host_device_env.NumDevices = number_devices;
1541     host_device_env.DeviceNum = device_id;
1542     host_device_env.DebugKind = 0;
1543     host_device_env.DynamicMemSize = dynamic_mem_size;
1544     if (char *envStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG")) {
1545       host_device_env.DebugKind = std::stoi(envStr);
1546     }
1547 
1548     int rc = get_symbol_info_without_loading((char *)image->ImageStart,
1549                                              img_size, sym(), &si);
1550     if (rc != 0) {
1551       DP("Finding global device environment '%s' - symbol missing.\n", sym());
1552       return;
1553     }
1554 
1555     if (si.size > sizeof(host_device_env)) {
1556       DP("Symbol '%s' has size %u, expected at most %zu.\n", sym(), si.size,
1557          sizeof(host_device_env));
1558       return;
1559     }
1560 
1561     valid = true;
1562   }
1563 
1564   bool in_image() { return si.sh_type != SHT_NOBITS; }
1565 
1566   hsa_status_t before_loading(void *data, size_t size) {
1567     if (valid) {
1568       if (in_image()) {
1569         DP("Setting global device environment before load (%u bytes)\n",
1570            si.size);
1571         uint64_t offset = (char *)si.addr - (char *)image->ImageStart;
1572         void *pos = (char *)data + offset;
1573         memcpy(pos, &host_device_env, si.size);
1574       }
1575     }
1576     return HSA_STATUS_SUCCESS;
1577   }
1578 
1579   hsa_status_t after_loading() {
1580     if (valid) {
1581       if (!in_image()) {
1582         DP("Setting global device environment after load (%u bytes)\n",
1583            si.size);
1584         int device_id = host_device_env.DeviceNum;
1585         auto &SymbolInfo = DeviceInfo.SymbolInfoTable[device_id];
1586         void *state_ptr;
1587         uint32_t state_ptr_size;
1588         hsa_status_t err = interop_hsa_get_symbol_info(
1589             SymbolInfo, device_id, sym(), &state_ptr, &state_ptr_size);
1590         if (err != HSA_STATUS_SUCCESS) {
1591           DP("failed to find %s in loaded image\n", sym());
1592           return err;
1593         }
1594 
1595         if (state_ptr_size != si.size) {
1596           DP("Symbol had size %u before loading, %u after\n", state_ptr_size,
1597              si.size);
1598           return HSA_STATUS_ERROR;
1599         }
1600 
1601         return DeviceInfo.freesignalpool_memcpy_h2d(state_ptr, &host_device_env,
1602                                                     state_ptr_size, device_id);
1603       }
1604     }
1605     return HSA_STATUS_SUCCESS;
1606   }
1607 };
1608 
1609 hsa_status_t impl_calloc(void **ret_ptr, size_t size, int DeviceId) {
1610   uint64_t rounded = 4 * ((size + 3) / 4);
1611   void *ptr;
1612   hsa_amd_memory_pool_t MemoryPool = DeviceInfo.getDeviceMemoryPool(DeviceId);
1613   hsa_status_t err = hsa_amd_memory_pool_allocate(MemoryPool, rounded, 0, &ptr);
1614   if (err != HSA_STATUS_SUCCESS) {
1615     return err;
1616   }
1617 
1618   hsa_status_t rc = hsa_amd_memory_fill(ptr, 0, rounded / 4);
1619   if (rc != HSA_STATUS_SUCCESS) {
1620     DP("zero fill device_state failed with %u\n", rc);
1621     core::Runtime::Memfree(ptr);
1622     return HSA_STATUS_ERROR;
1623   }
1624 
1625   *ret_ptr = ptr;
1626   return HSA_STATUS_SUCCESS;
1627 }
1628 
1629 bool image_contains_symbol(void *data, size_t size, const char *sym) {
1630   symbol_info si;
1631   int rc = get_symbol_info_without_loading((char *)data, size, sym, &si);
1632   return (rc == 0) && (si.addr != nullptr);
1633 }
1634 
1635 } // namespace
1636 
1637 namespace core {
1638 hsa_status_t allow_access_to_all_gpu_agents(void *ptr) {
1639   return hsa_amd_agents_allow_access(DeviceInfo.HSAAgents.size(),
1640                                      &DeviceInfo.HSAAgents[0], NULL, ptr);
1641 }
1642 } // namespace core
1643 
1644 extern "C" {
1645 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
1646   return elf_machine_id_is_amdgcn(image);
1647 }
1648 
1649 int __tgt_rtl_number_of_devices() {
1650   // If the construction failed, no methods are safe to call
1651   if (DeviceInfo.ConstructionSucceeded) {
1652     return DeviceInfo.NumberOfDevices;
1653   } else {
1654     DP("AMDGPU plugin construction failed. Zero devices available\n");
1655     return 0;
1656   }
1657 }
1658 
1659 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
1660   DP("Init requires flags to %ld\n", RequiresFlags);
1661   DeviceInfo.RequiresFlags = RequiresFlags;
1662   return RequiresFlags;
1663 }
1664 
1665 int32_t __tgt_rtl_init_device(int device_id) {
1666   hsa_status_t err;
1667 
1668   // this is per device id init
1669   DP("Initialize the device id: %d\n", device_id);
1670 
1671   hsa_agent_t agent = DeviceInfo.HSAAgents[device_id];
1672 
1673   // Get number of Compute Unit
1674   uint32_t compute_units = 0;
1675   err = hsa_agent_get_info(
1676       agent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT,
1677       &compute_units);
1678   if (err != HSA_STATUS_SUCCESS) {
1679     DeviceInfo.ComputeUnits[device_id] = 1;
1680     DP("Error getting compute units : settiing to 1\n");
1681   } else {
1682     DeviceInfo.ComputeUnits[device_id] = compute_units;
1683     DP("Using %d compute unis per grid\n", DeviceInfo.ComputeUnits[device_id]);
1684   }
1685 
1686   char GetInfoName[64]; // 64 max size returned by get info
1687   err = hsa_agent_get_info(agent, (hsa_agent_info_t)HSA_AGENT_INFO_NAME,
1688                            (void *)GetInfoName);
1689   if (err)
1690     DeviceInfo.GPUName[device_id] = "--unknown gpu--";
1691   else {
1692     DeviceInfo.GPUName[device_id] = GetInfoName;
1693   }
1694 
1695   if (print_kernel_trace & STARTUP_DETAILS)
1696     DP("Device#%-2d CU's: %2d %s\n", device_id,
1697        DeviceInfo.ComputeUnits[device_id],
1698        DeviceInfo.GPUName[device_id].c_str());
1699 
1700   // Query attributes to determine number of threads/block and blocks/grid.
1701   uint16_t workgroup_max_dim[3];
1702   err = hsa_agent_get_info(agent, HSA_AGENT_INFO_WORKGROUP_MAX_DIM,
1703                            &workgroup_max_dim);
1704   if (err != HSA_STATUS_SUCCESS) {
1705     DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::DefaultNumTeams;
1706     DP("Error getting grid dims: num groups : %d\n",
1707        RTLDeviceInfoTy::DefaultNumTeams);
1708   } else if (workgroup_max_dim[0] <= RTLDeviceInfoTy::HardTeamLimit) {
1709     DeviceInfo.GroupsPerDevice[device_id] = workgroup_max_dim[0];
1710     DP("Using %d ROCm blocks per grid\n",
1711        DeviceInfo.GroupsPerDevice[device_id]);
1712   } else {
1713     DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::HardTeamLimit;
1714     DP("Max ROCm blocks per grid %d exceeds the hard team limit %d, capping "
1715        "at the hard limit\n",
1716        workgroup_max_dim[0], RTLDeviceInfoTy::HardTeamLimit);
1717   }
1718 
1719   // Get thread limit
1720   hsa_dim3_t grid_max_dim;
1721   err = hsa_agent_get_info(agent, HSA_AGENT_INFO_GRID_MAX_DIM, &grid_max_dim);
1722   if (err == HSA_STATUS_SUCCESS) {
1723     DeviceInfo.ThreadsPerGroup[device_id] =
1724         reinterpret_cast<uint32_t *>(&grid_max_dim)[0] /
1725         DeviceInfo.GroupsPerDevice[device_id];
1726 
1727     if (DeviceInfo.ThreadsPerGroup[device_id] == 0) {
1728       DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size;
1729       DP("Default thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size);
1730     } else if (enforce_upper_bound(&DeviceInfo.ThreadsPerGroup[device_id],
1731                                    RTLDeviceInfoTy::Max_WG_Size)) {
1732       DP("Capped thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size);
1733     } else {
1734       DP("Using ROCm Queried thread limit: %d\n",
1735          DeviceInfo.ThreadsPerGroup[device_id]);
1736     }
1737   } else {
1738     DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size;
1739     DP("Error getting max block dimension, use default:%d \n",
1740        RTLDeviceInfoTy::Max_WG_Size);
1741   }
1742 
1743   // Get wavefront size
1744   uint32_t wavefront_size = 0;
1745   err =
1746       hsa_agent_get_info(agent, HSA_AGENT_INFO_WAVEFRONT_SIZE, &wavefront_size);
1747   if (err == HSA_STATUS_SUCCESS) {
1748     DP("Queried wavefront size: %d\n", wavefront_size);
1749     DeviceInfo.WarpSize[device_id] = wavefront_size;
1750   } else {
1751     // TODO: Burn the wavefront size into the code object
1752     DP("Warning: Unknown wavefront size, assuming 64\n");
1753     DeviceInfo.WarpSize[device_id] = 64;
1754   }
1755 
1756   // Adjust teams to the env variables
1757 
1758   if (DeviceInfo.Env.TeamLimit > 0 &&
1759       (enforce_upper_bound(&DeviceInfo.GroupsPerDevice[device_id],
1760                            DeviceInfo.Env.TeamLimit))) {
1761     DP("Capping max groups per device to OMP_TEAM_LIMIT=%d\n",
1762        DeviceInfo.Env.TeamLimit);
1763   }
1764 
1765   // Set default number of teams
1766   if (DeviceInfo.Env.NumTeams > 0) {
1767     DeviceInfo.NumTeams[device_id] = DeviceInfo.Env.NumTeams;
1768     DP("Default number of teams set according to environment %d\n",
1769        DeviceInfo.Env.NumTeams);
1770   } else {
1771     char *TeamsPerCUEnvStr = getenv("OMP_TARGET_TEAMS_PER_PROC");
1772     int TeamsPerCU = DefaultTeamsPerCU;
1773     if (TeamsPerCUEnvStr) {
1774       TeamsPerCU = std::stoi(TeamsPerCUEnvStr);
1775     }
1776 
1777     DeviceInfo.NumTeams[device_id] =
1778         TeamsPerCU * DeviceInfo.ComputeUnits[device_id];
1779     DP("Default number of teams = %d * number of compute units %d\n",
1780        TeamsPerCU, DeviceInfo.ComputeUnits[device_id]);
1781   }
1782 
1783   if (enforce_upper_bound(&DeviceInfo.NumTeams[device_id],
1784                           DeviceInfo.GroupsPerDevice[device_id])) {
1785     DP("Default number of teams exceeds device limit, capping at %d\n",
1786        DeviceInfo.GroupsPerDevice[device_id]);
1787   }
1788 
1789   // Adjust threads to the env variables
1790   if (DeviceInfo.Env.TeamThreadLimit > 0 &&
1791       (enforce_upper_bound(&DeviceInfo.NumThreads[device_id],
1792                            DeviceInfo.Env.TeamThreadLimit))) {
1793     DP("Capping max number of threads to OMP_TEAMS_THREAD_LIMIT=%d\n",
1794        DeviceInfo.Env.TeamThreadLimit);
1795   }
1796 
1797   // Set default number of threads
1798   DeviceInfo.NumThreads[device_id] = RTLDeviceInfoTy::Default_WG_Size;
1799   DP("Default number of threads set according to library's default %d\n",
1800      RTLDeviceInfoTy::Default_WG_Size);
1801   if (enforce_upper_bound(&DeviceInfo.NumThreads[device_id],
1802                           DeviceInfo.ThreadsPerGroup[device_id])) {
1803     DP("Default number of threads exceeds device limit, capping at %d\n",
1804        DeviceInfo.ThreadsPerGroup[device_id]);
1805   }
1806 
1807   DP("Device %d: default limit for groupsPerDevice %d & threadsPerGroup %d\n",
1808      device_id, DeviceInfo.GroupsPerDevice[device_id],
1809      DeviceInfo.ThreadsPerGroup[device_id]);
1810 
1811   DP("Device %d: wavefront size %d, total threads %d x %d = %d\n", device_id,
1812      DeviceInfo.WarpSize[device_id], DeviceInfo.ThreadsPerGroup[device_id],
1813      DeviceInfo.GroupsPerDevice[device_id],
1814      DeviceInfo.GroupsPerDevice[device_id] *
1815          DeviceInfo.ThreadsPerGroup[device_id]);
1816 
1817   return OFFLOAD_SUCCESS;
1818 }
1819 
1820 static __tgt_target_table *
1821 __tgt_rtl_load_binary_locked(int32_t device_id, __tgt_device_image *image);
1822 
1823 __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
1824                                           __tgt_device_image *image) {
1825   DeviceInfo.load_run_lock.lock();
1826   __tgt_target_table *res = __tgt_rtl_load_binary_locked(device_id, image);
1827   DeviceInfo.load_run_lock.unlock();
1828   return res;
1829 }
1830 
1831 __tgt_target_table *__tgt_rtl_load_binary_locked(int32_t device_id,
1832                                                  __tgt_device_image *image) {
1833   // This function loads the device image onto gpu[device_id] and does other
1834   // per-image initialization work. Specifically:
1835   //
1836   // - Initialize an DeviceEnvironmentTy instance embedded in the
1837   //   image at the symbol "omptarget_device_environment"
1838   //   Fields DebugKind, DeviceNum, NumDevices. Used by the deviceRTL.
1839   //
1840   // - Allocate a large array per-gpu (could be moved to init_device)
1841   //   - Read a uint64_t at symbol omptarget_nvptx_device_State_size
1842   //   - Allocate at least that many bytes of gpu memory
1843   //   - Zero initialize it
1844   //   - Write the pointer to the symbol omptarget_nvptx_device_State
1845   //
1846   // - Pulls some per-kernel information together from various sources and
1847   //   records it in the KernelsList for quicker access later
1848   //
1849   // The initialization can be done before or after loading the image onto the
1850   // gpu. This function presently does a mixture. Using the hsa api to get/set
1851   // the information is simpler to implement, in exchange for more complicated
1852   // runtime behaviour. E.g. launching a kernel or using dma to get eight bytes
1853   // back from the gpu vs a hashtable lookup on the host.
1854 
1855   const size_t img_size = (char *)image->ImageEnd - (char *)image->ImageStart;
1856 
1857   DeviceInfo.clearOffloadEntriesTable(device_id);
1858 
1859   // We do not need to set the ELF version because the caller of this function
1860   // had to do that to decide the right runtime to use
1861 
1862   if (!elf_machine_id_is_amdgcn(image)) {
1863     return NULL;
1864   }
1865 
1866   {
1867     auto env =
1868         device_environment(device_id, DeviceInfo.NumberOfDevices,
1869                            DeviceInfo.Env.DynamicMemSize, image, img_size);
1870 
1871     auto &KernelInfo = DeviceInfo.KernelInfoTable[device_id];
1872     auto &SymbolInfo = DeviceInfo.SymbolInfoTable[device_id];
1873     hsa_status_t err = module_register_from_memory_to_place(
1874         KernelInfo, SymbolInfo, (void *)image->ImageStart, img_size, device_id,
1875         [&](void *data, size_t size) {
1876           if (image_contains_symbol(data, size, "needs_hostcall_buffer")) {
1877             __atomic_store_n(&DeviceInfo.hostcall_required, true,
1878                              __ATOMIC_RELEASE);
1879           }
1880           return env.before_loading(data, size);
1881         },
1882         DeviceInfo.HSAExecutables);
1883 
1884     check("Module registering", err);
1885     if (err != HSA_STATUS_SUCCESS) {
1886       const char *DeviceName = DeviceInfo.GPUName[device_id].c_str();
1887       const char *ElfName = get_elf_mach_gfx_name(elf_e_flags(image));
1888 
1889       if (strcmp(DeviceName, ElfName) != 0) {
1890         DP("Possible gpu arch mismatch: device:%s, image:%s please check"
1891            " compiler flag: -march=<gpu>\n",
1892            DeviceName, ElfName);
1893       } else {
1894         DP("Error loading image onto GPU: %s\n", get_error_string(err));
1895       }
1896 
1897       return NULL;
1898     }
1899 
1900     err = env.after_loading();
1901     if (err != HSA_STATUS_SUCCESS) {
1902       return NULL;
1903     }
1904   }
1905 
1906   DP("AMDGPU module successfully loaded!\n");
1907 
1908   {
1909     // the device_State array is either large value in bss or a void* that
1910     // needs to be assigned to a pointer to an array of size device_state_bytes
1911     // If absent, it has been deadstripped and needs no setup.
1912 
1913     void *state_ptr;
1914     uint32_t state_ptr_size;
1915     auto &SymbolInfoMap = DeviceInfo.SymbolInfoTable[device_id];
1916     hsa_status_t err = interop_hsa_get_symbol_info(
1917         SymbolInfoMap, device_id, "omptarget_nvptx_device_State", &state_ptr,
1918         &state_ptr_size);
1919 
1920     if (err != HSA_STATUS_SUCCESS) {
1921       DP("No device_state symbol found, skipping initialization\n");
1922     } else {
1923       if (state_ptr_size < sizeof(void *)) {
1924         DP("unexpected size of state_ptr %u != %zu\n", state_ptr_size,
1925            sizeof(void *));
1926         return NULL;
1927       }
1928 
1929       // if it's larger than a void*, assume it's a bss array and no further
1930       // initialization is required. Only try to set up a pointer for
1931       // sizeof(void*)
1932       if (state_ptr_size == sizeof(void *)) {
1933         uint64_t device_State_bytes =
1934             get_device_State_bytes((char *)image->ImageStart, img_size);
1935         if (device_State_bytes == 0) {
1936           DP("Can't initialize device_State, missing size information\n");
1937           return NULL;
1938         }
1939 
1940         auto &dss = DeviceInfo.deviceStateStore[device_id];
1941         if (dss.first.get() == nullptr) {
1942           assert(dss.second == 0);
1943           void *ptr = NULL;
1944           hsa_status_t err = impl_calloc(&ptr, device_State_bytes, device_id);
1945           if (err != HSA_STATUS_SUCCESS) {
1946             DP("Failed to allocate device_state array\n");
1947             return NULL;
1948           }
1949           dss = {
1950               std::unique_ptr<void, RTLDeviceInfoTy::implFreePtrDeletor>{ptr},
1951               device_State_bytes,
1952           };
1953         }
1954 
1955         void *ptr = dss.first.get();
1956         if (device_State_bytes != dss.second) {
1957           DP("Inconsistent sizes of device_State unsupported\n");
1958           return NULL;
1959         }
1960 
1961         // write ptr to device memory so it can be used by later kernels
1962         err = DeviceInfo.freesignalpool_memcpy_h2d(state_ptr, &ptr,
1963                                                    sizeof(void *), device_id);
1964         if (err != HSA_STATUS_SUCCESS) {
1965           DP("memcpy install of state_ptr failed\n");
1966           return NULL;
1967         }
1968       }
1969     }
1970   }
1971 
1972   // Here, we take advantage of the data that is appended after img_end to get
1973   // the symbols' name we need to load. This data consist of the host entries
1974   // begin and end as well as the target name (see the offloading linker script
1975   // creation in clang compiler).
1976 
1977   // Find the symbols in the module by name. The name can be obtain by
1978   // concatenating the host entry name with the target name
1979 
1980   __tgt_offload_entry *HostBegin = image->EntriesBegin;
1981   __tgt_offload_entry *HostEnd = image->EntriesEnd;
1982 
1983   for (__tgt_offload_entry *e = HostBegin; e != HostEnd; ++e) {
1984 
1985     if (!e->addr) {
1986       // The host should have always something in the address to
1987       // uniquely identify the target region.
1988       DP("Analyzing host entry '<null>' (size = %lld)...\n",
1989          (unsigned long long)e->size);
1990       return NULL;
1991     }
1992 
1993     if (e->size) {
1994       __tgt_offload_entry entry = *e;
1995 
1996       void *varptr;
1997       uint32_t varsize;
1998 
1999       auto &SymbolInfoMap = DeviceInfo.SymbolInfoTable[device_id];
2000       hsa_status_t err = interop_hsa_get_symbol_info(
2001           SymbolInfoMap, device_id, e->name, &varptr, &varsize);
2002 
2003       if (err != HSA_STATUS_SUCCESS) {
2004         // Inform the user what symbol prevented offloading
2005         DP("Loading global '%s' (Failed)\n", e->name);
2006         return NULL;
2007       }
2008 
2009       if (varsize != e->size) {
2010         DP("Loading global '%s' - size mismatch (%u != %lu)\n", e->name,
2011            varsize, e->size);
2012         return NULL;
2013       }
2014 
2015       DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
2016          DPxPTR(e - HostBegin), e->name, DPxPTR(varptr));
2017       entry.addr = (void *)varptr;
2018 
2019       DeviceInfo.addOffloadEntry(device_id, entry);
2020 
2021       if (DeviceInfo.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
2022           e->flags & OMP_DECLARE_TARGET_LINK) {
2023         // If unified memory is present any target link variables
2024         // can access host addresses directly. There is no longer a
2025         // need for device copies.
2026         err = DeviceInfo.freesignalpool_memcpy_h2d(varptr, e->addr,
2027                                                    sizeof(void *), device_id);
2028         if (err != HSA_STATUS_SUCCESS)
2029           DP("Error when copying USM\n");
2030         DP("Copy linked variable host address (" DPxMOD ")"
2031            "to device address (" DPxMOD ")\n",
2032            DPxPTR(*((void **)e->addr)), DPxPTR(varptr));
2033       }
2034 
2035       continue;
2036     }
2037 
2038     DP("to find the kernel name: %s size: %lu\n", e->name, strlen(e->name));
2039 
2040     // errors in kernarg_segment_size previously treated as = 0 (or as undef)
2041     uint32_t kernarg_segment_size = 0;
2042     auto &KernelInfoMap = DeviceInfo.KernelInfoTable[device_id];
2043     hsa_status_t err = HSA_STATUS_SUCCESS;
2044     if (!e->name) {
2045       err = HSA_STATUS_ERROR;
2046     } else {
2047       std::string kernelStr = std::string(e->name);
2048       auto It = KernelInfoMap.find(kernelStr);
2049       if (It != KernelInfoMap.end()) {
2050         atl_kernel_info_t info = It->second;
2051         kernarg_segment_size = info.kernel_segment_size;
2052       } else {
2053         err = HSA_STATUS_ERROR;
2054       }
2055     }
2056 
2057     // default value GENERIC (in case symbol is missing from cubin file)
2058     llvm::omp::OMPTgtExecModeFlags ExecModeVal =
2059         llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC;
2060 
2061     // get flat group size if present, else Default_WG_Size
2062     int16_t WGSizeVal = RTLDeviceInfoTy::Default_WG_Size;
2063 
2064     // get Kernel Descriptor if present.
2065     // Keep struct in sync wih getTgtAttributeStructQTy in CGOpenMPRuntime.cpp
2066     struct KernDescValType {
2067       uint16_t Version;
2068       uint16_t TSize;
2069       uint16_t WG_Size;
2070     };
2071     struct KernDescValType KernDescVal;
2072     std::string KernDescNameStr(e->name);
2073     KernDescNameStr += "_kern_desc";
2074     const char *KernDescName = KernDescNameStr.c_str();
2075 
2076     void *KernDescPtr;
2077     uint32_t KernDescSize;
2078     void *CallStackAddr = nullptr;
2079     err = interop_get_symbol_info((char *)image->ImageStart, img_size,
2080                                   KernDescName, &KernDescPtr, &KernDescSize);
2081 
2082     if (err == HSA_STATUS_SUCCESS) {
2083       if ((size_t)KernDescSize != sizeof(KernDescVal))
2084         DP("Loading global computation properties '%s' - size mismatch (%u != "
2085            "%lu)\n",
2086            KernDescName, KernDescSize, sizeof(KernDescVal));
2087 
2088       memcpy(&KernDescVal, KernDescPtr, (size_t)KernDescSize);
2089 
2090       // Check structure size against recorded size.
2091       if ((size_t)KernDescSize != KernDescVal.TSize)
2092         DP("KernDescVal size %lu does not match advertized size %d for '%s'\n",
2093            sizeof(KernDescVal), KernDescVal.TSize, KernDescName);
2094 
2095       DP("After loading global for %s KernDesc \n", KernDescName);
2096       DP("KernDesc: Version: %d\n", KernDescVal.Version);
2097       DP("KernDesc: TSize: %d\n", KernDescVal.TSize);
2098       DP("KernDesc: WG_Size: %d\n", KernDescVal.WG_Size);
2099 
2100       if (KernDescVal.WG_Size == 0) {
2101         KernDescVal.WG_Size = RTLDeviceInfoTy::Default_WG_Size;
2102         DP("Setting KernDescVal.WG_Size to default %d\n", KernDescVal.WG_Size);
2103       }
2104       WGSizeVal = KernDescVal.WG_Size;
2105       DP("WGSizeVal %d\n", WGSizeVal);
2106       check("Loading KernDesc computation property", err);
2107     } else {
2108       DP("Warning: Loading KernDesc '%s' - symbol not found, ", KernDescName);
2109 
2110       // Flat group size
2111       std::string WGSizeNameStr(e->name);
2112       WGSizeNameStr += "_wg_size";
2113       const char *WGSizeName = WGSizeNameStr.c_str();
2114 
2115       void *WGSizePtr;
2116       uint32_t WGSize;
2117       err = interop_get_symbol_info((char *)image->ImageStart, img_size,
2118                                     WGSizeName, &WGSizePtr, &WGSize);
2119 
2120       if (err == HSA_STATUS_SUCCESS) {
2121         if ((size_t)WGSize != sizeof(int16_t)) {
2122           DP("Loading global computation properties '%s' - size mismatch (%u "
2123              "!= "
2124              "%lu)\n",
2125              WGSizeName, WGSize, sizeof(int16_t));
2126           return NULL;
2127         }
2128 
2129         memcpy(&WGSizeVal, WGSizePtr, (size_t)WGSize);
2130 
2131         DP("After loading global for %s WGSize = %d\n", WGSizeName, WGSizeVal);
2132 
2133         if (WGSizeVal < RTLDeviceInfoTy::Default_WG_Size ||
2134             WGSizeVal > RTLDeviceInfoTy::Max_WG_Size) {
2135           DP("Error wrong WGSize value specified in HSA code object file: "
2136              "%d\n",
2137              WGSizeVal);
2138           WGSizeVal = RTLDeviceInfoTy::Default_WG_Size;
2139         }
2140       } else {
2141         DP("Warning: Loading WGSize '%s' - symbol not found, "
2142            "using default value %d\n",
2143            WGSizeName, WGSizeVal);
2144       }
2145 
2146       check("Loading WGSize computation property", err);
2147     }
2148 
2149     // Read execution mode from global in binary
2150     std::string ExecModeNameStr(e->name);
2151     ExecModeNameStr += "_exec_mode";
2152     const char *ExecModeName = ExecModeNameStr.c_str();
2153 
2154     void *ExecModePtr;
2155     uint32_t varsize;
2156     err = interop_get_symbol_info((char *)image->ImageStart, img_size,
2157                                   ExecModeName, &ExecModePtr, &varsize);
2158 
2159     if (err == HSA_STATUS_SUCCESS) {
2160       if ((size_t)varsize != sizeof(llvm::omp::OMPTgtExecModeFlags)) {
2161         DP("Loading global computation properties '%s' - size mismatch(%u != "
2162            "%lu)\n",
2163            ExecModeName, varsize, sizeof(llvm::omp::OMPTgtExecModeFlags));
2164         return NULL;
2165       }
2166 
2167       memcpy(&ExecModeVal, ExecModePtr, (size_t)varsize);
2168 
2169       DP("After loading global for %s ExecMode = %d\n", ExecModeName,
2170          ExecModeVal);
2171 
2172       if (ExecModeVal < 0 ||
2173           ExecModeVal > llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD) {
2174         DP("Error wrong exec_mode value specified in HSA code object file: "
2175            "%d\n",
2176            ExecModeVal);
2177         return NULL;
2178       }
2179     } else {
2180       DP("Loading global exec_mode '%s' - symbol missing, using default "
2181          "value "
2182          "GENERIC (1)\n",
2183          ExecModeName);
2184     }
2185     check("Loading computation property", err);
2186 
2187     KernelsList.push_back(KernelTy(ExecModeVal, WGSizeVal, device_id,
2188                                    CallStackAddr, e->name, kernarg_segment_size,
2189                                    DeviceInfo.KernArgPool));
2190     __tgt_offload_entry entry = *e;
2191     entry.addr = (void *)&KernelsList.back();
2192     DeviceInfo.addOffloadEntry(device_id, entry);
2193     DP("Entry point %ld maps to %s\n", e - HostBegin, e->name);
2194   }
2195 
2196   return DeviceInfo.getOffloadEntriesTable(device_id);
2197 }
2198 
2199 void *__tgt_rtl_data_alloc(int device_id, int64_t size, void *, int32_t kind) {
2200   void *ptr = NULL;
2201   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2202 
2203   if (kind != TARGET_ALLOC_DEFAULT) {
2204     REPORT("Invalid target data allocation kind or requested allocator not "
2205            "implemented yet\n");
2206     return NULL;
2207   }
2208 
2209   hsa_amd_memory_pool_t MemoryPool = DeviceInfo.getDeviceMemoryPool(device_id);
2210   hsa_status_t err = hsa_amd_memory_pool_allocate(MemoryPool, size, 0, &ptr);
2211   DP("Tgt alloc data %ld bytes, (tgt:%016llx).\n", size,
2212      (long long unsigned)(Elf64_Addr)ptr);
2213   ptr = (err == HSA_STATUS_SUCCESS) ? ptr : NULL;
2214   return ptr;
2215 }
2216 
2217 int32_t __tgt_rtl_data_submit(int device_id, void *tgt_ptr, void *hst_ptr,
2218                               int64_t size) {
2219   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2220   __tgt_async_info AsyncInfo;
2221   int32_t rc = dataSubmit(device_id, tgt_ptr, hst_ptr, size, &AsyncInfo);
2222   if (rc != OFFLOAD_SUCCESS)
2223     return OFFLOAD_FAIL;
2224 
2225   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
2226 }
2227 
2228 int32_t __tgt_rtl_data_submit_async(int device_id, void *tgt_ptr, void *hst_ptr,
2229                                     int64_t size, __tgt_async_info *AsyncInfo) {
2230   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2231   if (AsyncInfo) {
2232     initAsyncInfo(AsyncInfo);
2233     return dataSubmit(device_id, tgt_ptr, hst_ptr, size, AsyncInfo);
2234   } else {
2235     return __tgt_rtl_data_submit(device_id, tgt_ptr, hst_ptr, size);
2236   }
2237 }
2238 
2239 int32_t __tgt_rtl_data_retrieve(int device_id, void *hst_ptr, void *tgt_ptr,
2240                                 int64_t size) {
2241   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2242   __tgt_async_info AsyncInfo;
2243   int32_t rc = dataRetrieve(device_id, hst_ptr, tgt_ptr, size, &AsyncInfo);
2244   if (rc != OFFLOAD_SUCCESS)
2245     return OFFLOAD_FAIL;
2246 
2247   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
2248 }
2249 
2250 int32_t __tgt_rtl_data_retrieve_async(int device_id, void *hst_ptr,
2251                                       void *tgt_ptr, int64_t size,
2252                                       __tgt_async_info *AsyncInfo) {
2253   assert(AsyncInfo && "AsyncInfo is nullptr");
2254   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2255   initAsyncInfo(AsyncInfo);
2256   return dataRetrieve(device_id, hst_ptr, tgt_ptr, size, AsyncInfo);
2257 }
2258 
2259 int32_t __tgt_rtl_data_delete(int device_id, void *tgt_ptr) {
2260   assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large");
2261   hsa_status_t err;
2262   DP("Tgt free data (tgt:%016llx).\n", (long long unsigned)(Elf64_Addr)tgt_ptr);
2263   err = core::Runtime::Memfree(tgt_ptr);
2264   if (err != HSA_STATUS_SUCCESS) {
2265     DP("Error when freeing CUDA memory\n");
2266     return OFFLOAD_FAIL;
2267   }
2268   return OFFLOAD_SUCCESS;
2269 }
2270 
2271 int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
2272                                          void **tgt_args,
2273                                          ptrdiff_t *tgt_offsets,
2274                                          int32_t arg_num, int32_t num_teams,
2275                                          int32_t thread_limit,
2276                                          uint64_t loop_tripcount) {
2277 
2278   DeviceInfo.load_run_lock.lock_shared();
2279   int32_t res =
2280       runRegionLocked(device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
2281                       num_teams, thread_limit, loop_tripcount);
2282 
2283   DeviceInfo.load_run_lock.unlock_shared();
2284   return res;
2285 }
2286 
2287 int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
2288                                     void **tgt_args, ptrdiff_t *tgt_offsets,
2289                                     int32_t arg_num) {
2290   // use one team and one thread
2291   // fix thread num
2292   int32_t team_num = 1;
2293   int32_t thread_limit = 0; // use default
2294   return __tgt_rtl_run_target_team_region(device_id, tgt_entry_ptr, tgt_args,
2295                                           tgt_offsets, arg_num, team_num,
2296                                           thread_limit, 0);
2297 }
2298 
2299 int32_t __tgt_rtl_run_target_team_region_async(
2300     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
2301     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t num_teams,
2302     int32_t thread_limit, uint64_t loop_tripcount,
2303     __tgt_async_info *AsyncInfo) {
2304   assert(AsyncInfo && "AsyncInfo is nullptr");
2305   initAsyncInfo(AsyncInfo);
2306 
2307   DeviceInfo.load_run_lock.lock_shared();
2308   int32_t res =
2309       runRegionLocked(device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
2310                       num_teams, thread_limit, loop_tripcount);
2311 
2312   DeviceInfo.load_run_lock.unlock_shared();
2313   return res;
2314 }
2315 
2316 int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
2317                                           void *tgt_entry_ptr, void **tgt_args,
2318                                           ptrdiff_t *tgt_offsets,
2319                                           int32_t arg_num,
2320                                           __tgt_async_info *AsyncInfo) {
2321   // use one team and one thread
2322   // fix thread num
2323   int32_t team_num = 1;
2324   int32_t thread_limit = 0; // use default
2325   return __tgt_rtl_run_target_team_region_async(
2326       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
2327       thread_limit, 0, AsyncInfo);
2328 }
2329 
2330 int32_t __tgt_rtl_synchronize(int32_t device_id, __tgt_async_info *AsyncInfo) {
2331   assert(AsyncInfo && "AsyncInfo is nullptr");
2332 
2333   // Cuda asserts that AsyncInfo->Queue is non-null, but this invariant
2334   // is not ensured by devices.cpp for amdgcn
2335   // assert(AsyncInfo->Queue && "AsyncInfo->Queue is nullptr");
2336   if (AsyncInfo->Queue) {
2337     finiAsyncInfo(AsyncInfo);
2338   }
2339   return OFFLOAD_SUCCESS;
2340 }
2341 } // extern "C"
2342