How to translate the built-in x86 GCC-style assembly to the Rust inline assembly?

I have the following built-in assembly in C:

unsigned long long result;
asm volatile(".byte 15;.byte 49;shlq $32,%%rdx;orq %%rdx,%%rax"
    : "=a" (result) ::  "%rdx");
return result;

I tried to rewrite it in Rust:

let result: u64;
unsafe {
    asm!(".byte 15\n\t
          .byte 49\n\t
          shlq 32, rdx\n\t
          orq  rdx, rax"
         : "=a"(result)
         :
         : "rdx"
         : "volatile"
         );
}
result

It does not recognize the constraint =a, and it gives me the wrong operand error for rdxboth raxin shlqand in orqinstructions. What is the correct way to rewrite the above C-string assembly in Rust?

+4
source share
1 answer

Rust is built on top of LLVM, so many low-level details like this can be gleaned from what LLVM or Clang do.

  • , : "={rax}"(result). GCC, a "a".

  • $$

  • %

let result: u64;
unsafe {
    asm!(".byte 15
          .byte 49
          shlq $$32, %rdx
          orq  %rdx, %rax"
         : "={rax}"(result)
         :
         : "rdx"
         : "volatile"
    );
}
result

rdtsc, :

let upper: u64;
let lower: u64;
unsafe {
    asm!("rdtsc"
         : "={rax}"(lower), 
           "={rdx}"(upper)
         :
         :
         : "volatile"
    );
}
upper << 32 | lower

, .


:

playground::thing1:
    #APP
    .byte   15
    .byte   49
    shlq    $32, %rdx
    orq %rdx, %rax
    #NO_APP
    retq

playground::thing2:
    #APP
    rdtsc
    #NO_APP
    shlq    $32, %rdx
    orq %rdx, %rax
    retq

, LLVM. :

#![feature(link_llvm_intrinsics)]

extern "C" {
    #[link_name = "llvm.x86.rdtsc"]
    fn rdtsc() -> u64;
}

fn main() {
    println!("{}", unsafe { rdtsc() })
}

:

+5

Source: https://habr.com/ru/post/1691745/


All Articles