UP | HOME

Pointer ref and deref
Compiler Implementation
COP-3402

Pointer operations in SimpleIR

Reference

t1 := &x

Store the address of x (not the value) in t1.

Dereference

t2 := *t1

t1 is an address. Take the value of memory at the address and store it in t2.

Dereference assignment

*t1 := 11

t1 is an address. Store the value 11 at that address.

Complete example

function main
localvars a b x y t1 t2 t3
params a b
x := 8
y := 9
t1 := &x
t2 := *t1
*t1 := 11
t3 := x
return x

What is the value of x that gets returned?

  • x gets 8
  • t1 gets the address of x
  • 11 gets stored at the address given by t1, which is the address of x
  • x's value is then 11

Stack-allocated variables

How are function-local variables stored at runtime?

Stack frame layout refresher

function main
localvars a b x y t1 t2 t3
params a b
x := 8
y := 9
t1 := &x
t2 := *t1
*t1 := 11
t3 := x
return x

Stack frame layout refresher

(Diagram)

  • Stack frame layout for the main function above.
  • Give numeric addresses to each frame entry.
  • Show %rbp

Assignment

How does assignment work in assembly?

Use an offset from %rbp

mov $8, -24(%rbp)

Getting (referencing) a pointer

t1 := &x

Stack frame, with addresses

How do we get the address?

  • What will hold the stack frame address?
  • What's the offset?
  • Assembly operations to compute the address?

Computing the address

  • Start with %rbp
  • Add the offset (it's negative so it's equivalent to subtraction)
  • Store the result

Does this involve the value of the address in anyway?

A little easier to see in when looking at the stack frame

Computing the address

(Diagram)

Assembly code

Assume the following offsets (see the stack frame)

Variable Offset
x -24
t1 -40

Assembly code

mov %rbp, %rax  # start with stack frame address
add $-24, %rax  # add the offset of the referenced var (x)
mov %rax, -40(%rbp)  # store the result in the assigned var (t1)

(Diagram)

Dereferencing a pointer

t2 := *t1

What's the value of t2?

  • If t1 = 260
  • If t1 = 260 and address 260 holds the value 10?

Following an address

What assembly instructions loads a value from an address?

Register indirect mov

mov (%rax), %rbx

(%rax) here means load the value at the address given in %rax.

Computing the address

  • Get the value of the de-ref'ed variable (the address)
  • Get the value of memory at that address
  • Store that the value of memory at that address

Computing the address

(Diagram)

Assembly code

Assume the following offsets

Variable Offset
x -24
t1 -40
t2 -48

Assembly code

mov -40(%rbp), %rax  # value of the deref'ed variable (t1)
mov (%rax), %rbx  # the value in memory at address %rax (*t1)
mov %rbx, -48(%rbp)  # store the result in the assigned var (t2)

Notice how the value of x is the same as the value of *t1. Why is that?

Show on stack frame why this is the case.

Author: Paul Gazzillo

Created: 2024-11-20 Wed 09:49

Validate