Repository navigation
Expand file tree
/
Copy pathPerfApi.cpp
More file actions
3262 lines (2728 loc) · 100 KB
/
Copy pathPerfApi.cpp
File metadata and controls
3262 lines (2728 loc) · 100 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
// Copyright 2024 Tenstorrent 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.
#include <algorithm>
#include <cinttypes>
#include <iomanip>
#include <ranges>
#include "PerfApi.hpp"
using namespace TT_PERF;
using CSRN = WdRiscv::CsrNumber;
using std::cerr;
// Exclude the rounding/flag fields of the combined FP/vector CSRs (fcsr = frm|fflags,
// vcsr = vxrm|vxsat) from speculative producer-consumer CSR forwarding. A forwarded rounding field
// gets re-injected into architectural state when a younger FP/vector op writes the sticky flag
// (fflags/vxsat): that puts the combined CSR in lastWrittenRegs_, so execute()'s "undo" re-pokes it
// from a prevValue still holding the forwarded value. An older retiring csrrs then reads the leaked
// value and diverges from the reference trace. Standalone CSRs (VL/VTYPE/VSTART/VLENB) lack this
// coupling and are forwarded normally.
static inline bool isNonForwardableCsr(unsigned csrNum)
{
switch (WdRiscv::CsrNumber(csrNum))
{
case CSRN::FFLAGS: case CSRN::FRM: case CSRN::FCSR: // fcsr group
case CSRN::VXSAT: case CSRN::VXRM: case CSRN::VCSR: // vcsr group
return true;
default:
return false;
}
}
// True if hardware can update csrNum without an instruction writing it, so a read at speculative
// execute and a read at retire may legitimately differ. See the use site in retire().
//
// Do not add: MTOPEI/STOPEI/VSTOPEI (reading them *claims* the interrupt -- not passive reads);
// SEED (fresh entropy per read unless --reproducibleseed); MSTATUS/SSTATUS (FS/VS/SD do
// drift, but both are written often and a forced rd would mask a write's real divergence).
static inline bool isAsyncUpdatedCsr(unsigned csrNum)
{
using CN = WdRiscv::CsrNumber;
auto inRange = [&](CN lo, CN hi) { return csrNum >= unsigned(lo) and csrNum <= unsigned(hi); };
switch (WdRiscv::CsrNumber(csrNum))
{
case CN::MIP: case CN::SIP: case CN::VSIP: // interrupt-pending, set by hardware
case CN::HIP: case CN::HVIP: case CN::MVIP:
case CN::MTOPI: case CN::STOPI: case CN::VSTOPI: // AIA top interrupt, recomputed
case CN::SCOUNTOVF: // Sscofpmf overflow (sets MIP.LCOFIP)
return true;
default: // free-running counters, one block each
return inRange(CN::CYCLE, CN::HPMCOUNTER31) or // 0xc00-0xc1f cycle/time/instret/hpm
inRange(CN::CYCLEH, CN::HPMCOUNTER31H) or // 0xc80-0xc9f RV32 high halves
inRange(CN::MCYCLE, CN::MHPMCOUNTER31) or // 0xb00-0xb1f machine
inRange(CN::MCYCLEH, CN::MHPMCOUNTER31H); // 0xb80-0xb9f machine, RV32 high
}
}
// True if csrNum is an AIA/Smcsrind indirect data window (MIREG*/SIREG*/VSIREG*): a CSR with no
// storage of its own that aliases whichever register its addressing context selects.
static inline bool isIndirectCsrWindow(unsigned csrNum)
{
using CN = WdRiscv::CsrNumber;
auto inRange = [&](CN lo, CN hi) { return csrNum >= unsigned(lo) and csrNum <= unsigned(hi); };
return inRange(CN::MIREG, CN::MIREG6) or
inRange(CN::SIREG, CN::SIREG6) or
inRange(CN::VSIREG, CN::VSIREG6);
}
template <typename URV>
PerfApi<URV>::PerfApi(SystemType& system)
: system_(system)
{
unsigned n = system.hartCount();
traceFiles_.resize(n);
hartPacketMaps_.resize(n);
hartStoreMaps_.resize(n);
hartLastRetired_.resize(n, initHartLastRetired);
hartRegProducers_.resize(n);
hartSpecLrs_.resize(n);
hartSpecCsrs_.resize(n);
for (auto& producers : hartRegProducers_)
producers.resize(totalRegCount_);
hartRawPtrs_.reserve(n);
for (unsigned i = 0; i < n; ++i)
hartRawPtrs_.push_back(system_.ithHart(i).get());
}
template <typename URV>
std::shared_ptr<typename PerfApi<URV>::HartType>
PerfApi<URV>::checkHart(const char* caller, unsigned hartIx)
{
auto hart = getHart(hartIx);
if (not hart)
{
cerr << caller << ": Bad hart index: " << hartIx << '\n';
assert(0 && "Error: Assertion failed -- bad hart index");
}
return hart;
}
template <typename URV>
typename PerfApi<URV>::HartType*
PerfApi<URV>::checkHartRaw(const char* caller, unsigned hartIx)
{
if (hartIx >= hartRawPtrs_.size()) [[unlikely]]
{
cerr << caller << ": Bad hart index: " << hartIx << '\n';
assert(0 && "Error: Assertion failed -- bad hart index");
return nullptr;
}
return hartRawPtrs_[hartIx];
}
template <typename URV>
std::shared_ptr<InstrPac>
PerfApi<URV>::checkTag(const char* caller, unsigned hartIx, uint64_t tag)
{
auto packetPtr = hartPacketMaps_[hartIx].findShared(tag);
if (packetPtr)
return packetPtr;
cerr << caller << ": Unknown tag (never fetched): " << tag << '\n';
assert(0 && "Error: Assertion failed -- unknown tag");
return nullptr;
}
template <typename URV>
InstrPac*
PerfApi<URV>::checkTagRaw(const char* caller, unsigned hartIx, uint64_t tag)
{
auto* packet = hartPacketMaps_[hartIx].find(tag);
if (packet)
return packet;
cerr << caller << ": Unknown tag (never fetched): " << tag << '\n';
assert(0 && "Error: Assertion failed -- unknown tag");
return nullptr;
}
template <typename URV>
bool
PerfApi<URV>::checkTime(const char* caller, uint64_t time)
{
if (time < time_)
{
cerr << caller << ": Bad time: " << time << '\n';
assert(0 && "Error: Assertion failed -- bad time value");
return false;
}
time_ = time;
return true;
}
template <typename URV>
bool
PerfApi<URV>::fetch(unsigned hartIx, uint64_t time, uint64_t tag, uint64_t vpc,
bool& trap, ExceptionCause& cause, uint64_t& trapPc)
{
if (commandLog_) [[unlikely]]
fprintf(commandLog_, "hart=%" PRIu32 " time=%" PRIu64 " perf_model_fetch %" PRIu64 " 0x%" PRIx64 "\n",
hartIx, time, tag, vpc);
auto* hart = checkHartRaw("Fetch", hartIx);
if (not hart) [[unlikely]]
return false;
if (not checkTime("Fetch", time)) [[unlikely]]
return false;
if (tag == 0) [[unlikely]]
{
cerr << "Error: PerfApi::fetch: Hart-ix=" << hartIx << " tag=" << tag
<< " zero tag is reserved.\n";
assert(0 && "Error: Assertion failed -- zero tag");
return false;
}
auto& packetMap = hartPacketMaps_[hartIx];
if (packetMap.wouldBeOutOfOrder(tag)) [[unlikely]]
{
cerr << "Error: PerfApi::fetch: Hart-ix=" << hartIx << "tag=" << tag
<< " tag is not in increasing order.\n";
assert(0 && "Error: Assertion failed -- tag out of order");
return false;
}
auto* existingPacket = getInstructionPacketRaw(hartIx, tag);
if (existingPacket) [[unlikely]]
{
cerr << "Error: PerfApi::fetch: Hart-ix=" << hartIx << "tag=" << tag
<< " tag is already fetched.\n";
return false; // Tag already fetched.
}
auto prev = this->prevFetch_;
if (prev and not prev->predicted() and not prev->trapped() and not prev->executed())
{
bool sequential = prev->instrVa() + prev->decodedInst().instSize() == vpc;
if (not prev->decodedInst().isBranch())
{
if (not sequential)
prev->predictBranch(true, vpc);
}
else
{
if (sequential)
prev->predictBranch(false, vpc);
}
}
uint64_t ppc = 0, ppc2 = 0; // Physical pc.
uint32_t opcode = 0;
uint64_t gpc = 0; // Guest physical pc.
cause = hart->fetchInstNoTrap(vpc, ppc, ppc2, gpc, opcode); // hart is now raw pointer
auto packet = std::make_shared<InstrPac>(tag, vpc, ppc, ppc2);
assert(packet);
packet->fetched_ = true;
packet->opcode_= opcode;
insertPacket(hartIx, tag, packet);
if (not decode(hartIx, time, tag))
assert(0 && "Error: Assertion failed -- failed to decode");
prevFetch_ = packet;
trap = cause != ExceptionCause::NONE;
packet->trap_ = trap;
packet->trapCause_ = uint64_t(cause);
if (prev and not prev->trapped() and prev->executed() and prev->nextIva_ != vpc)
{
packet->shouldFlush_ = true;
packet->flushVa_ = prev->nextIva_;
}
if (trap)
{
prevFetch_ = nullptr;
trapPc = 0;
}
return true;
}
template <typename URV>
bool
PerfApi<URV>::decode(unsigned hartIx, uint64_t time, uint64_t tag)
{
if (commandLog_) [[unlikely]]
fprintf(commandLog_, "hart=%" PRIu32 " time=%" PRIu64 " perf_model_decode %" PRIu64 "\n",
hartIx, time, tag);
if (not checkTime("Decode", time)) [[unlikely]]
return false;
auto* hartPtr = checkHartRaw("Decode", hartIx);
if (not hartPtr) [[unlikely]]
return false;
auto& hart = *hartPtr;
const auto packetSharedPtr = hartPacketMaps_[hartIx].findShared(tag);
if (not packetSharedPtr) [[unlikely]]
{
cerr << "Decode: Unknown tag (never fetched): " << tag << '\n';
assert(0 && "Error: Assertion failed -- unknown tag");
return false;
}
auto& packet = *packetSharedPtr;
if (packet.decoded())
return true;
hart.decode(packet.instrVa(), packet.instrPa(), packet.opcode_, packet.di_);
packet.decoded_ = true;
using OM = WdRiscv::OperandMode;
using OT = WdRiscv::OperandType;
determineExplicitOperands(packet);
// Determine effective group multiplier of vector operands. We do this before adding
// explicit operands as we may be producing vtype which affects LMUL.
if (packet.di_.isVector())
getVectorOperandsLmul(hart, packet);
determineImplicitOperands(packet);
// Collect producers of operands of this instruction.
auto& producers = hartRegProducers_[hartIx];
// NOLINTBEGIN(cppcoreguidelines-pro-bounds-constant-array-index)
const unsigned operandCount = packet.operandCount_;
for (unsigned i = 0; i < operandCount; ++i)
{
auto& op = packet.operands_[i];
auto mode = op.mode;
auto type = op.type;
if (type == OT::Imm)
continue;
assert(type != OT::None and mode != OM::None);
if (mode == OM::None)
continue;
unsigned regNum = op.number;
unsigned gri = globalRegIx(type, regNum);
if (type != OT::VecReg)
packet.opProducers_[i].scalar = producers[gri];
else
{
auto lmul = op.lmul;
assert(lmul != 0 and lmul <= maxEffLmul_);
auto& vec = packet.opProducers_[i].vec;
vec.reserve(lmul);
for (unsigned n = 0; n < lmul; ++n)
{
unsigned vgri = gri + n;
vec.push_back(producers[vgri]);
}
}
}
// Mark this instruction as the producer of each of its destination registers.
for (unsigned i = 0; i < operandCount; ++i)
{
auto& op = packet.operands_[i];
auto mode = op.mode;
if (mode == OM::Write or mode == OM::ReadWrite)
{
unsigned regNum = op.number;
auto type = op.type;
unsigned gri = globalRegIx(type, regNum);
if (regNum == 0 and type == OT::IntReg)
continue; // Reg X0 has no producer
if (type != OT::VecReg)
producers[gri] = packetSharedPtr;
else
{
auto lmul = op.lmul;
assert(lmul <= maxEffLmul_);
for (unsigned n = 0; n < lmul; ++n)
{
unsigned vgri = gri + n;
producers[vgri] = packetSharedPtr;
}
}
}
}
// NOLINTEND(cppcoreguidelines-pro-bounds-constant-array-index)
return true;
}
template <typename URV>
std::vector<typename PerfApi<URV>::CsrFwdSave>
PerfApi<URV>::pushSpecCsrContext(HartType& hart, unsigned hartIx, uint64_t tag,
const InstrPac* packet)
{
std::vector<CsrFwdSave> saves;
const auto& specCsrs = hartSpecCsrs_.at(hartIx);
if (specCsrs.empty())
return saves;
auto isPacketOperand = [packet](unsigned csrNum) {
if (not packet)
return false;
for (unsigned i = 0; i < packet->operandCount_; ++i)
{
const auto& op = packet->operands_[i]; // NOLINT(cppcoreguidelines-pro-bounds-constant-array-index)
if (op.type == OperandType::CsReg and op.number == csrNum)
return true;
}
return false;
};
saves.reserve(specCsrs.size());
for (const auto& entry : specCsrs)
{
if (entry.tag >= tag) continue; // forward only OLDER in-flight writes
if (isPacketOperand(entry.csrNum)) continue; // owned by set/restoreHartValues
if (isNonForwardableCsr(entry.csrNum)) continue; // FP/vector-format CSRs: see isNonForwardableCsr
URV prev{};
bool ok = hart.peekCsr(CSRN(entry.csrNum), prev);
saves.push_back({entry.csrNum, prev, ok});
if (ok) hart.pokeCsr(CSRN(entry.csrNum), URV(entry.newVal));
}
return saves;
}
template <typename URV>
void
PerfApi<URV>::popSpecCsrContext(HartType& hart, const std::vector<CsrFwdSave>& saves)
{
for (auto it = saves.rbegin(); it != saves.rend(); ++it)
if (it->ok)
hart.pokeCsr(CSRN(it->csrNum), it->prev);
}
template <typename URV>
bool
PerfApi<URV>::execute(unsigned hartIx, uint64_t time, uint64_t tag)
{
if (commandLog_) [[unlikely]]
fprintf(commandLog_, "hart=%" PRIu32 " time=%" PRIu64 " perf_model_execute %" PRIu64 "\n",
hartIx, time, tag);
if (not checkTime("Execute", time)) [[unlikely]]
return false;
auto* hartPtr = checkHartRaw("Execute", hartIx);
if (not hartPtr) [[unlikely]]
return false;
auto& hart = *hartPtr;
// Use findPacket to get both raw pointer and iterator, avoiding redundant lookups
auto lookupResult = findPacket(hartIx, tag);
if (not lookupResult) [[unlikely]]
{
cerr << "execute: Unknown tag (never fetched): " << tag << '\n';
assert(0 && "Error: Assertion failed -- unknown tag");
return false;
}
auto* pacPtr = lookupResult.packet;
auto& packet = *pacPtr;
const auto& di = packet.decodedInst();
#if 0
if (di.isLr())
return true; // LR is executed and retired at PerApi::retire.
#endif
auto& packetMap = hartPacketMaps_[hartIx];
if (packet.executed()) [[unlikely]]
{
// Instruction is being re-executed. Must be load/store. Every instruction that
// depends on it must be re-executed.
if (not di.isLoad() and not di.isStore())
assert(0 && "Error: Assertion failed -- re-executed instruction is not ld/store");
// Iterate over packets starting from current tag
for (auto iter = packetMap.iteratorAt(tag); iter != packetMap.end(); ++iter)
{
auto* succ = iter.packet();
if (succ->dependsOn(packet))
succ->executed_ = false;
}
}
// Indirect-CSR (AIA/Smcsrind) context pre-forwarding. MIREG*/SIREG*/VSIREG* alias whichever
// register their addressing context (the paired *ISELECT, plus hstatus.VGEIN for VSIREG*)
// selects. execute() forwards older in-flight CSR writes, but only after collectOperandValues()
// and its operand save -- too late for a window operand, which then resolves under a stale
// context and trips the save/set assert. So when an indirect window is accessed, forward the
// older-spec-CSR context now across both calls and undo it afterwards; other instructions are
// unaffected.
bool hasIndirectWindow = std::ranges::any_of(packet.operands_ | std::views::take(packet.operandCount_),
[](const auto& op) {
return op.type == OperandType::CsReg and isIndirectCsrWindow(op.number);
});
SpecCsrContext ctxFwds(hart, hasIndirectWindow
? pushSpecCsrContext(hart, hartIx, packet.tag_, &packet)
: std::vector<CsrFwdSave>{});
// Collect register operand values. Some values come from in-flight instructions
// (register renaming).
bool peekOk = collectOperandValues(hart, packet);
// Execute the instruction: Poke source register values, execute, recover destination
// register values.
if (not execute(hartIx, packet))
assert(0 && "Error: Assertion failed -- failed to execute instruction");
ctxFwds.pop();
// We should not fail to read an operand value unless there is an exception.
if (not peekOk)
assert(packet.trap_);
packet.executed_ = true;
packet.execTime_ = time;
if (packet.predicted_)
packet.mispredicted_ = packet.prTarget_ != packet.nextIva_;
if (packet.isBranch())
{
// Check if the next instruction in program order is at the right PC.
auto* nextPacket = packetMap.find(tag + 1);
if (nextPacket)
{
auto& next = *nextPacket;
if (next.iva_ != packet.nextIva_)
{
next.shouldFlush_ = true;
next.flushVa_ = packet.nextIva_;
}
if (next.executed_)
{
packet.shouldFlush_ = true;
packet.flushVa_ = packet.iva_;
}
}
}
return true;
}
template <typename URV>
bool
PerfApi<URV>::execute(unsigned hartIx, InstrPac& packet)
{
assert(packet.decoded());
auto* hartPtr = getHartRaw(hartIx);
assert(hartPtr);
auto& hart = *hartPtr;
uint64_t prevPc = hart.peekPc();
uint64_t prevInstrCount = hart.getInstructionCount();
hart.pokePc(packet.instrVa());
hart.setInstructionCount(packet.tag_ - 1);
// FIX: handle MSTATUSH
URV prevMstatus = 0;
if (not hart.peekCsr(CSRN::MSTATUS, prevMstatus))
assert(0 && "Error: Assertion failed");
// Architectural operand values; must precede the spec-CSR overlay.
std::array<OpVal, 9> prevVal;
bool saveOk = saveHartValues(hart, packet, prevVal);
// Before setHartValues: pokeCsr ignores VTYPE/VL/VSTART while VS is Off.
SpecCsrContext csrFwdSaves(hart, pushSpecCsrContext(hart, hartIx, packet.tag_, &packet));
// Install packet operand values (some obtained from previous in-flight instructions)
// into the hart registers.
bool setOk = setHartValues(hart, packet);
assert(hartLastRetired_[hartIx] == initHartLastRetired or packet.tag_ > hartLastRetired_[hartIx]);
// Only make the time adjustment when the hart has retired at least one instruction.
if (hartLastRetired_[hartIx] != initHartLastRetired)
{
auto itag = std::bit_cast<int64_t>(packet.tag_);
auto ilast = std::bit_cast<int64_t>(hartLastRetired_[hartIx]);
assert(itag >= 0 and ilast >= 0); // Check overflow
hart.adjustTime(itag - ilast - 1);
}
const auto& di = packet.decodedInst();
unsigned imsicId = 0, imsicGuest = 0;
if (di.isCsr())
saveImsicTopei(hart, CSRN(di.ithOperand(2)), imsicId, imsicGuest);
packet.privMode_ = hart.privilegeMode();
packet.virtMode_ = hart.virtMode();
// Save current reservation state before executing an LR so we can restore it after.
if (di.isLr())
packet.hadPriorLr_ = hart.getLr(packet.savedLrAddr_, packet.savedLrSize_);
// Before speculative SC execution, set the reservation from the paired LR (which may
// differ from what is currently in Memory due to other speculative LR executions).
uint64_t scPrevLrAddr = 0;
unsigned scPrevLrSize = 0;
bool scHadPrevLr = false;
if (di.isSc())
{
scHadPrevLr = hart.getLr(scPrevLrAddr, scPrevLrSize);
auto& specLrs = hartSpecLrs_[hartIx];
for (auto it = specLrs.rbegin(); it != specLrs.rend(); ++it)
if (it->tag < packet.tag_)
{
hart.makeLr(it->addr, it->size);
break;
}
}
// Execute
uint64_t execPreLrAddr = 0; unsigned execPreLrSize = 0;
bool execPreHadLr = hart.getLr(execPreLrAddr, execPreLrSize);
skipIoLoad_ = true; // Load from IO space takes effect at retire.
hart.singleStep();
skipIoLoad_ = false;
bool trap = hart.lastInstructionTrapped();
packet.trap_ = trap;
packet.interrupt_ = hart.lastInstructionInterrupted();
// After speculative LR execution, save its reservation to the spec list and then undo
// the makeLr so that Memory always reflects the architectural (retired) reservation.
if (di.isLr() and not trap)
{
uint64_t lrAddr = 0;
unsigned lrSize = 0;
if (hart.getLr(lrAddr, lrSize))
hartSpecLrs_[hartIx].push_back({packet.tag_, lrAddr, lrSize});
if (packet.hadPriorLr_)
hart.makeLr(packet.savedLrAddr_, packet.savedLrSize_);
else
hart.cancelLr(WdRiscv::CancelLrCause::FLUSH);
}
// For non-LR/non-SC instructions, singleStep may still mutate the hart's LR
// reservation (notably Zwrs WRS.NTO, which clears the reservation as part of its
// architectural semantics). Without restoring, the speculative reservation clear
// leaks into architectural state and a subsequent SC retire spuriously fails.
// LR/SC already manage the reservation themselves via the blocks above.
if (not di.isLr() and not di.isSc()) {
if (execPreHadLr) hart.makeLr(execPreLrAddr, execPreLrSize);
else hart.cancelLr(WdRiscv::CancelLrCause::FLUSH);
}
// After speculative SC execution, capture the outcome on the packet so the timing
// model can dispatch a store-buffer entry with the predicted result, then restore
// the previous reservation state so Memory reflects only architectural (retired) state.
if (di.isSc())
{
if (not trap)
recordScOutcome(hart, packet);
if (scHadPrevLr)
hart.makeLr(scPrevLrAddr, scPrevLrSize);
else
hart.cancelLr(WdRiscv::CancelLrCause::FLUSH);
}
if (trap)
packet.trapCause_ = hart.lastTrapCause();
// If save fails or set fails, there must be a trap.
if (not saveOk or not setOk)
{
if (not trap)
cerr << "PerfApi::execute: save/set operands failed for instruction tag " << packet.tag_ << '\n';
assert(trap);
}
// Record PC of subsequent packet.
packet.nextIva_ = hart.peekPc();
recordExecutionResults(hart, packet);
// CSR-write speculative outcome capture. Snapshot rd and the new CSR value while
// the hart is still in the post-singleStep state (before restoreHartValues wipes
// the CSR back to its pre-execute value). peekCsr gives the post-execute CSR
// value; rd already lives in destValues_. Done unconditionally for every
// non-trapping CSR op; retire() reconciles it for writes, the model decides
// whether to demote the write via FNSR or rely on the speculation path.
if (di.isCsr() and not trap)
{
const unsigned csrNum = di.ithOperand(2);
packet.csrExecuted_ = true;
packet.csrNum_ = csrNum;
URV csrVal{};
if (hart.peekCsr(CSRN(csrNum), csrVal))
packet.csrExecNewVal_ = csrVal;
if (di.op0() != 0)
packet.csrExecRd_ = packet.destValues_.at(0).second.scalar;
}
// Undo changes to the hart.
if (hartLastRetired_[hartIx] != initHartLastRetired)
hart.adjustTime(-(int64_t)(packet.tag_ - hartLastRetired_[hartIx])); // Restore timer value.
else
hart.adjustTime(-1); // untick one cycle for the first instruction
// Restore CSRs modified by the instruction or trap. TODO: For vector ld/st we have to
// restore partially modified vectors.
if (di.isXRet() and not trap)
{ // For an MRET/SRET/... Privilege may have been lowered. Restore it before restoring CSRs.
hart.setVirtualMode(hart.lastVirtMode());
hart.setPrivilegeMode(hart.lastPrivMode());
}
// Restore CSR changes due to a trap or to mret/sret or to side effects from
// vector/fp instructions (MSTATUS.VS, MSTATUS.FS, FCSR, etc...).
static thread_local std::vector<CSRN> csrns;
csrns.clear();
hart.lastCsr(csrns);
for (auto csrn : csrns)
{
URV value = hart.lastCsrValue(csrn);
if (not hart.pokeCsr(csrn, value))
assert(0);
if (trap or di.isXRet())
recordChangedCsr(hart, packet, csrn);
}
if (trap)
{ // Privilege raised. Restore it after restoring CSRs.
hart.setVirtualMode(hart.lastVirtMode());
hart.setPrivilegeMode(hart.lastPrivMode());
}
// Restore hart registers that we changed before single step.
restoreHartValues(hart, packet, prevVal);
URV mstatus = 0;
if (not hart.peekCsr(CSRN::MSTATUS, mstatus))
assert(0 && "Error: Assertion failed");
if (mstatus != prevMstatus)
hart.pokeCsr(CSRN::MSTATUS, prevMstatus);
if (di.isCsr())
restoreImsicTopei(hart, CSRN(di.ithOperand(2)), imsicId, imsicGuest);
// Back to architectural CSR state for the rest of the recovery below.
csrFwdSaves.pop();
// If this instruction is a CSR *write* that captured a predicted outcome, push
// it onto hartSpecCsrs_ so younger speculative consumers see the forwarded
// value. Read-only CSR ops (csrrs/c with rs1=x0) don't modify the CSR — pushing
// them would forward an irrelevant value (e.g. the current TIME) and cause
// spurious CsrMispredict at retire. The CSR operand at index 2 is ReadWrite for
// writes (csrrw and csrrs/c with rs1!=0) and Read for read-only forms.
if (di.isCsr() and not trap and packet.csrExecuted_
and di.effectiveIthOperandMode(2) == WdRiscv::OperandMode::ReadWrite
and not isNonForwardableCsr(packet.csrNum_))
{
// Insert in tag order: pushSpecCsrContext pokes in list order and needs the youngest
// write to a CSR last, and execute is out of order, so appending is not enough.
auto& specCsrs = hartSpecCsrs_[hartIx];
auto pos = std::upper_bound(specCsrs.begin(), specCsrs.end(), packet.tag_,
[](uint64_t t, const SpecCsrEntry& e) { return t < e.tag; });
specCsrs.insert(pos, {packet.tag_, packet.csrNum_, packet.csrExecNewVal_});
}
hart.setTargetProgramFinished(false);
hart.pokePc(prevPc);
hart.setInstructionCount(prevInstrCount);
// Collect the page table walks only when tracing is enabled.
if (traceFiles_[hartIx])
{
packet.fetchWalks_ = hart.virtMem().getFetchWalks();
packet.dataWalks_ = hart.virtMem().getDataWalks();
}
hart.clearTraceData();
return true;
}
template <typename URV>
void
PerfApi<URV>::recordScOutcome(HartType& hart, InstrPac& packet)
{
uint64_t sva = 0, spa1 = 0, spa2 = 0, sval = 0;
unsigned ssize = hart.lastStore(sva, spa1, spa2, sval);
packet.scExecuted_ = true;
packet.scExecSuccess_ = (ssize != 0); // lastStore reports zero size for failed SC
if (packet.scExecSuccess_)
{
packet.scStoreVal_ = sval;
packet.scPa1_ = spa1;
packet.scPa2_ = spa2;
packet.scSize_ = ssize;
}
}
template <typename URV>
void
PerfApi<URV>::recordChangedCsr(HartType& hart, InstrPac& packet, CSRN csrn)
{
Operand op;
op.type = OperandType::CsReg;
op.mode = OperandMode::Write; // Arbitrary.
op.number = unsigned(csrn);
URV csrVal{};
if (not hart.peekCsr(csrn, csrVal))
assert(0);
op.value.scalar = csrVal;
packet.changedCsrs_.at(packet.changedCsrCount_++) = op;
}
template <typename URV>
bool
PerfApi<URV>::retire(unsigned hartIx, uint64_t time, uint64_t tag,
TT_PERF::RetireResult* status)
{
using TT_PERF::RetireResult;
// Helper to set status and return false
auto fail = [&](RetireResult result) {
if (status)
*status = result;
return false;
};
if (commandLog_) [[unlikely]]
fprintf(commandLog_, "hart=%" PRIu32 " time=%" PRIu64 " perf_model_retire %" PRIu64 "\n",
hartIx, time, tag);
if (not checkTime("Retire", time)) [[unlikely]]
return fail(RetireResult::InvalidTime);
auto* hartPtr = checkHartRaw("Retire", hartIx);
if (not hartPtr) [[unlikely]]
return fail(RetireResult::InvalidHart);
// Use findPacket to get both raw pointer and iterator for later erase
auto lookupResult = findPacket(hartIx, tag);
if (not lookupResult) [[unlikely]]
{
cerr << "Retire: Unknown tag (never fetched): " << tag << '\n';
return fail(RetireResult::UnknownTag);
}
auto* pacPtr = lookupResult.packet;
auto& packet = *pacPtr;
auto& hart = *hartPtr;
if (hartLastRetired_[hartIx] != initHartLastRetired and tag <= hartLastRetired_[hartIx])
{
cerr << "Error: Hart=" << hartIx << " time=" << time << " tag=" << tag
<< " Out of order retire\n";
return fail(RetireResult::OutOfOrder);
}
const auto prevLastRetired = hartLastRetired_[hartIx];
hartLastRetired_[hartIx] = tag;
if (packet.retired())
{
cerr << "Error: Hart=" << hartIx << " time=" << time << " tag=" << tag
<< " Tag retired more than once\n";
return fail(RetireResult::AlreadyRetired);
}
if (packet.instrVa() != hart.peekPc())
{
cerr << "Error: Hart=" << hartIx << " time=" << time << " tag=" << tag << std::hex
<< " Wrong pc at retire: 0x" << packet.instrVa() << " expecting 0x"
<< hart.peekPc() << '\n' << std::dec;
return fail(RetireResult::WrongPc);
}
// A packet never executed (a client that does not speculate) is executed by this step.
const bool execAtRetire = not packet.executed();
bool peekOk = true;
if (execAtRetire)
{
peekOk = collectOperandValues(hart, packet);
packet.privMode_ = hart.privilegeMode();
packet.virtMode_ = hart.virtMode();
}
hart.setInstructionCount(tag - 1);
auto* traceFile = traceFiles_[hartIx];
hart.singleStep(nullptr);
const auto& di = packet.decodedInst();
if (execAtRetire)
{
bool trap = hart.lastInstructionTrapped();
packet.trap_ = trap;
if (not peekOk)
assert(trap);
if (di.isSc() and not trap)
recordScOutcome(hart, packet);
packet.nextIva_ = hart.peekPc();
recordExecutionResults(hart, packet); // Before the CSR rd poke below reads destValues_.
if (trap or di.isXRet())
{
std::vector<CSRN> csrns;
hart.lastCsr(csrns);
for (auto csrn : csrns)
recordChangedCsr(hart, packet, csrn);
}
packet.executed_ = true;
packet.execTime_ = time;
if (packet.predicted_)
packet.mispredicted_ = packet.prTarget_ != packet.nextIva_;
}
// SC reconciliation: capture the retire-time outcome from singleStep and overwrite
// the packet's SC fields so drainStore commits the architectural data. On a
// mismatch with the execute-time prediction, raise ScMispredict so the timing
// model flushes younger packets and reconciles its store buffer.
bool scMispredict = false;
if (di.isSc() and packet.scExecuted_ and not packet.trap_)
{
uint64_t sva = 0, spa1 = 0, spa2 = 0, sval = 0;
unsigned retireSize = hart.lastStore(sva, spa1, spa2, sval);
bool retireSuccess = (retireSize != 0);
if (retireSuccess != packet.scExecSuccess_)
{
scMispredict = true;
packet.shouldFlush_ = true;
packet.flushVa_ = packet.nextIva_; // refetch from instruction after SC
}
packet.scExecSuccess_ = retireSuccess;
packet.scSize_ = retireSize; // zero on failure
if (retireSuccess)
{
packet.scStoreVal_ = sval;
packet.scPa1_ = spa1;
packet.scPa2_ = spa2;
}
}
using CN = WdRiscv::CsrNumber;
if (di.isCsr() and di.op0() != 0)
{
unsigned csrNum = di.op2();
// Hardware updates some CSRs on its own, so retire()'s re-read yields a different rd than
// execute() sampled. Force the execute-time value: both samples are architecturally valid
// (the read simply happened earlier), and a stale rd is otherwise invisible here --
// checkExecVsRetire() exempts CSR ops -- until it aborts the run on the first dependent
// non-CSR instruction. OpenSBI pmu_ctr_start_hw() reads mip and branches on LCOFIP two
// instructions later, tripping the compare on the intervening slli.
//
// Read forms only (csrrs/csrrc rs1=x0, csrrsi/csrrci imm=0): on a write the execute-time
// value is a prediction whose divergence is a real CsrMispredict, reconciled below.
// FFLAGS/FCSR (flags accumulate from other FP ops) and MCYCLE/TIME predate this and stay
// forced for every form.
//
// TODO(revisit): this makes the execute-time sample authoritative, a perf-api contract
// choice -- a client sampling these non-speculatively wants the retire-time value instead.
const bool readForm = di.effectiveIthOperandMode(2) != WdRiscv::OperandMode::ReadWrite;
if (csrNum == unsigned(CN::MCYCLE) or csrNum == unsigned(CN::TIME) or
csrNum == unsigned(CN::FFLAGS) or csrNum == unsigned(CN::FCSR) or
(readForm and isAsyncUpdatedCsr(csrNum)))
{
hart.pokeIntReg(di.op0(), URV(packet.destValues_.at(0).second.scalar));
}
}
// CSR reconciliation for writes: compare the retire-time CSR new value and rd
// against the execute-time capture; on divergence raise CsrMispredict so the
// model can flush younger packets. The captured fields are then overwritten with
// the retire-time values for any downstream consumer. Read-only forms (csrrs/c
// with rs1=x0; csrrsi/csrrci with imm=0) are skipped via effectiveIthOperandMode
// — they don't modify the CSR, so there's nothing to reconcile, and
// time-advancing CSRs like TIME/MCYCLE would otherwise trip the comparison
// spuriously.
bool csrMispredict = false;
if (di.isCsr() and packet.csrExecuted_ and not packet.trap_
and di.effectiveIthOperandMode(2) == WdRiscv::OperandMode::ReadWrite)
{
URV retireCsrVal{};
bool csrOk = hart.peekCsr(CSRN(packet.csrNum_), retireCsrVal);
uint64_t retireRd = 0;
if (di.op0() != 0)
retireRd = hart.peekIntReg(di.op0());
const bool csrValueDiverged = csrOk and (uint64_t(retireCsrVal) != packet.csrExecNewVal_);
const bool rdDiverged = (di.op0() != 0) and (retireRd != packet.csrExecRd_);
if (csrValueDiverged or rdDiverged)
{
csrMispredict = true;
packet.shouldFlush_ = true;
packet.flushVa_ = packet.nextIva_; // refetch from instruction after the CSR write
}
if (csrOk) packet.csrExecNewVal_ = retireCsrVal;
packet.csrExecRd_ = retireRd;