Created
May 20, 2013 22:55
-
-
Save alxhill/5616252 to your computer and use it in GitHub Desktop.
Factorial in LLVM bytecode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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