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--present, The Simons Foundation
2// This file is part of TRIQS/nda and is licensed under the Apache License, Version 2.0.
3// SPDX-License-Identifier: Apache-2.0
4// See LICENSE in the root of this distribution for details.
5
10
11#pragma once
12
13#include "./address_space.hpp"
14#include "../device.hpp"
15
16#include <cstdlib>
17
18namespace nda::mem {
19
24
37 template <AddressSpace AdrSp>
38 void *malloc(size_t size) {
40 static_assert(nda::have_device == nda::have_cuda, "Adjust function for new device types");
41
42 void *ptr = nullptr;
43 if constexpr (AdrSp == Host) {
44 ptr = std::malloc(size); // NOLINT (we want to return a void*)
45 } else if constexpr (AdrSp == Device) {
46 device_error_check(cudaMalloc((void **)&ptr, size), "cudaMalloc");
47 } else {
48 device_error_check(cudaMallocManaged((void **)&ptr, size), "cudaMallocManaged");
49 }
50 return ptr;
51 }
52
63 template <AddressSpace AdrSp>
64 void free(void *p) {
66 static_assert(nda::have_device == nda::have_cuda, "Adjust function for new device types");
67
68 if constexpr (AdrSp == Host) {
69 std::free(p); // NOLINT (we want to call free with a void*)
70 } else {
71 device_error_check(cudaFree(p), "cudaFree");
72 }
73 }
74
76
77} // 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:135
#define device_error_check(ARG1, ARG2)
Trigger a compilation error every time the nda::device_error_check function is called.
Definition device.hpp:129
static constexpr bool have_device
Constexpr variable that is true if the project is configured with GPU support.
Definition device.hpp:132
void * malloc(size_t size)
Call the correct malloc function based on the given address space.
Definition malloc.hpp:38
void free(void *p)
Call the correct free function based on the given address space.
Definition malloc.hpp:64