Debian Codegraph @

openmp/device/src/Allocator.cpp

raw
1 //===------ State.cpp - OpenMP State & ICV interface ------------- 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 //===----------------------------------------------------------------------===//
10
11 #include "Shared/Environment.h"
12
13 #include "Allocator.h"
14 #include "Configuration.h"
15 #include "DeviceTypes.h"
16 #include "DeviceUtils.h"
17 #include "Mapping.h"
18 #include "Synchronization.h"
19
20 using namespace ompx;
21 using namespace allocator;
22
23 // Provide a default implementation of malloc / free for AMDGPU platforms built
24 // without 'libc' support.
25 extern "C" {
26 #if defined(__AMDGPU__) && !defined(OMPTARGET_HAS_LIBC)
27 [[gnu::weak]] void *malloc(size_t Size) { return allocator::alloc(Size); }
28 [[gnu::weak]] void free(void *Ptr) { allocator::free(Ptr); }
29 #else
30 [[gnu::leaf]] void *malloc(size_t Size);
31 [[gnu::leaf]] void free(void *Ptr);
32 #endif
33 }
34
35 static constexpr uint64_t MEMORY_SIZE = /* 1 MiB */ 1024 * 1024;
36 alignas(ALIGNMENT) static uint8_t Memory[MEMORY_SIZE] = {0};
37
38 // Fallback bump pointer interface for platforms without a functioning
39 // allocator.
40 struct BumpAllocatorTy final {
41 uint64_t Offset = 0;
42
43 void *alloc(uint64_t Size) {
44 Size = utils::roundUp(Size, uint64_t(allocator::ALIGNMENT));
45
46 uint64_t OldData = atomic::add(&Offset, Size, atomic::seq_cst);
47 if (OldData + Size >= MEMORY_SIZE)
48 __builtin_trap();
49
50 return &Memory[OldData];
51 }
52
53 void free(void *) {}
54 };
55
56 BumpAllocatorTy BumpAllocator;
57
58 /// allocator namespace implementation
59 ///
60 ///{
61
62 void *allocator::alloc(uint64_t Size) {
63 #if defined(__AMDGPU__) && !defined(OMPTARGET_HAS_LIBC)
64 return BumpAllocator.alloc(Size);
65 #else
66 return ::malloc(Size);
67 #endif
68 }
69
70 void allocator::free(void *Ptr) {
71 #if defined(__AMDGPU__) && !defined(OMPTARGET_HAS_LIBC)
72 BumpAllocator.free(Ptr);
73 #else
74 ::free(Ptr);
75 #endif
76 }
77
78 ///}