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