TRIQS/nda 1.3.0
Multi-dimensional array library for C++
Loading...
Searching...
No Matches
malloc.hpp
Go to the documentation of this file.
1// Copyright (c) 2022-2024 Simons Foundation
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0.txt
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// Authors: Thomas Hahn, Miguel Morales, Nils Wentzell
16
22#pragma once
23
24#include "./address_space.hpp"
25#include "../device.hpp"
26
27#include <cstdlib>
28
29namespace nda::mem {
30
48 template <AddressSpace AdrSp>
49 void *malloc(size_t size) {
51 static_assert(nda::have_device == nda::have_cuda, "Adjust function for new device types");
52
53 void *ptr = nullptr;
54 if constexpr (AdrSp == Host) {
55 ptr = std::malloc(size); // NOLINT (we want to return a void*)
56 } else if constexpr (AdrSp == Device) {
57 device_error_check(cudaMalloc((void **)&ptr, size), "cudaMalloc");
58 } else {
59 device_error_check(cudaMallocManaged((void **)&ptr, size), "cudaMallocManaged");
60 }
61 return ptr;
62 }
63
74 template <AddressSpace AdrSp>
75 void free(void *p) {
77 static_assert(nda::have_device == nda::have_cuda, "Adjust function for new device types");
78
79 if constexpr (AdrSp == Host) {
80 std::free(p); // NOLINT (we want to call free with a void*)
81 } else {
82 device_error_check(cudaFree(p), "cudaFree");
83 }
84 }
85
88} // namespace nda::mem
Provides definitions and type traits involving the different memory address spaces supported by nda.
Provides GPU and non-GPU specific functionality.
static const auto check_adr_sp_valid
Check validity of a set of nda::mem::AddressSpace values.
static constexpr bool have_cuda
Constexpr variable that is true if the project is configured with CUDA support.
Definition device.hpp:146
#define device_error_check(ARG1, ARG2)
Trigger a compilation error every time the nda::device_error_check function is called.
Definition device.hpp:140
static constexpr bool have_device
Constexpr variable that is true if the project is configured with GPU support.
Definition device.hpp:143
void * malloc(size_t size)
Call the correct malloc function based on the given address space.
Definition malloc.hpp:49
void free(void *p)
Call the correct free function based on the given address space.
Definition malloc.hpp:75