1 //===- SwapByteOrder.h - Generic and optimized byte swaps -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares generic and optimized functions to swap the byte order of
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_SYSTEM_SWAP_BYTE_ORDER_H
16 #define LLVM_SYSTEM_SWAP_BYTE_ORDER_H
18 #include "llvm/Support/type_traits.h"
19 #include "llvm/System/DataTypes.h"
26 template<typename value_type>
28 typename enable_if_c<sizeof(value_type) == 1
29 && std::numeric_limits<value_type>::is_integer,
31 SwapByteOrder(value_type Value) {
32 // No swapping needed.
36 template<typename value_type>
38 typename enable_if_c<sizeof(value_type) == 2
39 && std::numeric_limits<value_type>::is_integer,
41 SwapByteOrder(value_type Value) {
42 // Cast signed types to unsigned before swapping.
43 uint16_t value = static_cast<uint16_t>(Value);
44 #if defined(_MSC_VER) && !defined(_DEBUG)
45 // The DLL version of the runtime lacks these functions (bug!?), but in a
46 // release build they're replaced with BSWAP instructions anyway.
47 return _byteswap_ushort(value);
49 uint16_t Hi = value << 8;
50 uint16_t Lo = value >> 8;
51 return value_type(Hi | Lo);
55 template<typename value_type>
57 typename enable_if_c<sizeof(value_type) == 4
58 && std::numeric_limits<value_type>::is_integer,
60 SwapByteOrder(value_type Value) {
61 // Cast signed types to unsigned before swapping.
62 uint32_t value = static_cast<uint32_t>(Value);
63 #if defined(__llvm__) || \
64 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && !defined(__ICC)
65 return __builtin_bswap32(value);
66 #elif defined(_MSC_VER) && !defined(_DEBUG)
67 return _byteswap_ulong(value);
69 uint32_t Byte0 = value & 0x000000FF;
70 uint32_t Byte1 = value & 0x0000FF00;
71 uint32_t Byte2 = value & 0x00FF0000;
72 uint32_t Byte3 = value & 0xFF000000;
74 (Byte0 << 24) | (Byte1 << 8) | (Byte2 >> 8) | (Byte3 >> 24));
78 template<typename value_type>
80 typename enable_if_c<sizeof(value_type) == 8
81 && std::numeric_limits<value_type>::is_integer,
83 SwapByteOrder(value_type Value) {
84 // Cast signed types to unsigned before swapping.
85 uint64_t value = static_cast<uint64_t>(Value);
86 #if defined(__llvm__) || \
87 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && !defined(__ICC)
88 return __builtin_bswap64(value);
89 #elif defined(_MSC_VER) && !defined(_DEBUG)
90 return _byteswap_uint64(value);
92 uint64_t Hi = SwapByteOrder<uint32_t>(uint32_t(value));
93 uint32_t Lo = SwapByteOrder<uint32_t>(uint32_t(value >> 32));
94 return value_type((Hi << 32) | Lo);
98 } // end namespace sys
99 } // end namespace llvm