Overview


This is the bonus lab of this course.

In Lab 8, our goal is to extend the existing implementation to let it support array variables as function arguments.

Challenges


Pointer Type

In my existing implementation, array local variables are of the type ArrayType.

However, inside the function body, we need to use Pointer for the array Parameter, since instead of copying the whole array structure when entering the function, we merely transfer the pointer of the array.

To build an ArrayType, we need to use the statement:

type = LLVMPointerType(type, 0);

One important thing to notice is that the pointer we got here is the pointer that points to the array variable, which means that there are 2 indirect layers between the pointer and any of the array elements. So each time we want to use the array parameter, we need to load it first.

classDiagram
direction TD
  Pointer --> Array : load
	Array --> Ele1 : GEP
	Array --> Ele2 : GEP
	Array --> Ele3 : GEP
	Array --> Ele4 : GEP
	Array --> Ele5 : GEP

GEP with Pointer

Everything looks great hitherto until I try to access the array element.

In my previous implementation, all occurrences of the GEP instruction are used with 2 indices.

The operation done by the instruction GEP(x, i, j) is to get the $j$ th field of the $i$ th field of $x$, which works great before, because we only use stack pointer or pre-arranged global memory pointer then.

Therefore, with pure ArrayType, we need to get the element with the instruction GEP(x, i).

<aside> 💡 Why can’t we just skip the load and use GEP(ptr, 0, j)?

GEP won’t do any dereference, and it only computes the offset.

</aside>