| 1 |
""" |
| 2 |
This is the core of the vec. optimization. It combines dependency.py and schedule.py |
| 3 |
to rewrite a loop in vectorized form. |
| 4 |
|
| 5 |
See the rpython doc for more high level details. |
| 6 |
""" |
| 7 |
from __future__ import print_function |
| 8 |
|
| 9 |
import py |
| 10 |
import time |
| 11 |
|
| 12 |
from rpython.jit.metainterp.jitexc import NotAVectorizeableLoop, NotAProfitableLoop |
| 13 |
from rpython.jit.metainterp.compile import (CompileLoopVersionDescr, ResumeDescr) |
| 14 |
from rpython.jit.metainterp.history import (INT, FLOAT, VECTOR, ConstInt, ConstFloat, |
| 15 |
TargetToken, JitCellToken, AbstractFailDescr) |
| 16 |
from rpython.jit.metainterp.optimizeopt.optimizer import Optimizer, Optimization |
| 17 |
from rpython.jit.metainterp.optimizeopt.renamer import Renamer |
| 18 |
from rpython.jit.metainterp.optimizeopt.dependency import (DependencyGraph, |
| 19 |
MemoryRef, Node, IndexVar) |
| 20 |
from rpython.jit.metainterp.optimizeopt.version import LoopVersionInfo |
| 21 |
from rpython.jit.metainterp.optimizeopt.schedule import (VecScheduleState, |
| 22 |
SchedulerState, Scheduler, Pack, Pair, AccumPack, forwarded_vecinfo) |
| 23 |
from rpython.jit.metainterp.optimizeopt.guard import GuardStrengthenOpt |
| 24 |
from rpython.jit.metainterp.resoperation import (rop, ResOperation, GuardResOp, |
| 25 |
OpHelpers, VecOperation, VectorizationInfo) |
| 26 |
from rpython.rlib import listsort |
| 27 |
from rpython.rlib.objectmodel import we_are_translated |
| 28 |
from rpython.rlib.debug import debug_print, debug_start, debug_stop |
| 29 |
from rpython.rlib.jit import Counters |
| 30 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 31 |
from rpython.rtyper.lltypesystem import lltype, rffi |
| 32 |
from rpython.jit.backend.llsupport.symbolic import (WORD as INT_WORD, |
| 33 |
SIZEOF_FLOAT as FLOAT_WORD) |
| 34 |
|
| 35 |
def copy_resop(op): |
| 36 |
newop = op.copy() |
| 37 |
fwd = op.get_forwarded() |
| 38 |
if fwd is not None and isinstance(fwd, VectorizationInfo): |
| 39 |
newop.set_forwarded(fwd) |
| 40 |
return newop |
| 41 |
|
| 42 |
class VectorLoop(object): |
| 43 |
def __init__(self, label, oplist, jump): |
| 44 |
self.label = label |
| 45 |
self.inputargs = label.getarglist_copy() |
| 46 |
self.prefix = [] |
| 47 |
self.prefix_label = None |
| 48 |
assert self.label.getopnum() == rop.LABEL |
| 49 |
self.operations = oplist |
| 50 |
self.jump = jump |
| 51 |
assert self.jump.getopnum() == rop.JUMP |
| 52 |
self.align_operations = [] |
| 53 |
|
| 54 |
def setup_vectorization(self): |
| 55 |
for op in self.operations: |
| 56 |
op.set_forwarded(VectorizationInfo(op)) |
| 57 |
|
| 58 |
def teardown_vectorization(self): |
| 59 |
for op in self.operations: |
| 60 |
op.set_forwarded(None) |
| 61 |
|
| 62 |
def finaloplist(self, jitcell_token=None, reset_label_token=True, label=False): |
| 63 |
if jitcell_token: |
| 64 |
if reset_label_token: |
| 65 |
token = TargetToken(jitcell_token) |
| 66 |
token.original_jitcell_token = jitcell_token |
| 67 |
jitcell_token.target_tokens.append(token) |
| 68 |
self.label.setdescr(token) |
| 69 |
else: |
| 70 |
token = self.jump.getdescr() |
| 71 |
assert isinstance(token, TargetToken) |
| 72 |
if self.prefix_label: |
| 73 |
token = TargetToken(jitcell_token) |
| 74 |
token.original_jitcell_token = jitcell_token |
| 75 |
jitcell_token.target_tokens.append(token) |
| 76 |
self.prefix_label.setdescr(token) |
| 77 |
self.jump.setdescr(token) |
| 78 |
if reset_label_token: |
| 79 |
self.jump.setdescr(token) |
| 80 |
oplist = [] |
| 81 |
if self.prefix_label: |
| 82 |
oplist = self.prefix + [self.prefix_label] |
| 83 |
elif self.prefix: |
| 84 |
oplist = self.prefix |
| 85 |
if label: |
| 86 |
oplist = [self.label] + oplist |
| 87 |
if not label: |
| 88 |
for op in oplist: |
| 89 |
op.set_forwarded(None) |
| 90 |
self.jump.set_forwarded(None) |
| 91 |
ops = oplist + self.operations + [self.jump] |
| 92 |
return ops |
| 93 |
|
| 94 |
def clone(self): |
| 95 |
renamer = Renamer() |
| 96 |
label = copy_resop(self.label) |
| 97 |
prefix = [] |
| 98 |
for op in self.prefix: |
| 99 |
newop = copy_resop(op) |
| 100 |
renamer.rename(newop) |
| 101 |
if not newop.returns_void(): |
| 102 |
renamer.start_renaming(op, newop) |
| 103 |
prefix.append(newop) |
| 104 |
prefix_label = None |
| 105 |
if self.prefix_label: |
| 106 |
prefix_label = copy_resop(self.prefix_label) |
| 107 |
renamer.rename(prefix_label) |
| 108 |
oplist = [] |
| 109 |
for op in self.operations: |
| 110 |
newop = copy_resop(op) |
| 111 |
renamer.rename(newop) |
| 112 |
if not newop.returns_void(): |
| 113 |
renamer.start_renaming(op, newop) |
| 114 |
oplist.append(newop) |
| 115 |
jump = copy_resop(self.jump) |
| 116 |
renamer.rename(jump) |
| 117 |
loop = VectorLoop(copy_resop(self.label), oplist, jump) |
| 118 |
loop.prefix = prefix |
| 119 |
loop.prefix_label = prefix_label |
| 120 |
return loop |
| 121 |
|
| 122 |
def optimize_vector(trace, metainterp_sd, jitdriver_sd, warmstate, |
| 123 |
loop_info, loop_ops, jitcell_token=None): |
| 124 |
""" Enter the world of SIMD. Bails if it cannot transform the trace. """ |
| 125 |
user_code = not jitdriver_sd.vec and warmstate.vec_all |
| 126 |
e = len(loop_ops)-1 |
| 127 |
assert e > 0 |
| 128 |
assert rop.is_final(loop_ops[e].getopnum()) |
| 129 |
loop = VectorLoop(loop_info.label_op, loop_ops[:e], loop_ops[-1]) |
| 130 |
if user_code and user_loop_bail_fast_path(loop, warmstate): |
| 131 |
return loop_info, loop_ops |
| 132 |
|
| 133 |
info = LoopVersionInfo(loop_info) |
| 134 |
version = info.snapshot(loop) |
| 135 |
loop.setup_vectorization() |
| 136 |
try: |
| 137 |
debug_start("vec-opt-loop") |
| 138 |
metainterp_sd.logger_noopt.log_loop([], loop.finaloplist(label=True), -2, None, None, "pre vectorize") |
| 139 |
metainterp_sd.profiler.count(Counters.OPT_VECTORIZE_TRY) |
| 140 |
|
| 141 |
start = time.clock() |
| 142 |
opt = VectorizingOptimizer(metainterp_sd, jitdriver_sd, warmstate.vec_cost) |
| 143 |
oplist = opt.run_optimization(metainterp_sd, info, loop, jitcell_token, user_code) |
| 144 |
end = time.clock() |
| 145 |
|
| 146 |
metainterp_sd.profiler.count(Counters.OPT_VECTORIZED) |
| 147 |
metainterp_sd.logger_noopt.log_loop([], loop.finaloplist(label=True), -2, None, None, "post vectorize") |
| 148 |
nano = int((end-start)*10.0**9) |
| 149 |
debug_print("# vecopt factor: %d opcount: (%d -> %d) took %dns" % \ |
| 150 |
(opt.unroll_count+1, len(version.loop.operations), len(loop.operations), nano)) |
| 151 |
debug_stop("vec-opt-loop") |
| 152 |
|
| 153 |
info.label_op = loop.label |
| 154 |
return info, oplist |
| 155 |
except NotAVectorizeableLoop: |
| 156 |
debug_stop("vec-opt-loop") |
| 157 |
|
| 158 |
return loop_info, version.loop.finaloplist() |
| 159 |
except NotAProfitableLoop: |
| 160 |
debug_stop("vec-opt-loop") |
| 161 |
debug_print("failed to vectorize loop, cost model indicated it is not profitable") |
| 162 |
|
| 163 |
return loop_info, version.loop.finaloplist() |
| 164 |
except Exception as e: |
| 165 |
debug_stop("vec-opt-loop") |
| 166 |
debug_print("failed to vectorize loop. THIS IS A FATAL ERROR!") |
| 167 |
if we_are_translated(): |
| 168 |
llop.debug_print_traceback(lltype.Void) |
| 169 |
else: |
| 170 |
raise |
| 171 |
finally: |
| 172 |
loop.teardown_vectorization() |
| 173 |
return loop_info, loop_ops |
| 174 |
|
| 175 |
def user_loop_bail_fast_path(loop, warmstate): |
| 176 |
""" In a fast path over the trace loop: try to prevent vecopt |
| 177 |
of spending time on a loop that will most probably fail. |
| 178 |
""" |
| 179 |
|
| 180 |
resop_count = 0 |
| 181 |
vector_instr = 0 |
| 182 |
guard_count = 0 |
| 183 |
at_least_one_array_access = True |
| 184 |
for i,op in enumerate(loop.operations): |
| 185 |
if rop.is_jit_debug(op.opnum): |
| 186 |
continue |
| 187 |
|
| 188 |
if op.vector >= 0 and not rop.is_guard(op.opnum): |
| 189 |
vector_instr += 1 |
| 190 |
|
| 191 |
resop_count += 1 |
| 192 |
|
| 193 |
if op.is_primitive_array_access(): |
| 194 |
at_least_one_array_access = True |
| 195 |
|
| 196 |
if rop.is_call(op.opnum) or rop.is_call_assembler(op.opnum): |
| 197 |
return True |
| 198 |
|
| 199 |
if rop.is_guard(op.opnum): |
| 200 |
guard_count += 1 |
| 201 |
|
| 202 |
if not at_least_one_array_access: |
| 203 |
return True |
| 204 |
|
| 205 |
return False |
| 206 |
|
| 207 |
class VectorizingOptimizer(Optimizer): |
| 208 |
""" Try to unroll the loop and find instructions to group """ |
| 209 |
|
| 210 |
def __init__(self, metainterp_sd, jitdriver_sd, cost_threshold): |
| 211 |
Optimizer.__init__(self, metainterp_sd, jitdriver_sd) |
| 212 |
self.cpu = metainterp_sd.cpu |
| 213 |
self.vector_ext = self.cpu.vector_ext |
| 214 |
self.cost_threshold = cost_threshold |
| 215 |
self.packset = None |
| 216 |
self.unroll_count = 0 |
| 217 |
self.smallest_type_bytes = 0 |
| 218 |
self.orig_label_args = None |
| 219 |
|
| 220 |
def run_optimization(self, metainterp_sd, info, loop, jitcell_token, user_code): |
| 221 |
self.orig_label_args = loop.label.getarglist_copy() |
| 222 |
self.linear_find_smallest_type(loop) |
| 223 |
byte_count = self.smallest_type_bytes |
| 224 |
vsize = self.vector_ext.vec_size() |
| 225 |
|
| 226 |
|
| 227 |
if vsize == 0: |
| 228 |
debug_print("vector size is zero") |
| 229 |
raise NotAVectorizeableLoop |
| 230 |
if byte_count == 0: |
| 231 |
debug_print("could not find smallest type") |
| 232 |
raise NotAVectorizeableLoop |
| 233 |
if loop.label.getopnum() != rop.LABEL: |
| 234 |
debug_print("not a loop, can only vectorize loops") |
| 235 |
raise NotAVectorizeableLoop |
| 236 |
|
| 237 |
graph = self.analyse_index_calculations(loop) |
| 238 |
if graph is not None: |
| 239 |
state = SchedulerState(metainterp_sd.cpu, graph) |
| 240 |
self.schedule(state) |
| 241 |
|
| 242 |
|
| 243 |
self.unroll_count = self.get_unroll_count(vsize) |
| 244 |
align_unroll = self.unroll_count==1 and \ |
| 245 |
self.vector_ext.should_align_unroll |
| 246 |
self.unroll_loop_iterations(loop, self.unroll_count, |
| 247 |
align_unroll_once=align_unroll) |
| 248 |
|
| 249 |
|
| 250 |
graph = DependencyGraph(loop) |
| 251 |
self.find_adjacent_memory_refs(graph) |
| 252 |
self.extend_packset() |
| 253 |
self.combine_packset() |
| 254 |
costmodel = GenericCostModel(self.cpu, self.cost_threshold) |
| 255 |
state = VecScheduleState(graph, self.packset, self.cpu, costmodel) |
| 256 |
self.schedule(state) |
| 257 |
if not state.profitable(): |
| 258 |
raise NotAProfitableLoop |
| 259 |
gso = GuardStrengthenOpt(graph.index_vars) |
| 260 |
gso.propagate_all_forward(info, loop, user_code) |
| 261 |
|
| 262 |
|
| 263 |
graph = DependencyGraph(loop) |
| 264 |
state = SchedulerState(self.cpu, graph) |
| 265 |
state.schedule() |
| 266 |
|
| 267 |
info.extra_before_label = loop.align_operations |
| 268 |
for op in loop.align_operations: |
| 269 |
op.set_forwarded(None) |
| 270 |
|
| 271 |
return loop.finaloplist(jitcell_token=jitcell_token, reset_label_token=False) |
| 272 |
|
| 273 |
def unroll_loop_iterations(self, loop, unroll_count, align_unroll_once=False): |
| 274 |
""" Unroll the loop `unroll_count` times. There can be an additional unroll step |
| 275 |
if alignment might benefit """ |
| 276 |
numops = len(loop.operations) |
| 277 |
|
| 278 |
renamer = Renamer() |
| 279 |
operations = loop.operations |
| 280 |
orig_jump_args = loop.jump.getarglist()[:] |
| 281 |
prohibit_opnums = (rop.GUARD_FUTURE_CONDITION, |
| 282 |
rop.GUARD_NOT_INVALIDATED, |
| 283 |
rop.DEBUG_MERGE_POINT) |
| 284 |
unrolled = [] |
| 285 |
|
| 286 |
if align_unroll_once: |
| 287 |
unroll_count += 1 |
| 288 |
|
| 289 |
|
| 290 |
label_arg_count = len(orig_jump_args) |
| 291 |
label = loop.label |
| 292 |
jump = loop.jump |
| 293 |
new_label = loop.label |
| 294 |
for u in range(unroll_count): |
| 295 |
|
| 296 |
for i in range(label_arg_count): |
| 297 |
la = label.getarg(i) |
| 298 |
ja = jump.getarg(i) |
| 299 |
ja = renamer.rename_box(ja) |
| 300 |
if la != ja: |
| 301 |
renamer.start_renaming(la, ja) |
| 302 |
|
| 303 |
for i, op in enumerate(operations): |
| 304 |
if op.getopnum() in prohibit_opnums: |
| 305 |
continue |
| 306 |
copied_op = copy_resop(op) |
| 307 |
if not copied_op.returns_void(): |
| 308 |
|
| 309 |
|
| 310 |
renamer.start_renaming(op, copied_op) |
| 311 |
|
| 312 |
args = copied_op.getarglist() |
| 313 |
for a, arg in enumerate(args): |
| 314 |
value = renamer.rename_box(arg) |
| 315 |
copied_op.setarg(a, value) |
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
if copied_op.is_guard(): |
| 320 |
self.copy_guard_descr(renamer, copied_op) |
| 321 |
|
| 322 |
unrolled.append(copied_op) |
| 323 |
|
| 324 |
if align_unroll_once and u == 0: |
| 325 |
descr = label.getdescr() |
| 326 |
args = label.getarglist()[:] |
| 327 |
new_label = ResOperation(rop.LABEL, args, descr) |
| 328 |
renamer.rename(new_label) |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
args = loop.jump.getarglist() |
| 335 |
for i, arg in enumerate(args): |
| 336 |
value = renamer.rename_box(arg) |
| 337 |
loop.jump.setarg(i, value) |
| 338 |
|
| 339 |
loop.label = new_label |
| 340 |
if align_unroll_once: |
| 341 |
loop.align_operations = operations |
| 342 |
loop.operations = unrolled |
| 343 |
else: |
| 344 |
loop.operations = operations + unrolled |
| 345 |
|
| 346 |
def copy_guard_descr(self, renamer, copied_op): |
| 347 |
descr = copied_op.getdescr() |
| 348 |
if descr: |
| 349 |
assert isinstance(descr, ResumeDescr) |
| 350 |
copied_op.setdescr(descr.clone()) |
| 351 |
failargs = renamer.rename_failargs(copied_op, clone=True) |
| 352 |
if not we_are_translated(): |
| 353 |
for arg in failargs: |
| 354 |
if arg is None: |
| 355 |
continue |
| 356 |
assert not arg.is_constant() |
| 357 |
copied_op.setfailargs(failargs) |
| 358 |
|
| 359 |
def linear_find_smallest_type(self, loop): |
| 360 |
|
| 361 |
for i,op in enumerate(loop.operations): |
| 362 |
if op.is_primitive_array_access(): |
| 363 |
descr = op.getdescr() |
| 364 |
byte_count = descr.get_item_size_in_bytes() |
| 365 |
if self.smallest_type_bytes == 0 \ |
| 366 |
or byte_count < self.smallest_type_bytes: |
| 367 |
self.smallest_type_bytes = byte_count |
| 368 |
|
| 369 |
def get_unroll_count(self, simd_vec_reg_bytes): |
| 370 |
""" This is an estimated number of further unrolls """ |
| 371 |
|
| 372 |
byte_count = self.smallest_type_bytes |
| 373 |
if byte_count == 0: |
| 374 |
return 0 |
| 375 |
unroll_count = simd_vec_reg_bytes // byte_count |
| 376 |
return unroll_count-1 |
| 377 |
|
| 378 |
def find_adjacent_memory_refs(self, graph): |
| 379 |
""" The pre pass already builds a hash of memory references and the |
| 380 |
operations. Since it is in SSA form there are no array indices. |
| 381 |
If there are two array accesses in the unrolled loop |
| 382 |
i0,i1 and i1 = int_add(i0,c), then i0 = i0 + 0, i1 = i0 + 1. |
| 383 |
They are represented as a linear combination: i*c/d + e, i is a variable, |
| 384 |
all others are integers that are calculated in reverse direction |
| 385 |
""" |
| 386 |
loop = graph.loop |
| 387 |
operations = loop.operations |
| 388 |
|
| 389 |
self.packset = PackSet(self.vector_ext.vec_size()) |
| 390 |
memory_refs = graph.memory_refs.items() |
| 391 |
|
| 392 |
for node_a,memref_a in memory_refs: |
| 393 |
for node_b,memref_b in memory_refs: |
| 394 |
if memref_a is memref_b: |
| 395 |
continue |
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
if memref_a.is_adjacent_after(memref_b): |
| 400 |
pair = self.packset.can_be_packed(node_a, node_b, None, False) |
| 401 |
if pair: |
| 402 |
self.packset.add_pack(pair) |
| 403 |
|
| 404 |
def extend_packset(self): |
| 405 |
""" Follow dependency chains to find more candidates to put into |
| 406 |
pairs. |
| 407 |
""" |
| 408 |
pack_count = self.packset.pack_count() |
| 409 |
while True: |
| 410 |
i = 0 |
| 411 |
packs = self.packset.packs |
| 412 |
while i < len(packs): |
| 413 |
pack = packs[i] |
| 414 |
self.follow_def_uses(pack) |
| 415 |
i += 1 |
| 416 |
if pack_count == self.packset.pack_count(): |
| 417 |
pack_count = self.packset.pack_count() |
| 418 |
i = 0 |
| 419 |
while i < len(packs): |
| 420 |
pack = packs[i] |
| 421 |
self.follow_use_defs(pack) |
| 422 |
i += 1 |
| 423 |
if pack_count == self.packset.pack_count(): |
| 424 |
break |
| 425 |
pack_count = self.packset.pack_count() |
| 426 |
|
| 427 |
def follow_use_defs(self, pack): |
| 428 |
assert pack.numops() == 2 |
| 429 |
for ldep in pack.leftmost(True).depends(): |
| 430 |
for rdep in pack.rightmost(True).depends(): |
| 431 |
lnode = ldep.to |
| 432 |
rnode = rdep.to |
| 433 |
|
| 434 |
left = lnode.getoperation() |
| 435 |
args = pack.leftmost().getarglist() |
| 436 |
if left is None or left not in args: |
| 437 |
continue |
| 438 |
isomorph = isomorphic(lnode.getoperation(), rnode.getoperation()) |
| 439 |
if isomorph and lnode.is_before(rnode): |
| 440 |
pair = self.packset.can_be_packed(lnode, rnode, pack, False) |
| 441 |
if pair: |
| 442 |
self.packset.add_pack(pair) |
| 443 |
|
| 444 |
def follow_def_uses(self, pack): |
| 445 |
assert pack.numops() == 2 |
| 446 |
for ldep in pack.leftmost(node=True).provides(): |
| 447 |
for rdep in pack.rightmost(node=True).provides(): |
| 448 |
lnode = ldep.to |
| 449 |
rnode = rdep.to |
| 450 |
left = pack.leftmost() |
| 451 |
args = lnode.getoperation().getarglist() |
| 452 |
if left is None or left not in args: |
| 453 |
continue |
| 454 |
isomorph = isomorphic(lnode.getoperation(), rnode.getoperation()) |
| 455 |
if isomorph and lnode.is_before(rnode): |
| 456 |
pair = self.packset.can_be_packed(lnode, rnode, pack, True) |
| 457 |
if pair: |
| 458 |
self.packset.add_pack(pair) |
| 459 |
|
| 460 |
def combine_packset(self): |
| 461 |
""" Combination is done iterating the packs that have |
| 462 |
a sorted op index of the first operation (= left). |
| 463 |
If a pack is marked as 'full', the next pack that is |
| 464 |
encountered having the full_pack.right == pack.left, |
| 465 |
the pack is removed. This is because the packs have |
| 466 |
intersecting edges. |
| 467 |
""" |
| 468 |
if len(self.packset.packs) == 0: |
| 469 |
debug_print("packset is empty") |
| 470 |
raise NotAVectorizeableLoop |
| 471 |
i = 0 |
| 472 |
j = 0 |
| 473 |
end_ij = len(self.packset.packs) |
| 474 |
while True: |
| 475 |
len_before = len(self.packset.packs) |
| 476 |
i = 0 |
| 477 |
while i < end_ij: |
| 478 |
while j < end_ij and i < end_ij: |
| 479 |
if i == j: |
| 480 |
|
| 481 |
j += 1 |
| 482 |
continue |
| 483 |
pack1 = self.packset.packs[i] |
| 484 |
pack2 = self.packset.packs[j] |
| 485 |
if pack1.rightmost_match_leftmost(pack2): |
| 486 |
end_ij = self.packset.combine(i,j) |
| 487 |
else: |
| 488 |
|
| 489 |
|
| 490 |
j += 1 |
| 491 |
i += 1 |
| 492 |
j = 0 |
| 493 |
if len_before == len(self.packset.packs): |
| 494 |
break |
| 495 |
|
| 496 |
self.packset.split_overloaded_packs(self.cpu.vector_ext) |
| 497 |
|
| 498 |
if not we_are_translated(): |
| 499 |
|
| 500 |
self.packset.accum_vars = {} |
| 501 |
print("packs:") |
| 502 |
check = {} |
| 503 |
fail = False |
| 504 |
for pack in self.packset.packs: |
| 505 |
left = pack.operations[0] |
| 506 |
right = pack.operations[-1] |
| 507 |
if left in check or right in check: |
| 508 |
fail = True |
| 509 |
check[left] = None |
| 510 |
check[right] = None |
| 511 |
print(" ", pack) |
| 512 |
if fail: |
| 513 |
assert False |
| 514 |
|
| 515 |
def schedule(self, state): |
| 516 |
state.prepare() |
| 517 |
scheduler = Scheduler() |
| 518 |
scheduler.walk_and_emit(state) |
| 519 |
if not state.profitable(): |
| 520 |
return |
| 521 |
state.post_schedule() |
| 522 |
|
| 523 |
def analyse_index_calculations(self, loop): |
| 524 |
""" Tries to move guarding instructions an all the instructions that |
| 525 |
need to be computed for the guard to the loop header. This ensures |
| 526 |
that guards fail 'early' and relax dependencies. Without this |
| 527 |
step vectorization would not be possible! |
| 528 |
""" |
| 529 |
graph = DependencyGraph(loop) |
| 530 |
zero_deps = {} |
| 531 |
for node in graph.nodes: |
| 532 |
if node.depends_count() == 0: |
| 533 |
zero_deps[node] = 0 |
| 534 |
earlyexit = graph.imaginary_node("early exit") |
| 535 |
guards = graph.guards |
| 536 |
one_valid = False |
| 537 |
valid_guards = [] |
| 538 |
for guard_node in guards: |
| 539 |
modify_later = [] |
| 540 |
last_prev_node = None |
| 541 |
valid = True |
| 542 |
if guard_node in zero_deps: |
| 543 |
del zero_deps[guard_node] |
| 544 |
for prev_dep in guard_node.depends(): |
| 545 |
prev_node = prev_dep.to |
| 546 |
if prev_dep.is_failarg(): |
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
modify_later.append(prev_node) |
| 553 |
else: |
| 554 |
for path in prev_node.iterate_paths(None, backwards=True, blacklist=True): |
| 555 |
if not path.is_always_pure(): |
| 556 |
valid = False |
| 557 |
else: |
| 558 |
if path.last() in zero_deps: |
| 559 |
del zero_deps[path.last()] |
| 560 |
if not valid: |
| 561 |
break |
| 562 |
if valid: |
| 563 |
|
| 564 |
|
| 565 |
one_valid = True |
| 566 |
for node in modify_later: |
| 567 |
node.remove_edge_to(guard_node) |
| 568 |
|
| 569 |
|
| 570 |
for dep in guard_node.provides()[:]: |
| 571 |
assert not dep.target_node().is_imaginary() |
| 572 |
earlyexit.edge_to(dep.target_node(), failarg=True) |
| 573 |
guard_node.remove_edge_to(dep.target_node()) |
| 574 |
valid_guards.append(guard_node) |
| 575 |
|
| 576 |
guard_node.edge_to(earlyexit) |
| 577 |
self.mark_guard(guard_node, loop) |
| 578 |
for node in zero_deps.keys(): |
| 579 |
assert not node.is_imaginary() |
| 580 |
earlyexit.edge_to(node) |
| 581 |
if one_valid: |
| 582 |
return graph |
| 583 |
return None |
| 584 |
|
| 585 |
def mark_guard(self, node, loop): |
| 586 |
""" Marks this guard as an early exit! """ |
| 587 |
op = node.getoperation() |
| 588 |
assert isinstance(op, GuardResOp) |
| 589 |
if op.getopnum() in (rop.GUARD_TRUE, rop.GUARD_FALSE): |
| 590 |
descr = CompileLoopVersionDescr() |
| 591 |
olddescr = op.getdescr() |
| 592 |
if olddescr: |
| 593 |
descr.copy_all_attributes_from(olddescr) |
| 594 |
op.setdescr(descr) |
| 595 |
arglistcopy = loop.label.getarglist_copy() |
| 596 |
if not we_are_translated(): |
| 597 |
for arg in arglistcopy: |
| 598 |
assert not arg.is_constant() |
| 599 |
op.setfailargs(arglistcopy) |
| 600 |
|
| 601 |
class CostModel(object): |
| 602 |
""" Utility to estimate the savings for the new trace loop. |
| 603 |
The main reaons to have this is of frequent unpack instructions, |
| 604 |
and the missing ability (by design) to detect not vectorizable loops. |
| 605 |
""" |
| 606 |
def __init__(self, cpu, threshold): |
| 607 |
self.threshold = threshold |
| 608 |
self.vec_reg_size = cpu.vector_ext.vec_size() |
| 609 |
self.savings = 0 |
| 610 |
|
| 611 |
def reset_savings(self): |
| 612 |
self.savings = 0 |
| 613 |
|
| 614 |
def record_cast_int(self, op): |
| 615 |
raise NotImplementedError |
| 616 |
|
| 617 |
def record_pack_savings(self, pack, times): |
| 618 |
raise NotImplementedError |
| 619 |
|
| 620 |
def record_vector_pack(self, box, index, count): |
| 621 |
raise NotImplementedError |
| 622 |
|
| 623 |
def record_vector_unpack(self, box, index, count): |
| 624 |
raise NotImplementedError |
| 625 |
|
| 626 |
def unpack_cost(self, op, index, count): |
| 627 |
raise NotImplementedError |
| 628 |
|
| 629 |
def savings_for_pack(self, pack, times): |
| 630 |
raise NotImplementedError |
| 631 |
|
| 632 |
def profitable(self): |
| 633 |
return self.savings >= 0 |
| 634 |
|
| 635 |
class GenericCostModel(CostModel): |
| 636 |
def record_pack_savings(self, pack, times): |
| 637 |
cost, benefit_factor = (1,1) |
| 638 |
node = pack.operations[0] |
| 639 |
op = node.getoperation() |
| 640 |
if op.getopnum() == rop.INT_SIGNEXT: |
| 641 |
cost, benefit_factor = self.cb_signext(pack) |
| 642 |
|
| 643 |
self.savings += benefit_factor * times - cost |
| 644 |
|
| 645 |
def cb_signext(self, pack): |
| 646 |
left = pack.leftmost() |
| 647 |
if left.cast_to_bytesize() == left.cast_from_bytesize(): |
| 648 |
return 0, 0 |
| 649 |
|
| 650 |
return 1,0 |
| 651 |
|
| 652 |
def record_cast_int(self, fromsize, tosize, count): |
| 653 |
|
| 654 |
if fromsize == 8 and tosize == 4 and count == 2: |
| 655 |
self.savings -= 1 |
| 656 |
else: |
| 657 |
self.savings += -count |
| 658 |
|
| 659 |
def record_vector_pack(self, src, index, count): |
| 660 |
vecinfo = forwarded_vecinfo(src) |
| 661 |
if vecinfo.datatype == FLOAT: |
| 662 |
if index == 1 and count == 1: |
| 663 |
self.savings -= 2 |
| 664 |
return |
| 665 |
self.savings -= count |
| 666 |
|
| 667 |
def record_vector_unpack(self, src, index, count): |
| 668 |
self.record_vector_pack(src, index, count) |
| 669 |
|
| 670 |
def isomorphic(l_op, r_op): |
| 671 |
""" Subject of definition, here it is equal operation. |
| 672 |
See limintations (vectorization.rst). |
| 673 |
""" |
| 674 |
if l_op.getopnum() == r_op.getopnum(): |
| 675 |
l_vecinfo = forwarded_vecinfo(l_op) |
| 676 |
r_vecinfo = forwarded_vecinfo(r_op) |
| 677 |
return l_vecinfo.bytesize == r_vecinfo.bytesize |
| 678 |
return False |
| 679 |
|
| 680 |
class PackSet(object): |
| 681 |
_attrs_ = ('packs', 'vec_reg_size') |
| 682 |
def __init__(self, vec_reg_size): |
| 683 |
self.packs = [] |
| 684 |
self.vec_reg_size = vec_reg_size |
| 685 |
|
| 686 |
def pack_count(self): |
| 687 |
return len(self.packs) |
| 688 |
|
| 689 |
def add_pack(self, pack): |
| 690 |
self.packs.append(pack) |
| 691 |
|
| 692 |
def can_be_packed(self, lnode, rnode, origin_pack, forward): |
| 693 |
""" Check to ensure that two nodes might be packed into a Pair. |
| 694 |
""" |
| 695 |
if isomorphic(lnode.getoperation(), rnode.getoperation()): |
| 696 |
|
| 697 |
lop = lnode.getoperation() |
| 698 |
independent = lnode.independent(rnode) |
| 699 |
if independent: |
| 700 |
if forward and origin_pack.is_accumulating(): |
| 701 |
|
| 702 |
|
| 703 |
debug_print("splitted accum must be flushed here (not supported)") |
| 704 |
raise NotAVectorizeableLoop |
| 705 |
|
| 706 |
if self.contains_pair(lnode, rnode): |
| 707 |
return None |
| 708 |
|
| 709 |
if origin_pack is None: |
| 710 |
op = lnode.getoperation() |
| 711 |
if rop.is_primitive_load(op.opnum): |
| 712 |
return Pair(lnode, rnode) |
| 713 |
else: |
| 714 |
return Pair(lnode, rnode) |
| 715 |
if self.profitable_pack(lnode, rnode, origin_pack, forward): |
| 716 |
return Pair(lnode, rnode) |
| 717 |
else: |
| 718 |
if self.contains_pair(lnode, rnode): |
| 719 |
return None |
| 720 |
if origin_pack is not None: |
| 721 |
return self.accumulates_pair(lnode, rnode, origin_pack) |
| 722 |
return None |
| 723 |
|
| 724 |
def contains_pair(self, lnode, rnode): |
| 725 |
for pack in self.packs: |
| 726 |
if pack.leftmost(node=True) is lnode or \ |
| 727 |
pack.rightmost(node=True) is rnode: |
| 728 |
return True |
| 729 |
return False |
| 730 |
|
| 731 |
def profitable_pack(self, lnode, rnode, origin_pack, forward): |
| 732 |
if self.prohibit_packing(origin_pack, origin_pack.leftmost(), |
| 733 |
lnode.getoperation(), forward): |
| 734 |
return False |
| 735 |
if self.prohibit_packing(origin_pack, origin_pack.rightmost(), |
| 736 |
rnode.getoperation(), forward): |
| 737 |
return False |
| 738 |
return True |
| 739 |
|
| 740 |
def prohibit_packing(self, pack, packed, inquestion, forward): |
| 741 |
""" Blocks the packing of some operations """ |
| 742 |
if inquestion.vector == -1: |
| 743 |
return True |
| 744 |
if packed.is_primitive_array_access(): |
| 745 |
if packed.getarg(1) is inquestion: |
| 746 |
return True |
| 747 |
if not forward and inquestion.getopnum() == rop.INT_SIGNEXT: |
| 748 |
|
| 749 |
|
| 750 |
return True |
| 751 |
return False |
| 752 |
|
| 753 |
def combine(self, i, j): |
| 754 |
""" Combine two packs. It is assumed that the attribute self.packs |
| 755 |
is not iterated when calling this method. |
| 756 |
""" |
| 757 |
pkg_a = self.packs[i] |
| 758 |
pkg_b = self.packs[j] |
| 759 |
operations = pkg_a.operations |
| 760 |
for op in pkg_b.operations[1:]: |
| 761 |
operations.append(op) |
| 762 |
self.packs[i] = pkg_a.clone(operations) |
| 763 |
del self.packs[j] |
| 764 |
return len(self.packs) |
| 765 |
|
| 766 |
def accumulates_pair(self, lnode, rnode, origin_pack): |
| 767 |
|
| 768 |
assert isinstance(origin_pack, Pair) |
| 769 |
left = lnode.getoperation() |
| 770 |
opnum = left.getopnum() |
| 771 |
|
| 772 |
try: |
| 773 |
operator = AccumPack.SUPPORTED(opnum) |
| 774 |
except KeyError: |
| 775 |
pass |
| 776 |
else: |
| 777 |
right = rnode.getoperation() |
| 778 |
assert left.numargs() == 2 and not left.returns_void() |
| 779 |
scalar, index = self.getaccumulator_variable(left, right, origin_pack) |
| 780 |
if not scalar: |
| 781 |
return None |
| 782 |
|
| 783 |
for dep in lnode.provides(): |
| 784 |
if dep.to is rnode: |
| 785 |
if not dep.because_of(scalar): |
| 786 |
|
| 787 |
return None |
| 788 |
|
| 789 |
scalar = left.getarg(index) |
| 790 |
|
| 791 |
|
| 792 |
|
| 793 |
other_index = (index + 1) % 2 |
| 794 |
if left.getarg(other_index) is not origin_pack.leftmost(): |
| 795 |
return None |
| 796 |
if right.getarg(other_index) is not origin_pack.rightmost(): |
| 797 |
return None |
| 798 |
|
| 799 |
|
| 800 |
size = INT_WORD |
| 801 |
if left.type == 'f': |
| 802 |
size = FLOAT_WORD |
| 803 |
l_vecinfo = forwarded_vecinfo(left) |
| 804 |
r_vecinfo = forwarded_vecinfo(right) |
| 805 |
if not (l_vecinfo.bytesize == r_vecinfo.bytesize and l_vecinfo.bytesize == size): |
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
return None |
| 813 |
return AccumPack([lnode, rnode], operator, index) |
| 814 |
is_guard = left.is_guard() and left.getopnum() in (rop.GUARD_TRUE, rop.GUARD_FALSE) |
| 815 |
if is_guard: |
| 816 |
return AccumPack([lnode, rnode], 'g', 0) |
| 817 |
|
| 818 |
return None |
| 819 |
|
| 820 |
def getaccumulator_variable(self, left, right, origin_pack): |
| 821 |
for i, arg in enumerate(right.getarglist()): |
| 822 |
if arg is left: |
| 823 |
return arg, i |
| 824 |
return None, -1 |
| 825 |
|
| 826 |
def accumulate_prepare(self, state): |
| 827 |
vec_reg_size = state.vec_reg_size |
| 828 |
for pack in self.packs: |
| 829 |
if not pack.is_accumulating(): |
| 830 |
continue |
| 831 |
if pack.leftmost().is_guard(): |
| 832 |
|
| 833 |
continue |
| 834 |
for i,node in enumerate(pack.operations): |
| 835 |
op = node.getoperation() |
| 836 |
state.accumulation[op] = pack |
| 837 |
assert isinstance(pack, AccumPack) |
| 838 |
datatype = pack.getdatatype() |
| 839 |
bytesize = pack.getbytesize() |
| 840 |
count = vec_reg_size // bytesize |
| 841 |
signed = datatype == 'i' |
| 842 |
oplist = state.invariant_oplist |
| 843 |
|
| 844 |
if pack.reduce_init() == 0: |
| 845 |
vecop = OpHelpers.create_vec(datatype, bytesize, signed, count) |
| 846 |
oplist.append(vecop) |
| 847 |
opnum = rop.VEC_INT_XOR |
| 848 |
if datatype == FLOAT: |
| 849 |
|
| 850 |
raise NotImplementedError |
| 851 |
vecop = VecOperation(opnum, [vecop, vecop], |
| 852 |
vecop, count) |
| 853 |
oplist.append(vecop) |
| 854 |
elif pack.reduce_init() == 1: |
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
raise NotImplementedError |
| 859 |
|
| 860 |
vecop = OpHelpers.create_vec_expand(ConstFloat(1.0), bytesize, |
| 861 |
signed, count) |
| 862 |
oplist.append(vecop) |
| 863 |
else: |
| 864 |
raise NotImplementedError("cannot handle %s" % pack.operator) |
| 865 |
|
| 866 |
args = [vecop, pack.getleftmostseed(), ConstInt(0), ConstInt(1)] |
| 867 |
vecop = OpHelpers.create_vec_pack(datatype, args, bytesize, |
| 868 |
signed, count) |
| 869 |
oplist.append(vecop) |
| 870 |
seed = pack.getleftmostseed() |
| 871 |
state.accumulation[seed] = pack |
| 872 |
|
| 873 |
state.setvector_of_box(seed, 0, vecop) |
| 874 |
state.renamer.start_renaming(seed, vecop) |
| 875 |
|
| 876 |
def split_overloaded_packs(self, vector_ext): |
| 877 |
newpacks = [] |
| 878 |
for i,pack in enumerate(self.packs): |
| 879 |
load = pack.pack_load(self.vec_reg_size) |
| 880 |
if load > Pack.FULL: |
| 881 |
pack.split(newpacks, self.vec_reg_size, vector_ext) |
| 882 |
continue |
| 883 |
if load < Pack.FULL: |
| 884 |
for op in pack.operations: |
| 885 |
op.priority = -100 |
| 886 |
pack.clear() |
| 887 |
self.packs[i] = None |
| 888 |
continue |
| 889 |
self.packs = [pack for pack in self.packs + newpacks if pack] |