This repository was archived by the owner on Jan 4, 2026. It is now read-only.
forked from MatthieuDartiailh/bytecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfg.py
More file actions
265 lines (207 loc) · 8.11 KB
/
cfg.py
File metadata and controls
265 lines (207 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# alias to keep the 'bytecode' variable free
import bytecode as _bytecode
from bytecode.concrete import ConcreteInstr
from bytecode.instr import Label, SetLineno, Instr
class BasicBlock(_bytecode._InstrList):
def __init__(self, instructions=None):
# a BasicBlock object, or None
self.next_block = None
if instructions:
super().__init__(instructions)
def __iter__(self):
index = 0
while index < len(self):
instr = self[index]
index += 1
if not isinstance(instr, (SetLineno, Instr, ConcreteInstr)):
raise ValueError("BasicBlock must only contain SetLineno, "
"Instr and ConcreteInstr objects, "
"but %s was found"
% instr.__class__.__name__)
if isinstance(instr, Instr) and instr.has_jump():
if index < len(self):
raise ValueError("Only the last instruction of a basic "
"block can be a jump")
if not isinstance(instr.arg, BasicBlock):
raise ValueError("Jump target must a BasicBlock, got %s",
type(instr.arg).__name__)
yield instr
def get_jump(self):
if not self:
return None
last_instr = self[-1]
if not(isinstance(last_instr, Instr) and last_instr.has_jump()):
return None
target_block = last_instr.arg
assert isinstance(target_block, BasicBlock)
return target_block
class ControlFlowGraph(_bytecode.BaseBytecode):
def __init__(self):
super().__init__()
self._blocks = []
self._block_index = {}
self.argnames = []
self.add_block()
def get_block_index(self, block):
try:
return self._block_index[id(block)]
except KeyError:
raise ValueError("the block is not part of this bytecode")
def _add_block(self, block):
block_index = len(self._blocks)
self._blocks.append(block)
self._block_index[id(block)] = block_index
def add_block(self, instructions=None):
block = BasicBlock(instructions)
self._add_block(block)
return block
def __repr__(self):
return '<ControlFlowGraph block#=%s>' % len(self._blocks)
def _flat(self):
instructions = []
jumps = []
for block in self:
target_block = block.get_jump()
if target_block is not None:
instr = block[-1]
instr = ConcreteInstr(instr.name, 0, lineno=instr.lineno)
jumps.append((target_block, instr))
instructions.extend(block[:-1])
instructions.append(instr)
else:
instructions.extend(block)
for target_block, instr in jumps:
instr.arg = self.get_block_index(target_block)
return instructions
def __eq__(self, other):
if type(self) != type(other):
return False
if self.argnames != other.argnames:
return False
instrs1 = self._flat()
instrs2 = other._flat()
if instrs1 != instrs2:
return False
# FIXME: compare block.next_block
return super().__eq__(other)
def __len__(self):
return len(self._blocks)
def __iter__(self):
return iter(self._blocks)
def __getitem__(self, index):
if isinstance(index, BasicBlock):
index = self.get_block_index(index)
return self._blocks[index]
def __delitem__(self, index):
if isinstance(index, BasicBlock):
index = self.get_block_index(index)
block = self._blocks[index]
del self._blocks[index]
del self._block_index[id(block)]
for index in range(index, len(self)):
block = self._blocks[index]
self._block_index[id(block)] -= 1
def split_block(self, block, index):
if not isinstance(block, BasicBlock):
raise TypeError("expected block")
block_index = self.get_block_index(block)
if index < 0:
raise ValueError("index must be positive")
block = self._blocks[block_index]
if index == 0:
return block
if index > len(block):
raise ValueError("index out of the block")
instructions = block[index:]
if not instructions:
if block_index + 1 < len(self):
return self[block_index + 1]
del block[index:]
block2 = BasicBlock(instructions)
block.next_block = block2
for block in self[block_index + 1:]:
self._block_index[id(block)] += 1
self._blocks.insert(block_index + 1, block2)
self._block_index[id(block2)] = block_index + 1
return block2
@staticmethod
def from_bytecode(bytecode):
# label => instruction index
label_to_block_index = {}
jumps = []
block_starts = {}
for index, instr in enumerate(bytecode):
if isinstance(instr, Label):
label_to_block_index[instr] = index
else:
if isinstance(instr, Instr) and isinstance(instr.arg, Label):
jumps.append((index, instr.arg))
for target_index, target_label in jumps:
target_index = label_to_block_index[target_label]
block_starts[target_index] = target_label
bytecode_blocks = _bytecode.ControlFlowGraph()
bytecode_blocks._copy_attr_from(bytecode)
bytecode_blocks.argnames = list(bytecode.argnames)
# copy instructions, convert labels to block labels
block = bytecode_blocks[0]
labels = {}
jumps = []
for index, instr in enumerate(bytecode):
if index in block_starts:
old_label = block_starts[index]
if index != 0:
new_block = bytecode_blocks.add_block()
if not block[-1].is_final():
block.next_block = new_block
block = new_block
if old_label is not None:
labels[old_label] = block
elif block and isinstance(block[-1], Instr):
if block[-1].is_final():
block = bytecode_blocks.add_block()
elif block[-1].has_jump():
new_block = bytecode_blocks.add_block()
block.next_block = new_block
block = new_block
if isinstance(instr, Label):
continue
# don't copy SetLineno objects
if isinstance(instr, (Instr, ConcreteInstr)):
instr = instr.copy()
if isinstance(instr.arg, Label):
jumps.append(instr)
block.append(instr)
for instr in jumps:
label = instr.arg
instr.arg = labels[label]
return bytecode_blocks
def to_bytecode(self):
"""Convert to Bytecode."""
used_blocks = set()
for block in self:
target_block = block.get_jump()
if target_block is not None:
used_blocks.add(id(target_block))
labels = {}
jumps = []
instructions = []
for block in self:
if id(block) in used_blocks:
new_label = Label()
labels[id(block)] = new_label
instructions.append(new_label)
for instr in block:
# don't copy SetLineno objects
if isinstance(instr, (Instr, ConcreteInstr)):
instr = instr.copy()
if isinstance(instr.arg, BasicBlock):
jumps.append(instr)
instructions.append(instr)
# Map to new labels
for instr in jumps:
instr.arg = labels[id(instr.arg)]
bytecode = _bytecode.Bytecode()
bytecode._copy_attr_from(self)
bytecode.argnames = list(self.argnames)
bytecode[:] = instructions
return bytecode