You need to start with the LLVM language reference guide .
You can start by implementing trunc( ) , like something in this direction (warning, do not actually use this, it is intended as an example and is incorrect. See discussion below):
define float @trunc(float %x) { %rounded = fptosi float %x to i32 %asFloat = sitofp i32 %rounded to float ret float %asFloat }
The fptosi ... to ... documented as rounding a floating point value to an integer value according to a rounding cycle to zero. The sitofp ... to ... command converts this value back to a floating-point return value.
However, there is a problem with this implementation; after reading the link to the language I'm associated with, "the behavior of fptosi ... to ... is undefined if the result of rounding to the nearest integer cannot fit in the destination type."
This is fairly easy to get around, though, since all large enough floating point numbers are already integers and don't need to be rounded; if the absolute value of x greater than or equal to 2 ^ 23, you can simply return x itself.
(All this for single precision; for double, you most likely want to use i64 , and you will need to use a threshold of 2 ^ 52)
For other operations, such as floor and round , you can start with trunc , then check the residual x - trunc(x) and adjust the result accordingly.
Alternatively, you can refer to the host platform's C library, which already includes these features. This is an approach used by many programming languages.
source share