ridiculousfish / libdivide

Official git repository for libdivide: optimized integer division
http://libdivide.com
Other
1.09k stars 77 forks source link

Add a Constexpr zero-initializing constructor for divider #115

Closed sharkautarch closed 3 months ago

sharkautarch commented 3 months ago

Usecase:

For function-local static divider objects, and especially for (c++20 or later) static constinit divider objects. making the default constructor constexpr using a Constexpr zero-initializing constructor might sometimes result in better codegen

Otherwise, the compiler might make the static variable be dynamically initialized the first time the initializer statement is reached at runtime. https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables

Here's a godbolt link that demonstrates better codegen w/ constexpr default initialization: https://godbolt.org/z/s6xoK5xEe where latch(int) is normal static default initialization, and latch_constinit(int) is constinit static default initialization (constinit only works w/ constexpr constructors)

EDIT: I realized there were two problems with my original PR:

So instead of trying to make the default constructor constexpr, I've just added a constexpr constructor that takes a nullptr and zero-initializes the members.

which should allow for something like this: static constinit libdivide::divider<int64_t> static_div{nullptr};

I guess something like std::nullopt would be less awkward, but that would mean requiring another standard library header

ridiculousfish commented 3 months ago

Thank you!