Press enter to see results or esc to cancel.

Creating and Destroying Stack Frame

Programs created with Turbo Pascal use stack frame. This is part of the processor’s stack space which can be accessed using a dedicated base pointer (BP) register.

PUSH    BP
MOV     BP, SP
SUB     SP, StackFrameSize
...
...
...
MOV     SP, BP
POP     BP
RET

Stack frame is usually used for local variables. This is very convenient because BP can acces all pushed parameters (using positive offset) and local variables in stack frame (using negative offset). Two procedures generate code to create and destroy stack frame.

Procedure CreateStackFrame;
begin
  If (Instructions80286 in StatementCompilerSwitches) and (ProgramBlockMaxStackFrameOffset <> 0) and
    not (StackChecking in StatementCompilerSwitches) then
      begin
        GenerateInstruction_Byte (ENTER);
        GenerateInstruction_Word (- ProgramBlockMaxStackFrameOffset);
        GenerateInstruction_Byte (0);
      end else begin
                 GenerateInstruction_Byte (PUSH_BP);
                 GenerateInstruction_Word (MOV_BP_SP);
                 If StackChecking in StatementCompilerSwitches then
                  begin
                    GenerateInstruction_MOV_16BitReg_Immediate (rAX, - ProgramBlockMaxStackFrameOffset);
                    GenerateInstruction_CALL_FAR (SysProc_StackCheck);
                  end;
                 If ProgramBlockMaxStackFrameOffset <> 0 then
                   GenerateArithmeticInstruction_16BitReg_Immediate (SUB_SP, - ProgramBlockMaxStackFrameOffset);
               end;
end;

Procedure DestroyStackFrame;
begin
  If Instructions80286 in StatementCompilerSwitches then GenerateInstruction_Byte (LEAVE)
    else begin
           If ProgramBlockMaxStackFrameOffset or NumberOfLocalParameters <> 0 then GenerateInstruction_Word (MOV_SP_BP);
           GenerateInstruction_Byte (POP_BP)
         end;
end;