-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathread-encfile.py
executable file
·3135 lines (2714 loc) · 118 KB
/
read-encfile.py
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
#!/usr/bin/env python
# Read the encode format files
# -*- python -*-
#BEGIN_LEGAL
#
#Copyright (c) 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#END_LEGAL
# There are dictionaries of nonterminals and sequencers. The
# sequencers are ordered lists of nonterminals. The nonterminals
# consist of rule_t's. Each rule has conditions and actions. An
# action can be a simple bit encoding or it can be a binding of a
# value to a field. A condition contains a list of or'ed condtion_t's
# and a list of and'ed condition_t's. When all the and'ed conditions
# are satisfied and one of the or'ed conditions (if any) are
# satisfied, then the action should occur. The conditions are field
# values that are = or != to a right hand side. The right hand side
# could be a value or a nonterminal (NTLUF really). Also the field
# name could be bound to some bits that are used in the action, using
# square brackets after the name.
import re
import sys
import os
import optparse
import stat
import copy
def find_dir(d):
directory = os.getcwd()
last = ''
while directory != last:
target_directory = os.path.join(directory,d)
if os.path.exists(target_directory):
return target_directory
last = directory
directory = os.path.split(directory)[0]
return None
mbuild_install_path = os.path.join(os.path.dirname(sys.argv[0]),
'..', '..', 'mbuild')
if not os.path.exists(mbuild_install_path):
mbuild_install_path = find_dir('mbuild')
sys.path= [mbuild_install_path] + sys.path
try:
import mbuild
except:
sys.stderr.write("\nERROR(read-encfile.py): Could not find mbuild." +
" Should be a sibling of the xed2 directory.\n\n")
sys.exit(1)
xed2_src_path = os.path.join(os.path.dirname(sys.argv[0]))
if not os.path.exists(xed2_src_path):
xed2_src_path = find_dir('xed2')
sys.path= [xed2_src_path] + sys.path
sys.path= [ os.path.join(xed2_src_path,'pysrc') ] + sys.path
try:
from codegen import *
from genutil import *
from scatter import *
from verbosity import *
import slash_expand
import operand_storage
import nt_func_gen
import map_info_rdr
except:
sys.stderr.write("\nERROR(read-encfile.py): Could not find " +
"the xed directory for python imports.\n\n")
sys.exit(1)
import actions
import ins_emit
import encutil
from patterns import *
storage_fields = {}
def outreg():
return operand_storage.get_op_getter_full_func('outreg',
encutil.enc_strings)
def error_operand():
return operand_storage.get_op_getter_full_func('error',encutil.enc_strings)
xed_encoder_request = "xed_encoder_request_t"
output_file_emitters = []
def _vmsgb(s,b=''):
if vencode():
mbuild.msgb(s,b)
def make_writable(fn):
"""Make the file or directory readable/writable/executable by me"""
_rwx_by_me = stat.S_IWUSR| stat.S_IRUSR|stat.S_IXUSR
os.chmod(fn, _rwx_by_me)
def remove_file(fn):
"""Remove a file if it exists."""
if os.path.exists(fn):
_vmsgb("Removing ", fn)
make_writable(fn)
os.unlink(fn)
class blot_t(object):
"""A blot_t is make a fragment of a decoder pattern"""
def __init__(self,type=None):
self.type = type # 'bits', 'letters', 'nt', "od" (operand decider)
self.nt = None # name of a nonterminal
self.value = None # integer representing this blot_t's value
self.length = 0 # number of bits for this blot_t
self.letters = None # sequence of substitution letters for this blot. All must be the same letter
self.field_name = None # name of the operand storage field that has the values for this blot-t
self.field_offset = 0 # offset within the field
self.od_equals = None
def make_action_string(self):
"""
@rtype: string or None
@returns: string if the blot is something we want to make in to an action
"""
if vblot():
msgb("Making action for blot", str(self) )
if self.type == 'bits':
binary = ''.join(decimal_to_binary(self.value))
if vblot():
msgb("CONVERT", "%s <-- %s" % ( binary, str(self)))
blen = len(binary)
if blen < self.length:
# pad binary on the left with 0's until it is self.length bits long
need_zeros = self.length - blen
#msgerr("Padding with %d zeros" % need_zeros)
binary = "%s%s" % ('0'*need_zeros , binary)
blen = len(binary)
if blen > self.length:
die("bit length problem in %s --- %s" % (str(self), binary))
if self.field_name:
return "%s[0b%s]" % (self.field_name,binary)
return "0b%s" % binary
elif self.type == 'letters':
return "%s[%s]" % (self.field_name,self.letters)
elif self.type == 'od':
if self.od_equals == False:
#return "%s!=0x%x" % (self.field_name, self.value) #EXPERIMENT 2007-08-07
if vignoreod():
msgerr("Ignoring OD != relationships in actions: %s" % str(self))
return None
return "%s=0x%x" % (self.field_name, self.value)
elif self.type == 'nt':
return "%s()" % self.nt
else:
die("Unhandled type: %s" % self.type)
def __str__(self):
s = []
if self.type:
s.append("%8s" % self.type)
else:
s.append("%8s" % "no-type")
if self.nt:
s.append("nt: %s" % self.nt)
if self.field_name:
s.append("field_name: %s" % self.field_name)
if self.od_equals != None:
if self.od_equals:
v = '='
else:
v = '!='
s.append(v)
if self.type == 'letters':
s.append( "".join(self.letters) )
if self.value != None:
s.append("0x%x" % self.value) # print as HEX
s.append("(raw %s)" % self.value)
if self.nt == None and self.od_equals == None:
s.append("length: %d" % self.length)
s.append("field_offset: %d" % self.field_offset)
return ' '.join(s)
class operand_t(object):
"""These are main ISA (decode) operands being used for encode
conditions. They are either individual tokens or X=y bindings. The
tokens or RHS of bindings can have qualifiers separated by colons:
(1) r/w/rw/cr/crcw/rcw/cw, (2) EXPL, IMPL, SUPP or ECOND, (3)
length-code. The EXPL/IMPL/SUPP/ECOND is optional as is the length
code. Memops must have the length code."""
convert_pattern = re.compile(r'TXT=(?P<rhs>[0-9A-Za-z_]+)')
def __init__(self,s):
pieces=s.split(':')
op_or_binding = pieces[0]
self.lencode = '?'
self.vis = None
explicit_vis = None
self.rw = '?'
self.type = None # 'token', 'binding', 'ntluf'
if len(pieces) >= 2:
nxt= pieces[1]
if nxt in [ 'IMPL', 'SUPP','EXPL', 'ECOND']:
explicit_vis = nxt
else:
self.rw = pieces[1]
if len(pieces) >= 3:
for p in pieces[2:]:
cp=operand_t.convert_pattern.match(p)
if cp:
cvt = cp.group('rhs') # ignored
elif p in [ 'IMPL', 'SUPP', 'EXPL', 'ECOND']:
explicit_vis = p
elif self.lencode == '?':
self.lencode = p
else:
_vmsgb("Ignoring [%s] from %s" % (p,s))
#die("Unhandled operand: %s" % s)
self.value = None
self.ntluf = False
ap = equals_pattern.match(op_or_binding)
if ap: # binding
(self.var,self.value) = ap.group('lhs','rhs')
ntluf_match = nt_name_pattern.match(self.value)
if ntluf_match:
self.value = ntluf_match.group('ntname')
self.ntluf = True
self.type = 'ntluf'
else:
self.type = 'binding'
else: # operand (MEM/IMM/DISP/etc.)
self.var = op_or_binding
self.type = 'token'
if explicit_vis:
self.vis = explicit_vis
else:
default_vis = storage_fields[self.var].default_visibility
if default_vis == 'SUPPRESSED':
self.vis = 'SUPP'
elif default_vis == 'EXPLICIT':
self.vis = 'EXPL'
elif default_vis == 'ECOND':
self.vis = 'ECOND'
else:
die("unhandled default visibility: %s for %s" % (default_vis, self.var))
def make_condition(self):
"""
@rtype: condition_t or None
@return: list of conditions based on this operand """
# ignore suppressed operands in encode conditions
if self.vis == 'SUPP':
return None
# make s, a string from which we manufacture a condition_t
if self.type == 'binding':
if letter_pattern.match(self.value):
# associate the field with some letters
s = "%s[%s]=*" % (self.var, self.value)
else:
s = "%s=%s" % (self.var, self.value)
elif self.type == 'token':
s = "%s=1" % (self.var) # FIXME need to specify memop widths
elif self.type == 'ntluf':
s = "%s=%s()" % (self.var,self.value)
else:
die("Unhandled condition: %s" % str(self))
#msgerr("MAKE COND %s" % s)
c = condition_t(s)
#msgerr("XCOND type: %s var: %s lencode: %s" % (self.type, self.var, str(self.lencode)))
# FIXME: THIS IS A DISGUSTING HACK
if self.type == 'token' and self.var == 'MEM0':
# add a secondary condition for checking the width of the memop.
#
# NOTE: this MEM_WIDTH is not emitted! It is used in
# xed_encoder_request_t::memop_compatible()
c2 = condition_t('MEM_WIDTH',self.lencode) # MEM_WIDTH
#msgerr("\tRETURNING LIST WITH MEM_WIDTH")
return [c, c2]
return [c]
def __str__(self):
if self.vis == 'EXPL':
pvis = ''
else:
pvis = ":%s" % self.vis
if self.lencode == '?':
plen = ''
else:
plen = ":%s" % self.lencode
if self.rw == '?':
prw = ''
else:
prw = ":%s" % self.rw
if self.value:
if self.ntluf:
parens = '()'
else:
parens = ''
return "%s=%s%s%s%s%s" % ( self.var, self.value, parens, prw, plen, pvis)
return "%s%s%s%s" % ( self.var, prw, plen, pvis)
class rvalue_t(object):
"""The right hand side of an operand decider equation. It could be
a value, a NTLUF, a * or an @.
For thing that are bits * means any value.
A @ is shorthand for ==XED_REG_INVALID"""
def __init__(self, s):
self.string = s
m = nt_name_pattern.search(s)
if m:
self.nt = True
self.value = m.group('ntname')
else:
self.nt = False
if decimal_pattern.match(s) or binary_pattern.match(s):
#_vmsgb("MAKING NUMERIC FOR %s" %(s))
self.value = str(make_numeric(s))
else:
#_vmsgb("AVOIDING NUMERIC FOR %s" %(s))
self.value = s
def nonterminal(self):
"""Returns True if this rvalue is a nonterminal name"""
return self.nt
def null(self):
if self.value == '@':
return True
return False
def any_valid(self):
if self.value == '*':
return True
return False
def __str__(self):
s = self.value
if self.nt:
s += '()'
return s
class condition_t(object):
""" xxx[bits]=yyyy or xxx=yyy or xxx!=yyyy. bits can be x/n where
n is a repeat count. Can also be an 'otherwise' clause that is
the final action for a nonterminal if no other rule applies.
"""
def __init__(self,s,lencode=None):
#_vmsgb("examining %s" % s)
self.string = s
self.bits = None # bound bits
self.rvalue = None
self.equals = None
self.lencode = lencode # for memory operands
b = bit_expand_pattern.search(s)
if b:
expanded = b.group('bitname') * int(b.group('count'))
ss = bit_expand_pattern.sub(expanded,s)
else:
ss = s
rhs = None
e= equals_pattern.search(ss)
if e:
#_vmsgb("examining %s --- EQUALS" % s)
raw_left_side = e.group('lhs')
lhs = lhs_capture_pattern.search(raw_left_side)
self.equals = True
rhs = e.group('rhs')
self.rvalue = rvalue_t(rhs)
#_vmsgb("examining %s --- EQUALS rhs = %s" % (s,str(self.rvalue)))
else:
ne = not_equals_pattern.search(ss)
if ne:
raw_left_side = ne.group('lhs')
lhs = lhs_capture_pattern.search(raw_left_side)
self.equals = False
self.rvalue = rvalue_t(ne.group('rhs'))
else:
# no equals or not-equals... just a binding. assume "=*"
raw_left_side = ss
#msgerr("TOKEN OR BINDING %s" % (raw_left_side))
lhs = lhs_capture_pattern.search(raw_left_side)
self.equals = True
self.rvalue = rvalue_t('*')
# the lhs is set if we capture bits for an encode action
if lhs:
self.field_name = lhs.group('name')
self.bits = lhs.group('bits')
else:
#_vmsgb("examining %s --- NO LHS" % (s))
self.field_name = raw_left_side
if self.is_reg_type() and self.rvalue.any_valid():
die("Not supporting 'any value' (*) for reg type in: %s" % s)
if self.is_reg_type() and self.equals == False:
die("Not supporting non-equal sign for reg type in: %s" % s)
# Some bit bindings are done like "SIMM=iiiiiiii" instead
# of "MOD[mm]=*". We must handle them as well. Modify the captured rvalue
if rhs and self.equals:
rhs_short = no_underscores(rhs)
if letter_pattern.match(rhs_short):
#msgerr("LATE LETTER BINDING %s %s" % (raw_left_side, str(self.rvalue)))
self.bits = rhs_short
del self.rvalue
self.rvalue = rvalue_t('*')
return
#msgerr("NON BINDING %s" % (s)) # FIXME: what reaches here?
def contains(self, s):
if self.field_name == s:
return True
return False
def capture_info(self):
# FIXME: could locally bind bit fields in capture region to
# avoid redundant calls to xes.operands().
return ( operand_storage.get_op_getter_full_func(self.field_name,
encutil.enc_strings),
self.bits )
def is_bit_capture(self):
"""Binding an OD to some bits"""
if self.bits != None:
return True
return False
def is_otherwise(self):
"""Return True if this condition is an 'otherwise' final
condition."""
if self.field_name == 'otherwise':
return True
return False
def is_reg_type(self):
if self.field_name not in storage_fields:
return False
ctype = storage_fields[self.field_name].ctype
return ctype == 'xed_reg_enum_t'
def __str__(self):
s = [ self.field_name ]
if self.memory_condition(): # MEM_WIDTH
s.append(" (MEMOP %s)" % self.lencode)
if self.bits:
s.append( '[%s]' % (self.bits))
if self.equals:
s.append( '=' )
else:
s.append('!=')
s.append(str(self.rvalue))
return ''.join(s)
def memory_condition(self): # MEM_WIDTH
if self.lencode != None:
return True
return False
def emit_code(self):
#msgerr("CONDEMIT " + str(self))
if self.is_otherwise():
return "1"
if self.equals:
equals_string = '=='
else:
equals_string = '!='
#FIXME: get read off this old accessor
op_accessor = operand_storage.get_op_getter_full_func(self.field_name,
encutil.enc_strings)
if self.memory_condition(): # MEM_WIDTH
s = 'xed_encoder_request__memop_compatible(xes,XED_OPERAND_WIDTH_%s)' % (self.lencode.upper())
elif self.rvalue.nonterminal():
s = 'xed_encode_ntluf_%s(xes,%s)' % (self.rvalue.value,op_accessor)
elif self.rvalue.any_valid():
if storage_fields[self.field_name].ctype == 'xed_reg_enum_t':
# FOO=* is the same as FOO!=XED_REG_INVALID. So we
# invert the equals sign here.
if self.equals:
any_equals = "!="
else:
any_equals = "=="
s = "(%s %s XED_REG_INVALID)" % (op_accessor,any_equals)
else:
s = '1'
elif self.rvalue.null():
s = "(%s %s XED_REG_INVALID)" % (op_accessor,equals_string)
else: # normal bound value test
if self.rvalue.value == 'XED_REG_ERROR':
s = '0'
else:
#msgerr("CONDEMIT2 " + str(self) + " -> " + self.rvalue.value)
s = "(%s %s %s)" % (op_accessor,equals_string,
self.rvalue.value)
return s
class conditions_t(object):
"""Two lists of condition_t's. One gets ANDed together and one gets
ORed together. The OR-output gets ANDed with the rest of the AND
terms."""
def __init__(self):
self.and_conditions = []
def contains(self,s):
for c in self.and_conditions:
if c.contains(s):
return True
return False
def and_cond(self, c):
if is_stringish(c):
nc = condition_t(c)
else:
nc = c
self.and_conditions.append(nc)
def has_otherwise(self):
for a in self.and_conditions:
if a.is_otherwise():
return True
return False
def __str__(self):
s = []
for a in self.and_conditions:
s.append(str(a))
s.append(' ')
return ''.join(s)
def _captures_from_list(self, clist):
"""
@type clist: list of condition_t
@param clist: list of condition_t
Return a list of tuples (fieldname, bits) for use by code
generation (emit actions), by searching the conditions to see
which ones are captures"""
if vcapture():
msgb("CAPTURE COLLECTION USING:\n\t%s\n" % "\n\t".join( [ str(x) for x in clist] ))
full_captures = list(filter(lambda x: x.is_bit_capture(), clist))
captures = [ x.capture_info() for x in full_captures]
return captures
def compute_field_capture_list(self):
"""Study the conditions and return a list of tuples
(fieldname, bits) for use by code-emit actions, by searching
the conditions to see which ones are captures"""
captures = self._captures_from_list(self.and_conditions)
return captures
def field_names_from_list(self,clist):
"""Return a tuple of list of field names and list of NTS"""
field_names = []
nt_names = []
for cond in clist:
if cond.field_name:
field_names.append(cond.field_name)
if cond.rvalue and cond.rvalue.nonterminal():
nt_names.append(cond.rvalue.value)
return (field_names, nt_names)
def get_field_names(self):
"""Return a tuple of list of field names and list of NTS"""
and_field_names = self.field_names_from_list(self.and_conditions)
return ( and_field_names[0] , and_field_names[1])
def emit_code(self):
if len(self.and_conditions) == 1:
if self.and_conditions[0].is_otherwise():
return [ 'conditions_satisfied = 1;' ]
# conditions_satisfied = f1 && f2 && f3
#
# if conditions are operand deciders we just do the test.
# if conditions are NTLUFs then we must see if the name is in
# the set defined by the NTLUF. For example, BASE0=ArAX(). If
# BASE0 is rAX then we are and the corresponding subexpression
# should be True.
s = ['conditions_satisfied = ' ]
emitted = False
if len(self.and_conditions) == 0:
# no conditions. that's okay. encoder's job is simple in this case...
s.append('1')
emitted = True
elif (len(self.and_conditions) == 1 and
self.and_conditions[0].field_name == 'ENCODER_PREFERRED'):
s.append('1')
emitted = True
else:
first_and = True
for and_cond in self.and_conditions:
if and_cond.field_name == 'ENCODER_PREFERRED':
continue
try:
t = and_cond.emit_code()
if t != '1':
if first_and:
first_and = False
else:
s.append( ' &&\n\t\t ')
emitted = True
s.append( t )
except:
die("Could not emit code for condition %s of %s" %
(str(and_cond), str(self)) )
if not emitted:
s.append('1')
s.append(';')
return [ ''.join(s) ]
class iform_builder_t(object):
def __init__(self):
self.iforms = {}
def remember_iforms(self,ntname):
if ntname not in self.iforms:
self.iforms[ntname] = True
def _build(self):
self.cgen = c_class_generator_t("xed_encoder_iforms_t", var_prefix="x_")
for v in self.iforms.keys():
self.cgen.add_var(v, 'xed_uint32_t', accessors='none')
def emit_header(self):
self._build()
return self.cgen.emit_decl()
iform_builder = iform_builder_t() # FIXME GLOBAL
class rule_t(object):
"""The encoder conditions -> actions. These are stored in nonterminals."""
def __init__(self, conditions, action_list, nt):
"""
@type conditions: conditions_t
@param conditions: a conditions_t object specifying the encode conditions
@type action_list: list of strings/action_t
@param action_list: list of actions can string or action_t obj.
@type nt: string
@param nt: the nt which this rule is belong to
"""
_vmsgb("MAKING RULE", "%s - > %s" % (str(conditions), str(action_list)))
self.default = False #indicates whether this rule is a default rule
self.nt = nt
self.index = 0 #index is used to identify the correct emit order
self.conditions = self.handle_enc_preferred(conditions)
self.actions = []
for action in action_list:
if is_stringish(action):
self.actions.append(actions.action_t(action))
else:
self.actions.append(action)
def __str__(self):
s = [ str(self.conditions) , " ->\t" ]
first = True
for a in self.actions:
if first:
first=False
else:
s.append(" \t")
s.append(str(a))
return ''.join(s)
def handle_enc_preferred(self,conditions):
''' remove the ENCODER_PREFERRED constraint and replace it with
an attribute '''
for cond in conditions.and_conditions:
if cond.field_name == "ENCODER_PREFERRED":
self.enc_preferred = True
conditions.and_conditions.remove(cond)
else:
self.enc_preferred = False
return conditions
def compute_field_capture_list(self):
"""Look at the conditions and return a list of tuples
(fieldname, bits) for use by code generation, by searching the
conditions to see which one s are captures"""
# 2009-02-08: using the bind-phase test conditions is wrong,
# as we do not need to test all the bindings.
return self.conditions.compute_field_capture_list()
def prepare_value_for_emit(self, a):
"""@return: (length-in-bits, value-as-hex)"""
if a.emit_type == 'numeric':
v = hex(a.int_value)
return (a.nbits, v) # return v with the leading 0x
s = a.value
if hex_pattern.match(s):
return ((len(s)-2)*4, s) #hex nibbles - 0x -> bytes
s_short = no_underscores(s)
if bits_pattern.match(s_short): # ones and zeros
return (len(s_short), hex(int(s_short,2)))
die("prepare_value_for_emit: Unhandled value [%s] for rule: [%s]" %(s,str(self)))
def uses_bit_vector(self):
"""For encoding multiple prefixes, we need to stash multiple values in the IFORM. This is the key."""
for a in self.actions:
if a.is_field_binding():
if a.field_name == 'NO_RETURN': # FIXME: check value ==1?
return True
return False
def has_nothing_action(self):
for a in self.actions:
if a.is_nothing():
return True
return False
def has_error_action(self):
for a in self.actions:
if a.is_error():
return True
elif a.is_field_binding() and a.field_name == 'ERROR':
return True
return False
def has_emit_action(self):
for a in self.actions:
if a.is_emit_action():
return True
return False
def has_nonterminal_action(self):
for a in self.actions:
if a.is_nonterminal():
return True
return False
def has_naked_bit_action(self):
for a in self.actions:
if a.naked_bits():
return True
return False
def has_no_return_action(self):
for a in self.actions:
if a.is_field_binding():
# for repeating prefixes, we have the NO_RETURN field.
if a.field_name == 'NO_RETURN': # FIXME: check value ==1?
return True
return False
def has_otherwise_rule(self):
if self.conditions.has_otherwise():
return True
return False
def get_nt_in_cond_list(self):
#returns the condition with nt, if exists
nts = []
for cond in self.conditions.and_conditions:
rvalue = cond.rvalue
if rvalue.nonterminal():
nts.append(cond)
if len(nts) == 0:
return None
if len(nts) == 1:
return nts[0]
error = ("the rule %s has more than one nt in the" +
"condition list, we do not support it currently") % str(self)
die(error)
def emit_isa_rule(self, ith_rule, group):
''' emit code for INSTRUCTION's rule:
1. conditions.
2. set of the encoders iform index.
3. call the field binding pattern function to set values to fields.
4. nonterminal action type.
'''
lines = []
# 1.
lines.extend( self.conditions.emit_code() )
lines.append( "if (conditions_satisfied) {")
lines.append( " okay=1;")
# 2.
obj_name = encutil.enc_strings['obj_str']
set_iform = 'xed_encoder_request_set_iform_index'
code = '%s(%s,iform_ids[iclass_index][%d])'
code = code % (set_iform,obj_name,ith_rule)
lines.append(' %s;' % code)
# 3.
get_fb_ptrn = (' fb_ptrn_function = '+
'xed_encoder_get_fb_ptrn(%s);' % obj_name )
lines.append(get_fb_ptrn)
#call function that sets the values to the fileid
lines.append(' (*fb_ptrn_function)(%s);' % obj_name)
# 4.
for a in self.actions:
if a.is_nonterminal():
lines += a.emit_code('BIND')
lines.append( " if (okay) return 1;")
lines.append( "}")
return lines
def emit_rule_bind(self, ith_rule, nt_name, ntluf):
lines = []
#
# emit code for the conditions and if the conditions are true, do the action
#
lines.extend( self.conditions.emit_code() )
lines.append( "if (conditions_satisfied) {")
lines.append( " okay=1;") # 2007-07-03 start okay over again...
obj_name = encutil.enc_strings['obj_str']
do_return = True
use_bit_vector = self.uses_bit_vector()
has_nothing_action = self.has_nothing_action()
has_error_action = self.has_error_action()
has_nonterminal_action = self.has_nonterminal_action()
has_emit_action = self.has_emit_action()
# NESTED FUNCTION!
def emit_code_bind_sub(a,lines, do_return):
#msgerr("Codegen for action %s" % str(a))
if a.is_field_binding():
# for repeating prefixes, we have the NO_RETURN field.
if a.field_name == 'NO_RETURN': # FIXME: could check bound value == 1.
do_return = False
lines.extend( a.emit_code('BIND') )
return do_return
# first do the non nonterminals
for a in self.actions:
if not a.is_nonterminal():
do_return = emit_code_bind_sub(a, lines, do_return)
# do the nonterminals after everything else
for a in self.actions:
if a.is_nonterminal():
do_return = emit_code_bind_sub(a, lines, do_return)
#here we are setting the enc iform ordinal
if (has_emit_action or has_nonterminal_action) and \
not has_error_action:
# We do not set the iform for the "nothing" actions.
if not has_nothing_action:
if use_bit_vector:
code = 'xed_encoder_request_iforms(%s)->x_%s |=(1<<%d)'
code = code % (obj_name,nt_name,ith_rule)
lines.append( ' %s;' % code)
else:
code = 'xed_encoder_request_iforms(%s)->x_%s=%d'
code = code % (obj_name,nt_name,ith_rule)
lines.append( ' %s;' % code)
iform_builder.remember_iforms(nt_name)
if do_return:
# 2007-07-03 I added the condtional return to allow
# checking other encode options in the event that a
# sub-nonterminal (in this case SIMMz) tanks a partially made "BIND" decision.
lines.append( " if (okay) return 1;")
lines.append( "}")
return lines
def emit_rule_emit(self, ith_rule_arg, nt_name, captures):
"""Return a list of lines of code for the nonterminal function.
@type ith_rule_arg: integer
@param ith_rule_arg: number of the iform for which we are emitting code.
@type ntname: string
@param ntname: name of the nonterm
@type captures: list
@param captures: list of tuples (c-string,bits) (optional)
"""
lines = []
# emit code for the conditions and if the conditions are true, do the action
use_bit_vector = self.uses_bit_vector()
has_error_action = self.has_error_action()
has_nothing_action = self.has_nothing_action()
has_no_return_action = self.has_no_return_action()
has_otherwise_rule = self.has_otherwise_rule()
#complicated_nt are nonterminals that can not be auto generated using
#hash function and lookup tables due to their complexity
#so we generete them in the old if statement structure
complicated_nt = nt_func_gen.get_complicated_nt()
# the 'INSTRUCTIONS' and the complicated nts emit iform are
# using the old ordering mechnism
# all other nts are using the new attribute index to set the order
ith_rule = ith_rule_arg
if nt_name != 'INSTRUCTIONS' and nt_name not in complicated_nt:
ith_rule = self.index
has_otherwise_rule = self.default
if veemit():
msgb("EEMIT", "%d %s %s" % (ith_rule, nt_name, self.__str__()))
if has_no_return_action:
cond_else = '/* no return */ '
else:
cond_else = '/* %d */ ' % (ith_rule)
if has_otherwise_rule:
# 2007-07-23: otherwise rules always fire in emit. There
# is no "else" for the otherwise rule. It is a catch-all.
lines.append( "if (1) { /*otherwise*/")
elif has_nothing_action:
# Some rules have 'nothing' actions that serve as epsilon accepts.
lines.append( "%sif (1) { /* nothing */" % (cond_else))
for a in self.actions:
if not a.is_nothing():
die("Nothing action mixed with other actions")
elif has_error_action:
#
# do not check the iform on error actions -- just ignore
# them. They are caught in the "BIND" step.
return []
elif use_bit_vector:
lines.append( "%sif (iform&(1<<%d)) {" % (cond_else,ith_rule))
else:
lines.append( "%sif (iform==%d) {" % (cond_else,ith_rule))
do_return = True
for a in self.actions:
if veemit():
msgb("Codegen for action", str(a))
if a.is_field_binding():
# for repeating prefixes, we have the NO_RETURN field.
if a.field_name == 'NO_RETURN': # FIXME: check value ==1?
do_return = False
continue
if a.is_nonterminal():
if veemit():
msgb("EEMIT NT ACTION", str(a))
t = a.emit_code('EMIT') # EMIT for NTs
if veemit():
for x in t:
msgb("NT EMIT", x)
lines.extend( t )
elif a.is_emit_action():
# emit actions require knowledge of all the conditions
# which have the field bindings so we emit them here.
if captures:
list_of_tuples = captures