Docsity

Function Calls & Returns in HPC: Stack Implementation & Memory Management, Slides of Computer Science

Partial preview of the text

Download Function Calls & Returns in HPC: Stack Implementation & Memory Management and more Slides Computer Science in PDF only on Docsity!

High Performance Computing

Lecture 8

2

Example: Function Call and Return

What must be done on a function call?

 Pass parameters on stack  Transfer control to start of function  Remember return address  Where?  Save register values  Allocate space for local variables on stack

What must be done on a function return?

 Pass return value (through stack)  Restore register values  Clean up stack  Transfer control back to return address On a stack (in main memory) on stack from the stack

4

Implementing a Stack in Memory.

0x 0x 0x 0x R29 0x PushByte: SUBI R29, R29, 1 SB 0(R29), Rs PopByte: LB Rd, 0(R29) ADDI R29, R29, 1 Example: Growing down (into lower addresses) in memory R29 pointing at current top of stack element

5

Function Call and Return

void A() { … B(5); … } void B (int x) { int a, b; … return(); } ADDI R1, R0, 5 ADDI R29, R29, 4 SW 0(R29), R B:

5 (int x) Function Call/Return Stack JAL B

7

Function Call and Return

void A() { … B(5); … } void B (int x) { int a, b; … return(); } ADDI R1, R0, 5 ADDI R29, R29, 4 SW 0(R29), R JAL B ADDI R29, R29, 4 SW 0(R29), R B:

5 (int x) Return address Local int a Local int b ADDI R29, R29, 8 … SUBI R29, R29, 16 LW R31, 8(R29) JR R Function Call/Return Stack

8

Use of Main Memory by a Program

 Instructions (code, text)

 Data used in different ways

 Stack allocated

 Heap allocated

 Statically allocated

text data stack heap Use of memory addresses

10

Heap Allocated Variables

 Managed by a memory allocation library

 Functions like malloc, realloc ,free

 Get `linked’ (joined) to your program if they

are called

 Executed just like other program functions

 What about growth of the heap area?

 Managed by the library functions