opt_test.nx source
↩ module page · 51 lines · 1413 B
1// opt_test.nx -- self-test for opt.nx.
2//
3// Builds a trivial IR for `(10+20)*3`, runs opt_run, checks the
4// result collapsed to const 90.
5
6import "syscalls.nx"
7import "types.nx"
8import "ir.nx"
9import "opt.nx"
10
11func main() -> i64 {
12 let m_raw: *u8 = sys_mmap(256)
13 let m: *Module = m_raw as *Module
14 m.name = "opt_test" as *u8
15 m.functions = 0 as *Function
16 m.n_functions = 0
17
18 let f: *Function = ir_function_new(m, "main" as *u8, 4, ir_type_i64())
19 let b: *BasicBlock = ir_block_new(f)
20
21 let c10: i64 = ir_const_i64(f, 10)
22 let c20: i64 = ir_const_i64(f, 20)
23 let c3: i64 = ir_const_i64(f, 3)
24 let sum: i64 = ir_emit_binop(b, OP_ADD, c10, c20, ir_type_i64())
25 let prod: i64 = ir_emit_binop(b, OP_MUL, sum, c3, ir_type_i64())
26 ir_emit_return(b, prod)
27
28 if f.n_values != 5 { return 10 }
29 if f.n_instrs != 3 { return 11 }
30
31 opt_run(f)
32
33 let vp: *Value = val_at(f, prod)
34 if vp.kind != VK_CONST_INT { return 20 }
35 if vp.const_int != 90 { return 21 }
36
37 var count: i64 = 0
38 var inst: *Instr = b.head
39 while inst != (0 as *Instr) {
40 count = count + 1
41 inst = inst.next
42 }
43 if count < 1 { return 30 }
44 if count > 2 { return 31 }
45
46 let vop: *Value = val_at(f, b.tail.op0)
47 if vop.kind != VK_CONST_INT { return 40 }
48 if vop.const_int != 90 { return 41 }
49
50 return 0
51}