Skip to content

Calling Conventions 09 custom backend

Mugundan edited this page Nov 27, 2026 · 1 revision

Custom Backend Guide and Checklist

Relevant source files

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

This page puts the pieces together for a made-up "Toy" target: a 32-bit machine with arguments in `r0`–`r3`, then the stack; results in `r0`/`r1`; `r8`–`r11` and `lr` callee-saved. Every code block is **illustrative, not LLVM source**; check exact signatures against `TargetLowering.h` at your LLVM version.

Purpose and Scope

The files to write, a complete LowerCall, and a checklist with tests. LowerFormalArguments and LowerReturn for Toy are on LowerFormalArguments and LowerReturn. Where this fits in a whole backend is on the bring-up wiki.

Files

File Contents
ToyCallingConv.td CC_Toy, RetCC_Toy, CSR_Toy
Toy.td include "ToyCallingConv.td" after the registers
CMakeLists.txt tablegen(LLVM ToyGenCallingConv.inc -gen-callingconv)
ToyISelLowering.cpp #include "ToyGenCallingConv.inc", the three hooks, CanLowerReturn
ToyInstrInfo.td ToyISD::CALL/RET nodes, CALL, RET, ADJCALLSTACKDOWN/UP pseudos
ToyRegisterInfo.cpp getCalleeSavedRegs → CSR_Toy_SaveList, getCallPreservedMask → CSR_Toy_RegMask
ToyFrameLowering.cpp eliminateCallFramePseudoInstr

TableGen

def CC_Toy : CallingConv<[
  CCIfByVal<CCPassByVal<4, 4>>,
  CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
  CCIfType<[i32], CCAssignToReg<[R0, R1, R2, R3]>>,
  CCIfType<[i32], CCAssignToStack<4, 4>>
]>;
def RetCC_Toy : CallingConv<[
  CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
  CCIfType<[i32], CCAssignToReg<[R0, R1]>>
]>;
def CSR_Toy : CalleeSavedRegs<(add R8, R9, R10, R11, LR)>;

// Call-frame pseudos: become CALLSEQ_START / CALLSEQ_END
let Defs = [SP], Uses = [SP] in {
def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2),
                              [(callseq_start timm:$amt1, timm:$amt2)]>;
def ADJCALLSTACKUP   : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2),
                              [(callseq_end timm:$amt1, timm:$amt2)]>;
}

The call-frame pseudos must also be passed to the TargetInstrInfo constructor (ToyGenInstrInfo(STI, Toy::ADJCALLSTACKDOWN, Toy::ADJCALLSTACKUP)), so that generic code knows their opcodes.

LowerCall

SDValue ToyTargetLowering::LowerCall(CallLoweringInfo &CLI,
                                     SmallVectorImpl<SDValue> &InVals) const {
  SelectionDAG &DAG = CLI.DAG;
  SDLoc DL = CLI.DL;
  MachineFunction &MF = DAG.getMachineFunction();
  CLI.IsTailCall = false;                         // no tail calls yet

  SmallVector<CCValAssign, 16> ArgLocs;
  CCState CCInfo(CLI.CallConv, CLI.IsVarArg, MF, ArgLocs, *DAG.getContext());
  CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Toy);
  unsigned NumBytes = CCInfo.getStackSize();

  SDValue Chain = DAG.getCALLSEQ_START(CLI.Chain, NumBytes, 0, DL);

  SmallVector<std::pair<Register, SDValue>, 4> RegsToPass;
  SmallVector<SDValue, 8> MemOps;
  SDValue SP = DAG.getRegister(Toy::SP, MVT::i32);
  for (unsigned i = 0; i != ArgLocs.size(); ++i) {
    CCValAssign &VA = ArgLocs[i];
    SDValue Arg = CLI.OutVals[i];
    switch (VA.getLocInfo()) {
    case CCValAssign::Full: break;
    case CCValAssign::SExt: Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); break;
    case CCValAssign::ZExt: Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); break;
    case CCValAssign::AExt: Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); break;
    default: llvm_unreachable("unexpected LocInfo");
    }
    if (VA.isRegLoc()) {
      RegsToPass.push_back({VA.getLocReg(), Arg});
    } else {
      SDValue Addr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP,
                                 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
      MemOps.push_back(DAG.getStore(Chain, DL, Arg, Addr, MachinePointerInfo()));
    }
  }
  if (!MemOps.empty())
    Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);

  SDValue Glue;
  for (auto &[Reg, Val] : RegsToPass) {
    Chain = DAG.getCopyToReg(Chain, DL, Reg, Val, Glue);
    Glue = Chain.getValue(1);
  }

  SDValue Callee = CLI.Callee;
  if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, MVT::i32);
  else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee))
    Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);

  SmallVector<SDValue, 8> Ops = {Chain, Callee};
  for (auto &[Reg, Val] : RegsToPass)
    Ops.push_back(DAG.getRegister(Reg, Val.getValueType()));
  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
  Ops.push_back(DAG.getRegisterMask(TRI->getCallPreservedMask(MF, CLI.CallConv)));
  if (Glue.getNode())
    Ops.push_back(Glue);

  Chain = DAG.getNode(ToyISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
  Glue = Chain.getValue(1);
  Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
  Glue = Chain.getValue(1);

  SmallVector<CCValAssign, 4> RVLocs;
  CCState RetInfo(CLI.CallConv, CLI.IsVarArg, MF, RVLocs, *DAG.getContext());
  RetInfo.AnalyzeCallResult(CLI.Ins, RetCC_Toy);
  for (CCValAssign &VA : RVLocs) {
    SDValue V = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
    Chain = V.getValue(1);
    Glue = V.getValue(2);
    if (VA.getLocVT() != VA.getValVT())
      V = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), V);
    InVals.push_back(V);
  }
  return Chain;
}

This follows the same order as AArch64's version (see LowerCall): analyze, CALLSEQ_START, convert, store or queue, glued copies, call node with mask, CALLSEQ_END, results.

Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10442-10492, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11063-11129, llvm/include/llvm/CodeGen/CallingConvLower.h:284-304

Checklist

  • CC_Toy and RetCC_Toy cover every legal type (otherwise unable to allocate function argument #N)
  • CSR_Toy matches the ABI document; getCalleeSavedRegs and getCallPreservedMask return it
  • LowerFormalArguments: one InVals entry per Ins entry, registers via addLiveIn, stack via CreateFixedObject
  • LowerReturn: glued copies, return registers as operands of the return node
  • CanLowerReturn uses CheckReturn, so large returns are demoted to sret
  • LowerCall: register mask on every call; CALLSEQ_START/END with the right byte count
  • ADJCALLSTACKDOWN/UP pseudos registered with TargetInstrInfo, removed by eliminateCallFramePseudoInstr
  • Extensions: arguments marked signext/zeroext are extended by the caller (LocInfo SExt/ZExt)
  • Varargs and tail calls disabled until the basics pass
Test Expect
i32 f(i32 a, i32 b) { return a + b; } a in r0, b in r1, result in r0
Six i32 arguments Fifth and sixth loaded from the incoming stack area
Call with six arguments Two stores to [sp], [sp+4]; ADJCALLSTACKDOWN 8 in MIR
i8 signext argument Caller sign-extends; callee sees AssertSext
Value live across a call Allocator uses r8–r11; prologue saves it
i64 return on 32-bit Toy Split over r0/r1
i128 return Demoted to a hidden sret pointer

Run each with llc -march=toy -verify-machineinstrs and compare with -stop-after=finalize-isel output, as in the AArch64 walkthroughs.

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