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