1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef BERBERIS_REGS_H_
18 #define BERBERIS_REGS_H_
19 
20 #include <cstdint>
21 #include <cstring>
22 
23 #include "berberis/base/bit_util.h"
24 #if !defined(__aarch64__)
25 #include "berberis/intrinsics/intrinsics_float.h"
26 #endif
27 
28 namespace berberis {
29 
30 template <typename IntegerType>
31 inline auto GPRRegToInteger(uint64_t arg)
32     -> std::enable_if_t<std::is_integral_v<IntegerType> && sizeof(IntegerType) <= sizeof(uint64_t),
33                         IntegerType> {
34   return static_cast<IntegerType>(arg);
35 }
36 
37 template <typename IntegerType>
38 inline auto IntegerToGPRReg(IntegerType arg)
39     -> std::enable_if_t<std::is_integral_v<IntegerType> && sizeof(IntegerType) <= sizeof(uint64_t),
40                         uint64_t> {
41   if constexpr (sizeof(IntegerType) <= sizeof(uint32_t)) {
42     return static_cast<int32_t>(arg);
43   } else {
44     return bit_cast<uint64_t>(arg);
45   }
46 }
47 
48 template <typename FloatType>
49 inline FloatType FPRegToFloat(uint64_t arg);
50 
51 template <>
52 inline intrinsics::Float32 FPRegToFloat<intrinsics::Float32>(uint64_t arg) {
53   intrinsics::Float32 result;
54   memcpy(&result, &arg, sizeof(intrinsics::Float32));
55   return result;
56 }
57 
58 template <>
59 inline intrinsics::Float64 FPRegToFloat<intrinsics::Float64>(uint64_t arg) {
60   return bit_cast<intrinsics::Float64>(arg);
61 }
62 
63 template <typename FloatType>
64 inline uint64_t FloatToFPReg(FloatType arg);
65 
66 template <>
67 inline uint64_t FloatToFPReg<intrinsics::Float32>(intrinsics::Float32 arg) {
68   // Note: NanBoxAndSetFpReg would properly Nan-box the value.
69   return bit_cast<uint32_t>(arg);
70 }
71 
72 template <>
73 inline uint64_t FloatToFPReg<intrinsics::Float64>(intrinsics::Float64 arg) {
74   return bit_cast<uint64_t>(arg);
75 }
76 
77 }  // namespace berberis
78 
79 #endif  // BERBERIS_REGS_H_
80