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