-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathlibrary.py
More file actions
2200 lines (1938 loc) · 74.6 KB
/
library.py
File metadata and controls
2200 lines (1938 loc) · 74.6 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
"""
This module defines functions directly available in high-level programs,
in particularly providing flow control and output.
"""
from Compiler.types import cint,sint,cfix,sfix,sfloat,MPCThread,Array,MemValue,cgf2n,sgf2n,_number,_mem,_register,regint,Matrix,_types, cfloat, _single, localint, personal, copy_doc, _vec, SubMultiArray, _secret
from Compiler.instructions import *
from Compiler.util import tuplify,untuplify,is_zero
from Compiler.allocator import RegintOptimizer, AllocPool
from Compiler.program import Tape
from Compiler import instructions,instructions_base,comparison,util,types
import inspect,math
import random
import collections
import operator
import copy
from functools import reduce
def get_program():
return instructions.program
def get_tape():
return get_program().curr_tape
def get_block():
return get_program().curr_block
def vectorize(function):
def mask_output(value, active: regint):
if value is None:
return None
if isinstance(value, tuple):
return tuple(mask_output(x, active) for x in value)
if isinstance(value, list):
return [mask_output(x, active) for x in value]
try:
size = value.size
except AttributeError:
return value
if size == 1:
return value
return value * active
def get_vector_size(call_args, call_kwargs):
if len(call_args) > 0 and 'size' in dir(call_args[0]):
return call_args[0].size
elif 'size' in call_kwargs:
return call_kwargs['size']
else:
return None
def vectorized_function(*args, **kwargs):
active_vector_size = regint.conv(kwargs.pop('active_length', None))
size = get_vector_size(args, kwargs)
if size is not None:
if 'size' in kwargs:
del kwargs['size']
instructions_base.set_global_vector_size(size)
set_active_vector_size = active_vector_size is not None and size is not None and size > 1
context_saved_arg = None
if set_active_vector_size:
context_saved_arg = get_arg()
starg(-active_vector_size)
res = function(*args, **kwargs)
if set_active_vector_size:
starg(context_saved_arg)
active = regint.inc(size) < active_vector_size
res = mask_output(res, active)
if size is not None:
instructions_base.reset_global_vector_size()
return res
vectorized_function.__name__ = function.__name__
copy_doc(vectorized_function, function)
return vectorized_function
def set_instruction_type(function):
def instruction_typed_function(*args, **kwargs):
if len(args) > 0 and isinstance(args[0], Tape.Register):
if args[0].is_gf2n:
instructions_base.set_global_instruction_type('gf2n')
else:
instructions_base.set_global_instruction_type('modp')
res = function(*args, **kwargs)
instructions_base.reset_global_instruction_type()
else:
res = function(*args, **kwargs)
return res
instruction_typed_function.__name__ = function.__name__
return instruction_typed_function
def _expand_to_print(val):
return ('[' + ', '.join('%s' for i in range(len(val))) + ']',) + tuple(val)
def print_str(s, *args, print_secrets=False):
""" Print a string, with optional args for adding
variables/registers with ``%s``.
:param s: format string
:param args: arguments (any type)
:param print_secrets: whether to output secret shares
"""
def print_plain_str(ss):
""" Print a plain string (no custom formatting options) """
ss = bytearray(ss, 'utf8')
i = 1
while 4*i <= len(ss):
print_char4(ss[4*(i-1):4*i])
i += 1
i = 4*(i-1)
while i < len(ss):
print_char(ss[i])
i += 1
if len(args) != s.count('%s'):
raise CompilerError('Incorrect number of arguments for string format:', s)
substrings = s.split('%s')
def secret_error(x):
raise CompilerError(
'Cannot print secret value %s, activate printing of shares with '
"'print_secrets=True'" % args[i])
for i,ss in enumerate(substrings):
print_plain_str(ss)
if i < len(args):
if isinstance(args[i], MemValue):
val = args[i].read()
else:
val = args[i]
if isinstance(val, Tape.Register):
from Compiler.GC.types import sbits
if val.is_clear:
val.print_reg_plain()
elif print_secrets and isinstance(val, (_secret, sbits)):
val.output()
else:
secret_error(args[i])
elif isinstance(val, cfix):
val.print_plain()
elif isinstance(val, sfix) or isinstance(val, sfloat):
if print_secrets:
val.output()
else:
secret_error(args[i])
elif isinstance(val, cfloat):
val.print_float_plain()
elif isinstance(val, (list, tuple)):
print_str(*_expand_to_print(val), print_secrets=print_secrets)
elif isinstance(val, (Array, SubMultiArray)):
val.output(print_secrets=print_secrets)
else:
try:
val.output()
except (AttributeError, TypeError):
print_plain_str(str(val))
def print_ln(s='', *args, **kwargs):
""" Print line, with optional args for adding variables/registers
with ``%s``. By default only player 0 outputs, but the ``-I``
command-line option changes that.
:param s: Python string with same number of ``%s`` as length of :py:obj:`args`
:param args: list of public values (regint/cint/int/cfix/cfloat/localint)
:param print_secrets: whether to output secret shares
Example:
.. code::
print_ln('a is %s.', a.reveal())
"""
print_str(str(s) + '\n', *args, **kwargs)
def print_both(s, end='\n'):
""" Print line during compilation and execution. """
print(s, end=end)
print_str(s + end)
def print_ln_if(cond, ss, *args):
""" Print line if :py:obj:`cond` is true. The further arguments
are treated as in :py:func:`print_str`/:py:func:`print_ln`.
:param cond: regint/cint/int/localint
:param ss: Python string
:param args: list of public values
Example:
.. code::
print_ln_if(get_player_id() == 0, 'Player 0 here')
"""
print_str_if(cond, ss + '\n', *args)
def print_str_if(cond, ss, *args):
""" Print string conditionally. See :py:func:`print_ln_if` for details. """
if util.is_constant(cond):
if cond:
print_str(ss, *args)
else:
subs = ss.split('%s')
assert len(subs) == len(args) + 1
if isinstance(cond, localint):
cond = cond._v
for i, s in enumerate(subs):
if i != 0:
val = args[i - 1]
try:
val.output_if(cond)
except:
if isinstance(val, (list, tuple, Array)):
print_str_if(cond, *_expand_to_print(val))
else:
print_str_if(cond, str(val))
s = bytearray(s, 'utf8')
s += b'\0' * ((-len(s)) % 4)
while s:
cond.print_if(s[:4])
s = s[4:]
def print_ln_to(player, ss, *args):
""" Print line at :py:obj:`player` only. Note that printing is
disabled by default except at player 0. Activate interactive mode
with `-I` or use `-OF .` to enable it for all players.
:param player: int
:param ss: Python string
:param args: list of values known to :py:obj:`player`
Example::
print_ln_to(player, 'output for %s: %s', player, x.reveal_to(player))
"""
cond = player == get_player_id()
new_args = []
for arg in args:
if isinstance(arg, personal):
if util.is_constant(arg.player) ^ util.is_constant(player):
match = False
else:
if util.is_constant(player):
match = arg.player == player
else:
match = id(arg.player) == id(player)
if not match:
raise CompilerError('player mismatch in personal printing')
new_args.append(arg._v)
else:
new_args.append(arg)
print_ln_if(cond, ss, *new_args)
def print_float_precision(n):
""" Set the precision for floating-point printing.
:param n: number of digits (int) """
print_float_prec(n)
def runtime_error(msg='', *args):
""" Print an error message and abort the runtime.
Parameters work as in :py:func:`print_ln` """
print_str('User exception: ')
print_ln(msg, *args)
crash()
def runtime_error_if(condition, msg='', *args):
""" Conditionally print an error message and abort the runtime.
:param condition: regint/cint/int/cbit
:param msg: message
:param args: list of public values to fit ``%s`` in the message
"""
print_ln_if(condition, msg, *args)
crash(condition)
def crash(condition=None):
""" Crash virtual machine.
:param condition: crash if true (default: true)
"""
if isinstance(condition, localint):
# allow crash on local values
condition = condition._v
if condition is None:
condition = regint(1)
instructions.crash(regint.conv(condition))
def public_input():
""" Public input read from ``Programs/Public-Input/<progname>``. """
res = cint()
pubinput(res)
return res
# mostly obsolete functions
# use the equivalent from types.py
@vectorize
def store_in_mem(value, address):
if isinstance(value, int):
value = regint(value)
try:
value.store_in_mem(address)
except AttributeError:
if isinstance(value, (list, tuple)):
for i, x in enumerate(value):
store_in_mem(x, address + i)
return
# legacy
if value.is_clear:
if isinstance(address, cint):
stmci(value, address)
else:
stmc(value, address)
else:
if isinstance(address, cint):
stmsi(value, address)
else:
stms(value, address)
@set_instruction_type
@vectorize
def reveal(secret):
try:
return secret.reveal()
except AttributeError:
if secret.is_clear:
return secret
if secret.is_gf2n:
res = cgf2n()
else:
res = cint()
instructions.asm_open(True, res, secret)
return res
@vectorize
def get_thread_number():
""" Returns the thread number. """
res = regint()
ldtn(res)
return res
@vectorize
def get_arg():
""" Returns the thread argument. """
res = regint()
ldarg(res)
return res
def get_cmdline_arg(idx):
""" Return run-time command-line argument. """
res = regint()
cmdlinearg(res, regint.conv(idx))
return localint(res)
def make_array(l, t=None):
if isinstance(l, types._structure):
res = Array(len(l), t or type(l))
res[:] = l
else:
l = list(l)
res = Array(len(l), t or type(l[0]) if l else cint)
res.assign(l)
return res
class FunctionTapeCall:
def __init__(self, thread, base, bases):
self.thread = thread
self.base = base
self.bases = bases
def start(self):
self.thread.start(self.base)
return self
def join(self):
self.thread.join()
if self.base is not None:
instructions.program.free(self.base, 'ci')
class Function:
def __init__(self, function, name=None, compile_args=[]):
self.last_key = None
self.function = function
self.name = name
if name is None:
self.name = self.function.__name__
self.compile_args = compile_args
def __call__(self, *args):
args = tuple(arg.read() if isinstance(arg, MemValue) else arg for arg in args)
runtime_args = []
reg_args = []
key = self.base_key(),
for i,arg in enumerate(args):
if isinstance(arg, types._vectorizable):
key += (arg.shape, arg.value_type)
else:
arg = MemValue(arg)
reg_args.append(arg)
t = arg.value_type
key += (arg.size, t)
runtime_args.append(arg)
if key != self.last_key:
# first call
outer_runtime_args = runtime_args
def wrapped_function(*compile_args):
addresses = regint.Array(len(outer_runtime_args),
address=get_arg())
runtime_args = []
for i, arg in enumerate(outer_runtime_args):
if isinstance(arg, MemValue):
arg = arg.value_type.load_mem(
address=addresses[i], size=arg.size)
runtime_args.append(arg)
self.result = self.function(
*(list(compile_args) + runtime_args))
return self.result
self.on_first_call(wrapped_function)
self.last_key = key
addresses = regint.Array(len(runtime_args))
for i, arg in enumerate(reg_args):
addresses[i] = arg.address
return self.on_call(addresses._address,
[(arg.value_type, arg.address) for arg in reg_args])
class FunctionTape(Function):
# not thread-safe
def __init__(self, function, name=None, compile_args=[],
single_thread=False):
Function.__init__(self, function, name, compile_args)
self.single_thread = single_thread
def on_first_call(self, wrapped_function):
self.thread = MPCThread(wrapped_function, self.name,
args=self.compile_args,
single_thread=self.single_thread)
def on_call(self, base, bases):
return FunctionTapeCall(self.thread, base, bases)
@staticmethod
def base_key():
pass
class FunctionCallTape(FunctionTape):
def __init__(self, *args, **kwargs):
super(FunctionTape, self).__init__(*args, **kwargs)
self.instances = {}
@staticmethod
def get_key(args, kwargs):
key = (get_program(),)
def process_for_key(arg):
nonlocal key
if isinstance(arg, types._vectorizable):
key += (arg.value_type, tuple(arg.shape))
elif isinstance(arg, Tape.Register):
key += (type(arg), arg.size)
elif isinstance(arg, list):
key += (tuple(arg), 'l')
else:
key += (arg,)
for arg in args:
process_for_key(arg)
for name, arg in sorted(kwargs.items()):
key += (name, 'kw')
process_for_key(arg)
return key
def __call__(self, *args, **kwargs):
key = self.get_key(args, kwargs)
if key not in self.instances:
my_args = []
def wrapped_function():
actual_call_args = []
def process_for_call(arg):
if isinstance(arg, Tape.Register):
my_arg = arg.same_type()
call_arg(my_arg, base.vm_types[my_arg.reg_type])
my_args.append(my_arg)
return my_arg
elif isinstance(arg, types._vectorizable):
my_arg = arg.same_shape(address=regint())
my_arg.alloc_address = arg.address
call_arg(my_arg.address, base.vm_types['ci'])
my_args.append(my_arg)
my_arg = arg.same_shape(
address=MemValue(my_arg.address))
return my_arg
actual_call_args.append(my_arg)
else:
my_args.append(arg)
return arg
for arg in args:
actual_call_args.append(process_for_call(arg))
actual_call_kwargs = {}
for name, arg in sorted(kwargs.items()):
actual_call_kwargs[name] = process_for_call(arg)
self.result = self.function(*actual_call_args,
**actual_call_kwargs)
if self.result is not None:
self.result = list(tuplify(self.result))
for i, res in enumerate(self.result):
if util.is_constant(res):
self.result[i] = regint(res)
self.on_first_call(wrapped_function, key, my_args)
for name, arg in sorted(kwargs.items()):
args += arg,
return self.on_call(*self.instances[key], args)
def on_first_call(self, wrapped_function, key, inside_args):
program = get_program()
program.curr_tape
tape_handle = len(program.tapes)
# entry for recursion
self.instances[key] = tape_handle, None, inside_args
assert tape_handle == program.new_tape(
wrapped_function, name=self.name, args=self.compile_args,
single_thread=get_tape().singular, finalize=False,
thread_pool=get_tape().free_threads)
tape = program.tapes[tape_handle]
if self.result is not None:
self.result = list(tuplify(self.result))
for reg in self.result:
reg.can_eliminate = False
tape.return_values.append(reg)
assert not tape.purged
get_program().finalize_tape(tape)
self.instances[key] = tape_handle, self.result, inside_args
def on_call(self, tape_handle, result, inside_args, args):
tape = get_program().tapes[tape_handle]
if tape.ran_threads and tape.free_threads != get_tape().free_threads:
raise CompilerError(
'cannot call thread-running tape from another thread')
assert len(inside_args) == len(args)
out_result = []
call_args = []
if result is not None:
out_result = [reg.same_type() for reg in result]
for x, y in zip(out_result, result):
call_args += [
1, instructions_base.vm_types[x.reg_type],
x.size, x, y]
for x, y in zip(inside_args, args):
if isinstance(x, Tape.Register):
call_args += [
0, instructions_base.vm_types[x.reg_type],
x.size, x, y]
elif isinstance(x, types._vectorizable):
call_args += [0, base.vm_types['ci'], 1,
x.address, regint.conv(y.address)]
call_tape(tape_handle, regint(0),
*call_args)
break_point('call-%s' % self.name)
return untuplify(tuple(out_result))
class ExportFunction(FunctionCallTape):
def __init__(self, function):
super(ExportFunction, self).__init__(function)
self.done = set()
def __call__(self, *args, **kwargs):
if kwargs:
raise CompilerError('keyword arguments not supported')
def arg_signature(arg):
if isinstance(arg, types._structure):
return '%s:%d' % (arg.arg_type(), arg.size)
elif isinstance(arg, types._vectorizable):
from .GC.types import sbitvec
if issubclass(arg.value_type, sbitvec):
return 'sbv:[%dx%d]' % (arg.total_size(),
arg.value_type.n_bits)
else:
return '%s:[%d]' % (arg.value_type.arg_type(),
arg.total_size())
else:
raise CompilerError('argument not supported: %s' % arg)
signature = []
for arg in args:
signature.append(arg_signature(arg))
signature = tuple(signature)
key = self.get_key(args, kwargs)
if key in self.instances and signature not in self.done:
raise CompilerError('signature conflict')
super(ExportFunction, self).__call__(*args, **kwargs)
if signature not in self.done:
filename = '%s/%s/%s-%s' % (get_program().programs_dir, 'Functions',
self.name, '-'.join(signature))
print('Writing to', filename)
out = open(filename, 'w')
print(get_program().name, file=out)
print(self.instances[key][0], file=out)
result = self.instances[key][1]
try:
if result is not None:
result = untuplify(result)
print(arg_signature(result), result.i, file=out)
else:
print('- 0', file=out)
except CompilerError:
raise CompilerError('return type not supported: %s' % result)
for arg in self.instances[key][2]:
if isinstance(arg, types._structure):
print(arg.i, end=' ', file=out)
elif isinstance(arg, types._vectorizable):
assert util.is_constant(arg.alloc_address)
print(arg.alloc_address, arg.address.i, end=' ', file=out)
else:
CompilerError('argument not supported: %s', arg)
print(file=out)
self.done.add(signature)
def function_tape(function):
return FunctionTape(function)
def function_tape_with_compile_args(*args):
def wrapper(function):
return FunctionTape(function, compile_args=args)
return wrapper
def single_thread_function_tape(function):
return FunctionTape(function, single_thread=True)
def function_call_tape(function):
if get_program().use_tape_calls:
return FunctionCallTape(function)
else:
return function
def method_call_tape(function):
tapes = {}
def wrapper(self, *args, **kwargs):
def use(name):
x = self.__dict__[name]
return not isinstance(x, types.MultiArray) or \
x.array._address is not None
key = (type(self),) + tuple(filter(use, sorted(self.__dict__)))
member_key = key[1:]
if key not in tapes:
def f(*args, **kwargs):
class Dummy(type(self)):
__init__ = lambda self: None
dummy = Dummy()
members = args[:len(member_key)]
real_args = args[len(member_key):]
addresses = {}
for name, member in zip(member_key, members):
dummy.__dict__[name] = member
if isinstance(member, types._vectorizable):
addresses[name] = member.address
res = function(dummy, *real_args, **kwargs)
for name, member in zip(member_key, members):
new_member = dummy.__dict__[name]
desc = '%s in %s.%s' % (name, type(self).__name__,
function.__name__)
if id(new_member) != id(member):
raise CompilerError('cannot change members '
'in method tape (%s)' % desc)
if isinstance(member, types._vectorizable) and \
id(new_member.address) != id(addresses[name]):
raise CompilerError('cannot change memory address '
'in method tape (%s)' % desc)
if set(member_key) != set(dummy.__dict__):
raise CompilerError('cannot add members '
'in method tape (%s)' % desc)
return res
f.__name__ = '%s-%s' % (type(self).__name__, function.__name__)
tapes[key] = function_call_tape(f)
members = tuple(self.__dict__[x] for x in member_key)
res = tapes[key](*(members + args), **kwargs)
return res
return wrapper
def function(function):
""" Create a run-time function. The arguments can be memory or basic
types, and return values can be basic types::
@function
def f(x, y, z):
y.write(1)
z[0] = 2
return x + 3
a = MemValue(sint(0))
b = sint.Array(10)
c = f(sint(4), a, b)
print_ln('%s %s %s', a.reveal(), b[0].reveal(), c.reveal())
This should output::
1 2 7
You can use run-time functions recursively but without return
values in this case.
"""
return FunctionCallTape(function)
def export(function):
return ExportFunction(function)
def memorize(x, write=True):
if isinstance(x, (tuple, list)):
return tuple(memorize(i, write=write) for i in x)
elif x is None:
return
else:
return MemValue(x, write=write)
def unmemorize(x):
if isinstance(x, (tuple, list)):
return tuple(unmemorize(i) for i in x)
elif x is None:
return
else:
return x.read()
def write_mem(dest, source):
if isinstance(dest, (tuple, list)):
assert len(dest) == len(source)
for x, y in zip(dest, source):
write_mem(x, y)
elif dest is None:
return
else:
dest.write(source)
class FunctionBlock(Function):
def on_first_call(self, wrapped_function):
p_return_address = get_tape().program.malloc(1, 'ci')
old_block = get_tape().active_basicblock
parent_node = old_block.req_node
get_tape().open_scope(lambda x: x[0], None, 'begin-' + self.name)
block = get_tape().active_basicblock
block.alloc_pool = AllocPool(parent=block.alloc_pool)
del parent_node.children[-1]
self.node = block.req_node
if get_program().verbose:
print('Compiling function', self.name)
result = wrapped_function(*self.compile_args)
if result is not None:
self.result = memorize(result)
else:
self.result = None
if get_program().verbose:
print('Done compiling function', self.name)
get_tape().function_basicblocks[block] = p_return_address
return_address = regint.load_mem(p_return_address)
get_tape().active_basicblock.set_exit(instructions.jmpi(return_address, add_to_prog=False))
self.last_sub_block = get_tape().active_basicblock
get_tape().close_scope(old_block, parent_node, 'end-' + self.name)
old_block.set_exit(instructions.jmp(0, add_to_prog=False), get_tape().active_basicblock)
self.basic_block = block
def on_call(self, base, bases):
if base is not None:
instructions.starg(regint(base))
block = self.basic_block
if block not in get_tape().function_basicblocks:
raise CompilerError('unknown function')
old_block = get_tape().active_basicblock
old_block.set_exit(instructions.jmp(0, add_to_prog=False), block)
p_return_address = get_tape().function_basicblocks[block]
return_address = regint()
old_block.return_address_store = instructions.ldint(return_address, 0)
return_address.store_in_mem(p_return_address)
get_tape().start_new_basicblock(name='call-' + self.name)
get_tape().active_basicblock.set_return(old_block, self.last_sub_block)
get_block().req_node.children.append(self.node)
if self.result is not None:
return unmemorize(self.result)
@staticmethod
def base_key():
return get_tape()
def function_block(function):
return FunctionBlock(function)
def function_block_with_compile_args(*args):
def wrapper(function):
return FunctionBlock(function, compile_args=args)
return wrapper
def method_block(function):
# If you use this, make sure to use MemValue for all member
# variables.
compiled_functions = {}
def wrapper(self, *args):
if self in compiled_functions:
return compiled_functions[self](*args)
else:
name = '%s-%s' % (type(self).__name__, function.__name__)
block = FunctionBlock(function, name=name, compile_args=(self,))
compiled_functions[self] = block
return block(*args)
return wrapper
def cond_swap(x, y, key_indices=None):
from .types import SubMultiArray
if isinstance(x, (Array, SubMultiArray)):
assert len(key_indices) == 1
b = x[key_indices[0]] > y[key_indices[0]]
return list(zip(*[b.cond_swap(xx, yy) for xx, yy in zip(x, y)]))
b = x < y
if isinstance(x, sfloat):
res = ([], [])
for i,j in enumerate(('v','p','z','s')):
xx = x.__getattribute__(j)
yy = y.__getattribute__(j)
bx = b * xx
by = b * yy
res[0].append(bx + yy - by)
res[1].append(xx - bx + by)
return sfloat(*res[0]), sfloat(*res[1])
return b.cond_swap(y, x)
def sort(a):
print("WARNING: you're using bubble sort")
res = a
for i in range(len(a)):
for j in reversed(list(range(i))):
res[j], res[j+1] = cond_swap(res[j], res[j+1])
return res
def odd_even_merge(a):
if len(a) == 2:
a[0], a[1] = cond_swap(a[0], a[1])
else:
even = a[::2]
odd = a[1::2]
odd_even_merge(even)
odd_even_merge(odd)
a[0] = even[0]
for i in range(1, len(a) // 2):
a[2*i-1], a[2*i] = cond_swap(odd[i-1], even[i])
a[-1] = odd[-1]
def odd_even_merge_sort(a):
if len(a) == 1:
return
elif len(a) % 2 == 0:
aa = a
a = list(a)
lower = a[:len(a)//2]
upper = a[len(a)//2:]
odd_even_merge_sort(lower)
odd_even_merge_sort(upper)
a[:] = lower + upper
odd_even_merge(a)
aa[:] = a
else:
raise CompilerError('Length of list must be power of two')
def chunky_odd_even_merge_sort(a):
raise CompilerError(
'This function has been removed, use loopy_odd_even_merge_sort instead')
def chunkier_odd_even_merge_sort(a, n=None, max_chunk_size=512, n_threads=7, use_chunk_wraps=False):
raise CompilerError(
'This function has been removed, use loopy_odd_even_merge_sort instead')
def loopy_chunkier_odd_even_merge_sort(a, n=None, max_chunk_size=512, n_threads=7):
raise CompilerError(
'This function has been removed, use loopy_odd_even_merge_sort instead')
def loopy_odd_even_merge_sort(a, sorted_length=1, n_parallel=32,
n_threads=None, key_indices=None):
get_program().reading('sorting', 'KSS13', 'Section 6.1')
a_in = a
if isinstance(a_in, list):
a = Array.create_from(a)
steps = {}
l = sorted_length
while l < len(a):
l *= 2
k = 1
while k < l:
k *= 2
n_innermost = 1 if k == 2 else k // 2 - 1
key = k
if key not in steps:
@function_block
def step(l):
l = MemValue(l)
m = 2 ** int(math.ceil(math.log(len(a), 2)))
@for_range_opt_multithread(n_threads, m // k)
def _(i):
n_inner = l // k
j = i % n_inner
i //= n_inner
base = i*l + j
step = l//k
def swap(base, step):
if m == len(a):
a[base], a[base + step] = \
cond_swap(a[base], a[base + step],
key_indices=key_indices)
else:
# ignore values outside range
go = base + step < len(a)
x = a.maybe_get(go, base)
y = a.maybe_get(go, base + step)
tmp = cond_swap(x, y, key_indices=key_indices)
for i, idx in enumerate((base, base + step)):
a.maybe_set(go, idx, tmp[i])
if k == 2:
swap(base, step)
else:
@for_range_opt(n_innermost)
def f(i):
m1 = step + i * 2 * step
m2 = m1 + base
swap(m2, step)
steps[key] = step
steps[key](l)
if isinstance(a_in, list):
a_in[:] = list(a)
def mergesort(A):
if not get_program().options.insecure:
raise CompilerError('mergesort reveals the order of elements, '
'use --insecure to activate it')
B = Array(len(A), sint)
def merge(i_left, i_right, i_end):
i0 = MemValue(i_left)
i1 = MemValue(i_right)
@for_range(i_left, i_end)
def loop(j):
if_then(and_(lambda: i0 < i_right,
or_(lambda: i1 >= i_end,
lambda: regint(reveal(A[i0] <= A[i1])))))
B[j] = A[i0]
i0.iadd(1)
else_then()
B[j] = A[i1]
i1.iadd(1)
end_if()
width = MemValue(1)
@do_while
def width_loop():
@for_range(0, len(A), 2 * width)
def merge_loop(i):
merge(i, i + width, i + 2 * width)
A.assign(B)
width.imul(2)
return width < len(A)
def _range_prep(start, stop, step):
if stop is None:
stop = start
start = 0
if step is None:
step = 1
if util.is_zero(step):
raise CompilerError('step must not be zero')
# copy to avoid update
stop = type(stop)(stop)
return start, stop, step
def range_loop(loop_body, start, stop=None, step=None):
start, stop, step = _range_prep(start, stop, step)
def loop_fn(i):
res = loop_body(i)
return util.if_else(res == 0, stop, i + step)
if isinstance(step, int):
if step > 0:
condition = lambda x: x < stop
elif step < 0:
condition = lambda x: x > stop
else:
b = step > 0
condition = lambda x: b * (x < stop) + (1 - b) * (x > stop)
while_loop(loop_fn, condition, start, g=loop_body.__globals__)
if isinstance(start, int) and isinstance(stop, int) \
and isinstance(step, int):
# known loop count
if condition(start):
get_block().req_node.children[-1].aggregator = \
lambda x: int(ceil(((stop - start) / step))) * x[0]
def for_range(start, stop=None, step=None):
"""
Decorator to execute loop bodies consecutively. Arguments work as
in Python :py:func:`range`, but they can be any public
integer. Information has to be passed out via container types such
as :py:class:`~Compiler.types.Array` or using :py:func:`update`.
Note that changing Python data structures such
as lists within the loop is not possible, but the compiler cannot
warn about this.
:param start/stop/step: regint/cint/int