Software APIs
sw
device
lib
base
math.h
Go to the documentation of this file.
1
// Copyright lowRISC contributors (OpenTitan project).
2
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3
// SPDX-License-Identifier: Apache-2.0
4
5
#ifndef OPENTITAN_SW_DEVICE_LIB_BASE_MATH_H_
6
#define OPENTITAN_SW_DEVICE_LIB_BASE_MATH_H_
7
8
#include <
stdint.h
>
9
10
#include "
sw/device/lib/base/macros.h
"
11
12
#ifdef __cplusplus
13
extern
"C"
{
14
#endif // __cplusplus
15
16
/**
17
* @file
18
* @brief Math helper functions.
19
*/
20
21
/**
22
* Computes the 64-bit quotient `a / b` by way of schoolbook long division.
23
*
24
* This function is intentionally very slow: 64-bit divisions should not be
25
* a frequent occurence, and faster algorithms result in unreasonable code-size
26
* expenditure.
27
*
28
* Performing division with the / operator in C code that runs on a 32-bit
29
* device can emit a polyfill like `__udivdi3`; normally, this would
30
* be provided by a compiler runtime like libgcc_s, but we intentionally do not
31
* link that into on-device binaries. This function should be use to resolve
32
* link errors involving `__udiv` symbols. We do not provide a libgcc-style
33
* linker alias for this function, because this operation should be explicit and
34
* not over-used.
35
*
36
* If passed a non-null pointer, this function will also provide the remainder
37
* as a side-product.
38
*
39
* If `b == 0`, this function produces undefined behavior (in practice, a
40
* garbage result or a loop without forward progress).
41
*
42
* @param a The dividend.
43
* @param b The divisor.
44
* @param[out] rem_out An optional out-parameter for the remainder.
45
* @return The quotient.
46
*/
47
OT_WARN_UNUSED_RESULT
48
uint64_t
udiv64_slow
(uint64_t a, uint64_t b, uint64_t *rem_out);
49
50
/**
51
* Computes ceil(a / b) in an overflow-safe way.
52
*
53
* If `b == 0`, this function produces undefined behavior.
54
*
55
* @param a The dividend.
56
* @param b The divisor.
57
* @return Result, ceil(a / b).
58
*/
59
OT_WARN_UNUSED_RESULT
60
inline
size_t
ceil_div
(
size_t
a,
size_t
b) {
61
size_t
out = a / b;
62
if
(a % b != 0) {
63
out++;
64
}
65
return
out;
66
}
67
68
#ifdef __cplusplus
69
}
// extern "C"
70
#endif // __cplusplus
71
72
#endif // OPENTITAN_SW_DEVICE_LIB_BASE_MATH_H_
Return to
OpenTitan Documentation