http://gcc.gnu.org/bugzilla/show_bug.cgi?id=55393



             Bug #: 55393

           Summary: gcc/g++ multiplies two unsigned integers using the

                    IMULQ instruction

    Classification: Unclassified

           Product: gcc

           Version: unknown

            Status: UNCONFIRMED

          Severity: normal

          Priority: P3

         Component: c++

        AssignedTo: unassig...@gcc.gnu.org

        ReportedBy: cos...@claycon.org





g++ -Wall -Wextra -O2 -o mult mult.cpp

g++ (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)

64bit



mult.cpp:



#include <iostream>



void

display(

        unsigned long int num,

        unsigned long int mult)

{

        unsigned long int tmp = num * mult;

        std::cout << "mult " << mult << "\n num " << num

                << "\n tmp " << tmp << std::endl;



        if (tmp < num)

                std::cout << "overflow" << std::endl;

}



int

main(

        int /* argc */,

        char ** /* argv */)

{

        unsigned long int num = 999999999999999999;

        unsigned long int mult = 1024;



        display(num, mult);

        return 0;

}



Problem:

"overflow" is not displayed as expected.



Analysis:

gcc generates an IMULQ instruction to calculate the value of tmp.

The value of num has bit 63 set.  Since IMULQ sees that argument

as signed, it results in an incorrect number that happens to be

greater than num.



IMULQ will generate the wrong result when the result just fits

into 64 bits too, even though the result would have been correct

(with no overflow) had the proper instruction been used.



Fix:

Whenever the multiplication operands are both unsigned, gcc should

generate an unsigned multiply instruction (MULQ in this case), unless

it can prove that the result would fit into 63 bits.

Reply via email to