Skip to content

Instantly share code, notes, and snippets.

@mepcotterell
Last active February 19, 2019 12:32
Show Gist options
  • Save mepcotterell/0c28275ed0b6d996066608799b10582b to your computer and use it in GitHub Desktop.
Save mepcotterell/0c28275ed0b6d996066608799b10582b to your computer and use it in GitHub Desktop.
/* This file contains an unoptimized, recursive GCD implementation. */
/* The code assumes %rdi and %rsi will be unsigned... if signed, then cqto will be needed to sign-extend %rax to %rdx:%rax. */
/* What are some ways to optimize it? */
.data
fmtstr:
.ascii "%d\n"
.text
.globl gcd
.type gcd, @function
gcd:
pushq %rbp ;
movq %rsp, %rbp ;
pushq %rbx ;
cmpq $0, %rsi ;
jnz gcd_b_nz ;
jmp gcd_cont ;
gcd_b_nz:
movq $0, %rdx ; // %rdx:%rax see next
movq %rdi, %rax ; // %rdx:%rax is the 128-bit dividend (numerator)
movq %rsi, %rbx ; // %rbx is the 64-bit divisor (denominator)
divq %rbx ; // perform %rdx:%rax ÷ %rbx (unsigned)
movq %rsi, %rdi ;
movq %rdx, %rsi ;
callq gcd ;
gcd_cont:
movq %rdi, %rax ;
popq %rbx ;
movq %rbp, %rsp ;
popq %rbp ;
ret ;
.text
.globl main
.type main, @function
main:
pushq %rbp ;
movq %rsp, %rbp ;
movq $54, %rdi ;
movq $24, %rsi ;
callq gcd ;
movq $fmtstr, %rdi ;
movq %rax, %rsi ;
xorl %eax, %eax ; // for a variadic call, %eax should indicate number of floating point parameters
callq printf ;
xorl %eax, %eax ;
movq %rbp, %rsp ;
popq %rbp ;
ret ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment