| 1 | from rpython.translator.translator import TranslationContext |
| 2 | from rpython.translator.backendopt.innerloop import find_inner_loops |
| 3 | from rpython.conftest import option |
| 4 | |
| 5 | def test_simple_loop(): |
| 6 | def snippet_fn(x, y): |
| 7 | while y > 0: |
| 8 | y -= x |
| 9 | return y |
| 10 | t = TranslationContext() |
| 11 | graph = t.buildflowgraph(snippet_fn) |
| 12 | if option.view: |
| 13 | t.view() |
| 14 | loops = find_inner_loops(graph) |
| 15 | assert len(loops) == 1 |
| 16 | loop = loops[0] |
| 17 | assert loop.headblock.operations[0].opname == 'gt' |
| 18 | assert len(loop.links) == 2 |
| 19 | assert loop.links[0] in loop.headblock.exits |
| 20 | assert loop.links[1] in loop.links[0].target.exits |
| 21 | assert loop.links[1].target is loop.headblock |
| 22 | |
| 23 | def test_two_loops(): |
| 24 | def snippet_fn(x, y): |
| 25 | while y > 0: |
| 26 | y -= x |
| 27 | while y < 0: |
| 28 | y += x |
| 29 | return y |
| 30 | t = TranslationContext() |
| 31 | graph = t.buildflowgraph(snippet_fn) |
| 32 | if option.view: |
| 33 | t.view() |
| 34 | loops = find_inner_loops(graph) |
| 35 | assert len(loops) == 2 |
| 36 | assert loops[0].headblock is not loops[1].headblock |
| 37 | for loop in loops: |
| 38 | assert loop.headblock.operations[0].opname in ('gt', 'lt') |
| 39 | assert len(loop.links) == 2 |
| 40 | assert loop.links[0] in loop.headblock.exits |
| 41 | assert loop.links[1] in loop.links[0].target.exits |
| 42 | assert loop.links[1].target is loop.headblock |
| 43 | |
| 44 | def test_nested_loops(): |
| 45 | def snippet_fn(x, z): |
| 46 | y = 0 |
| 47 | while y <= 10: |
| 48 | while z < y: |
| 49 | z += y |
| 50 | y += 1 |
| 51 | return z |
| 52 | t = TranslationContext() |
| 53 | graph = t.buildflowgraph(snippet_fn) |
| 54 | if option.view: |
| 55 | t.view() |
| 56 | loops = find_inner_loops(graph) |
| 57 | assert len(loops) == 1 |
| 58 | loop = loops[0] |
| 59 | assert loop.headblock.operations[0].opname == 'lt' |
| 60 | assert len(loop.links) == 2 |
| 61 | assert loop.links[0] in loop.headblock.exits |
| 62 | assert loop.links[1] in loop.links[0].target.exits |
| 63 | assert loop.links[1].target is loop.headblock |