Skip to content

Frame Lowering 04 pei pass

Mugundan edited this page Nov 27, 2026 · 1 revision

The PEI Pass

Relevant source files

The following files were used as context for generating this wiki page:

The prologue/epilogue insertion pass (`PEIImpl`, pass name `prolog-epilog`) runs once per function after register allocation and shrink wrapping. It performs the steps below in a fixed order. Each step either changes `MachineFrameInfo` or the instructions, and several call target hooks.

Purpose and Scope

The order of steps in PEIImpl::run and what each one does. The hooks themselves are on TargetFrameLowering Hooks.

The Order

bool PEIImpl::run(MachineFunction &MF) {
  ...
  RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr;
  FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF);
  ...
  TFI->spillFPBP(MF);
  ...
  calculateCallFrameInfo(MF);
  ...
  calculateSaveRestoreBlocks(MF);
  ...
  if (MF.getTarget().usesPhysRegsForValues())
    spillCalleeSavedRegs(MF);
  ...
  TFI->processFunctionBeforeFrameFinalized(MF, RS);
  ...
  calculateFrameObjectOffsets(MF);
  ...
  if (!F.hasFnAttribute(Attribute::Naked))
    insertPrologEpilogCode(MF);
  ...
  TFI->processFunctionBeforeFrameIndicesReplaced(MF, RS);
  ...
  if (TFI->needsFrameIndexResolution(MF)) {
    ...
    if (TRI->eliminateFrameIndicesBackwards())
      replaceFrameIndicesBackward(MF);
    else
      replaceFrameIndices(MF);
  }
  ...
  if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
    scavengeFrameVirtualRegs(MF, *RS);
flowchart TD
    A["1. calculateCallFrameInfo<br/>max call frame size; remove call-frame pseudos"] --> B["2. calculateSaveRestoreBlocks<br/>entry + return blocks, or shrink-wrap points"]
    B --> C["3. spillCalleeSavedRegs<br/>determineCalleeSaves, slots, save/restore code"]
    C --> D["4. processFunctionBeforeFrameFinalized (target)"]
    D --> E["5. calculateFrameObjectOffsets<br/>offset for every object, stack size"]
    E --> F["6. insertPrologEpilogCode<br/>emitPrologue / emitEpilogue"]
    F --> G["7. replaceFrameIndices<br/>eliminateFrameIndex per operand"]
    G --> H["8. scavengeFrameVirtualRegs"]
Loading

Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:211-283

1. Call Frame Information

calculateCallFrameInfo computes MaxCallFrameSize (the largest outgoing argument area) from the ADJCALLSTACKDOWN/UP pseudos. If the target can simplify them (canSimplifyCallFramePseudos, true when the call frame is reserved), it calls eliminateCallFramePseudoInstr on each one right away. Targets with no call-frame pseudos (opcode ~0u) skip the whole step.

Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:370-407

2. Save and Restore Blocks

  // Use the points found by shrink-wrapping, if any.
  if (!MFI.getSavePoints().empty()) {
    ...
    SaveBlocks.push_back(SavePoint.first);
    ...
    return;
  }

  // Save refs to entry and return blocks.
  SaveBlocks.push_back(&MF.front());
  for (MachineBasicBlock &MBB : MF) {
    if (MBB.isEHFuncletEntry())
      SaveBlocks.push_back(&MBB);
    if (MBB.isReturnBlock())
      RestoreBlocks.push_back(&MBB);
  }

Without shrink wrapping, the prologue goes in the entry block and an epilogue in every return block. A tail-call block (ending in TCRETURN) is a return block too, so it gets an epilogue before its jump.

Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:411-443

3. Callee-Saved Registers

  // Determine which of the registers in the callee save list should be saved.
  BitVector SavedRegs;
  TFI->determineCalleeSaves(MF, SavedRegs, RS);

  // Assign stack slots for any callee-saved registers that must be spilled.
  assignCalleeSavedSpillSlots(MF, SavedRegs);
  ...
      for (MachineBasicBlock *SaveBlock : SaveBlocks)
        insertCSRSaves(*SaveBlock, CSI);

insertCSRSaves (line 618) first offers the whole list to the target's spillCalleeSavedRegisters. If that returns false, it calls TargetFrameLowering::spillCalleeSavedRegister once per register, and that default calls TII->storeRegToStackSlot. insertCSRRestores (634) does the same before the block's first terminator, in reverse order, through restoreCalleeSavedRegister and loadRegFromStackSlot:

  MachineBasicBlock::iterator I = SaveBlock.begin();
  if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
    for (const CalleeSavedInfo &CS : CSI) {
      TFI->spillCalleeSavedRegister(SaveBlock, I, CS, TII, TRI);
    }
  }

Details on Callee-Saved Registers.

Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:652-700, llvm/lib/CodeGen/PrologEpilogInserter.cpp:618-650, llvm/lib/CodeGen/TargetFrameLoweringImpl.cpp:211-240

5. Frame Object Offsets

calculateFrameObjectOffsets walks the objects in a fixed order: past the fixed objects, then callee-saved slots, then the local block, then other objects (protected objects for stack protectors first), aligning each one. Offsets are measured in the direction of stack growth from the incoming SP:

  // Start at the beginning of the local area.
  // The Offset is the distance from the stack top in the direction
  // of stack growth -- so it's always nonnegative.
  int LocalAreaOffset = TFI.getOffsetOfLocalArea();

At the end it adds MaxCallFrameSize if the call frame is reserved, then rounds up to the stack alignment. It uses getStackAlign() if the function has calls or allocas, otherwise getTransientStackAlign(), and in either case at least the largest object alignment. Finally it calls setStackSize. For AArch64 withcall the result is stackSize: 16 with x19 at offset −8 and lr at −16 (see MachineFrameInfo).

Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:854-900, llvm/lib/CodeGen/PrologEpilogInserter.cpp:1112-1158

6. Prologue and Epilogue

  // Add prologue to the function...
  for (MachineBasicBlock *SaveBlock : SaveBlocks)
    TFI.emitPrologue(MF, *SaveBlock);

  // Add epilogue to restore the callee-save registers in each exiting block.
  for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
    TFI.emitEpilogue(MF, *RestoreBlock);

Then optional extras: zeroing call-used registers, inline stack probes, segmented stacks, HiPE. The prologue is emitted after the callee-saved stores already placed by step 3, so emitPrologue usually skips over them (they carry the FrameSetup flag).

Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:1165-1199

7–8. Frame Indices and Scavenging

replaceFrameIndices (line 1377) walks every instruction, tracks the SP adjustment between call-frame pseudos that were not removed, and calls TRI->eliminateFrameIndex for each frame-index operand. Targets that set eliminateFrameIndicesBackwards use replaceFrameIndicesBackward (1349), which lets the register scavenger run backwards in the same walk. Any virtual registers the target created during elimination are then given physical registers by scavengeFrameVirtualRegs. See Frame Index Elimination.

Sources: llvm/lib/CodeGen/PrologEpilogInserter.cpp:1349-1392

Seeing It

llc -O2 -mtriple=aarch64-linux-gnu -stop-before=prolog-epilog and -stop-after=prolog-epilog print the function on either side of this pass; the walkthroughs compare them.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally