Home | History | Annotate | Line # | Download | only in builtins
      1 /* ===-- udivsi3.c - Implement __udivsi3 -----------------------------------===
      2  *
      3  *                     The LLVM Compiler Infrastructure
      4  *
      5  * This file is dual licensed under the MIT and the University of Illinois Open
      6  * Source Licenses. See LICENSE.TXT for details.
      7  *
      8  * ===----------------------------------------------------------------------===
      9  *
     10  * This file implements __udivsi3 for the compiler_rt library.
     11  *
     12  * ===----------------------------------------------------------------------===
     13  */
     14 
     15 #include "int_lib.h"
     16 
     17 /* Returns: a / b */
     18 
     19 /* Translated from Figure 3-40 of The PowerPC Compiler Writer's Guide */
     20 
     21 /* This function should not call __divsi3! */
     22 COMPILER_RT_ABI su_int
     23 __udivsi3(su_int n, su_int d)
     24 {
     25     const unsigned n_uword_bits = sizeof(su_int) * CHAR_BIT;
     26     su_int q;
     27     su_int r;
     28     unsigned sr;
     29     /* special cases */
     30     if (d == 0)
     31         return 0; /* ?! */
     32     if (n == 0)
     33         return 0;
     34     sr = __builtin_clz(d) - __builtin_clz(n);
     35     /* 0 <= sr <= n_uword_bits - 1 or sr large */
     36     if (sr > n_uword_bits - 1)  /* d > r */
     37         return 0;
     38     if (sr == n_uword_bits - 1)  /* d == 1 */
     39         return n;
     40     ++sr;
     41     /* 1 <= sr <= n_uword_bits - 1 */
     42     /* Not a special case */
     43     q = n << (n_uword_bits - sr);
     44     r = n >> sr;
     45     su_int carry = 0;
     46     for (; sr > 0; --sr)
     47     {
     48         /* r:q = ((r:q)  << 1) | carry */
     49         r = (r << 1) | (q >> (n_uword_bits - 1));
     50         q = (q << 1) | carry;
     51         /* carry = 0;
     52          * if (r.all >= d.all)
     53          * {
     54          *      r.all -= d.all;
     55          *      carry = 1;
     56          * }
     57          */
     58         const si_int s = (si_int)(d - r - 1) >> (n_uword_bits - 1);
     59         carry = s & 1;
     60         r -= d & s;
     61     }
     62     q = (q << 1) | carry;
     63     return q;
     64 }
     65 
     66 #if defined(__ARM_EABI__)
     67 AEABI_RTABI su_int __aeabi_uidiv(su_int n, su_int d) COMPILER_RT_ALIAS(__udivsi3);
     68 #endif
     69