SizeTraits.h revision 5460a1f25d9ddecb5c70667267d66d51af177a99
1//===- SizeTraits.h -------------------------------------------------------===//
2//
3//                     The MCLinker Project
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#ifndef MCLD_SIZE_TRAITS_H
10#define MCLD_SIZE_TRAITS_H
11#ifdef ENABLE_UNITTEST
12#include <gtest.h>
13#endif
14
15#include <llvm/Support/DataTypes.h>
16
17namespace mcld
18{
19
20template<size_t SIZE>
21struct SizeTraits;
22
23template<>
24class SizeTraits<32>
25{
26  typedef uint32_t Address;
27  typedef uint32_t Offset;
28  typedef uint32_t Word;
29  typedef int32_t  SWord;
30};
31
32template<>
33class SizeTraits<64>
34{
35  typedef uint64_t Address;
36  typedef uint64_t Offset;
37  typedef uint64_t Word;
38  typedef int64_t  SWord;
39};
40
41/// alignAddress - helper function to align an address with given alignment
42/// constraint
43///
44/// @param pAddr - the address to be aligned
45/// @param pAlignConstraint - the alignment used to align the given address
46inline void alignAddress(uint64_t& pAddr, uint64_t pAlignConstraint)
47{
48  if (pAlignConstraint != 0)
49    pAddr = (pAddr + pAlignConstraint - 1) &~ (pAlignConstraint - 1);
50}
51
52template<size_t Constraint>
53uint64_t Align(uint64_t pAddress);
54
55template<>
56inline uint64_t Align<32>(uint64_t pAddress)
57{
58  return (pAddress + 0x1F) & (~0x1F);
59}
60
61template<>
62inline uint64_t Align<64>(uint64_t pAddress)
63{
64  return (pAddress + 0x3F) & (~0x3F);
65}
66
67/// bswap16 - byte swap 16-bit version
68/// @ref binary utilities - elfcpp_swap
69inline uint16_t bswap16(uint16_t pData)
70{
71   return ((pData >> 8) & 0xFF) | ((pData & 0xFF) << 8);
72}
73
74/// bswap32 - byte swap 32-bit version
75/// @ref elfcpp_swap
76inline uint32_t bswap32(uint32_t pData)
77{
78   return (((pData & 0xFF000000) >> 24) |
79           ((pData & 0x00FF0000) >>  8) |
80           ((pData & 0x0000FF00) <<  8) |
81           ((pData & 0x000000FF) << 24));
82
83}
84
85/// bswap64 - byte swap 64-bit version
86/// @ref binary utilities - elfcpp_swap
87inline uint64_t bswap64(uint64_t pData)
88{
89   return (((pData & 0xFF00000000000000ULL) >> 56) |
90           ((pData & 0x00FF000000000000ULL) >> 40) |
91           ((pData & 0x0000FF0000000000ULL) >> 24) |
92           ((pData & 0x000000FF00000000ULL) >>  8) |
93           ((pData & 0x00000000FF000000ULL) <<  8) |
94           ((pData & 0x0000000000FF0000ULL) << 24) |
95           ((pData & 0x000000000000FF00ULL) << 40) |
96           ((pData & 0x00000000000000FFULL) << 56));
97}
98
99} // namespace of mcld
100
101#endif
102
103