1 //===-- Implementation of crt for amdgpu ----------------------------------===// 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 #include "src/__support/GPU/utils.h" 10 #include "src/__support/RPC/rpc_client.h" 11 #include "src/__support/macros/config.h" 12 #include "src/stdlib/atexit.h" 13 #include "src/stdlib/exit.h" 14 15 extern "C" int main(int argc, char **argv, char **envp); 16 17 namespace LIBC_NAMESPACE_DECL { 18 19 extern "C" uintptr_t __init_array_start[]; 20 extern "C" uintptr_t __init_array_end[]; 21 extern "C" uintptr_t __fini_array_start[]; 22 extern "C" uintptr_t __fini_array_end[]; 23 24 using InitCallback = void(int, char **, char **); 25 using FiniCallback = void(void); 26 27 static void call_init_array_callbacks(int argc, char **argv, char **env) { 28 size_t init_array_size = __init_array_end - __init_array_start; 29 for (size_t i = 0; i < init_array_size; ++i) 30 reinterpret_cast<InitCallback *>(__init_array_start[i])(argc, argv, env); 31 } 32 33 static void call_fini_array_callbacks() { 34 size_t fini_array_size = __fini_array_end - __fini_array_start; 35 for (size_t i = fini_array_size; i > 0; --i) 36 reinterpret_cast<FiniCallback *>(__fini_array_start[i - 1])(); 37 } 38 39 } // namespace LIBC_NAMESPACE_DECL 40 41 extern "C" [[gnu::visibility("protected"), clang::amdgpu_kernel]] void 42 _begin(int argc, char **argv, char **env) { 43 // We want the fini array callbacks to be run after other atexit 44 // callbacks are run. So, we register them before running the init 45 // array callbacks as they can potentially register their own atexit 46 // callbacks. 47 LIBC_NAMESPACE::atexit(&LIBC_NAMESPACE::call_fini_array_callbacks); 48 LIBC_NAMESPACE::call_init_array_callbacks(argc, argv, env); 49 } 50 51 extern "C" [[gnu::visibility("protected"), clang::amdgpu_kernel]] void 52 _start(int argc, char **argv, char **envp, int *ret) { 53 // Invoke the 'main' function with every active thread that the user launched 54 // the _start kernel with. 55 __atomic_fetch_or(ret, main(argc, argv, envp), __ATOMIC_RELAXED); 56 } 57 58 extern "C" [[gnu::visibility("protected"), clang::amdgpu_kernel]] void 59 _end(int retval) { 60 // Only a single thread should call `exit` here, the rest should gracefully 61 // return from the kernel. This is so only one thread calls the destructors 62 // registred with 'atexit' above. 63 LIBC_NAMESPACE::exit(retval); 64 } 65