]> git.proxmox.com Git - rustc.git/blob - src/binaryen/src/support/utilities.h
New upstream version 1.23.0+dfsg1
[rustc.git] / src / binaryen / src / support / utilities.h
1 /*
2 * Copyright 2016 WebAssembly Community Group participants
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 wasm_support_utilities_h
18 #define wasm_support_utilities_h
19
20 #include "compiler-support.h"
21
22 #include <cassert>
23 #include <cstdint>
24 #include <cstring>
25 #include <memory>
26 #include <iostream>
27 #include <type_traits>
28
29 namespace wasm {
30
31 // Type punning needs to be done through this function to avoid undefined
32 // behavior: unions and reinterpret_cast aren't valid approaches.
33 template <class Destination, class Source>
34 inline Destination bit_cast(const Source& source) {
35 static_assert(sizeof(Destination) == sizeof(Source),
36 "bit_cast needs to be between types of the same size");
37 static_assert(std::is_pod<Destination>::value, "non-POD bit_cast undefined");
38 static_assert(std::is_pod<Source>::value, "non-POD bit_cast undefined");
39 Destination destination;
40 std::memcpy(&destination, &source, sizeof(destination));
41 return destination;
42 }
43
44 inline bool isPowerOf2(uint32_t v) {
45 return v && !(v & (v - 1));
46 }
47
48 inline size_t alignAddr(size_t address, size_t alignment) {
49 assert(alignment && isPowerOf2((uint32_t)alignment) &&
50 "Alignment is not a power of two!");
51
52 assert(address + alignment - 1 >= address);
53
54 return ((address + alignment - 1) & ~(alignment - 1));
55 }
56
57 template<typename T, typename... Args>
58 std::unique_ptr<T> make_unique(Args&&... args)
59 {
60 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
61 }
62
63 // For fatal errors which could arise from input (i.e. not assertion failures)
64 class Fatal {
65 public:
66 Fatal() {
67 std::cerr << "Fatal: ";
68 }
69 template<typename T>
70 Fatal &operator<<(T arg) {
71 std::cerr << arg;
72 return *this;
73 }
74 WASM_NORETURN ~Fatal() {
75 std::cerr << "\n";
76 exit(1);
77 }
78 };
79
80
81 } // namespace wasm
82
83 #endif // wasm_support_utilities_h