Skip to content

Calling Conventions 03 ccstate

Mugundan edited this page Nov 27, 2026 · 1 revision

CCState and CCValAssign

Relevant source files

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

`CCState` is the bookkeeping object passed to every generated calling-convention function. It records which registers are already taken and how much stack has been used, and it collects the result: one `CCValAssign` per value, saying "this value lives in register R" or "this value lives at stack offset N", plus how it was extended or converted on the way.

Purpose and Scope

The CCValAssign record, the CCAssignFn signature, the CCState allocation functions and the Analyze* drivers. How the three lowering hooks consume the result is on LowerFormalArguments, LowerCall and LowerReturn.

Data Flow

flowchart LR
    INS["Ins / Outs<br/>(ISD::InputArg / OutputArg)"] --> AN["CCState::Analyze*"]
    AN -->|"for each value"| FN["CCAssignFn<br/>(generated CC_Toy)"]
    FN -->|"AllocateReg / AllocateStack"| ST["CCState: UsedRegs, StackSize"]
    FN -->|"addLoc"| LOCS["SmallVector&lt;CCValAssign&gt;"]
    LOCS --> HOOK["target hook walks the list"]
Loading

CCValAssign

Each entry holds the value number, its original type (ValVT), the type in the location (LocVT), either a register or a stack offset, and a LocInfo describing the conversion:

class CCValAssign {
public:
  enum LocInfo {
    Full,      // The value fills the full location.
    SExt,      // The value is sign extended in the location.
    ZExt,      // The value is zero extended in the location.
    AExt,      // The value is extended with undefined upper bits.
    ...
    BCvt,      // The value is bit-converted in the location.
    Trunc,     // The value is truncated in the location.
    ...
    FPExt,     // The floating-point value is fp-extended in the location.
    Indirect   // The location contains pointer to the value.
Accessor Meaning
isRegLoc() / getLocReg() Value is in a physical register
isMemLoc() / getLocMemOffset() Value is on the stack at this offset from the start of the argument area
getValVT() / getLocVT() Type before and after conversion
getLocInfo() How to convert (SExt → emit AssertSext on entry, SIGN_EXTEND at a call, ...)
needsCustom() Set by a CCCustom handler; the hook must handle it specially

Sources: llvm/include/llvm/CodeGen/CallingConvLower.h:34-55

The CCAssignFn Signature

Every Entry = 1 record becomes a function of this type:

typedef bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT,
                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
                        Type *OrigTy, CCState &State);

It returns false when it assigned a location and true when no rule matched. Targets can also write these by hand and mix them with generated ones.

Sources: llvm/include/llvm/CodeGen/CallingConvLower.h:157-166

Allocation

CCAssignToReg<[...]> turns into a call to AllocateReg, which picks the first unallocated register in the list and marks it (and its aliases) used:

  MCRegister AllocateReg(ArrayRef<MCPhysReg> Regs) {
    unsigned FirstUnalloc = getFirstUnallocated(Regs);
    if (FirstUnalloc == Regs.size())
      return MCRegister();    // Didn't find the reg.

    // Mark the register and any aliases as allocated.
    MCPhysReg Reg = Regs[FirstUnalloc];
    MarkAllocated(Reg);
    return Reg;

Because aliases are marked, assigning W0 also makes X0 unavailable. CCAssignToStack<Size, Align> becomes AllocateStack:

  int64_t AllocateStack(unsigned Size, Align Alignment) {
    int64_t Offset;
    if (NegativeOffsets) {
      StackSize = alignTo(StackSize + Size, Alignment);
      Offset = -StackSize;
    } else {
      Offset = alignTo(StackSize, Alignment);
      StackSize = Offset + Size;
    }
    MaxStackArgAlign = std::max(Alignment, MaxStackArgAlign);
    ensureMaxAlignment(Alignment);
    return Offset;
  }

After the analysis, getStackSize() is the total size of the outgoing (or incoming) stack argument area. LowerCall passes it to CALLSEQ_START.

Sources: llvm/include/llvm/CodeGen/CallingConvLower.h:246, llvm/include/llvm/CodeGen/CallingConvLower.h:333-360, llvm/include/llvm/CodeGen/CallingConvLower.h:408-431

The Analyze Drivers

Function Used by Input On failure
AnalyzeFormalArguments(Ins, Fn) LowerFormalArguments ISD::InputArg report_fatal_error("unable to allocate function argument #N")
AnalyzeCallOperands(Outs, Fn) LowerCall ISD::OutputArg llvm_unreachable (prints the type in debug builds)
AnalyzeCallResult(Ins, Fn) LowerCall ISD::InputArg fatal error
AnalyzeReturn(Outs, Fn) LowerReturn ISD::OutputArg report_fatal_error("unable to allocate function return #N")
CheckReturn(Outs, Fn) CanLowerReturn ISD::OutputArg returns false

All of them are the same loop: call Fn for each value with ValVT == LocVT and LocInfo == Full:

CCState::AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
                                CCAssignFn Fn) {
  unsigned NumArgs = Ins.size();

  for (unsigned i = 0; i != NumArgs; ++i) {
    MVT ArgVT = Ins[i].VT;
    ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
    if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, Ins[i].OrigTy, *this))
      report_fatal_error("unable to allocate function argument #" + Twine(i));
  }
}

CheckReturn is the only one that does not fail: it is used to ask whether the return fits, and if not, LLVM rewrites the function to return through a hidden sret pointer.

AArch64 does not use AnalyzeFormalArguments directly: it writes the loop itself so it can pass the original i8/i16 type as ValVT for stack arguments (see LowerFormalArguments).

Sources: llvm/lib/CodeGen/CallingConvLower.cpp:85-141, llvm/lib/CodeGen/CallingConvLower.cpp:164-180

Construction and byval

CCState::CCState(CallingConv::ID CC, bool IsVarArg, MachineFunction &MF,
                 SmallVectorImpl<CCValAssign> &Locs, LLVMContext &Context,
                 bool NegativeOffsets)

IsVarArg is what CCIfVarArg tests. NegativeOffsets is for targets whose argument area grows the other way.

HandleByVal (reached from CCPassByVal) takes the size and alignment from the byval attribute, lets the target claim registers for part of the aggregate through TargetLowering::HandleByVal, and allocates the rest on the stack:

  Align Alignment = ArgFlags.getNonZeroByValAlign();
  unsigned Size  = ArgFlags.getByValSize();
  ...
  MF.getSubtarget().getTargetLowering()->HandleByVal(this, Size, Alignment);
  Size = unsigned(alignTo(Size, MinAlign));
  uint64_t Offset = AllocateStack(Size, Alignment);
  addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));

Sources: llvm/lib/CodeGen/CallingConvLower.cpp:28-59, llvm/include/llvm/CodeGen/CallingConvLower.h:433-442

Other Helpers

Function Line Use
getRemainingRegParmsForType 203 Registers still free for a type (musttail forwarding)
analyzeMustTailForwardedRegisters 243 Keep unused argument registers live through a musttail vararg thunk
resultsCompatible 264 Do two conventions return values in the same places? (tail-call check)

Sources: llvm/lib/CodeGen/CallingConvLower.cpp:203-264

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