Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)

From: Ranier Vilela <ranier(dot)vf(at)gmail(dot)com>
To: Pg Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Optmize bitmapword macros calc (src/backend/nodes/bitmapset.c)
Date: 2024-01-29 16:30:47
Message-ID: CAEudQAoj9YDp+gecJaKnYsOTJWrf-CyjsiqAA6NJ6O1y+Dm4tw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

IMO I believe that bitmapset can obtain an optimization in the calculation
of the WORDNUM and BITNUM macros.

As you know, in bitmapset, negative members are not allowed.

if (x < 0)
elog(ERROR, "negative bitmapset member not allowed");

Then, allow the compiler to optimize and do the calculations in unsigned.

I did a demonstration in compiler explorer.
https://godbolt.org/z/c68o43Eq1

It is demonstrated here as well.

Generated instructions: GCC 13.2

#define WORDNUM_f1(x) ((x) / BITS_PER_BITMAPWORD)
mov eax, DWORD PTR [rbp-20]
lea edx, [rax+63]
test eax, eax
cmovs eax, edx
sar eax, 6
mov DWORD PTR [rbp-4], eax

#define WORDNUM_f2(x) ((bitmapword) (x) / BITS_PER_BITMAPWORD)
mov eax, DWORD PTR [rbp-20]
cdqe
shr rax, 6
mov DWORD PTR [rbp-4], eax

#define BITNUM_f1(x) ((x) % BITS_PER_BITMAPWORD)
mov edx, DWORD PTR [rbp-20]
mov eax, edx
sar eax, 31
shr eax, 26
add edx, eax
and edx, 63
sub edx, eax
mov DWORD PTR [rbp-4], edx

#define BITNUM_f2(x) ((bitmapword) (x) % BITS_PER_BITMAPWORD)
mov eax, DWORD PTR [rbp-20]
and eax, 63
mov DWORD PTR [rbp-4], eax

As you can see, when calculations are done in unsigned,
the generated instructions are optimized.

Patch attached.

Best regards,
Ranier Vilela

Attachment Content-Type Size
optimize_bitmapset_bitmapword_calc.patch application/x-patch 548 bytes

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Ranier Vilela 2024-01-29 16:39:32 Re: Should we remove -Wdeclaration-after-statement?
Previous Message Dave Cramer 2024-01-29 16:20:18 Re: [PATCH] Add native windows on arm64 support