Skip to content

Commit 6de4de8

Browse files
authored
[libc] implement endian related macros (#126368)
Follow up of #125168. This patch adds endian-related macros to `endian.h`. We utilize compiler built-ins for byte swap functions, which are already included in our minimal supported compiler version.
1 parent 82cbb02 commit 6de4de8

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

libc/include/llvm-libc-macros/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,8 @@ add_macro_header(
314314
endian_macros
315315
HDR
316316
endian-macros.h
317+
DEPENDS
318+
.stdint_macros
317319
)
318320

319321
add_macro_header(

libc/include/llvm-libc-macros/endian-macros.h

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,42 @@
99
#ifndef LLVM_LIBC_MACROS_ENDIAN_MACROS_H
1010
#define LLVM_LIBC_MACROS_ENDIAN_MACROS_H
1111

12+
#include "stdint-macros.h"
13+
1214
#define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__
1315
#define BIG_ENDIAN __ORDER_BIG_ENDIAN__
1416
#define BYTE_ORDER __BYTE_ORDER__
1517

18+
#if BYTE_ORDER == LITTLE_ENDIAN
19+
20+
#define htobe16(x) __builtin_bswap16((x))
21+
#define htobe32(x) __builtin_bswap32((x))
22+
#define htobe64(x) __builtin_bswap64((x))
23+
#define htole16(x) ((uint16_t)(x))
24+
#define htole32(x) ((uint32_t)(x))
25+
#define htole64(x) ((uint64_t)(x))
26+
#define be16toh(x) __builtin_bswap16((x))
27+
#define be32toh(x) __builtin_bswap32((x))
28+
#define be64toh(x) __builtin_bswap64((x))
29+
#define le16toh(x) ((uint16_t)(x))
30+
#define le32toh(x) ((uint32_t)(x))
31+
#define le64toh(x) ((uint64_t)(x))
32+
33+
#else
34+
35+
#define htobe16(x) ((uint16_t)(x))
36+
#define htobe32(x) ((uint32_t)(x))
37+
#define htobe64(x) ((uint64_t)(x))
38+
#define htole16(x) __builtin_bswap16((x))
39+
#define htole32(x) __builtin_bswap32((x))
40+
#define htole64(x) __builtin_bswap64((x))
41+
#define be16toh(x) ((uint16_t)(x))
42+
#define be32toh(x) ((uint32_t)(x))
43+
#define be64toh(x) ((uint64_t)(x))
44+
#define le16toh(x) __builtin_bswap16((x))
45+
#define le32toh(x) __builtin_bswap32((x))
46+
#define le64toh(x) __builtin_bswap64((x))
47+
48+
#endif
49+
1650
#endif // LLVM_LIBC_MACROS_ENDIAN_MACROS_H

0 commit comments

Comments
 (0)