| 1 | import random |
| 2 | from rpython.tool.algo.unionfind import UnionFind |
| 3 | from rpython.translator.backendopt.graphanalyze import (Dependency, |
| 4 | DependencyTracker, BoolGraphAnalyzer) |
| 5 | |
| 6 | |
| 7 | class FakeGraphAnalyzer: |
| 8 | def __init__(self): |
| 9 | self._analyzed_calls = UnionFind(lambda graph: Dependency(self)) |
| 10 | |
| 11 | @staticmethod |
| 12 | def bottom_result(): |
| 13 | return 0 |
| 14 | |
| 15 | @staticmethod |
| 16 | def join_two_results(result1, result2): |
| 17 | return result1 | result2 |
| 18 | |
| 19 | |
| 20 | def test_random_graphs(): |
| 21 | for _ in range(100): |
| 22 | N = 10 |
| 23 | edges = [(random.randrange(N), random.randrange(N)) |
| 24 | for i in range(N*N//3)] |
| 25 | |
| 26 | def expected(node1): |
| 27 | prev = set() |
| 28 | seen = set([node1]) |
| 29 | while len(seen) > len(prev): |
| 30 | prev = set(seen) |
| 31 | for a, b in edges: |
| 32 | if a in seen: |
| 33 | seen.add(b) |
| 34 | return sum([1 << n for n in seen]) |
| 35 | |
| 36 | def rectrack(n, tracker): |
| 37 | if not tracker.enter(n): |
| 38 | return tracker.get_cached_result(n) |
| 39 | result = 1 << n |
| 40 | for a, b in edges: |
| 41 | if a == n: |
| 42 | result |= rectrack(b, tracker) |
| 43 | tracker.leave_with(result) |
| 44 | return result |
| 45 | |
| 46 | analyzer = FakeGraphAnalyzer() |
| 47 | for n in range(N): |
| 48 | tracker = DependencyTracker(analyzer) |
| 49 | method1 = rectrack(n, tracker) |
| 50 | method2 = expected(n) |
| 51 | assert method1 == method2 |
| 52 | |
| 53 | |
| 54 | def test_delayed_fnptr(): |
| 55 | from rpython.flowspace.model import SpaceOperation |
| 56 | from rpython.rtyper.annlowlevel import MixLevelHelperAnnotator |
| 57 | from rpython.translator.translator import TranslationContext |
| 58 | t = TranslationContext() |
| 59 | t.buildannotator() |
| 60 | t.buildrtyper() |
| 61 | annhelper = MixLevelHelperAnnotator(t.rtyper) |
| 62 | def f(): |
| 63 | pass |
| 64 | c_f = annhelper.constfunc(f, [], None) |
| 65 | op = SpaceOperation('direct_call', [c_f], None) |
| 66 | analyzer = BoolGraphAnalyzer(t) |
| 67 | assert analyzer.analyze(op) |
| 68 | |
| 69 | |
| 70 | def test_null_fnptr(): |
| 71 | from rpython.flowspace.model import SpaceOperation, Constant |
| 72 | from rpython.rtyper.lltypesystem.lltype import Void, FuncType, nullptr |
| 73 | from rpython.translator.translator import TranslationContext |
| 74 | t = TranslationContext() |
| 75 | fnptr = nullptr(FuncType([], Void)) |
| 76 | op = SpaceOperation('direct_call', [Constant(fnptr)], None) |
| 77 | analyzer = BoolGraphAnalyzer(t) |
| 78 | assert not analyzer.analyze(op) |