Cairo’s Function Exercise I

Compile and run (with at least 10 steps) the following code. Use the –print_memory and –relocate_prints flags for cairo-run.

func main():
    call foo
    call foo
    call foo

    ret
end

func foo():
    [ap] = 1000; ap++
    ret
end

Try to think what happens when the cpu gets to the ret instruction (which of the registers ap, fp, pc should change when ret is executed and to what values?).

Solution

For starters, here’s the memory profile of the exercise execution:

$ cairo-compile exercise.cairo --output exercise.json 
$ cairo-run --program=exercise.json --print_memory --relocate_prints
>>>
Addr  Value
-----------
⋮
1     1226245742482522112
2     7
3     1226245742482522112
4     5
5     1226245742482522112
6     3
7     2345108766317314046
8     5189976364521848832
9     1000
10    2345108766317314046
11    22
12    22
13    13
14    3
15    1000
16    13
17    5
18    1000
19    13
20    7
21    1000

Our program invokes the function foo three times and from the docs we are told that function calls work similar to program jumps. We can then infer that the number 1226245742482522112 is a jump instruction and that the integer that appears right after is how many places the pc counter should be moved forward to arrive at the beginning of foo

The first jump requires the pc counter to move 7 places forward and that would take us to memory address 8 where we find what I believe is an ap assignment instruction (5189976364521848832) as it is followed by the number 1000.

Of course, a function call differs from a regular jump in that we will need to jump back to the caller when the called function ends (returns). Jumping back means not only moving back the pc pointer but also moving back the fp pointer as we have to go back to the original scope. Right before our first jump we can see that the compiler stores on address 13 the value 13 as in, “this is where fp should be pointing to after foo returns”; and on address 14 the value 3 as in, “this is where pc should be pointing to resume its execution on main”.

Reference

The exercise in this article can be found in this section of the Cairo docs.

So, what do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.