Get GCC To Use Carry Logic For Arbitrary Precision Arithmetic Without Inline Assembly?

前端 未结 1 1620
天涯浪人
天涯浪人 2021-02-08 15:33

When working with arbitrary precision arithmetic (e.g. 512-bit integers), is there any way to get GCC to use ADC and similar instructions without using inline assembly?

相关标签:
1条回答
  • 2021-02-08 16:16

    GCC will use the carry flag if it can see that it needs to:
    When adding two uint64_t values on a 32-bit machine, for example, this must result in one 32-bit ADD plus one 32-bit ADC. But apart from those cases, where the compiler is forced to use the carry, it probably cannot be persuaded to do so w/o assembler. Therefore, it may be beneficial to use the biggest integer type available to allow GCC to optimize operations by effectively letting it know that the single 'components' of the value belong together.

    For the simple addition, another way to calculate the carry could be to look at the relevant bits in the operands, like:

    uint32_t aa,bb,rr;
    bool msbA, msbB, msbR, carry;
    // ...
    
    rr = aa+bb;
    
    msbA = aa >= (1<<31); // equivalent: (aa & (1<<31)) != 0;
    msbB = bb >= (1<<31);
    msbR = rr >= (1<<31);
    
    
    carry = (msbA && msbB) || ( !msbR && ( msbA || msbB) );
    
    0 讨论(0)
提交回复
热议问题