Created
May 17, 2014 23:20
-
-
Save ishikawa/c5262168701f8da28e24 to your computer and use it in GitHub Desktop.
This file contains 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
require 'llvm/core' | |
require 'llvm/analysis' | |
require 'llvm/execution_engine' | |
mod = LLVM::Module.new("test.fprintf") | |
str = "value = %d\n" | |
V_STRING = mod.globals.add(LLVM::Array(LLVM::Int8, str.size + 1), "str") do |value| | |
value.linkage = :internal | |
value.unnamed_addr = true | |
value.global_constant = 1 | |
value.initializer = LLVM::ConstantArray.string(str) | |
end | |
# int fprintf(T_FILE * restrict stream, const char * restrict format, ...); | |
T_FILE = LLVM::Type.struct([], false, "struct.FILE") | |
V_STDERR = mod.globals.add(LLVM::Pointer(T_FILE), "__stderrp"); # Mac OS X 10.9 | |
fprintf = mod.functions.add("fprintf", [T_FILE.pointer, LLVM::Pointer(LLVM::Int8)], LLVM::Int, :varargs => true) do |fn, stream, format| | |
stream.name = "stream" | |
format.name = "format" | |
fn.add_attribute(:no_unwind_attribute) | |
end | |
mod.functions.add("main", [], LLVM::Int) do |fn| | |
fn.basic_blocks.append.build do |builder| | |
format = builder.gep(V_STRING, [LLVM::Int(0), LLVM::Int(0)]) | |
stream = builder.load(V_STDERR) | |
builder.call(fprintf, stream, format, LLVM::Int(rand 1000)) | |
builder.ret LLVM::Int(0) | |
end | |
end | |
mod.verify! | |
mod.dump | |
# ; ModuleID = 'test.fprintf' | |
# | |
# %struct.FILE = type opaque | |
# | |
# @str = internal unnamed_addr constant [12 x i8] c"value = %d\0A\00" | |
# @__stderrp = external global %struct.FILE* | |
# | |
# ; Function Attrs: nounwind | |
# declare i32 @fprintf(%struct.FILE*, i8*, ...) #0 | |
# | |
# define i32 @main() { | |
# %1 = load %struct.FILE** @__stderrp | |
# %2 = call i32 (%struct.FILE*, i8*, ...)* @fprintf(%struct.FILE* %1, i8* getelementptr inbounds ([12 x i8]* @str, i32 0, i32 0), i32 406) | |
# ret i32 0 | |
# } | |
# | |
# attributes #0 = { nounwind } | |
# ---- JIT | |
LLVM.init_jit | |
engine = LLVM::JITCompiler.new(mod) | |
engine.run_function(mod.functions["main"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment