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