division-by-constant.h 2.6 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_BASE_DIVISION_BY_CONSTANT_H_
#define V8_BASE_DIVISION_BY_CONSTANT_H_

8 9 10
#include <stdint.h>

#include "src/base/base-export.h"
11
#include "src/base/export-template.h"
12

13 14 15 16 17 18 19 20 21
namespace v8 {
namespace base {

// ----------------------------------------------------------------------------

// The magic numbers for division via multiplication, see Warren's "Hacker's
// Delight", chapter 10. The template parameter must be one of the unsigned
// integral types.
template <class T>
22
struct EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT) MagicNumbersForDivision {
23 24
  MagicNumbersForDivision(T m, unsigned s, bool a)
      : multiplier(m), shift(s), add(a) {}
25 26 27
  bool operator==(const MagicNumbersForDivision& rhs) const {
    return multiplier == rhs.multiplier && shift == rhs.shift && add == rhs.add;
  }
28 29 30 31 32 33 34 35 36 37

  T multiplier;
  unsigned shift;
  bool add;
};


// Calculate the multiplier and shift for signed division via multiplication.
// The divisor must not be -1, 0 or 1 when interpreted as a signed value.
template <class T>
38 39
EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
MagicNumbersForDivision<T> SignedDivisionByConstant(T d);
40 41 42 43 44 45

// Calculate the multiplier and shift for unsigned division via multiplication,
// see Warren's "Hacker's Delight", chapter 10. The divisor must not be 0 and
// leading_zeros can be used to speed up the calculation if the given number of
// upper bits of the dividend value are known to be zero.
template <class T>
46 47
EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
MagicNumbersForDivision<T> UnsignedDivisionByConstant(
48 49
    T d, unsigned leading_zeros = 0);

50 51 52 53 54
// Explicit instantiation declarations.
extern template struct EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
    MagicNumbersForDivision<uint32_t>;
extern template struct EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
    MagicNumbersForDivision<uint64_t>;
55

56 57 58 59 60 61 62 63 64 65 66
extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
    MagicNumbersForDivision<uint32_t> SignedDivisionByConstant(uint32_t d);
extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
    MagicNumbersForDivision<uint64_t> SignedDivisionByConstant(uint64_t d);

extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
    MagicNumbersForDivision<uint32_t> UnsignedDivisionByConstant(
        uint32_t d, unsigned leading_zeros);
extern template EXPORT_TEMPLATE_DECLARE(V8_BASE_EXPORT)
    MagicNumbersForDivision<uint64_t> UnsignedDivisionByConstant(
        uint64_t d, unsigned leading_zeros);
67

68 69 70 71
}  // namespace base
}  // namespace v8

#endif  // V8_BASE_DIVISION_BY_CONSTANT_H_