1 2 // This examples creates and runs the equivalent of this C function: 3 // 4 // int square(int i) 5 // { 6 // return i * i; 7 // } 8 9 module gccjitd.examples.square; 10 11 import gccjit.d; 12 13 JITResult create_fn() 14 { 15 // Create a compilation context 16 JITContext ctxt = new JITContext(); 17 18 // Turn these on to get various kinds of debugging 19 version(none) 20 { 21 ctxt.setOption(JITBoolOption.DUMP_INITIAL_TREE, true); 22 ctxt.setOption(JITBoolOption.DUMP_INITIAL_GIMPLE, true); 23 ctxt.setOption(JITBoolOption.DUMP_GENERATED_CODE, true); 24 } 25 26 // Adjust this to control optimization level of the generated code 27 version(none) 28 ctxt.setOption(JITIntOption.OPTIMIZATION_LEVEL, 3); 29 30 // Create parameter "i" 31 JITParam param_i = ctxt.newParam(JITTypeKind.INT, "i"); 32 // Create the function 33 JITFunction fn = ctxt.newFunction(JITFunctionKind.EXPORTED, 34 JITTypeKind.INT, 35 "square", false, param_i); 36 37 // Create a basic block within the function 38 JITBlock block = fn.newBlock("entry"); 39 40 // This basic block is relatively simple 41 block.endWithReturn(ctxt.newBinaryOp(JITBinaryOp.MULT, 42 ctxt.getType(JITTypeKind.INT), 43 param_i, param_i)); 44 45 // Having populated the context, compile it 46 JITResult result = ctxt.compile(); 47 return result; 48 } 49 50 int square(int i) 51 { 52 JITResult result = create_fn(); 53 54 // Look up a specific machine code routine within the JITResult, 55 // in this case, the function we created above. 56 void *void_ptr = result.getCode("square"); 57 58 // Now turn it into something we can call from D. 59 auto code = cast(int function(int))(void_ptr); 60 61 // Now try running the code 62 return code(i); 63 } 64 65 void main() 66 { 67 import std.stdio : writeln; 68 writeln(square(5)); 69 }