How can Duff's device code be compiled?

前端 未结 5 1503
既然无缘
既然无缘 2020-12-10 17:21

I understood why Duff\'s device is faster than normal loop code which can be unrolled but is not optimized. But I can\'t understand how the code can be compiled yet.
I g

5条回答
  •  执念已碎
    2020-12-10 18:01

    The "how it works" is simple enough.

    Both C and C++ are compiled languages, and normally compiled to the platforms machine code. Machine code has no concept of block structures - all block structures must be translated to a form that uses (in effect) some mix of unconditional and conditional gotos.

    The C syntax rules allow the switch statement and loop to be combined in a way which is not a true hierarchical block structure, but which tangles control flow. So long as the compiler can cope with this (which any good compiler should) there is no problem in the underlying machine code. The result will be "spaghetti", but generated machine code that has been through an optimiser is always spaghetti - it's not meant to be human readable, so it's not an issue. The issue here is that the source code is spaghetti too, even though the gotos have been "hidden".

    Note - although any good compiler should cope with Duffs device, as others have already commented, that doesn't mean it will cope well enough to optimise it properly - only well enough to generate correct executable code. This is one of these old strange idioms that once had a purpose, but which is more likely now to confuse your compiler and sabotage it's ability to generate efficient code.

    EDIT

    The following is related to Duffs device, and may help illustrate the basic idea...

    switch (count & 1)
    {
      case 0 : goto lbl0;
      case 1 : goto lbl1;
    }
    
    lbl0:
    
    while (count != 0)
    {
      handle_one ();
      count--;
    lbl1:
      handle_one ();
      count--;
    }
    

    Having case clauses inside the loop is conceptually no different to having goto-target labels inside the loop, as above.

    Warning - this is purely for illustration of an idea, and should not be copied in real life code.

提交回复
热议问题