0

I've used the following two different approaches to referencing a variable in assembly. Using the variable itself:

# Move a variable, directly referencing it rather than relative to %rip
movzbq   my_var,   %r14
leaq     my_var,   %r15

And then using the relative address to rip:

# Move a variable, then its address into two registers
movzbq  my_var(%rip),   %r14
leaq    my_var(%rip),   %r15 

I find the first one (of course) more readable than the second. What are the differences between the two different approaches, and is one preferred over another?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 2
    The second is position independent and that may even be required on some systems for ASLR. Also it can work even if your variable is not in 32 bit address range. – Jester Aug 22 '20 at 21:46
  • @Jester thanks, yea your comment + the duplicate answer what I was asking. – samuelbrody1249 Aug 22 '20 at 21:50
  • Compilers will never ever use the first because it's inefficient (costs an extra byte of code size). Only `mov $my_var, %edi` in non-PIE executables is better than RIP-relative LEA. [How to load address of function or label into register in GNU Assembler](https://stackoverflow.com/q/57212012) – Peter Cordes Aug 22 '20 at 21:50
  • Also, you never need to use `movzbq`; just use `movzbl` and let implicit zero-extension to 64-bit do the upper 32 bits. That avoids a REX prefix (saving code size) when the destination is RAX..RDI. (R8D .. R15D still need a REX prefix anyway for the register number, so it's probably not faster to still use 32-bit operand-size.) – Peter Cordes Aug 22 '20 at 21:55
  • @PeterCordes sorry for the basic question, but what's the difference between `my_var` and `$my_var` ? – samuelbrody1249 Aug 22 '20 at 21:56
  • 1
    `$foo` is an immediate operand. (The symbol address). `foo` is a memory reference; the memory *at* that symbol address. Read an AT&T syntax tutorial or guide if you don't know the basics. https://stackoverflow.com/tags/att/info – Peter Cordes Aug 22 '20 at 22:02

0 Answers0