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