Skip to content
This repository
Browse code

Reduce the number of expensive division instructions done by _parse_i…

…nteger()

_parse_integer() does one or two division instructions (which are slow)
per digit parsed to perform the overflow check.

Furthermore, these are particularly expensive examples of division
instruction as the number of clock cycles required to complete them may
go up with the position of the most significant set bit in the dividend:

	if (*res > div_u64(ULLONG_MAX - val, base))

which is as maximal as possible.

Worse, on 32-bit arches, more than one of these division instructions
may be required per digit.

So, assuming we don't support a base of more than 16, skip the check if the
top nibble of the result is not set at this point.

Signed-off-by: David Howells <dhowells@redhat.com>
[ Changed it to not dereference the pointer all the time - even if the
  compiler can and does optimize it away, the code just looks cleaner.
  And edited the top nybble test slightly to make the code generated on
  x86-64 better in the loop - test against a hoisted constant instead of
  shifting and testing the result ]
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
  • Loading branch information...
commit 690d137f448d4c4da9001871e6569d5636f116c7 1 parent d65b4e9
David Howells authored torvalds committed

Showing 1 changed file with 13 additions and 5 deletions. Show diff stats Hide diff stats

  1. +13 5 lib/kstrtox.c
18 lib/kstrtox.c
@@ -44,12 +44,13 @@ const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
44 44 *
45 45 * Don't you dare use this function.
46 46 */
47   -unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *res)
  47 +unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long *p)
48 48 {
  49 + unsigned long long res;
49 50 unsigned int rv;
50 51 int overflow;
51 52
52   - *res = 0;
  53 + res = 0;
53 54 rv = 0;
54 55 overflow = 0;
55 56 while (*s) {
@@ -64,12 +65,19 @@ unsigned int _parse_integer(const char *s, unsigned int base, unsigned long long
64 65
65 66 if (val >= base)
66 67 break;
67   - if (*res > div_u64(ULLONG_MAX - val, base))
68   - overflow = 1;
69   - *res = *res * base + val;
  68 + /*
  69 + * Check for overflow only if we are within range of
  70 + * it in the max base we support (16)
  71 + */
  72 + if (unlikely(res & (~0ull << 60))) {
  73 + if (res > div_u64(ULLONG_MAX - val, base))
  74 + overflow = 1;
  75 + }
  76 + res = res * base + val;
70 77 rv++;
71 78 s++;
72 79 }
  80 + *p = res;
73 81 if (overflow)
74 82 rv |= KSTRTOX_OVERFLOW;
75 83 return rv;

0 comments on commit 690d137

Please sign in to comment.
Something went wrong with that request. Please try again.