c++assemblyvisual-studio-2008x86-64rdrand

How to add RDRAND instruction into 64-bit code compiled with VS 2008?


I'm working on a C++ project in Visual Studio 2008 IDE, where I need to use Intel's new RDRAND instruction. I did a quick search, and MSDN recommends using _rdrand64_step intrinsic defined in immintrin.h, which I do not have in VS 2008.

In a 32-bit compiled code I can get away with using asm keyword as such:

    __asm
    {
        xor eax, eax

        ;RDRAND instruction = Set random value into EAX.
        ;Will set overflow [C] flag if success
        _emit 0x0F
        _emit 0xC7
        _emit 0xF0
    }

But on x64 asm is not supported.

Can you suggest how can I compile my project for 64-bit with the RDRAND instruction?


Solution

  • You either need to upgrade your compiler to one that does support the _rdrand64_step intrinsic (supported since Visual Studio 2012), or use normal (external) assembly to create your own functions (since Visual C++ does not support inline assembly for x86-64 targets).

    For example:

    _TEXT   SEGMENT
    
        PUBLIC rdrand32_step
        PUBLIC rdrand32_retry
        PUBLIC rdrand64_step
        PUBLIC rdrand64_retry
    
        ; int rdrand32_step(unsigned *p)
    rdrand32_step PROC
        xor     eax, eax
        rdrand  edx
        ; DB    0fh, 0c7h, 0f2h
        setc    al
        mov     [rcx], edx
        ret
    rdrand32_step ENDP
    
        ; unsigned rdrand32_retry()
    rdrand32_retry PROC
    retry:
        rdrand  eax
        ; DB    0fh, 0c7h, 0f0h
        jnc     retry
        ret
    rdrand32_retry ENDP
    
        ; int rdrand64_step(unsigned long long *p)
    rdrand64_step PROC
        xor     eax, eax
        rdrand  rdx
        ; DB    048h, 0fh, 0c7h, 0f2h
        setc    al
        mov     [rcx], edx
        ret
    rdrand64_step ENDP
    
        ; unsigned long long rdrand64_retry()
    rdrand64_retry PROC
    retry:
        rdrand  rax
        ; DB    048h, 0fh, 0c7h, 0f0h
        jnc     retry
        ret
    rdrand64_retry ENDP
    
    _TEXT   ENDS
    
        END
    

    If you're using the version of MASM from Visual Studio 2008, you'll probably have to comment out the RDRAND instructions and uncomment the DB directives that follow them.