fenbf / cppstories-discussions

4 stars 1 forks source link

2024/unroll-templates-lambdas-and-fold/ #148

Open utterances-bot opened 2 months ago

utterances-bot commented 2 months ago

Practical C++17: Loop Unrolling with Lambdas and Fold Expressions - C++ Stories

In this blog post, we’ll delve into the unroll() template function for template unrolling, understand its mechanics, and see how it can improve your code. We’ll look at lambdas, fold expressions, and integer sequences. Let’s get started! A little background   In a recent article Vector math library codegen in Debug · Aras’ website - Aras Pranckevičius discusses some coding techniques that help with performance of debug code… and I came across an intriguing technique utilized in the Blender Math library that he used in his text.

https://www.cppstories.com/2024/unroll-templates-lambdas-and-fold/

eao197 commented 2 months ago

Does the Vector4::operator[] contains a UB? AFAIK, the fact that &x+1==&y doesn't make &x+1 a valid pointer to Vector4::y. Please see slides to the A Deep Dive Into C++ Object Lifetimes talk, slide 71:

int foo() {
  int x, y;
  y = 11;
  if (&x + 1 == &y)
    do_sth(&x);
  return y;
}
void do_sth(int* ptr) {
  *(ptr + 1) = 42; // UB, address not in range
}
Riztazz commented 2 months ago

Won't most sane compilers unroll those loops on their own during optimization pass? Can't stop thinking about this after i've read the article https://github.com/Kittnz/Sunwell/blob/master/src/server/game/DungeonFinding/LFG.h#L136 lmao

fenbf commented 1 month ago

Thanks for the comment @Riztazz - as for your question about optimization: it depends, and it's best to measure your specific case.

As for the code:

bool operator<(const Lfg5Guids& x) const
    {
        // not neat, but fast xD
        if (guid[0]<=x.guid[0]) {

looks scary as well :D

fenbf commented 1 month ago

Thanks for the comment @eao197 - I'm not sure if that's the same case as you show in the example. You have two separate variables there... while in our case we have two data members that share the lies next to each other in the layout of the object. For general case it might be quite unsafe, but if we have floats or doubles then we have proper alignment and no padding so we should be safe.

But for better-looking code I'll update the example to use union with explicit array field.

nscooling commented 1 month ago

Isn't using the union and 'duck typing' UB?

fenbf commented 1 month ago

@nscooling thanks! yes, you're correct! I seem to forget about that guideline:

C.183:

[C.183: Don’t use a union for type punning](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c183-dont-use-a-union-for-type-punning):

It is undefined behaviour to read a union member with a different type from the one with which it was written. Such punning is invisible, or at least harder to spot than using a named cast. Type punning using a union is a source of errors.