Repository navigation
Expand file tree
/
Copy pathtranslate.py
More file actions
1388 lines (1268 loc) · 58.4 KB
/
Copy pathtranslate.py
File metadata and controls
1388 lines (1268 loc) · 58.4 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import opcode
import sys
import types
import __builtin__
import numpy as np
from llvm import _ObjectCache, WeakValueDictionary
import llvm.core as lc
import llvm.passes as lp
import llvm.ee as le
from utils import itercode, debugout, Complex64, Complex128
from ._ext import make_ufunc
from .cfg import ControlFlowGraph
from .llvm_types import _plat_bits, _int1, _int8, _int32, _intp, _intp_star, \
_void_star, _float, _double, _complex64, _complex128, _pyobject_head, \
_trace_refs_, _head_len, _numpy_struct, _numpy_array, \
_numpy_array_field_ofs
from .multiarray_api import MultiarrayAPI
if __debug__:
import pprint
_int32_zero = lc.Constant.int(_int32, 0)
# Translate Python bytecode to LLVM IR
# For type-inference we need a mapping showing what the output type
# is from any operation and the input types. We can assume if it is
# not in this table that the output type is the same as the input types
typemaps = {
}
#hasconst
#hasname
#hasjrel
#haslocal
#hascompare
#hasfree
def map_to_function(func, typs, mod):
typs = [str_to_llvmtype(x) if isinstance(x, str) else x for x in typs]
INTR = getattr(lc, 'INTR_%s' % func.__name__.upper())
return lc.Function.intrinsic(mod, INTR, typs)
class DelayedObj(object):
def __init__(self, base, args):
self.base = base
self.args = args
def get_start(self):
if len(self.args) > 1:
ret_val = self.args[0]
else:
# FIXME: Need to infer case where this might be over floats.
ret_val = Variable(lc.Constant.int(_intp, 0))
return ret_val
def get_inc(self):
if len(self.args) > 2:
ret_val = self.args[2]
else:
# FIXME: Need to infer case where this might be over floats.
ret_val = Variable(lc.Constant.int(_intp, 1))
return ret_val
def get_stop(self):
return self.args[0 if (len(self.args) == 1) else 1]
class MethodReference(object):
def __init__(self, object_var, py_method):
self.object_var = object_var
self.py_method = py_method
class _LLVMCaster(object):
# NOTE: Using a class to lower namespace polution here. The
# following would be class methods, but we'd have to index them
# using "class.method" in the cast dictionary to get the proper
# binding, and that'd only succeed after the class has been built.
def build_pointer_cast(_, builder, lval1, lty2):
return builder.bitcast(lval1, lty2)
def build_int_cast(_, builder, lval1, lty2, unsigned = False):
width1 = lval1.type.width
width2 = lty2.width
ret_val = lval1
if width2 > width1:
if unsigned:
ret_val = builder.zext(lval1, lty2)
else:
ret_val = builder.sext(lval1, lty2)
elif width2 < width1:
print("Warning: Perfoming downcast. May lose information.")
ret_val = builder.trunc(lval1, lty2)
return ret_val
def build_float_cast(_, builder, lval1, lty2):
raise NotImplementedError("FIXME")
def build_int_to_float_cast(_, builder, lval1, lty2, unsigned = False):
ret_val = None
if unsigned:
ret_val = builder.uitofp(lval1, lty2)
else:
ret_val = builder.sitofp(lval1, lty2)
return ret_val
def build_float_to_int_cast(_, builder, lval1, lty2, unsigned = False):
ret_val = None
if unsigned:
ret_val = builder.fptoui(lval1, lty2)
else:
ret_val = builder.fptosi(lval1, lty2)
return ret_val
CAST_MAP = {
lc.TYPE_POINTER : build_pointer_cast,
lc.TYPE_INTEGER : build_int_cast,
lc.TYPE_FLOAT : build_float_cast,
(lc.TYPE_INTEGER, lc.TYPE_FLOAT) : build_int_to_float_cast,
(lc.TYPE_INTEGER, lc.TYPE_DOUBLE) : build_int_to_float_cast,
(lc.TYPE_FLOAT, lc.TYPE_INTEGER) : build_float_to_int_cast,
(lc.TYPE_DOUBLE, lc.TYPE_INTEGER) : build_float_to_int_cast,
}
@classmethod
def build_cast(cls, builder, lval1, lty2, *args, **kws):
ret_val = None
lty1 = lval1.type
lkind1 = lty1.kind
lkind2 = lty2.kind
if lkind1 == lkind2:
if lkind1 in cls.CAST_MAP:
ret_val = cls.CAST_MAP[lkind1](cls, builder, lval1, lty2,
*args, **kws)
else:
map_index = (lkind1, lkind2)
if map_index in cls.CAST_MAP:
ret_val = cls.CAST_MAP[map_index](cls, builder, lval1, lty2,
*args, **kws)
return ret_val
# Variables placed on the stack.
# They allow an indirection
# So, that when used in an operation, the correct
# LLVM type can be inserted.
class Variable(object):
def __init__(self, val, argtyp = None, exact_typ = None):
if isinstance(val, Variable):
self.val = val.val
self._llvm = val._llvm
self.typ = val.typ
return
self.val = val
if isinstance(val, lc.Value):
self._llvm = val
if argtyp is None:
if exact_typ is None:
self.typ = llvmtype_to_strtype(val.type)
else:
self.typ = exact_typ
else:
self.typ = convert_to_strtype(argtyp)
else:
self._llvm = None
self.typ = pythontype_to_strtype(type(val))
def __repr__(self):
return ('<Variable(val=%r, _llvm=%r, typ=%r)>' %
(self.val, self._llvm, self.typ))
def llvm(self, typ=None, mod=None, builder = None):
if self._llvm:
ret_val = self._llvm
if typ is not None and typ != self.typ:
ret_val = None
ltyp = str_to_llvmtype(typ)
if builder:
ret_val = _LLVMCaster.build_cast(builder, self._llvm, ltyp)
if ret_val is None:
raise ValueError("Unsupported cast (from %r.typ to %r)" %
(self, typ))
return ret_val
else:
if typ is None:
typ = 'f64' if self.typ is None else self.typ
if typ == 'f64':
res = lc.Constant.real(lc.Type.double(), float(self.val))
elif typ == 'f32':
res = lc.Constant.real(lc.Type.float(), float(self.val))
elif typ[0] == 'i':
res = lc.Constant.int(lc.Type.int(int(typ[1:])),
int(self.val))
elif typ[0] == 'c':
ltyp = _float if typ[1:] == '64' else _double
res = lc.Constant.struct([
lc.Constant.real(ltyp, self.val.real),
lc.Constant.real(ltyp, self.val.imag)])
elif typ[0] == 'func':
res = map_to_function(self.val, typ[1:], mod)
return res
def is_phi(self):
return isinstance(self._llvm, lc.PHINode)
def is_module(self):
return isinstance(self.val, types.ModuleType)
_compare_mapping_float = {'>':lc.FCMP_OGT,
'<':lc.FCMP_OLT,
'==':lc.FCMP_OEQ,
'>=':lc.FCMP_OGE,
'<=':lc.FCMP_OLE,
'!=':lc.FCMP_ONE}
_compare_mapping_sint = {'>':lc.ICMP_SGT,
'<':lc.ICMP_SLT,
'==':lc.ICMP_EQ,
'>=':lc.ICMP_SGE,
'<=':lc.ICMP_SLE,
'!=':lc.ICMP_NE}
_compare_mapping_uint = {'>':lc.ICMP_UGT,
'<':lc.ICMP_ULT,
'==':lc.ICMP_EQ,
'>=':lc.ICMP_UGE,
'<=':lc.ICMP_ULE,
'!=':lc.ICMP_NE}
class _LLVMModuleUtils(object):
__string_constants = {}
@classmethod
def get_printf(cls, module):
try:
ret_val = module.get_function_named('printf')
except:
ret_val = module.add_function(
lc.Type.function(_int32, [_void_star], True),
'printf')
return ret_val
@classmethod
def get_string_constant(cls, module, const_str):
if (module, const_str) in cls.__string_constants:
ret_val = cls.__string_constants[(module, const_str)]
else:
lconst_str = lc.Constant.stringz(const_str)
ret_val = module.add_global_variable(lconst_str.type, "__STR_%d" %
(len(cls.__string_constants),))
ret_val.initializer = lconst_str
ret_val.linkage = lc.LINKAGE_INTERNAL
cls.__string_constants[(module, const_str)] = ret_val
return ret_val
@classmethod
def build_print_string_constant(cls, translator, out_val):
# FIXME: This is just a hack to get things going. There is a
# corner case where formatting markup in the string can cause
# undefined behavior, and for 100% correctness we'd have to
# escape string formatting sequences.
llvm_printf = cls.get_printf(translator.mod)
return translator.builder.call(llvm_printf, [
translator.builder.gep(cls.get_string_constant(translator.mod,
out_val),
[_int32_zero, _int32_zero])])
@classmethod
def build_print_number(cls, translator, out_var):
llvm_printf = cls.get_printf(translator.mod)
if out_var.typ[0] == 'i':
if int(out_var.typ[1:]) < 64:
fmt = "%d"
typ = "i32"
else:
fmt = "%ld"
typ = "i64"
elif out_var.typ[0] == 'f':
if int(out_var.typ[1:]) < 64:
fmt = "%f"
typ = "f32"
else:
fmt = "%lf"
typ = "f64"
else:
raise NotImplementedError("FIXME (type %r not supported in "
"build_print_number())" % (out_var.typ,))
return translator.builder.call(llvm_printf, [
translator.builder.gep(
cls.get_string_constant(translator.mod, fmt),
[_int32_zero, _int32_zero]),
out_var.llvm(typ, builder = translator.builder)])
@classmethod
def build_debugout(cls, translator, args):
if translator.optimize:
print("Warning: Optimization turned on, debug output code may "
"be optimized out.")
res = cls.build_print_string_constant(translator, "debugout: ")
for arg in args:
arg_type = arg.typ
if arg.typ is None:
arg_type = type(arg.val)
if isinstance(arg.val, str):
res = cls.build_print_string_constant(translator, arg.val)
elif typ_isa_number(arg_type):
res = cls.build_print_number(translator, arg)
else:
raise NotImplementedError("Don't know how to output stuff of "
"type %r at present." % arg_type)
res = cls.build_print_string_constant(translator, "\n")
return res, None
@classmethod
def build_len(cls, translator, args):
if (len(args) == 1 and
args[0]._llvm is not None and
args[0]._llvm.type == _numpy_array):
lfunc = None
shape_ofs = _numpy_array_field_ofs['shape']
res = translator.builder.load(
translator.builder.load(
translator.builder.gep(args[0]._llvm, [
_int32_zero, lc.Constant.int(_int32, shape_ofs)])))
else:
raise NotImplementedError("Currently unable to handle calls to "
"len() for arguments that are not Numpy "
"arrays.")
return res, None
@classmethod
def get_py_incref(cls, module):
try:
ret_val = module.get_function_named('Py_IncRef')
except:
ret_val = module.add_function(
lc.Type.function(_void_star, [_void_star]), 'Py_IncRef')
return ret_val
@classmethod
def build_zeros_like(cls, translator, args):
assert (len(args) == 1 and
args[0]._llvm is not None and
args[0]._llvm.type == _numpy_array), (
"Expected Numpy array argument to numpy.zeros_like().")
translator.init_multiarray()
larr = args[0]._llvm
largs = [translator.builder.load(
translator.builder.gep(larr, [
_int32_zero,
lc.Constant.int(_int32,
_numpy_array_field_ofs[field_name])]))
for field_name in ('ndim', 'shape', 'descr')]
largs.append(_int32_zero)
lfunc = translator.ma_obj.load_PyArray_Zeros(translator.mod,
translator.builder)
res = translator.builder.bitcast(
translator.builder.call(
cls.get_py_incref(translator.mod),
[translator.builder.call(lfunc, largs)]),
_numpy_array)
if __debug__:
print "build_zeros_like(): lfunc =", str(lfunc)
print "build_zeros_like(): largs =", [str(arg) for arg in largs]
return res, args[0].typ
@classmethod
def get_py_modulo(cls, module, typ):
modulo_fn = '__py_modulo_%s' % typ
try:
ret_val = module.get_function_named(modulo_fn)
except:
ltyp = str_to_llvmtype(typ)
ret_val = module.add_function(
lc.Type.function(ltyp, [ltyp, ltyp]), modulo_fn)
ret_val.linkage = lc.LINKAGE_INTERNAL
entry_block = ret_val.append_basic_block('entry')
different_sign_block = ret_val.append_basic_block('different_sign')
join_block = ret_val.append_basic_block('join')
builder = lc.Builder.new(entry_block)
arg2 = ret_val.args[1]
srem = builder.srem(ret_val.args[0], arg2)
width = int(typ[1:])
lbits_shifted = lc.Constant.int(str_to_llvmtype(typ), width - 1)
srem_sign = builder.lshr(srem, lbits_shifted)
arg2_sign = builder.lshr(arg2, lbits_shifted)
same_sign = builder.icmp(lc.ICMP_EQ, srem_sign, arg2_sign)
builder.cbranch(same_sign, join_block, different_sign_block)
builder.position_at_end(different_sign_block)
different_sign_res = builder.add(srem, arg2)
builder.branch(join_block)
builder.position_at_end(join_block)
res = builder.phi(ltyp)
res.add_incoming(srem, entry_block)
res.add_incoming(different_sign_res, different_sign_block)
builder.ret(res)
return ret_val
@classmethod
def build_conj(cls, translator, args):
print args
assert ((len(args) == 1) and (args[0]._llvm is not None) and
(args[0]._llvm.type in (_complex64, _complex128)))
larg = args[0]._llvm
elem_ltyp = _float if larg.type == _complex64 else _double
new_imag_lval = translator.builder.fmul(
lc.Constant.real(elem_ltyp, -1.),
translator.builder.extract_value(larg, 1))
assert hasattr(translator.builder, 'insert_value'), (
"llvm-py support for LLVMBuildInsertValue() required to build "
"code for complex conjugates.")
res = translator.builder.insert_value(larg, new_imag_lval, 1)
return res, None
PY_CALL_TO_LLVM_CALL_MAP = {
debugout : _LLVMModuleUtils.build_debugout,
len : _LLVMModuleUtils.build_len,
np.zeros_like : _LLVMModuleUtils.build_zeros_like,
np.complex64.conj : _LLVMModuleUtils.build_conj,
np.complex128.conj : _LLVMModuleUtils.build_conj,
np.complex64.conjugate : _LLVMModuleUtils.build_conj,
np.complex128.conjugate : _LLVMModuleUtils.build_conj,
}
class LLVMControlFlowGraph (ControlFlowGraph):
def __init__ (self, translator = None):
self.translator = translator
super(LLVMControlFlowGraph, self).__init__()
def add_block (self, key, value = None):
if self.translator is not None:
if key not in self.translator.blocks:
lfunc = self.translator.lfunc
lblock = lfunc.append_basic_block('BLOCK_%d' % key)
assert isinstance(lblock, lc.BasicBlock), (
"Expected %r from llvm-py, got instance of type %r, "
"however." % (lc.BasicBlock, type(lblock)))
self.translator.blocks[key] = lblock
else:
lblock = self.translator.blocks[key]
if value is None:
value = lblock
return super(LLVMControlFlowGraph, self).add_block(key, value)
# The following overloaded methods implement a state machine
# intended to recognize the opcode sequence: GET_ITER, FOR_ITER,
# STORE_FAST. Any other sequence is (currently) rejected in
# control-flow analysis.
def op_GET_ITER (self, i, op, arg):
self.saw_get_iter_at = (self.crnt_block, i)
return False
def op_FOR_ITER (self, i, op, arg):
if (hasattr(self, "saw_get_iter_at") and
self.saw_get_iter_at[1] == i - 1):
self.add_block(i)
self.add_block(i + 3)
self.add_edge(self.crnt_block, i + 3)
self.add_edge(i, i + 3)
self.add_block(i + arg + 3)
self.add_edge(i + 3, i + arg + 3)
# The following is practically meaningless since we are
# hijacking normal control flow, and injecting a synthetic
# basic block at i + 3, but still correct if we want to
# enforce some weird loop invariant over the symbolic
# execution loop.
self.crnt_block = i
else:
raise NotImplementedError("Unable to handle FOR_ITER appearing "
"after any opcode other than GET_ITER.")
return True
def op_STORE_FAST (self, i, op, arg):
if hasattr(self, "saw_get_iter_at"):
get_iter_block, get_iter_index = self.saw_get_iter_at
del self.saw_get_iter_at
if get_iter_index == i - 4:
self.blocks_writes[get_iter_block].add(arg)
self.blocks_writer[get_iter_block][arg] = get_iter_index
self.blocks_writes[i - 3].add(arg)
self.blocks_writer[i - 3][arg] = i - 3
self.blocks_reads[i].add(arg)
self.add_block(i + 3)
self.add_edge(i, i + 3)
else:
# FIXME: (?) Are there corner cases where this will fail to
# eventually detect a pattern miss?
raise NotImplementedError(
"Detected GET_ITER, FOR_ITER opcodes not immediately "
"followed by STORE_FAST at instruction index %d." %
(get_iter_index,))
ret_val = False
else:
ret_val = super(LLVMControlFlowGraph, self).op_STORE_FAST(
i, op, arg)
return ret_val
def compute_dataflow (self):
"""Overload the base class to induce a writer update for phi
nodes, otherwise later phi node calculations won't work."""
ret_val = super(LLVMControlFlowGraph, self).compute_dataflow()
self.update_for_ssa()
return ret_val
class Translate(object):
def __init__(self, func, ret_type='d', arg_types=['d'], **kws):
self.func = func
self.fco = func.func_code
self.names = self.fco.co_names
self.varnames = self.fco.co_varnames
self.constants = self.fco.co_consts
self.costr = func.func_code.co_code
# Just the globals we will use
self._myglobals = {}
for name in self.names:
try:
self._myglobals[name] = func.func_globals[name]
except KeyError:
# Assumption here is that any name not in globals or
# builtins is an attribtue.
self._myglobals[name] = getattr(__builtin__, name, None)
# NOTE: Was seeing weird corner case where
# llvm.core.Module.new() was not returning a module object,
# thinking this was caused by compiling the same function
# twice while the module was being garbage collected, and
# llvm.core.Module.new() would return whatever was left lying
# around. Using the translator address in the module name
# might fix this.
# NOTE: It doesn't. Have to manually flush the llvm-py object cache
# since not even forcing garbage collection is reliable.
global _ObjectCache
setattr(_ObjectCache, '_ObjectCache__instances', WeakValueDictionary())
self.mod = lc.Module.new('%s_mod_%x' % (func.__name__, id(self)))
assert isinstance(self.mod, lc.Module), (
"Expected %r from llvm-py, got instance of type %r, however." %
(lc.Module, type(self.mod)))
self._delaylist = [range, xrange, enumerate]
self.ret_type = ret_type
self.arg_types = arg_types
self.setup_func()
self.ee = None
self.ma_obj = None
self.optimize = kws.pop('optimize', True)
self.flags = kws
def setup_func(self):
# The return type will not be known until the return
# function is created. So, we will need to
# walk through the code twice....
# Once to get the type of the return, and again to
# emit the instructions.
# For now, we assume the function has been called already
# or the return type is otherwise known and passed in
self.ret_ltype = convert_to_llvmtype(self.ret_type)
# The arg_ltypes we will be able to get from what is passed in
argnames = self.fco.co_varnames[:self.fco.co_argcount]
self.arg_ltypes = [convert_to_llvmtype(x) for x in self.arg_types]
ty_func = lc.Type.function(self.ret_ltype, self.arg_ltypes)
self.lfunc = self.mod.add_function(ty_func, self.func.func_name)
assert isinstance(self.lfunc, lc.Function), (
"Expected %r from llvm-py, got instance of type %r, however." %
(lc.Function, type(self.lfunc)))
self.nlocals = len(self.fco.co_varnames)
self._locals = [None] * self.nlocals
for i, (name, typ) in enumerate(zip(argnames, self.arg_types)):
assert isinstance(self.lfunc.args[i], lc.Argument), (
"Expected %r from llvm-py, got instance of type %r, however." %
(lc.Argument, type(self.lfunc.args[i])))
self.lfunc.args[i].name = name
# Store away arguments in locals
self._locals[i] = Variable(self.lfunc.args[i], typ)
entry = self.lfunc.append_basic_block('Entry')
assert isinstance(entry, lc.BasicBlock), (
"Expected %r from llvm-py, got instance of type %r, however." %
(lc.BasicBlock, type(entry)))
self.blocks = {0:entry}
self.cfg = None
self.blocks_locals = {}
self.pending_phis = {}
self.pending_blocks = {}
self.stack = []
self.loop_stack = []
def translate(self):
"""Translate the function
"""
self.cfg = LLVMControlFlowGraph.build_cfg(self.fco, self)
self.cfg.compute_dataflow()
if __debug__:
self.cfg.pprint()
for i, op, arg in itercode(self.costr):
name = opcode.opname[op]
# Change the builder if the line-number
# is in the list of blocks.
if i in self.blocks.keys():
if i > 0:
# Emit a branch to link blocks up if the previous
# block was not explicitly branched out of...
bb_instrs = self.builder.basic_block.instructions
if ((len(bb_instrs) == 0) or
(not bb_instrs[-1].is_terminator)):
self.builder.branch(self.blocks[i])
# Copy the locals exiting the soon to be
# preceeding basic block.
self.blocks_locals[self.crnt_block] = self._locals[:]
# Ensure we are playing with locals that might
# actually precede the next block.
self.check_locals(i)
self.crnt_block = i
self.builder = lc.Builder.new(self.blocks[i])
self.build_phi_nodes(self.crnt_block)
getattr(self, 'op_'+name)(i, op, arg)
# Perform code optimization
if self.optimize:
fpm = lp.FunctionPassManager.new(self.mod)
fpm.initialize()
fpm.add(lp.PASS_DEAD_CODE_ELIMINATION)
fpm.run(self.lfunc)
fpm.finalize()
if __debug__:
print self.mod
def _get_ee(self):
if self.ee is None:
self.ee = le.ExecutionEngine.new(self.mod)
return self.ee
def build_call_to_translated_function(self, target_translator, args):
# FIXME: At some point, I assume we'll actually want to index
# by argument types, so this will grab the best suited
# translation of a function based on the caller circumstance.
if len(args) != len(self.arg_types):
raise TypeError("Mismatched argument count in call to translated "
"function (%r)." % (self.func))
ee = self._get_ee()
func_name = '%s_%d' % (self.func.__name__, id(self))
try:
lfunc_ptr_ptr = target_translator.mod.get_global_variable_named(
func_name)
except:
# FIXME: This is linkage at its grossest (and least
# dynamic - what if the called function is recompiled at
# some point?). See if there is some way to link this up
# using symbols and module linkage settings.
lfunc_ptr_ty = self.lfunc.type
lfunc_ptr_ptr = target_translator.mod.add_global_variable(
lfunc_ptr_ty, func_name)
lfunc_ptr_ptr.initializer = lc.Constant.inttoptr(
lc.Constant.int(_intp, ee.get_pointer_to_function(self.lfunc)),
lfunc_ptr_ty)
lfunc_ptr_ptr.linkage = lc.LINKAGE_INTERNAL
lfunc = target_translator.builder.load(lfunc_ptr_ptr)
if __debug__:
print "build_call_to_translated_function():", str(lfunc)
largs = [arg.llvm(convert_to_strtype(param_typ),
builder = target_translator.builder)
for arg, param_typ in zip(args, self.arg_types)]
res = target_translator.builder.call(lfunc, largs)
res_typ = convert_to_strtype(self.ret_type)
return res, res_typ
def has_pending_phi(self, instr_index, local_index):
return ((instr_index in self.pending_phis) and
(local_index in self.pending_phis[instr_index]))
def add_pending_phi(self, instr_index, local_index, phi, pred):
if instr_index not in self.pending_phis:
locals_map = {}
self.pending_phis[instr_index] = locals_map
else:
locals_map = self.pending_phis[instr_index]
if local_index not in locals_map:
# Note that the same reaching definition might "arrive"
# via more than one predecessor block, so we keep a list
# of predecessors, not just one.
locals_map[local_index] = (phi, [pred])
else:
assert locals_map[local_index][0] == phi, (
"Internal compiler error!")
locals_map[local_index][1].append(pred)
def handle_pending_phi(self, instr_index, local_index, value):
phi, pred_lblocks = self.pending_phis[instr_index][local_index]
if isinstance(value, Variable):
value = value.llvm(llvmtype_to_strtype(phi.type))
else:
assert isinstance(value, lc.Value), "Internal compiler error!"
for pred_lblock in pred_lblocks:
phi.add_incoming(value, pred_lblock)
def add_phi_incomming(self, phi, crnt_block, pred, local):
'''Take one of three actions:
1. If the predecessor block has already been visited, add its
exit value for the given local to the phi node under
construction.
2. If the predecessor has not been visited, but the block that
defines the reaching definition for that local value, add the
definition value to the phi node under construction.
3. If the reaching definition has not been visited, add a
pending call to PHINode.add_incoming() which will be caught by
op_STORE_LOCAL().
'''
if pred in self.blocks_locals and pred not in self.pending_blocks:
pred_locals = self.blocks_locals[pred]
assert pred_locals[local] is not None, ("Internal error. "
"Local value definition missing from block that has "
"already been visited.")
phi.add_incoming(pred_locals[local].llvm(
llvmtype_to_strtype(phi.type)), self.blocks[pred])
else:
reaching_defs = self.cfg.get_reaching_definitions(crnt_block)
if __debug__:
print("add_phi_incomming(): reaching_defs = %s\n "
"crnt_block=%r, pred=%r, local=%r" %
(pprint.pformat(reaching_defs), crnt_block, pred, local))
definition_block = reaching_defs[pred][local]
if ((definition_block in self.blocks_locals) and
(definition_block not in self.pending_blocks)):
defn_locals = self.blocks_locals[definition_block]
assert defn_locals[local] is not None, ("Internal error. "
"Local value definition missing from block that has "
"already been visited.")
phi.add_incomming(defn_locals[local].llvm(
llvmtype_to_strtype(phi.type)), self.blocks[pred])
else:
definition_index = self.cfg.blocks_writer[definition_block][
local]
self.add_pending_phi(definition_index, local, phi,
self.blocks[pred])
def build_phi_nodes(self, crnt_block):
'''Determine if any phi nodes need to be created, and if so,
do it.'''
preds = self.cfg.blocks_in[crnt_block]
if len(preds) > 1:
phis_needed = self.cfg.phi_needed(crnt_block)
if len(phis_needed) > 0:
reaching_defs = self.cfg.get_reaching_definitions(crnt_block)
for local in phis_needed:
# Infer type from current local value.
oldlocal = self._locals[local]
# NOTE: Also seeing builder.phi returning
# non-PHINode instances intermittently (see NOTE
# above for llvm.core.Module.new()).
phi = self.builder.phi(str_to_llvmtype(oldlocal.typ))
assert isinstance(phi, lc.PHINode), (
"Intermittent llvm-py error encountered (builder.phi()"
" result type was %r, not %r)." %
(type(phi), lc.PHINode))
newlocal = Variable(phi)
self._locals[local] = newlocal
for pred in preds:
self.add_phi_incomming(phi, crnt_block, pred, local)
# This is a local write, even if it is synthetic,
# so check to see if we are responsible for back
# patching any pending phis.
if self.has_pending_phi(crnt_block, local):
# FIXME: There may be the potential for a
# corner case where a STORE_FAST occurs at the
# top of a join. This will cause multiple,
# ambiguous, calls to PHINode.add_incomming()
# (once here, and once in op_STORE_FAST()).
# Currently checking for this in
# numba.cfg.ControlFlowGraph._writes_local().
# Assertion should fail when
# LLVMControlFlowGraph calls
# self.update_for_ssa().
self.handle_pending_phi(crnt_block, local, phi)
def get_preceding_locals(self, preds):
'''Given an iterable set of preceding basic blocks, check to
see if one of them has already been symbolically executed. If
so, return the symbolic locals recorded as leaving that basic
block. Returns None otherwise.'''
pred_list = list(preds)
pred_list.sort()
pred_list.reverse()
next_locals = None
for next_pred in pred_list:
if next_pred in self.blocks_locals:
next_locals = self.blocks_locals[next_pred]
break
return next_locals
def check_locals(self, i):
'''Given the instruction index of the next block, determine if
the current block is in the set of the next block's
predecessors. If not, change out the locals to those of a
predecessor that has already been symbolically run.
'''
if self.crnt_block not in self.cfg.blocks_in[i]:
next_locals = self.get_preceding_locals(self.cfg.blocks_in[i])
if next_locals is None:
if (len(self.stack) > 0 and
isinstance(self.stack[-1].val, DelayedObj)):
# When we detect that we are in a for loop over a
# simple range, fallback to the block dominator so we
# at least have type information for the locals.
assert next_locals is None, "Internal compiler error!"
next_locals = self.get_preceding_locals(
self.cfg.blocks_dom[i])
elif len(self.cfg.blocks_in[i]) == 0:
# Ignore unreachable basic blocks (this happens when
# the Python compiler doesn't know that all paths have
# already returned something).
assert i != 0, ("Translate.check_locals() should not be "
"called for the entry block.")
next_locals = self._locals
else:
assert next_locals is not None, "Internal compiler error!"
self._locals = next_locals[:]
def get_ctypes_func(self, llvm=True):
ee = self._get_ee()
import ctypes
restype = convert_to_ctypes(self.ret_type)
prototype = ctypes.CFUNCTYPE(restype,
*[convert_to_ctypes(x)
for x in self.arg_types])
if hasattr(restype, 'make_ctypes_prototype_wrapper'):
# See numba.utils.ComplexMixin for an example of
# make_ctypes_prototype_wrapper().
prototype = restype.make_ctypes_prototype_wrapper(prototype)
if llvm:
PY_CALL_TO_LLVM_CALL_MAP[self.func] = \
self.build_call_to_translated_function
return prototype(ee.get_pointer_to_function(self.lfunc))
else:
return prototype(self.func)
def make_ufunc(self, name=None):
if self.ee is None:
self.ee = le.ExecutionEngine.new(self.mod)
if name is None:
name = self.func.func_name
return make_ufunc(self.ee.get_pointer_to_function(self.lfunc),
name)
# This won't convert any llvm types. It assumes
# the llvm types in args are either fixed or not-yet specified.
def func_resolve_type(self, func, args):
# already an llvm function
if func.val and func.val is func._llvm:
typs = [llvmtype_to_strtype(x) for x in func._llvm.type.pointee.args]
lfunc = func._llvm
# The function is one of the delayed list
elif func.val in self._delaylist:
return None, DelayedObj(func.val, args)
else:
# Assume we are calling into an intrinsic function...
# we need to generate the function including the types
typs = [arg.typ if arg._llvm is not None else '' for arg in args]
# pick first one as choice
choicetype = None
for typ in typs:
if typ is not None:
choicetype = typ
break
if choicetype is None:
raise TypeError, "All types are unspecified"
typs = [choicetype if x is None else x for x in typs]
lfunc = map_to_function(func.val, typs, self.mod)
llvm_args = [arg.llvm(typ) for typ, arg in zip(typs, args)]
return lfunc, llvm_args
def init_multiarray(self):
'''Builds the MultiarrayAPI object and adds a PyArray_API
variable to the current module under construction.
Should be called by code generators (like
_LLVMModuleUtils.build_zeros_like()) that build Numpy-like
functionality to ensure the ma_obj member has been
initialized.'''
if self.ma_obj is None:
self.ma_obj = MultiarrayAPI()
self.ma_obj.set_PyArray_API(self.mod)
def _revisit_block(self, block_index):
block_state = (self.crnt_block, self.builder, self._locals[:])
self.crnt_block = block_index
self.builder = lc.Builder.new(self.blocks[block_index])
self.builder.position_at_beginning(self.blocks[block_index])
return block_state
def _restore_block(self, block_state):
self.blocks_locals[self.crnt_block] = self._locals[:]
self.crnt_block, self.builder, self._locals = block_state
def _generate_for_loop(self, i , op, arg, delayer):
'''Generates code for a simple for loop (a loop over range,
xrange, or arange).'''
false_jump_target = self.pending_blocks.pop(i - 3)
crnt_block_data = self._revisit_block(i - 3)
inc_variable = delayer.val.get_inc()
self.op_LOAD_FAST(i - 3, None, arg)
self.stack.append(inc_variable)
self.op_INPLACE_ADD(i - 3, None, None)
self.op_STORE_FAST(i - 3, None, arg)
self._restore_block(crnt_block_data)
self.op_LOAD_FAST(i, None, arg)
self.stack.append(delayer.val.get_stop())
# FIXME: This should really test to see if we are increasing
# the iteration variable (inc > 0) or decreasing (inc < 0),
# and select the comparison operator based on that. This currently
# only works if the increment is a constant integer value.
cmp_op_str = '<'
llvm_inc = inc_variable._llvm
# FIXME: Handle other types.
if hasattr(inc_variable, 'as_int') and llvm_inc.as_int() < 0:
cmp_op_str = '>='
self.op_COMPARE_OP(i, None, opcode.cmp_op.index(cmp_op_str))
self.op_POP_JUMP_IF_FALSE(i, None, false_jump_target)
def op_LOAD_FAST(self, i, op, arg):
self.stack.append(Variable(self._locals[arg]))
def op_STORE_FAST(self, i, op, arg):
oldval = self._locals[arg]
newval = self.stack.pop(-1)
if isinstance(newval.val, DelayedObj):
self._generate_for_loop(i, op, arg, newval)
else:
if self.has_pending_phi(i, arg):
self.handle_pending_phi(i, arg, newval)
self._locals[arg] = newval
def op_LOAD_GLOBAL(self, i, op, arg):
self.stack.append(Variable(self._myglobals[self.names[arg]]))
def op_LOAD_CONST(self, i, op, arg):
const = Variable(self.constants[arg])
self.stack.append(const)
def op_BINARY_ADD(self, i, op, arg):
arg2 = self.stack.pop(-1)
arg1 = self.stack.pop(-1)
if __debug__:
print("op_BINARY_ADD(): %r + %r" % (arg1, arg2))
typ, arg1, arg2 = resolve_type(arg1, arg2, self.builder)
if typ[0] == 'f':
res = self.builder.fadd(arg1, arg2)
else: # typ[0] == 'i'
res = self.builder.add(arg1, arg2)
self.stack.append(Variable(res))
def op_INPLACE_ADD(self, i, op, arg):
# FIXME: Trivial inspection seems to illustrate a mostly
# identical semantics to BINARY_ADD for numerical inputs.
# Verify this, or figure out what the corner cases are that
# require a separate symbolic execution procedure.
return self.op_BINARY_ADD(i, op, arg)
def op_BINARY_SUBTRACT(self, i, op, arg):
arg2 = self.stack.pop(-1)
arg1 = self.stack.pop(-1)
typ, arg1, arg2 = resolve_type(arg1, arg2, self.builder)
if typ[0] == 'f':
res = self.builder.fsub(arg1, arg2)
else: # typ[0] == 'i'
res = self.builder.sub(arg1, arg2)
self.stack.append(Variable(res))
def op_BINARY_MULTIPLY(self, i, op, arg):
arg2 = self.stack.pop(-1)
arg1 = self.stack.pop(-1)
typ, arg1, arg2 = resolve_type(arg1, arg2, self.builder)
if typ[0] == 'f':
res = self.builder.fmul(arg1, arg2)
else: # typ[0] == 'i'
res = self.builder.mul(arg1, arg2)
self.stack.append(Variable(res))
def op_INPLACE_MULTIPLY(self, i, op, arg):
# FIXME: See note for op_INPLACE_ADD
return self.op_BINARY_MULTIPLY(i, op, arg)
def op_BINARY_DIVIDE(self, i, op, arg):
arg2 = self.stack.pop(-1)
arg1 = self.stack.pop(-1)
typ, arg1, arg2 = resolve_type(arg1, arg2, self.builder)
if typ[0] == 'f':