Quiz Entry - updated: 2026.07.14
What does cdq (or cqto) do and when does it appear?
They sign-extend %eax into the %edx:%eax pair (or %rax into %rdx:%rax) so a signed idiv has a correct double-width dividend.
* cdq/cltd sign-extends %eax into %edx:%eax so a signed idiv gets a correct double-width dividend. cqto does the same for %rax into %rdx:%rax. Quotient → %eax, remainder → %edx. *
# Sign-extend eax into edx:eax
cdq
# Then divide edx:eax by ecx
idivl %ecx
Why needed? idiv divides a 64-bit value (%edx:%eax) by a 32-bit divisor. If you only have a 32-bit number in %eax, you need cdq to fill %edx with the sign bit so the 64-bit value represents the same number.
| Instruction | AT&T name | Operation |
|---|---|---|
cdq |
cltd |
Sign-extend %eax → %edx:%eax (32→64) |
cqto |
cqto |
Sign-extend %rax → %rdx:%rax (64→128) |
Pattern — signed division:
mov %esi, %eax
cdq
idivl %ecx
This computes %esi / %ecx (signed). Result in %eax, remainder in %edx.
Go deeper:
CWD/CDQ/CQO (felixcloutier) — Primary reference: CDQ produces a quadword dividend from a doubleword before division; CQO the octaword case.
IDIV signed division (felixcloutier) — Shows idiv dividing EDX:EAX (or RDX:RAX), which is precisely why cdq must run first.