Skip to content

Instantly share code, notes, and snippets.

@alxhill
Created May 20, 2013 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alxhill/5616252 to your computer and use it in GitHub Desktop.
Save alxhill/5616252 to your computer and use it in GitHub Desktop.
Factorial in LLVM bytecode
; the string used in printf
@.str = private unnamed_addr constant [4 x i8] c"%d\0A\00", align 1
define i64 @fact(i64 %n) nounwind readnone ssp uwtable {
entry:
; go to retn if n is 1, else branch to retfactn
%0 = icmp eq i64 %n, 1
br i1 %0, label %retn, label %retfactn
retn:
ret i64 %n
retfactn:
; subtract 1 from n and call fact with this value,
; then multiply the result by n
%n1 = add i64 %n, -1
%1 = tail call i64 @fact(i64 %n1) nounwind ssp
%2 = mul i64 %1, %n
ret i64 %2
}
define i32 @main(i32 %argc, i8** nocapture %argv) nounwind ssp {
entry:
; get the factorial value of 15
%0 = tail call i64 @fact(i64 15)
; weird shit needed to call printf...
%1 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([4 x i8]* @.str, i64 0, i64 0), i64 %0) nounwind
ret i32 0
}
declare i32 @printf(i8* nocapture, ...) nounwind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment