Repository navigation
Calling Conventions 08 tail calls
Relevant source files
The following files were used as context for generating this wiki page:
How AArch64 decides whether a call marked tail can really be a tail call, and what LowerCall does differently for it. Line numbers for AArch64ISelLowering.cpp are from the committed file at a2171756.
if (IsTailCall) {
// Check if it's really possible to do a tail call.
IsTailCall = isEligibleForTailCallOptimization(CLI);
// A sibling call is one where we're under the usual C ABI and not planning
// to change that but can still do a tail call:
if (!ZAMarkerNode && !TailCallOpt && IsTailCall &&
CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
IsSibCall = true;
...
}
if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
report_fatal_error("failed to perform tail call elimination on a call "
"site marked musttail");The IR tail marker is only a hint; the target decides. musttail turns a "no" into a fatal error.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10516-10532
The checks, in order (function starts at line 10055):
| Check | Lines | Why |
|---|---|---|
Callee convention can be tail called (mayTailCallThisCC) |
10058-10059 | Some conventions never allow it |
| SME streaming / ZA state changes | 10071-10079 | State must be restored after the call |
| Windows convention on non-Windows OS | 10091-10096 | X18 must be saved and restored |
Caller has a byval argument |
10098-10105 | The callee's arguments would overwrite it |
Windows inreg sret mismatch |
10107-10121 |
x0 must be returned |
| Guaranteed TCO convention | 10126 | If so, eligible (the remaining checks are for sibcalls) |
| Weak external callee | 10129-10141 | Linker may replace the call with a NOP |
Return values in the same places (resultsCompatible) |
10154-10158 | Callee's return goes straight to our caller |
Callee preserves every register the caller must (regmaskSubsetEqual) |
10159-10169 | Otherwise our caller sees clobbered CSRs |
| Variadic stack arguments | 10181-10191 | Conservatively rejected |
| Stack arguments fit our incoming area | 10209-10212 |
CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea() → no |
| Arguments in callee-saved registers match | 10215-10216 | parametersInCSRMatch |
The stack-size check is why LowerFormalArguments records setBytesInStackArgArea (see LowerFormalArguments).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10055-10218, llvm/lib/CodeGen/CallingConvLower.cpp:264
| Normal call | Sibling call | Guaranteed tail call | |
|---|---|---|---|
NumBytes |
Stack size of arguments | 0 | Aligned to 16; FPDiff = reusable bytes − needed |
CALLSEQ_START |
Yes | No | Yes, with 0 |
| Stack argument stores | SP + offset |
Into the caller's incoming area | Into fixed objects offset by FPDiff
|
| Node | AArch64ISD::CALL |
AArch64ISD::TC_RETURN |
AArch64ISD::TC_RETURN |
| After the node |
CALLSEQ_END, result copies |
Nothing: it ends the block | Nothing |
// Get a count of how many bytes are to be pushed on the stack.
unsigned NumBytes = CCInfo.getStackSize();
if (IsSibCall) {
// Since we're not changing the ABI to make this a tail call, the memory
// operands are already available in the caller's incoming argument space.
NumBytes = 0;
}
...
// If we're doing a tall call, use a TC_RETURN here rather than an
// actual call instruction.
if (IsTailCall) {
MF.getFrameInfo().setHasTailCall();
SDValue Ret = DAG.getNode(Opc, DL, MVT::Other, Ops);
...
return Ret;
}setHasTailCall tells frame lowering that the epilogue must be placed before the TC_RETURN jump (see the frame wiki).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10534-10560, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11091-11105
declare i64 @g(i64)
define i64 @sib(i64 %x) {
%r = tail call i64 @g(i64 %x)
ret i64 %r
}
define i64 @notail(i64 %x) {
%r = call i64 @g(i64 %x)
%s = add i64 %r, %x
ret i64 %s
}After instruction selection (-stop-after=finalize-isel), sib has no call frame and no return, just the tail-call pseudo carrying the register mask:
%0:gpr64 = COPY $x0
$x0 = COPY %0
TCRETURNdi @g, 0, csr_aarch64_aapcs, implicit $sp, implicit $x0
Final assembly (llc -O2 -mtriple=aarch64-linux-gnu):
sib: // @sib
.cfi_startproc
b g
.Lfunc_end0:
.cfi_endproc
notail: // @notail
.cfi_startproc
stp x30, x19, [sp, #-16]! // 16-byte Folded Spill
.cfi_def_cfa_offset 16
.cfi_offset w19, -8
.cfi_offset w30, -16
mov x19, x0
bl g
add x0, x0, x19
ldp x30, x19, [sp], #16 // 16-byte Folded Reload
retnotail cannot be a tail call because work remains after the call, so it needs a frame, a saved link register and a callee-saved register for %x.
Tail calls are optional. Return false from your eligibility check (or ignore CLI.IsTailCall, setting it to false) until normal calls work; only musttail IR then fails. When adding sibling calls, start with the strictest version: same calling convention, no stack arguments, no byval, results in the same registers. Add a TCRETURN pseudo that the epilogue code recognizes and that expands to a branch after frame lowering.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look