-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathuiCA.py
executable file
·2096 lines (1768 loc) · 92.9 KB
/
uiCA.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 python3
import argparse
import importlib
import os
import re
from collections import Counter, deque, namedtuple, OrderedDict
from concurrent import futures
from heapq import heappop, heappush
from itertools import count, repeat
from typing import List, Dict, NamedTuple, Optional
import random
random.seed(0)
import xed
from facile import *
from instrData.uArchInfo import allPorts, ALUPorts
from instructions import *
from microArchConfigs import MicroArchConfig, MicroArchConfigs
from utils import *
from x64_lib import *
class UopProperties:
def __init__(self, instr, possiblePorts, inputOperands, outputOperands, latencies, divCycles=0, isLoadUop=False, isStoreAddressUop=False, memAddr=None,
isStoreDataUop=False, isFirstUopOfInstr=False, isLastUopOfInstr=False, isRegMergeUop=False):
self.instr = instr
self.possiblePorts = possiblePorts
self.inputOperands = inputOperands
self.outputOperands = outputOperands
self.latencies = latencies # latencies[outOp] = x
self.divCycles = divCycles
self.isLoadUop = isLoadUop
self.isStoreAddressUop = isStoreAddressUop
self.memAddr = memAddr
self.isStoreDataUop = isStoreDataUop
self.isFirstUopOfInstr = isFirstUopOfInstr
self.isLastUopOfInstr = isLastUopOfInstr
self.isRegMergeUop = isRegMergeUop
def __str__(self):
return 'UopProperties(ports: {}, in: {}, out: {}, lat: {})'.format(self.possiblePorts, self.inputOperands, self.outputOperands, self.latencies)
class Uop:
idx_iter = count()
def __init__(self, prop, instrI):
self.idx = next(self.idx_iter)
self.prop: UopProperties = prop
self.instrI: InstrInstance = instrI
self.fusedUop: Optional[FusedUop] = None # fused-domain uop that contains this uop
self.actualPort = None
self.eliminated = False
self.renamedInputOperands: List[RenamedOperand] = []
self.renamedOutputOperands: List[RenamedOperand] = []
self.storeBufferEntry = None
self.latReducedDueToFastPtrChasing = False
self.readyForDispatch = None
self.dispatched = None
self.executed = None
def getUnfusedUops(self):
return [self]
def __str__(self):
return 'Uop(idx: {}, rnd: {}, p: {})'.format(self.idx, self.instrI.rnd, self.actualPort)
class FusedUop:
def __init__(self, uops: List[Uop]):
self.__uops = uops
for uop in uops:
uop.fusedUop = self
self.laminatedUop: Optional[LaminatedUop] = None # laminated-domain uop that contains this
self.issued = None # cycle in which this uop was issued
self.retired = None # cycle in which this uop was retired
self.retireIdx = None # how many other uops were already retired in the same cycle
def getUnfusedUops(self):
return self.__uops
class LaminatedUop:
def __init__(self, fusedUops: List[FusedUop]):
self.__fusedUops = fusedUops
for fUop in fusedUops:
fUop.laminatedUop = self
self.addedToIDQ = None # cycle in which this uop was added to the IDQ
self.uopSource = None # MITE, DSB, MS, LSD, or SE
def getFusedUops(self):
return self.__fusedUops
def getUnfusedUops(self):
return [uop for fusedUop in self.getFusedUops() for uop in fusedUop.getUnfusedUops()]
class StackSyncUop(Uop):
def __init__(self, instrI, uArchConfig):
inOp = RegOperand('RSP')
outOp = RegOperand('RSP')
prop = UopProperties(instrI.instr, ALUPorts[uArchConfig.name], [inOp], [outOp], {outOp: 1}, isFirstUopOfInstr=True)
Uop.__init__(self, prop, instrI)
class StoreBufferEntry:
def __init__(self, abstractAddress):
self.abstractAddress = abstractAddress # (base, index, scale, disp)
self.uops = [] # uops that write to this entry
self.addressReadyCycle = None
self.dataReadyCycle = None
class RenamedOperand:
def __init__(self, nonRenamedOperand=None, uop=None, ready=None):
self.nonRenamedOperand = nonRenamedOperand
self.uop = uop # uop that writes this operand
self.__ready = ready # cycle in which operand becomes ready
def getReadyCycle(self):
if self.__ready is not None:
return self.__ready
if self.uop.dispatched is None:
return None
lat = self.uop.prop.latencies.get(self.nonRenamedOperand, 1)
if self.uop.latReducedDueToFastPtrChasing:
lat -= 1
if self.uop.prop.isLoadUop and (self.uop.storeBufferEntry is not None):
sb = self.uop.storeBufferEntry
if (sb.addressReadyCycle is None) or (sb.dataReadyCycle is None):
return None
memReady = max(sb.addressReadyCycle, sb.dataReadyCycle) + 4 # ToDo
self.__ready = max(self.uop.dispatched + lat, memReady)
else:
self.__ready = self.uop.dispatched + lat
return self.__ready
RenameDictEntry = namedtuple('RenameDictEntry', ['renamedOp', 'renamedByElim32BitMove'])
class Renamer:
def __init__(self, IDQ, reorderBuffer, uArchConfig: MicroArchConfig, initPolicy):
self.IDQ = IDQ
self.reorderBuffer = reorderBuffer
self.uArchConfig = uArchConfig
self.absValGen = AbstractValueGenerator(initPolicy)
self.renameDict = {}
# renamed operands written by current instr.
self.curInstrRndRenameDict = {}
self.curInstrPseudoOpDict = {}
self.nGPRMoveElimInCycle = {}
self.multiUseGPRDict = {}
self.multiUseGPRDictUseInCycle = {}
self.nSIMDMoveElimInCycle = {}
self.multiUseSIMDDict = {}
self.multiUseSIMDDictUseInCycle = {}
self.renamerActiveCycle = 0
self.curStoreBufferEntry = None
self.storeBufferEntryDict = {}
self.lastRegMergeIssued = None # last uop for which register merge uops were issued
def cycle(self):
self.renamerActiveCycle += 1
renamerUops = []
while self.IDQ:
lamUop = self.IDQ[0]
firstUnfusedUop = lamUop.getUnfusedUops()[0]
regMergeProps = firstUnfusedUop.prop.instr.regMergeUopPropertiesList
if firstUnfusedUop.prop.isFirstUopOfInstr and regMergeProps:
if renamerUops:
break
if self.lastRegMergeIssued != firstUnfusedUop:
for mergeProp in regMergeProps:
mergeUop = FusedUop([Uop(mergeProp, firstUnfusedUop.instrI)])
renamerUops.append(mergeUop)
firstUnfusedUop.instrI.regMergeUops.append(LaminatedUop([mergeUop]))
self.lastRegMergeIssued = firstUnfusedUop
break
if firstUnfusedUop.prop.isFirstUopOfInstr and firstUnfusedUop.prop.instr.isSerializingInstr and not self.reorderBuffer.isEmpty():
break
fusedUops = lamUop.getFusedUops()
if len(renamerUops) + len(fusedUops) > self.uArchConfig.issueWidth:
break
renamerUops.extend(fusedUops)
self.IDQ.popleft()
nGPRMoveElim = 0
nSIMDMoveElim = 0
for fusedUop in renamerUops:
for uop in fusedUop.getUnfusedUops():
if uop.prop.instr.mayBeEliminated and (not uop.prop.isRegMergeUop) and (not isinstance(uop, StackSyncUop)):
canonicalInpReg = getCanonicalReg(uop.prop.instr.inputRegOperands[0].reg)
if (canonicalInpReg in GPRegs):
if self.uArchConfig.moveEliminationGPRSlots == 'unlimited':
nGPRMoveElimPossible = 1
else:
nGPRMoveElimPossible = (self.uArchConfig.moveEliminationGPRSlots - nGPRMoveElim
- sum(self.nGPRMoveElimInCycle.get(self.renamerActiveCycle - i, 0) for i in range(1, self.uArchConfig.moveEliminationPipelineLength))
- self.multiUseGPRDictUseInCycle.get(self.renamerActiveCycle - self.uArchConfig.moveEliminationPipelineLength, 0))
if nGPRMoveElimPossible > 0:
uop.eliminated = True
nGPRMoveElim += 1
elif ('MM' in canonicalInpReg):
if self.uArchConfig.moveEliminationSIMDSlots == 'unlimited':
nSIMDMoveElimPossible = 1
else:
nSIMDMoveElimPossible = (self.uArchConfig.moveEliminationSIMDSlots - nSIMDMoveElim
- sum(self.nSIMDMoveElimInCycle.get(self.renamerActiveCycle - i, 0) for i in range(1, self.uArchConfig.moveEliminationPipelineLength))
- self.multiUseSIMDDictUseInCycle.get(self.renamerActiveCycle - self.uArchConfig.moveEliminationPipelineLength, 0))
if nSIMDMoveElimPossible > 0:
uop.eliminated = True
nSIMDMoveElim += 1
if (nGPRMoveElim == 0) and (not self.uArchConfig.moveEliminationGPRAllAliasesMustBeOverwritten):
for k, v in list(self.multiUseGPRDict.items()):
if len(v) <= 1:
del self.multiUseGPRDict[k]
if nSIMDMoveElim == 0:
for k, v in list(self.multiUseSIMDDict.items()):
if len(v) <= 1:
del self.multiUseSIMDDict[k]
for fusedUop in renamerUops:
for uop in fusedUop.getUnfusedUops():
if uop.eliminated:
is32BitMove = (getRegSize(uop.prop.instr.outputRegOperands[0].reg) == 32)
canonicalInpReg = getCanonicalReg(uop.prop.instr.inputRegOperands[0].reg)
canonicalOutReg = getCanonicalReg(uop.prop.instr.outputRegOperands[0].reg)
if (canonicalInpReg in GPRegs):
curMultiUseDict = self.multiUseGPRDict
else:
curMultiUseDict = self.multiUseSIMDDict
entry = self.renameDict.setdefault(canonicalInpReg, RenameDictEntry(RenamedOperand(ready=-1), False))
self.curInstrRndRenameDict[canonicalOutReg] = RenameDictEntry(entry.renamedOp, is32BitMove)
if not entry.renamedOp in curMultiUseDict:
curMultiUseDict[entry.renamedOp] = set()
curMultiUseDict[entry.renamedOp].update([canonicalInpReg, canonicalOutReg])
key = self.getRenameDictKey(uop.prop.instr.outputRegOperands[0])
self.absValGen.setAbstractValueForCurInstr(key, uop.prop.instr)
else:
if uop.prop.instr.uops or isinstance(uop, StackSyncUop):
if uop.prop.isStoreAddressUop:
key = self.getStoreBufferKey(uop.prop.memAddr)
self.curStoreBufferEntry = StoreBufferEntry(key)
self.storeBufferEntryDict[key] = self.curStoreBufferEntry
if uop.prop.isStoreAddressUop or uop.prop.isStoreDataUop:
uop.storeBufferEntry = self.curStoreBufferEntry
self.curStoreBufferEntry.uops.append(uop)
if uop.prop.isLoadUop:
key = self.getStoreBufferKey(uop.prop.memAddr)
baseReg = uop.prop.memAddr.get('base')
baseEntry = self.renameDict.get(getCanonicalReg(baseReg)) if baseReg else None
baseInstr = baseEntry.renamedOp.uop.prop.instr if (baseEntry and baseEntry.renamedOp.uop) else None
indexReg = uop.prop.memAddr.get('index')
indexEntry = self.renameDict.get(getCanonicalReg(indexReg)) if indexReg else None
indexInstr = indexEntry.renamedOp.uop.prop.instr if (indexEntry and indexEntry.renamedOp.uop) else None
uop.latReducedDueToFastPtrChasing = latReducedDueToFastPtrChasing(self.uArchConfig, uop.prop.memAddr, baseInstr, indexInstr,
(baseEntry and baseEntry.renamedByElim32BitMove))
uop.storeBufferEntry = self.storeBufferEntryDict.get(key, None)
for inpOp in uop.prop.inputOperands:
if isinstance(inpOp, PseudoOperand):
renOp = self.curInstrPseudoOpDict[inpOp]
else:
key = self.getRenameDictKey(inpOp)
renOp = self.renameDict.setdefault(key, RenameDictEntry(RenamedOperand(ready=-1), False)).renamedOp
uop.renamedInputOperands.append(renOp)
for outOp in uop.prop.outputOperands:
renOp = RenamedOperand(outOp, uop)
uop.renamedOutputOperands.append(renOp)
if isinstance(outOp, PseudoOperand):
self.curInstrPseudoOpDict[outOp] = renOp
else:
key = self.getRenameDictKey(outOp)
self.curInstrRndRenameDict[key] = RenameDictEntry(renOp, False)
if isinstance(outOp, RegOperand):
self.absValGen.setAbstractValueForCurInstr(key, uop.prop.instr)
else:
# e.g., xor rax, rax
for op in uop.prop.instr.outputRegOperands:
self.curInstrRndRenameDict[getCanonicalReg(op.reg)] = RenameDictEntry(RenamedOperand(uop=uop, ready=-1), False)
if uop.prop.isLastUopOfInstr or uop.prop.isRegMergeUop or isinstance(uop, StackSyncUop):
for key in self.curInstrRndRenameDict:
if key in self.renameDict:
prevRenOp = self.renameDict[key].renamedOp
if (not uop.eliminated) or (prevRenOp != self.curInstrRndRenameDict[key].renamedOp):
if (key in GPRegs) and (prevRenOp in self.multiUseGPRDict):
self.multiUseGPRDict[prevRenOp].remove(key)
elif (type(key) == str) and ('MM' in key) and (prevRenOp in self.multiUseSIMDDict):
if self.multiUseSIMDDict[prevRenOp]:
self.multiUseSIMDDict[prevRenOp].remove(key)
self.renameDict.update(self.curInstrRndRenameDict)
self.absValGen.finishCurInstr()
self.curInstrRndRenameDict.clear()
self.curInstrPseudoOpDict.clear()
self.nGPRMoveElimInCycle[self.renamerActiveCycle] = nGPRMoveElim
self.nSIMDMoveElimInCycle[self.renamerActiveCycle] = nSIMDMoveElim
for k, v in list(self.multiUseGPRDict.items()):
if len(v) == 0:
del self.multiUseGPRDict[k]
if self.multiUseGPRDict:
self.multiUseGPRDictUseInCycle[self.renamerActiveCycle] = len(self.multiUseGPRDict)
for k, v in list(self.multiUseSIMDDict.items()):
if len(v) == 0:
del self.multiUseSIMDDict[k]
if self.multiUseSIMDDict:
self.multiUseSIMDDictUseInCycle[self.renamerActiveCycle] = len(self.multiUseSIMDDict)
return renamerUops
def getRenameDictKey(self, op):
if isinstance(op, RegOperand):
return getCanonicalReg(op.reg)
elif isinstance(op, FlagOperand):
return op.flags
else:
return None
def getStoreBufferKey(self, memAddr):
if memAddr is None:
return None
return (self.absValGen.getAbstractValueForReg(memAddr.get('base')), self.absValGen.getAbstractValueForReg(memAddr.get('index')),
memAddr.get('scale'), memAddr.get('disp'))
class FrontEnd:
def __init__(self, instructions: List[Instr], reorderBuffer, scheduler, uArchConfig: MicroArchConfig,
unroll, alignmentOffset, initPolicy, perfEvents, simpleFrontEnd=False):
self.IDQ = deque()
self.renamer = Renamer(self.IDQ, reorderBuffer, uArchConfig, initPolicy)
self.reorderBuffer = reorderBuffer
self.scheduler = scheduler
self.uArchConfig = uArchConfig
self.unroll = unroll
self.alignmentOffset = alignmentOffset
self.perfEvents = perfEvents
self.MS = MicrocodeSequencer(self.uArchConfig)
self.instructionQueue = deque()
self.preDecoder = PreDecoder(self.instructionQueue, self.uArchConfig)
self.decoder = Decoder(self.instructionQueue, self.MS, self.uArchConfig)
self.RSPOffset = 0
self.allGeneratedInstrInstances: List[InstrInstance] = []
self.DSB = DSB(self.MS, self.uArchConfig)
self.addressesInDSB = set()
self.LSDUnrollCount = 1
if simpleFrontEnd:
self.uopSource = None
else:
self.uopSource = 'MITE'
if unroll or simpleFrontEnd:
self.cacheBlockGenerator = CacheBlockGenerator(instructions, True, self.alignmentOffset)
else:
self.cacheBlocksForNextRoundGenerator = CacheBlocksForNextRoundGenerator(instructions, self.alignmentOffset)
cacheBlocksForFirstRound = next(self.cacheBlocksForNextRoundGenerator)
if self.uArchConfig.DSBBlockSize == 32:
allBlocksCanBeCached = all(canBeInDSB(block, uArchConfig.DSBBlockSize) for cb in cacheBlocksForFirstRound
for block in split64ByteBlockTo32ByteBlocks(cb) if block)
else:
allBlocksCanBeCached = all(canBeInDSB(block, uArchConfig.DSBBlockSize) for block in cacheBlocksForFirstRound)
allInstrsCanBeUsedByLSD = all(instrI.instr.canBeUsedByLSD() for cb in cacheBlocksForFirstRound for instrI in cb)
nUops = sum(len(instrI.uops) for cb in cacheBlocksForFirstRound for instrI in cb)
if allBlocksCanBeCached and self.uArchConfig.LSDEnabled and allInstrsCanBeUsedByLSD and (nUops <= self.uArchConfig.IDQWidth):
self.uopSource = 'LSD'
self.LSDUnrollCount = self.uArchConfig.LSDUnrolling.get(nUops, 1)
for cacheBlock in cacheBlocksForFirstRound + [cb for _ in range(0, self.LSDUnrollCount-1) for cb in next(self.cacheBlocksForNextRoundGenerator)]:
self.addNewCacheBlock(cacheBlock)
else:
self.findCacheableAddresses(cacheBlocksForFirstRound)
for cacheBlock in cacheBlocksForFirstRound:
self.addNewCacheBlock(cacheBlock)
if self.alignmentOffset in self.addressesInDSB:
self.uopSource = 'DSB'
def cycle(self, clock):
issueUops = []
if not self.reorderBuffer.isFull() and not self.scheduler.isFull(): # len(self.IDQ) >= uArchConfig.issueWidth and the first check seems to be wrong, but leads to better results
issueUops = self.renamer.cycle()
for fusedUop in issueUops:
fusedUop.issued = clock
self.reorderBuffer.cycle(clock, issueUops)
self.scheduler.cycle(clock, issueUops)
if self.reorderBuffer.isFull():
self.perfEvents.setdefault(clock, {})['RBFull'] = 1
if self.scheduler.isFull():
self.perfEvents.setdefault(clock, {})['RSFull'] = 1
if len(self.instructionQueue) + self.uArchConfig.preDecodeWidth > self.uArchConfig.IQWidth:
self.perfEvents.setdefault(clock, {})['IQFull'] = 1
if len(self.IDQ) + self.uArchConfig.DSBWidth > self.uArchConfig.IDQWidth:
self.perfEvents.setdefault(clock, {})['IDQFull'] = 1
return
if self.uopSource is None:
while len(self.IDQ) < self.uArchConfig.issueWidth:
for instrI in next(self.cacheBlockGenerator):
self.allGeneratedInstrInstances.append(instrI)
for lamUop in instrI.uops:
self.addStackSyncUop(clock, lamUop.getUnfusedUops()[0])
for uop in lamUop.getUnfusedUops():
self.IDQ.append(LaminatedUop([FusedUop([uop])]))
elif self.uopSource == 'LSD':
if not self.IDQ:
for _ in range(0, self.LSDUnrollCount):
for cacheBlock in next(self.cacheBlocksForNextRoundGenerator):
self.addNewCacheBlock(cacheBlock)
else:
# add new cache blocks
while len(self.DSB.DSBBlockQueue) < 2 and len(self.preDecoder.B16BlockQueue) < 4:
if self.unroll:
self.addNewCacheBlock(next(self.cacheBlockGenerator))
else:
for cacheBlock in next(self.cacheBlocksForNextRoundGenerator):
self.addNewCacheBlock(cacheBlock)
# add new uops to IDQ
newUops = []
if self.MS.isBusy():
newUops = self.MS.cycle()
elif self.uopSource == 'MITE':
self.preDecoder.cycle(clock)
newInstrIUops = self.decoder.cycle(clock)
newUops = [u for _, u in newInstrIUops if u is not None]
if not self.unroll and newInstrIUops:
curInstrI = newInstrIUops[-1][0]
if curInstrI.instr.isLastDecodedInstr() and (curInstrI.instr.isBranchInstr or curInstrI.instr.macroFusedWithNextInstr):
if self.alignmentOffset in self.addressesInDSB:
self.uopSource = 'DSB'
elif self.uopSource == 'DSB':
newInstrIUops = self.DSB.cycle()
newUops = [u for _, u in newInstrIUops if u is not None]
if newUops and newUops[-1].getUnfusedUops()[-1].prop.isLastUopOfInstr:
curInstrI = newInstrIUops[-1][0]
if curInstrI.instr.isLastDecodedInstr():
nextAddr = self.alignmentOffset
else:
nextAddr = curInstrI.address + (len(curInstrI.instr.opcode) // 2)
if nextAddr not in self.addressesInDSB:
self.uopSource = 'MITE'
for lamUop in newUops:
self.addStackSyncUop(clock, lamUop.getUnfusedUops()[0])
self.IDQ.append(lamUop)
lamUop.addedToIDQ = clock
def findCacheableAddresses(self, cacheBlocksForFirstRound):
for cacheBlock in cacheBlocksForFirstRound:
if self.uArchConfig.DSBBlockSize == 32:
splitCacheBlocks = [block for block in split64ByteBlockTo32ByteBlocks(cacheBlock) if block]
if self.uArchConfig.both32ByteBlocksMustBeCacheable and any((not canBeInDSB(block, self.uArchConfig.DSBBlockSize)) for block in splitCacheBlocks):
return
else:
splitCacheBlocks = [cacheBlock]
for block in splitCacheBlocks:
if canBeInDSB(block, self.uArchConfig.DSBBlockSize):
for instrI in block:
self.addressesInDSB.add(instrI.address)
else:
return
def addNewCacheBlock(self, cacheBlock):
self.allGeneratedInstrInstances.extend(cacheBlock)
if self.uopSource == 'LSD':
for instrI in cacheBlock:
self.IDQ.extend(instrI.uops)
instrI.source = 'LSD'
for uop in instrI.uops:
uop.uopSource = 'LSD'
else:
if self.uArchConfig.DSBBlockSize == 32:
blocks = split64ByteBlockTo32ByteBlocks(cacheBlock)
else:
blocks = [cacheBlock]
for block in blocks:
if not block: continue
if block[0].address in self.addressesInDSB:
for instrI in block:
instrI.source = 'DSB'
self.DSB.DSBBlockQueue += getDSBBlocks(block)
else:
for instrI in block:
instrI.source = 'MITE'
if self.uArchConfig.DSBBlockSize == 32:
B16Blocks = split32ByteBlockTo16ByteBlocks(block)
else:
B16Blocks = split64ByteBlockTo16ByteBlocks(block)
for B16Block in B16Blocks:
if not B16Block: continue
self.preDecoder.B16BlockQueue.append(deque(B16Block))
lastInstrI = B16Block[-1]
if lastInstrI.instr.isBranchInstr and (lastInstrI.address % 16) + (len(lastInstrI.instr.opcode) // 2) > 16:
# branch instr. ends in next block
self.preDecoder.B16BlockQueue.append(deque())
def addStackSyncUop(self, clock, uop):
if not uop.prop.isFirstUopOfInstr:
return
instr = uop.prop.instr
requiresSyncUop = False
if self.RSPOffset and any((getCanonicalReg(op.reg) == 'RSP') for op in instr.inputRegOperands+instr.memAddrOperands if not op.isImplicitStackOperand):
requiresSyncUop = True
self.RSPOffset = 0
self.RSPOffset += instr.implicitRSPChange
if self.RSPOffset > 192:
requiresSyncUop = True
self.RSPOffset = 0
if any((getCanonicalReg(op.reg) == 'RSP') for op in instr.outputRegOperands):
self.RSPOffset = 0
if requiresSyncUop:
stackSyncUop = StackSyncUop(uop.instrI, self.uArchConfig)
lamUop = LaminatedUop([FusedUop([stackSyncUop])])
self.IDQ.append(lamUop)
lamUop.addedToIDQ = clock
lamUop.uopSource = 'SE'
uop.instrI.stackSyncUops.append(lamUop)
DSBEntry = namedtuple('DSBEntry', ['slot', 'instrI', 'uop', 'MSUops', 'requiresExtraEntry'])
class DSB:
def __init__(self, MS, uArchConfig: MicroArchConfig):
self.MS = MS
self.DSBBlockQueue = deque()
self.uArchConfig = uArchConfig
self.delayInPrevCycle = False
def cycle(self):
retList = []
DSBBlock = self.DSBBlockQueue[0]
newDSBBlockStarted = (DSBBlock[0].slot == 0)
secondDSBBlockLoaded = False
remainingSlots = self.uArchConfig.DSBWidth
delayInPrevCycle = self.delayInPrevCycle
self.delayInPrevCycle = False
while remainingSlots > 0:
if not DSBBlock:
if (not secondDSBBlockLoaded) and self.DSBBlockQueue and (not self.DSBBlockQueue[0][-1].MSUops):
secondDSBBlockLoaded = True
DSBBlock = self.DSBBlockQueue[0]
prevInstrI = retList[-1][0]
if ((prevInstrI.address + len(prevInstrI.instr.opcode)/2 != DSBBlock[0].instrI.address) and
not prevInstrI.instr.isLastDecodedInstr()):
# next instr not in DSB
return retList
else:
return retList
entry = DSBBlock[0]
if entry.requiresExtraEntry and (remainingSlots < 2):
return retList
if entry.uop:
retList.append((entry.instrI, entry.uop))
entry.uop.uopSource = 'DSB'
if entry.requiresExtraEntry:
remainingSlots = 0
self.delayInPrevCycle = True
else:
remainingSlots -= 1
if entry.MSUops:
self.MS.addUops(entry.MSUops, 'DSB')
remainingSlots = 0
DSBBlock.popleft()
if not DSBBlock:
self.DSBBlockQueue.popleft()
if remainingSlots and self.DSBBlockQueue and (self.uArchConfig.DSBWidth == 6):
nextInstrAddr = self.DSBBlockQueue[0][0].instrI.address
nextInstrInSameMemoryBlock = (nextInstrAddr//self.uArchConfig.DSBBlockSize == entry.instrI.address//self.uArchConfig.DSBBlockSize)
if (self.uArchConfig.DSBBlockSize == 32) and nextInstrInSameMemoryBlock and entry.instrI.instr.isLastDecodedInstr() and (not delayInPrevCycle):
remainingSlots = 0
elif not nextInstrInSameMemoryBlock:
if newDSBBlockStarted:
if len(retList) in [1, 2]:
remainingSlots = 4
elif len(retList) in [3, 4]:
remainingSlots = 2
elif len(retList) == 5:
remainingSlots = 1
elif entry.instrI.instr.isLastDecodedInstr():
if (len(retList) == 1) or ((len(retList) == 2) and (entry.slot >= 4)):
remainingSlots = 4
else:
remainingSlots = min(remainingSlots, 2)
return retList
class MicrocodeSequencer:
def __init__(self, uArchConfig: MicroArchConfig):
self.uArchConfig = uArchConfig
self.uopQueue = deque()
self.stalled = 0
self.postStall = 0
def cycle(self):
uops = []
if self.stalled:
self.stalled -= 1
elif self.uopQueue:
while self.uopQueue and len(uops) < 4:
uops.append(self.uopQueue.popleft())
if not self.uopQueue:
self.stalled = self.postStall
return uops
def addUops(self, uops, prevUopSource):
self.uopQueue.extend(uops)
for lamUop in uops:
lamUop.uopSource = 'MS'
if prevUopSource == 'MITE':
self.stalled = 1
self.postStall = 1
elif prevUopSource == 'DSB':
self.stalled = self.uArchConfig.DSB_MS_Stall
self.postStall = 0
def isBusy(self):
return (len(self.uopQueue) > 0) or self.stalled
class Decoder:
def __init__(self, instructionQueue, MS: MicrocodeSequencer, uArchConfig: MicroArchConfig):
self.instructionQueue = instructionQueue
self.MS = MS
self.uArchConfig = uArchConfig
def cycle(self, clock):
uopsList = []
nDecodedInstrs = 0
remainingDecoderSlots = self.uArchConfig.nDecoders
while self.instructionQueue:
instrI: InstrInstance = self.instructionQueue[0]
if instrI.instr.macroFusedWithPrevInstr:
self.instructionQueue.popleft()
instrI.removedFromIQ = clock
continue
if instrI.predecoded + self.uArchConfig.predecodeDecodeDelay > clock:
break
if uopsList and instrI.instr.complexDecoder:
break
if instrI.instr.macroFusibleWith:
if (not self.uArchConfig.macroFusibleInstrCanBeDecodedAsLastInstr) and (nDecodedInstrs == self.uArchConfig.nDecoders-1):
break
if (len(self.instructionQueue) <= 1) or (self.instructionQueue[1].predecoded + self.uArchConfig.predecodeDecodeDelay > clock):
break
self.instructionQueue.popleft()
instrI.removedFromIQ = clock
if instrI.instr.uopsMITE:
for lamUop in instrI.uops[:instrI.instr.uopsMITE]:
uopsList.append((instrI, lamUop))
lamUop.uopSource = 'MITE'
else:
uopsList.append((instrI, None))
if instrI.instr.uopsMS:
self.MS.addUops(instrI.uops[instrI.instr.uopsMITE:], 'MITE')
break
if instrI.instr.complexDecoder:
remainingDecoderSlots = min(remainingDecoderSlots - 1, instrI.instr.nAvailableSimpleDecoders)
else:
remainingDecoderSlots -= 1
nDecodedInstrs += 1
if remainingDecoderSlots <= 0:
break
if instrI.instr.isBranchInstr or instrI.instr.macroFusedWithNextInstr:
break
return uopsList
def isEmpty(self):
return (not self.instructionQueue)
class PreDecoder:
def __init__(self, instructionQueue, uArchConfig: MicroArchConfig):
self.uArchConfig = uArchConfig
self.B16BlockQueue = deque() # a deque of 16 Byte blocks (i.e., deques of InstrInstances)
self.instructionQueue = instructionQueue
self.curBlock = None
self.nonStalledPredecCyclesForCurBlock = 0
self.preDecQueue = deque() # instructions are queued here before they are added to the instruction queue after all stalls have been resolved
self.stalled = 0
self.partialInstrI = None
def cycle(self, clock):
if not self.stalled:
if ((not self.preDecQueue) and (self.B16BlockQueue or self.partialInstrI)
and len(self.instructionQueue) + self.uArchConfig.preDecodeWidth <= self.uArchConfig.IQWidth):
if self.partialInstrI is not None:
self.preDecQueue.append(self.partialInstrI)
self.partialInstrI = None
if not self.curBlock:
if len(self.B16BlockQueue) < self.uArchConfig.preDecodeBlockSize // 16:
return
self.curBlock = deque()
for _ in range(self.uArchConfig.preDecodeBlockSize // 16):
self.curBlock.extend(self.B16BlockQueue.popleft())
self.stalled = max(0, sum(3 for ii in self.curBlock if ii.instr.lcpStall) - max(0, self.nonStalledPredecCyclesForCurBlock - 1))
self.nonStalledPredecCyclesForCurBlock = 0
while self.curBlock and len(self.preDecQueue) < self.uArchConfig.preDecodeWidth:
if instrInstanceCrossesPredecBlockBoundary(self.curBlock[0], self.uArchConfig.preDecodeBlockSize):
break
self.preDecQueue.append(self.curBlock.popleft())
if len(self.curBlock) == 1:
instrI = self.curBlock[0]
if instrInstanceCrossesPredecBlockBoundary(instrI, self.uArchConfig.preDecodeBlockSize):
offsetOfNominalOpcode = (instrI.address % 16) + instrI.instr.posNominalOpcode
if (len(self.preDecQueue) < self.uArchConfig.preDecodeWidth) or (offsetOfNominalOpcode >= 16):
self.partialInstrI = instrI
self.curBlock.popleft()
self.nonStalledPredecCyclesForCurBlock += 1
if not self.stalled:
for instrI in self.preDecQueue:
instrI.predecoded = clock
self.instructionQueue.append(instrI)
self.preDecQueue.clear()
self.stalled = max(0, self.stalled-1)
def isEmpty(self):
return (not self.B16BlockQueue) and (not self.preDecQueue) and (not self.partialInstrI)
class ReorderBuffer:
def __init__(self, retireQueue, uArchConfig: MicroArchConfig):
self.uops = deque()
self.retireQueue = retireQueue
self.uArchConfig = uArchConfig
def isEmpty(self):
return not self.uops
def isFull(self):
return len(self.uops) + self.uArchConfig.issueWidth > self.uArchConfig.RBWidth
def cycle(self, clock, newUops):
self.retireUops(clock)
self.addUops(clock, newUops)
def retireUops(self, clock):
nRetiredInSameCycle = 0
for _ in range(0, self.uArchConfig.retireWidth):
if not self.uops: break
fusedUop = self.uops[0]
unfusedUops = fusedUop.getUnfusedUops()
if all((u.executed is not None and u.executed < clock) for u in unfusedUops):
self.uops.popleft()
self.retireQueue.append(fusedUop)
fusedUop.retired = clock
fusedUop.retireIdx = nRetiredInSameCycle
nRetiredInSameCycle += 1
else:
break
def addUops(self, clock, newUops):
for fusedUop in newUops:
self.uops.append(fusedUop)
for uop in fusedUop.getUnfusedUops():
if (not uop.prop.possiblePorts) or uop.eliminated:
uop.executed = clock
class Scheduler:
def __init__(self, uArchConfig: MicroArchConfig):
self.uArchConfig = uArchConfig
self.uops = set()
self.portUsage = {p:0 for p in allPorts[self.uArchConfig.name]}
self.portUsageAtStartOfCycle = {}
self.nextP23Port = '2'
self.nextP49Port = '4'
self.nextP78Port = '7'
self.uopsDispatchedInPrevCycle = [] # the port usage counter is decreased one cycle after uops are dispatched
self.readyQueue = {p:[] for p in allPorts[self.uArchConfig.name]}
self.readyDivUops = []
self.uopsReadyInCycle = {}
self.nonReadyUops = [] # uops not yet added to uopsReadyInCycle (in order)
self.pendingUops = set() # dispatched, but not finished uops
self.pendingStoreFenceUops = deque()
self.storeUopsSinceLastStoreFence = []
self.pendingLoadFenceUops = deque()
self.loadUopsSinceLastLoadFence = []
self.blockedResources = dict() # for how many remaining cycle a resource will be blocked
self.blockedResources['div'] = 0
self.dependentUops = dict() # uops that have an operand that is written by a non-executed uop
def isFull(self):
return len(self.uops) + self.uArchConfig.issueWidth > self.uArchConfig.RSWidth
def cycle(self, clock, newUops):
if clock in self.uopsReadyInCycle:
for uop in self.uopsReadyInCycle[clock]:
if uop.prop.divCycles:
heappush(self.readyDivUops, (uop.idx, uop))
else:
heappush(self.readyQueue[uop.actualPort], (uop.idx, uop))
del self.uopsReadyInCycle[clock]
self.addNewUops(clock, newUops)
self.dispatchUops(clock)
self.processPendingUops()
self.processNonReadyUops(clock)
self.processPendingFences(clock)
self.updateBlockedResources()
def dispatchUops(self, clock):
applicablePorts = list(allPorts[self.uArchConfig.name])
if ('4' in applicablePorts) and ('9' in applicablePorts) and self.readyQueue['4'] and self.readyQueue['9']:
# two stores can be executed in the same cycle if they access the same cache line; see 'Paired Stores' in the optimization manual
uop4 = self.readyQueue['4'][0][1]
uop9 = self.readyQueue['9'][0][1]
addr4 = uop4.storeBufferEntry.abstractAddress
addr9 = uop9.storeBufferEntry.abstractAddress
if addr4 and addr9 and ((addr4[0] != addr9[0]) or (addr4[1] != addr9[1]) or (addr4[2] != addr9[2]) or (abs(addr4[3]-addr9[3]) >= 64)):
if uop4.idx <= uop9.idx:
applicablePorts.remove('9')
else:
applicablePorts.remove('4')
if self.uArchConfig.slow256BitMemAcc and self.readyQueue['2'] and self.readyQueue['3']:
uop2 = self.readyQueue['2'][0][1]
uop3 = self.readyQueue['3'][0][1]
if uop2.prop.isLoadUop and uop3.prop.isLoadUop and (('M256' in uop2.instrI.instr.instrStr) or ('M256' in uop3.instrI.instr.instrStr)):
applicablePorts.remove('3' if uop2.idx < uop3.idx else '2')
uopsDispatched = []
for port in applicablePorts:
queue = self.readyQueue[port]
if (port == '0' and (not self.blockedResources['div']) and self.readyDivUops
and ((not self.readyQueue['0']) or self.readyDivUops[0][0] < self.readyQueue['0'][0][0])):
queue = self.readyDivUops
if self.blockedResources.get('port' + port):
continue
if not queue:
continue
uop = heappop(queue)[1]
uop.dispatched = clock
self.uops.remove(uop)
uopsDispatched.append(uop)
self.pendingUops.add(uop)
self.blockedResources['div'] += uop.prop.divCycles
if self.uArchConfig.slow256BitMemAcc and (port == '4') and ('M256' in uop.instrI.instr.instrStr):
self.blockedResources['port' + port] = 2
for uop in self.uopsDispatchedInPrevCycle:
self.portUsage[uop.actualPort] -= 1
self.uopsDispatchedInPrevCycle = uopsDispatched
def processPendingUops(self):
for uop in list(self.pendingUops):
finishTime = uop.dispatched + 2
if uop.prop.isFirstUopOfInstr and (uop.prop.instr.TP is not None):
finishTime = max(finishTime, uop.dispatched + uop.prop.instr.TP)
notFinished = False
for renOutOp in uop.renamedOutputOperands:
readyCycle = renOutOp.getReadyCycle()
if readyCycle is None:
notFinished = True
break
finishTime = max(finishTime, readyCycle)
if notFinished:
continue
if uop.prop.isStoreAddressUop:
addrReady = uop.dispatched + 5 # ToDo
uop.storeBufferEntry.addressReadyCycle = addrReady
finishTime = max(finishTime, addrReady)
if uop.prop.isStoreDataUop:
dataReady = uop.dispatched + 1 # ToDo
uop.storeBufferEntry.dataReadyCycle = dataReady
finishTime = max(finishTime, dataReady)
for depUop in self.dependentUops.pop(uop, []):
self.checkDependingUopsExecuted(depUop)
self.pendingUops.remove(uop)
uop.executed = finishTime
def processPendingFences(self, clock):
for queue, uopsSinceLastFence in [(self.pendingLoadFenceUops, self.loadUopsSinceLastLoadFence),
(self.pendingStoreFenceUops, self.storeUopsSinceLastStoreFence)]:
if queue:
executedCycle = queue[0].executed
if (executedCycle is not None) and executedCycle <= clock:
queue.popleft()
del uopsSinceLastFence[:]
def processNonReadyUops(self, clock):
newReadyUops = set()
for uop in self.nonReadyUops:
if self.checkUopReady(clock, uop):
newReadyUops.add(uop)
self.nonReadyUops = [u for u in self.nonReadyUops if (u not in newReadyUops)]
def updateBlockedResources(self):
for r in self.blockedResources.keys():
self.blockedResources[r] = max(0, self.blockedResources[r] - 1)
# adds ready uops to self.uopsReadyInCycle
def checkUopReady(self, clock, uop):
if uop.readyForDispatch is not None:
return True
if uop.prop.instr.isLoadSerializing:
if uop.prop.isFirstUopOfInstr and (self.pendingLoadFenceUops[0] != uop or
any((uop2.executed is None) or (uop2.executed > clock) for uop2 in self.loadUopsSinceLastLoadFence)):
return False
elif uop.prop.instr.isStoreSerializing:
if uop.prop.isFirstUopOfInstr and (self.pendingStoreFenceUops[0] != uop or
any((uop2.executed is None) or (uop2.executed > clock) for uop2 in self.storeUopsSinceLastStoreFence)):
return False
else:
if uop.prop.isLoadUop and self.pendingLoadFenceUops and self.pendingLoadFenceUops[0].idx < uop.idx:
return False
if (uop.prop.isStoreDataUop or uop.prop.isStoreAddressUop) and self.pendingStoreFenceUops and self.pendingStoreFenceUops[0].idx < uop.idx:
return False
if uop.prop.isFirstUopOfInstr and self.blockedResources.get(uop.prop.instr.instrStr, 0) > 0:
return False
readyForDispatchCycle = self.getReadyForDispatchCycle(clock, uop)
if readyForDispatchCycle is None:
return False
uop.readyForDispatch = readyForDispatchCycle
self.uopsReadyInCycle.setdefault(readyForDispatchCycle, []).append(uop)
if uop.prop.isFirstUopOfInstr and (uop.prop.instr.TP is not None):
self.blockedResources[uop.prop.instr.instrStr] = uop.prop.instr.TP
if uop.prop.isLoadUop:
self.loadUopsSinceLastLoadFence.append(uop)
if uop.prop.isStoreDataUop or uop.prop.isStoreAddressUop:
self.storeUopsSinceLastStoreFence.append(uop)
return True
def addNewUops(self, clock, newUops):
self.portUsageAtStartOfCycle[clock] = dict(self.portUsage)
portCombinationsInCurCycle = {}
for issueSlot, fusedUop in enumerate(newUops):
for uop in fusedUop.getUnfusedUops():
if (not uop.prop.possiblePorts) or uop.eliminated: