1# RUN: %PYTHON %s | FileCheck %s 2 3import gc 4import io 5import itertools 6from mlir.ir import * 7from mlir.dialects import builtin 8from mlir.dialects import cf 9from mlir.dialects import func 10 11 12def run(f): 13 print("\nTEST:", f.__name__) 14 f() 15 gc.collect() 16 assert Context._get_live_count() == 0 17 return f 18 19 20# CHECK-LABEL: TEST: testBlockCreation 21# CHECK: func @test(%[[ARG0:.*]]: i32, %[[ARG1:.*]]: i16) 22# CHECK: cf.br ^bb1(%[[ARG1]] : i16) 23# CHECK: ^bb1(%[[PHI0:.*]]: i16): 24# CHECK: cf.br ^bb2(%[[ARG0]] : i32) 25# CHECK: ^bb2(%[[PHI1:.*]]: i32): 26# CHECK: return 27@run 28def testBlockCreation(): 29 with Context() as ctx, Location.unknown(): 30 module = Module.create() 31 with InsertionPoint(module.body): 32 f_type = FunctionType.get( 33 [IntegerType.get_signless(32), 34 IntegerType.get_signless(16)], []) 35 f_op = func.FuncOp("test", f_type) 36 entry_block = f_op.add_entry_block() 37 i32_arg, i16_arg = entry_block.arguments 38 successor_block = entry_block.create_after(i32_arg.type) 39 with InsertionPoint(successor_block) as successor_ip: 40 assert successor_ip.block == successor_block 41 func.ReturnOp([]) 42 middle_block = successor_block.create_before(i16_arg.type) 43 44 with InsertionPoint(entry_block) as entry_ip: 45 assert entry_ip.block == entry_block 46 cf.BranchOp([i16_arg], dest=middle_block) 47 48 with InsertionPoint(middle_block) as middle_ip: 49 assert middle_ip.block == middle_block 50 cf.BranchOp([i32_arg], dest=successor_block) 51 print(module.operation) 52 # Ensure region back references are coherent. 53 assert entry_block.region == middle_block.region == successor_block.region 54 55 56# CHECK-LABEL: TEST: testFirstBlockCreation 57# CHECK: func @test(%{{.*}}: f32) 58# CHECK: return 59@run 60def testFirstBlockCreation(): 61 with Context() as ctx, Location.unknown(): 62 module = Module.create() 63 f32 = F32Type.get() 64 with InsertionPoint(module.body): 65 f = func.FuncOp("test", ([f32], [])) 66 entry_block = Block.create_at_start(f.operation.regions[0], [f32]) 67 with InsertionPoint(entry_block): 68 func.ReturnOp([]) 69 70 print(module) 71 assert module.operation.verify() 72 assert f.body.blocks[0] == entry_block 73 74 75# CHECK-LABEL: TEST: testBlockMove 76# CHECK: %0 = "realop"() ({ 77# CHECK: ^bb0([[ARG0:%.+]]: f32): 78# CHECK: "ret"([[ARG0]]) : (f32) -> () 79# CHECK: }) : () -> f32 80@run 81def testBlockMove(): 82 with Context() as ctx, Location.unknown(): 83 ctx.allow_unregistered_dialects = True 84 module = Module.create() 85 f32 = F32Type.get() 86 with InsertionPoint(module.body): 87 dummy = Operation.create("dummy", regions=1) 88 block = Block.create_at_start(dummy.operation.regions[0], [f32]) 89 with InsertionPoint(block): 90 ret_op = Operation.create("ret", operands=[block.arguments[0]]) 91 realop = Operation.create("realop", 92 results=[r.type for r in ret_op.operands], 93 regions=1) 94 block.append_to(realop.operation.regions[0]) 95 dummy.operation.erase() 96 print(module) 97