summaryrefslogtreecommitdiff
path: root/src/gpu-compute/wavefront.cc
blob: 42739a7b098328acff34967d5be0842720b324c2 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
/*
 * Copyright (c) 2011-2015 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * For use for simulation and test purposes only
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Author: Lisa Hsu
 */

#include "gpu-compute/wavefront.hh"

#include "debug/GPUExec.hh"
#include "debug/WavefrontStack.hh"
#include "gpu-compute/code_enums.hh"
#include "gpu-compute/compute_unit.hh"
#include "gpu-compute/gpu_dyn_inst.hh"
#include "gpu-compute/shader.hh"
#include "gpu-compute/vector_register_file.hh"

Wavefront*
WavefrontParams::create()
{
    return new Wavefront(this);
}

Wavefront::Wavefront(const Params *p)
  : SimObject(p), callArgMem(nullptr)
{
    lastTrace = 0;
    simdId = p->simdId;
    wfSlotId = p->wf_slot_id;
    status = S_STOPPED;
    reservedVectorRegs = 0;
    startVgprIndex = 0;
    outstandingReqs = 0;
    memReqsInPipe = 0;
    outstandingReqsWrGm = 0;
    outstandingReqsWrLm = 0;
    outstandingReqsRdGm = 0;
    outstandingReqsRdLm = 0;
    rdLmReqsInPipe = 0;
    rdGmReqsInPipe = 0;
    wrLmReqsInPipe = 0;
    wrGmReqsInPipe = 0;

    barrierCnt = 0;
    oldBarrierCnt = 0;
    stalledAtBarrier = false;

    memTraceBusy = 0;
    oldVgprTcnt = 0xffffffffffffffffll;
    oldDgprTcnt = 0xffffffffffffffffll;
    oldVgpr.resize(p->wfSize);

    pendingFetch = false;
    dropFetch = false;
    condRegState = new ConditionRegisterState();
    maxSpVgprs = 0;
    maxDpVgprs = 0;
    lastAddr.resize(p->wfSize);
    workItemFlatId.resize(p->wfSize);
    oldDgpr.resize(p->wfSize);
    barCnt.resize(p->wfSize);
    for (int i = 0; i < 3; ++i) {
        workItemId[i].resize(p->wfSize);
    }
}

void
Wavefront::regStats()
{
    SimObject::regStats();

    srcRegOpDist
        .init(0, 4, 2)
        .name(name() + ".src_reg_operand_dist")
        .desc("number of executed instructions with N source register operands")
        ;

    dstRegOpDist
        .init(0, 3, 2)
        .name(name() + ".dst_reg_operand_dist")
        .desc("number of executed instructions with N destination register "
              "operands")
        ;

    // FIXME: the name of the WF needs to be unique
    numTimesBlockedDueWAXDependencies
        .name(name() + ".timesBlockedDueWAXDependencies")
        .desc("number of times the wf's instructions are blocked due to WAW "
              "or WAR dependencies")
        ;

    // FIXME: the name of the WF needs to be unique
    numTimesBlockedDueRAWDependencies
        .name(name() + ".timesBlockedDueRAWDependencies")
        .desc("number of times the wf's instructions are blocked due to RAW "
              "dependencies")
        ;

    // FIXME: the name of the WF needs to be unique
    numTimesBlockedDueVrfPortAvail
        .name(name() + ".timesBlockedDueVrfPortAvail")
        .desc("number of times instructions are blocked due to VRF port "
              "availability")
        ;
}

void
Wavefront::init()
{
    reservedVectorRegs = 0;
    startVgprIndex = 0;
}

void
Wavefront::resizeRegFiles(int num_cregs, int num_sregs, int num_dregs)
{
    condRegState->init(num_cregs);
    maxSpVgprs = num_sregs;
    maxDpVgprs = num_dregs;
}

Wavefront::~Wavefront()
{
    if (callArgMem)
        delete callArgMem;
    delete condRegState;
}

void
Wavefront::start(uint64_t _wf_dyn_id,uint64_t _base_ptr)
{
    wfDynId = _wf_dyn_id;
    basePtr = _base_ptr;
    status = S_RUNNING;
}

bool
Wavefront::isGmInstruction(GPUDynInstPtr ii)
{
    if (IS_OT_READ_PM(ii->opType()) || IS_OT_WRITE_PM(ii->opType()) ||
        IS_OT_ATOMIC_PM(ii->opType())) {
        return true;
    }

    if (IS_OT_READ_GM(ii->opType()) || IS_OT_WRITE_GM(ii->opType()) ||
        IS_OT_ATOMIC_GM(ii->opType())) {
        return true;
    }

    if (IS_OT_FLAT(ii->opType())) {
        return true;
    }

    return false;
}

bool
Wavefront::isLmInstruction(GPUDynInstPtr ii)
{
    if (IS_OT_READ_LM(ii->opType()) || IS_OT_WRITE_LM(ii->opType()) ||
        IS_OT_ATOMIC_LM(ii->opType())) {
        return true;
    }

    return false;
}

bool
Wavefront::isOldestInstALU()
{
    assert(!instructionBuffer.empty());
    GPUDynInstPtr ii = instructionBuffer.front();

    if (status != S_STOPPED && (ii->opType() == Enums::OT_NOP ||
        ii->opType() == Enums::OT_RET || ii->opType() == Enums::OT_BRANCH ||
        ii->opType() == Enums::OT_ALU || IS_OT_LDAS(ii->opType()) ||
        ii->opType() == Enums::OT_KERN_READ)) {
        return true;
    }

    return false;
}

bool
Wavefront::isOldestInstBarrier()
{
    assert(!instructionBuffer.empty());
    GPUDynInstPtr ii = instructionBuffer.front();

    if (status != S_STOPPED && ii->opType() == Enums::OT_BARRIER) {
        return true;
    }

    return false;
}

bool
Wavefront::isOldestInstGMem()
{
    assert(!instructionBuffer.empty());
    GPUDynInstPtr ii = instructionBuffer.front();

    if (status != S_STOPPED && (IS_OT_READ_GM(ii->opType()) ||
        IS_OT_WRITE_GM(ii->opType()) || IS_OT_ATOMIC_GM(ii->opType()))) {

        return true;
    }

    return false;
}

bool
Wavefront::isOldestInstLMem()
{
    assert(!instructionBuffer.empty());
    GPUDynInstPtr ii = instructionBuffer.front();

    if (status != S_STOPPED && (IS_OT_READ_LM(ii->opType()) ||
        IS_OT_WRITE_LM(ii->opType()) || IS_OT_ATOMIC_LM(ii->opType()))) {

        return true;
    }

    return false;
}

bool
Wavefront::isOldestInstPrivMem()
{
    assert(!instructionBuffer.empty());
    GPUDynInstPtr ii = instructionBuffer.front();

    if (status != S_STOPPED && (IS_OT_READ_PM(ii->opType()) ||
        IS_OT_WRITE_PM(ii->opType()) || IS_OT_ATOMIC_PM(ii->opType()))) {

        return true;
    }

    return false;
}

bool
Wavefront::isOldestInstFlatMem()
{
    assert(!instructionBuffer.empty());
    GPUDynInstPtr ii = instructionBuffer.front();

    if (status != S_STOPPED && IS_OT_FLAT(ii->opType())) {

        return true;
    }

    return false;
}

// Return true if the Wavefront's instruction
// buffer has branch instruction.
bool
Wavefront::instructionBufferHasBranch()
{
    for (auto it : instructionBuffer) {
        GPUDynInstPtr ii = it;

        if (ii->opType() == Enums::OT_RET || ii->opType() == Enums::OT_BRANCH) {
            return true;
        }
    }

    return false;
}

// Remap HSAIL register to physical VGPR.
// HSAIL register = virtual register assigned to an operand by HLC compiler
uint32_t
Wavefront::remap(uint32_t vgprIndex, uint32_t size, uint8_t mode)
{
    assert((vgprIndex < reservedVectorRegs) && (reservedVectorRegs > 0));
    // add the offset from where the VGPRs of the wavefront have been assigned
    uint32_t physicalVgprIndex = startVgprIndex + vgprIndex;
    // HSAIL double precision (DP) register: calculate the physical VGPR index
    // assuming that DP registers are placed after SP ones in the VRF. The DP
    // and SP VGPR name spaces in HSAIL mode are separate so we need to adjust
    // the DP VGPR index before mapping it to the physical VRF address space
    if (mode == 1 && size > 4) {
        physicalVgprIndex = startVgprIndex + maxSpVgprs + (2 * vgprIndex);
    }

    assert((startVgprIndex <= physicalVgprIndex) &&
           (startVgprIndex + reservedVectorRegs - 1) >= physicalVgprIndex);

    // calculate absolute physical VGPR index
    return physicalVgprIndex % computeUnit->vrf[simdId]->numRegs();
}

// Return true if this wavefront is ready
// to execute an instruction of the specified type.
int
Wavefront::ready(itype_e type)
{
    // Check to make sure wave is running
    if (status == S_STOPPED || status == S_RETURNING ||
        instructionBuffer.empty()) {
        return 0;
    }

    // Is the wave waiting at a barrier
    if (stalledAtBarrier) {
        if (!computeUnit->AllAtBarrier(barrierId,barrierCnt,
                        computeUnit->getRefCounter(dispatchId, wgId))) {
            // Are all threads at barrier?
            return 0;
        }
        oldBarrierCnt = barrierCnt;
        stalledAtBarrier = false;
    }

    // Read instruction
    GPUDynInstPtr ii = instructionBuffer.front();

    bool ready_inst M5_VAR_USED = false;
    bool glbMemBusRdy = false;
    bool glbMemIssueRdy = false;
    if (type == I_GLOBAL || type == I_FLAT || type == I_PRIVATE) {
        for (int j=0; j < computeUnit->numGlbMemUnits; ++j) {
            if (computeUnit->vrfToGlobalMemPipeBus[j].prerdy())
                glbMemBusRdy = true;
            if (computeUnit->wfWait[j].prerdy())
                glbMemIssueRdy = true;
        }
    }
    bool locMemBusRdy = false;
    bool locMemIssueRdy = false;
    if (type == I_SHARED || type == I_FLAT) {
        for (int j=0; j < computeUnit->numLocMemUnits; ++j) {
            if (computeUnit->vrfToLocalMemPipeBus[j].prerdy())
                locMemBusRdy = true;
            if (computeUnit->wfWait[j].prerdy())
                locMemIssueRdy = true;
        }
    }

    // The following code is very error prone and the entire process for
    // checking readiness will be fixed eventually.  In the meantime, let's
    // make sure that we do not silently let an instruction type slip
    // through this logic and always return not ready.
    if (!(ii->opType() == Enums::OT_BARRIER || ii->opType() == Enums::OT_NOP ||
          ii->opType() == Enums::OT_RET || ii->opType() == Enums::OT_BRANCH ||
          ii->opType() == Enums::OT_ALU || IS_OT_LDAS(ii->opType()) ||
          ii->opType() == Enums::OT_KERN_READ ||
          ii->opType() == Enums::OT_ARG ||
          IS_OT_READ_GM(ii->opType()) || IS_OT_WRITE_GM(ii->opType()) ||
          IS_OT_ATOMIC_GM(ii->opType()) || IS_OT_READ_LM(ii->opType()) ||
          IS_OT_WRITE_LM(ii->opType()) || IS_OT_ATOMIC_LM(ii->opType()) ||
          IS_OT_READ_PM(ii->opType()) || IS_OT_WRITE_PM(ii->opType()) ||
          IS_OT_ATOMIC_PM(ii->opType()) || IS_OT_FLAT(ii->opType()))) {
        panic("next instruction: %s is of unknown type\n", ii->disassemble());
    }

    DPRINTF(GPUExec, "CU%d: WF[%d][%d]: Checking Read for Inst : %s\n",
            computeUnit->cu_id, simdId, wfSlotId, ii->disassemble());

    if (type == I_ALU && ii->opType() == Enums::OT_BARRIER) {
        // Here for ALU instruction (barrier)
        if (!computeUnit->wfWait[simdId].prerdy()) {
            // Is wave slot free?
            return 0;
        }

        // Are there in pipe or outstanding memory requests?
        if ((outstandingReqs + memReqsInPipe) > 0) {
            return 0;
        }

        ready_inst = true;
    } else if (type == I_ALU && ii->opType() == Enums::OT_NOP) {
        // Here for ALU instruction (nop)
        if (!computeUnit->wfWait[simdId].prerdy()) {
            // Is wave slot free?
            return 0;
        }

        ready_inst = true;
    } else if (type == I_ALU && ii->opType() == Enums::OT_RET) {
        // Here for ALU instruction (return)
        if (!computeUnit->wfWait[simdId].prerdy()) {
            // Is wave slot free?
            return 0;
        }

        // Are there in pipe or outstanding memory requests?
        if ((outstandingReqs + memReqsInPipe) > 0) {
            return 0;
        }

        ready_inst = true;
    } else if (type == I_ALU && (ii->opType() == Enums::OT_BRANCH ||
               ii->opType() == Enums::OT_ALU || IS_OT_LDAS(ii->opType()) ||
               ii->opType() == Enums::OT_KERN_READ ||
               ii->opType() == Enums::OT_ARG)) {
        // Here for ALU instruction (all others)
        if (!computeUnit->wfWait[simdId].prerdy()) {
            // Is alu slot free?
            return 0;
        }
        if (!computeUnit->vrf[simdId]->vrfOperandAccessReady(this, ii,
                    VrfAccessType::RD_WR)) {
            return 0;
        }

        if (!computeUnit->vrf[simdId]->operandsReady(this, ii)) {
            return 0;
        }
        ready_inst = true;
    } else if (type == I_GLOBAL && (IS_OT_READ_GM(ii->opType()) ||
               IS_OT_WRITE_GM(ii->opType()) || IS_OT_ATOMIC_GM(ii->opType()))) {
        // Here Global memory instruction
        if (IS_OT_READ_GM(ii->opType()) || IS_OT_ATOMIC_GM(ii->opType())) {
            // Are there in pipe or outstanding global memory write requests?
            if ((outstandingReqsWrGm + wrGmReqsInPipe) > 0) {
                return 0;
            }
        }

        if (IS_OT_WRITE_GM(ii->opType()) || IS_OT_ATOMIC_GM(ii->opType()) ||
            IS_OT_HIST_GM(ii->opType())) {
            // Are there in pipe or outstanding global memory read requests?
            if ((outstandingReqsRdGm + rdGmReqsInPipe) > 0)
                return 0;
        }

        if (!glbMemIssueRdy) {
            // Is WV issue slot free?
            return 0;
        }

        if (!glbMemBusRdy) {
            // Is there an available VRF->Global memory read bus?
            return 0;
        }

        if (!computeUnit->globalMemoryPipe.
            isGMReqFIFOWrRdy(rdGmReqsInPipe + wrGmReqsInPipe)) {
            // Can we insert a new request to the Global Mem Request FIFO?
            return 0;
        }
        // can we schedule source & destination operands on the VRF?
        if (!computeUnit->vrf[simdId]->vrfOperandAccessReady(this, ii,
                    VrfAccessType::RD_WR)) {
            return 0;
        }
        if (!computeUnit->vrf[simdId]->operandsReady(this, ii)) {
            return 0;
        }
        ready_inst = true;
    } else if (type == I_SHARED && (IS_OT_READ_LM(ii->opType()) ||
               IS_OT_WRITE_LM(ii->opType()) || IS_OT_ATOMIC_LM(ii->opType()))) {
        // Here for Shared memory instruction
        if (IS_OT_READ_LM(ii->opType()) || IS_OT_ATOMIC_LM(ii->opType())) {
            if ((outstandingReqsWrLm + wrLmReqsInPipe) > 0) {
                return 0;
            }
        }

        if (IS_OT_WRITE_LM(ii->opType()) || IS_OT_ATOMIC_LM(ii->opType()) ||
            IS_OT_HIST_LM(ii->opType())) {
            if ((outstandingReqsRdLm + rdLmReqsInPipe) > 0) {
                return 0;
            }
        }

        if (!locMemBusRdy) {
            // Is there an available VRF->LDS read bus?
            return 0;
        }
        if (!locMemIssueRdy) {
            // Is wave slot free?
            return 0;
        }

        if (!computeUnit->localMemoryPipe.
            isLMReqFIFOWrRdy(rdLmReqsInPipe + wrLmReqsInPipe)) {
            // Can we insert a new request to the LDS Request FIFO?
            return 0;
        }
        // can we schedule source & destination operands on the VRF?
        if (!computeUnit->vrf[simdId]->vrfOperandAccessReady(this, ii,
                    VrfAccessType::RD_WR)) {
            return 0;
        }
        if (!computeUnit->vrf[simdId]->operandsReady(this, ii)) {
            return 0;
        }
        ready_inst = true;
    } else if (type == I_PRIVATE && (IS_OT_READ_PM(ii->opType()) ||
               IS_OT_WRITE_PM(ii->opType()) || IS_OT_ATOMIC_PM(ii->opType()))) {
        // Here for Private memory instruction ------------------------    //
        if (IS_OT_READ_PM(ii->opType()) || IS_OT_ATOMIC_PM(ii->opType())) {
            if ((outstandingReqsWrGm + wrGmReqsInPipe) > 0) {
                return 0;
            }
        }

        if (IS_OT_WRITE_PM(ii->opType()) || IS_OT_ATOMIC_PM(ii->opType()) ||
            IS_OT_HIST_PM(ii->opType())) {
            if ((outstandingReqsRdGm + rdGmReqsInPipe) > 0) {
                return 0;
            }
        }

        if (!glbMemBusRdy) {
            // Is there an available VRF->Global memory read bus?
            return 0;
        }

        if (!glbMemIssueRdy) {
             // Is wave slot free?
            return 0;
        }

        if (!computeUnit->globalMemoryPipe.
            isGMReqFIFOWrRdy(rdGmReqsInPipe + wrGmReqsInPipe)) {
            // Can we insert a new request to the Global Mem Request FIFO?
            return 0;
        }
        // can we schedule source & destination operands on the VRF?
        if (!computeUnit->vrf[simdId]->vrfOperandAccessReady(this, ii,
                    VrfAccessType::RD_WR)) {
            return 0;
        }
        if (!computeUnit->vrf[simdId]->operandsReady(this, ii)) {
            return 0;
        }
        ready_inst = true;
    } else if (type == I_FLAT && IS_OT_FLAT(ii->opType())) {
        if (!glbMemBusRdy) {
            // Is there an available VRF->Global memory read bus?
            return 0;
        }

        if (!locMemBusRdy) {
            // Is there an available VRF->LDS read bus?
            return 0;
        }

        if (!glbMemIssueRdy) {
            // Is wave slot free?
            return 0;
        }

        if (!locMemIssueRdy) {
            return 0;
        }
        if (!computeUnit->globalMemoryPipe.
            isGMReqFIFOWrRdy(rdGmReqsInPipe + wrGmReqsInPipe)) {
            // Can we insert a new request to the Global Mem Request FIFO?
            return 0;
        }

        if (!computeUnit->localMemoryPipe.
            isLMReqFIFOWrRdy(rdLmReqsInPipe + wrLmReqsInPipe)) {
            // Can we insert a new request to the LDS Request FIFO?
            return 0;
        }
        // can we schedule source & destination operands on the VRF?
        if (!computeUnit->vrf[simdId]->vrfOperandAccessReady(this, ii,
                    VrfAccessType::RD_WR)) {
            return 0;
        }
        // are all the operands ready? (RAW, WAW and WAR depedencies met?)
        if (!computeUnit->vrf[simdId]->operandsReady(this, ii)) {
            return 0;
        }
        ready_inst = true;
    } else {
        return 0;
    }

    assert(ready_inst);

    DPRINTF(GPUExec, "CU%d: WF[%d][%d]: Ready Inst : %s\n", computeUnit->cu_id,
            simdId, wfSlotId, ii->disassemble());
    return 1;
}

void
Wavefront::updateResources()
{
    // Get current instruction
    GPUDynInstPtr ii = instructionBuffer.front();
    assert(ii);
    computeUnit->vrf[simdId]->updateResources(this, ii);
    // Single precision ALU or Branch or Return or Special instruction
    if (ii->opType() == Enums::OT_ALU || ii->opType() == Enums::OT_SPECIAL ||
        ii->opType() == Enums::OT_BRANCH || IS_OT_LDAS(ii->opType()) ||
        // FIXME: Kernel argument loads are currently treated as ALU operations
        // since we don't send memory packets at execution. If we fix that then
        // we should map them to one of the memory pipelines
        ii->opType()==Enums::OT_KERN_READ ||
        ii->opType()==Enums::OT_ARG ||
        ii->opType()==Enums::OT_RET) {
        computeUnit->aluPipe[simdId].preset(computeUnit->shader->
                                            ticks(computeUnit->spBypassLength()));
        // this is to enforce a fixed number of cycles per issue slot per SIMD
        computeUnit->wfWait[simdId].preset(computeUnit->shader->
                                           ticks(computeUnit->issuePeriod));
    } else if (ii->opType() == Enums::OT_BARRIER) {
        computeUnit->wfWait[simdId].preset(computeUnit->shader->
                                           ticks(computeUnit->issuePeriod));
    } else if (ii->opType() == Enums::OT_FLAT_READ) {
        assert(Enums::SC_NONE != ii->executedAs());
        memReqsInPipe++;
        rdGmReqsInPipe++;
        if ( Enums::SC_SHARED == ii->executedAs() ) {
            computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
                preset(computeUnit->shader->ticks(4));
            computeUnit->wfWait[computeUnit->ShrMemUnitId()].
                preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
        } else {
            computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
                preset(computeUnit->shader->ticks(4));
            computeUnit->wfWait[computeUnit->GlbMemUnitId()].
                preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
        }
    } else if (ii->opType() == Enums::OT_FLAT_WRITE) {
        assert(Enums::SC_NONE != ii->executedAs());
        memReqsInPipe++;
        wrGmReqsInPipe++;
        if (Enums::SC_SHARED == ii->executedAs()) {
            computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
                preset(computeUnit->shader->ticks(8));
            computeUnit->wfWait[computeUnit->ShrMemUnitId()].
                preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
        } else {
            computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
                preset(computeUnit->shader->ticks(8));
            computeUnit->wfWait[computeUnit->GlbMemUnitId()].
                preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
        }
    } else if (IS_OT_READ_GM(ii->opType())) {
        memReqsInPipe++;
        rdGmReqsInPipe++;
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            preset(computeUnit->shader->ticks(4));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_WRITE_GM(ii->opType())) {
        memReqsInPipe++;
        wrGmReqsInPipe++;
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            preset(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_ATOMIC_GM(ii->opType())) {
        memReqsInPipe++;
        wrGmReqsInPipe++;
        rdGmReqsInPipe++;
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            preset(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_READ_LM(ii->opType())) {
        memReqsInPipe++;
        rdLmReqsInPipe++;
        computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
            preset(computeUnit->shader->ticks(4));
        computeUnit->wfWait[computeUnit->ShrMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_WRITE_LM(ii->opType())) {
        memReqsInPipe++;
        wrLmReqsInPipe++;
        computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
            preset(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->ShrMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_ATOMIC_LM(ii->opType())) {
        memReqsInPipe++;
        wrLmReqsInPipe++;
        rdLmReqsInPipe++;
        computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
            preset(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->ShrMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_READ_PM(ii->opType())) {
        memReqsInPipe++;
        rdGmReqsInPipe++;
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            preset(computeUnit->shader->ticks(4));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_WRITE_PM(ii->opType())) {
        memReqsInPipe++;
        wrGmReqsInPipe++;
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            preset(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_ATOMIC_PM(ii->opType())) {
        memReqsInPipe++;
        wrGmReqsInPipe++;
        rdGmReqsInPipe++;
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            preset(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            preset(computeUnit->shader->ticks(computeUnit->issuePeriod));
    }
}

void
Wavefront::exec()
{
    // ---- Exit if wavefront is inactive ----------------------------- //

    if (status == S_STOPPED || status == S_RETURNING ||
        instructionBuffer.empty()) {
        return;
    }

    // Get current instruction

    GPUDynInstPtr ii = instructionBuffer.front();

    const uint32_t old_pc = pc();
    DPRINTF(GPUExec, "CU%d: WF[%d][%d]: wave[%d] Executing inst: %s "
            "(pc: %i)\n", computeUnit->cu_id, simdId, wfSlotId, wfDynId,
            ii->disassemble(), old_pc);
    ii->execute();
    // access the VRF
    computeUnit->vrf[simdId]->exec(ii, this);
    srcRegOpDist.sample(ii->numSrcRegOperands());
    dstRegOpDist.sample(ii->numDstRegOperands());
    computeUnit->numInstrExecuted++;
    computeUnit->execRateDist.sample(computeUnit->totalCycles.value() -
                                     computeUnit->lastExecCycle[simdId]);
    computeUnit->lastExecCycle[simdId] = computeUnit->totalCycles.value();
    if (pc() == old_pc) {
        uint32_t new_pc = old_pc + 1;
        // PC not modified by instruction, proceed to next or pop frame
        pc(new_pc);
        if (new_pc == rpc()) {
            popFromReconvergenceStack();
            discardFetch();
        } else {
            instructionBuffer.pop_front();
        }
    }

    if (computeUnit->shader->hsail_mode==Shader::SIMT) {
        const int num_active_lanes = execMask().count();
        computeUnit->controlFlowDivergenceDist.sample(num_active_lanes);
        computeUnit->numVecOpsExecuted += num_active_lanes;
        if (isGmInstruction(ii)) {
            computeUnit->activeLanesPerGMemInstrDist.sample(num_active_lanes);
        } else if (isLmInstruction(ii)) {
            computeUnit->activeLanesPerLMemInstrDist.sample(num_active_lanes);
        }
    }

    // ---- Update Vector ALU pipeline and other resources ------------------ //
    // Single precision ALU or Branch or Return or Special instruction
    if (ii->opType() == Enums::OT_ALU || ii->opType() == Enums::OT_SPECIAL ||
        ii->opType() == Enums::OT_BRANCH || IS_OT_LDAS(ii->opType()) ||
        // FIXME: Kernel argument loads are currently treated as ALU operations
        // since we don't send memory packets at execution. If we fix that then
        // we should map them to one of the memory pipelines
        ii->opType() == Enums::OT_KERN_READ ||
        ii->opType() == Enums::OT_ARG ||
        ii->opType() == Enums::OT_RET) {
        computeUnit->aluPipe[simdId].set(computeUnit->shader->
                                         ticks(computeUnit->spBypassLength()));

        // this is to enforce a fixed number of cycles per issue slot per SIMD
        computeUnit->wfWait[simdId].set(computeUnit->shader->
                                        ticks(computeUnit->issuePeriod));
    } else if (ii->opType() == Enums::OT_BARRIER) {
        computeUnit->wfWait[simdId].set(computeUnit->shader->
                                        ticks(computeUnit->issuePeriod));
    } else if (ii->opType() == Enums::OT_FLAT_READ) {
        assert(Enums::SC_NONE != ii->executedAs());

        if (Enums::SC_SHARED == ii->executedAs()) {
            computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
                set(computeUnit->shader->ticks(4));
            computeUnit->wfWait[computeUnit->ShrMemUnitId()].
                set(computeUnit->shader->ticks(computeUnit->issuePeriod));
        } else {
            computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
                set(computeUnit->shader->ticks(4));
            computeUnit->wfWait[computeUnit->GlbMemUnitId()].
                set(computeUnit->shader->ticks(computeUnit->issuePeriod));
        }
    } else if (ii->opType() == Enums::OT_FLAT_WRITE) {
        assert(Enums::SC_NONE != ii->executedAs());
        if (Enums::SC_SHARED == ii->executedAs()) {
            computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
                set(computeUnit->shader->ticks(8));
            computeUnit->wfWait[computeUnit->ShrMemUnitId()].
                set(computeUnit->shader->ticks(computeUnit->issuePeriod));
        } else {
            computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
                set(computeUnit->shader->ticks(8));
            computeUnit->wfWait[computeUnit->GlbMemUnitId()].
                set(computeUnit->shader->ticks(computeUnit->issuePeriod));
        }
    } else if (IS_OT_READ_GM(ii->opType())) {
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            set(computeUnit->shader->ticks(4));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            set(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_WRITE_GM(ii->opType())) {
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            set(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            set(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_ATOMIC_GM(ii->opType())) {
        computeUnit->vrfToGlobalMemPipeBus[computeUnit->nextGlbRdBus()].
            set(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->GlbMemUnitId()].
            set(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_READ_LM(ii->opType())) {
        computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
            set(computeUnit->shader->ticks(4));
        computeUnit->wfWait[computeUnit->ShrMemUnitId()].
            set(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_WRITE_LM(ii->opType())) {
        computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
            set(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->ShrMemUnitId()].
            set(computeUnit->shader->ticks(computeUnit->issuePeriod));
    } else if (IS_OT_ATOMIC_LM(ii->opType())) {
        computeUnit->vrfToLocalMemPipeBus[computeUnit->nextLocRdBus()].
            set(computeUnit->shader->ticks(8));
        computeUnit->wfWait[computeUnit->ShrMemUnitId()].
            set(computeUnit->shader->ticks(computeUnit->issuePeriod));
    }
}

bool
Wavefront::waitingAtBarrier(int lane)
{
    return barCnt[lane] < maxBarCnt;
}

void
Wavefront::pushToReconvergenceStack(uint32_t pc, uint32_t rpc,
                                    const VectorMask& mask)
{
    assert(mask.count());
    reconvergenceStack.emplace_back(new ReconvergenceStackEntry{pc, rpc, mask});
}

void
Wavefront::popFromReconvergenceStack()
{
    assert(!reconvergenceStack.empty());

    DPRINTF(WavefrontStack, "[%2d, %2d, %2d, %2d] %s %3i => ",
            computeUnit->cu_id, simdId, wfSlotId, wfDynId,
            execMask().to_string<char, std::string::traits_type,
            std::string::allocator_type>().c_str(), pc());

    reconvergenceStack.pop_back();

    DPRINTF(WavefrontStack, "%3i %s\n", pc(),
            execMask().to_string<char, std::string::traits_type,
            std::string::allocator_type>().c_str());

}

void
Wavefront::discardFetch()
{
    instructionBuffer.clear();
    dropFetch |=pendingFetch;
}

uint32_t
Wavefront::pc() const
{
    return reconvergenceStack.back()->pc;
}

uint32_t
Wavefront::rpc() const
{
    return reconvergenceStack.back()->rpc;
}

VectorMask
Wavefront::execMask() const
{
    return reconvergenceStack.back()->execMask;
}

bool
Wavefront::execMask(int lane) const
{
    return reconvergenceStack.back()->execMask[lane];
}


void
Wavefront::pc(uint32_t new_pc)
{
    reconvergenceStack.back()->pc = new_pc;
}

uint32_t
Wavefront::getStaticContextSize() const
{
    return barCnt.size() * sizeof(int) + sizeof(wfId) + sizeof(maxBarCnt) +
           sizeof(oldBarrierCnt) + sizeof(barrierCnt) + sizeof(wgId) +
           sizeof(computeUnit->cu_id) + sizeof(barrierId) + sizeof(initMask) +
           sizeof(privBase) + sizeof(spillBase) + sizeof(ldsChunk) +
           computeUnit->wfSize() * sizeof(ReconvergenceStackEntry);
}

void
Wavefront::getContext(const void *out)
{
    uint8_t *iter = (uint8_t *)out;
    for (int i = 0; i < barCnt.size(); i++) {
        *(int *)iter = barCnt[i]; iter += sizeof(barCnt[i]);
    }
    *(int *)iter = wfId; iter += sizeof(wfId);
    *(int *)iter = maxBarCnt; iter += sizeof(maxBarCnt);
    *(int *)iter = oldBarrierCnt; iter += sizeof(oldBarrierCnt);
    *(int *)iter = barrierCnt; iter += sizeof(barrierCnt);
    *(int *)iter = computeUnit->cu_id; iter += sizeof(computeUnit->cu_id);
    *(uint32_t *)iter = wgId; iter += sizeof(wgId);
    *(uint32_t *)iter = barrierId; iter += sizeof(barrierId);
    *(uint64_t *)iter = initMask.to_ullong(); iter += sizeof(initMask.to_ullong());
    *(Addr *)iter = privBase; iter += sizeof(privBase);
    *(Addr *)iter = spillBase; iter += sizeof(spillBase);

    int stackSize = reconvergenceStack.size();
    ReconvergenceStackEntry empty = {std::numeric_limits<uint32_t>::max(),
                                    std::numeric_limits<uint32_t>::max(),
                                    std::numeric_limits<uint64_t>::max()};
    for (int i = 0; i < workItemId[0].size(); i++) {
        if (i < stackSize) {
            *(ReconvergenceStackEntry *)iter = *reconvergenceStack.back();
            iter += sizeof(ReconvergenceStackEntry);
            reconvergenceStack.pop_back();
        } else {
            *(ReconvergenceStackEntry *)iter = empty;
            iter += sizeof(ReconvergenceStackEntry);
        }
    }

    int wf_size = computeUnit->wfSize();
    for (int i = 0; i < maxSpVgprs; i++) {
        uint32_t vgprIdx = remap(i, sizeof(uint32_t), 1);
        for (int lane = 0; lane < wf_size; lane++) {
            uint32_t regVal = computeUnit->vrf[simdId]->
                            read<uint32_t>(vgprIdx,lane);
            *(uint32_t *)iter = regVal; iter += sizeof(regVal);
        }
    }

    for (int i = 0; i < maxDpVgprs; i++) {
        uint32_t vgprIdx = remap(i, sizeof(uint64_t), 1);
        for (int lane = 0; lane < wf_size; lane++) {
            uint64_t regVal = computeUnit->vrf[simdId]->
                            read<uint64_t>(vgprIdx,lane);
            *(uint64_t *)iter = regVal; iter += sizeof(regVal);
        }
    }

    for (int i = 0; i < condRegState->numRegs(); i++) {
        for (int lane = 0; lane < wf_size; lane++) {
            uint64_t regVal = condRegState->read<uint64_t>(i, lane);
            *(uint64_t *)iter = regVal; iter += sizeof(regVal);
        }
    }

    /* saving LDS content */
    if (ldsChunk)
        for (int i = 0; i < ldsChunk->size(); i++) {
            char val = ldsChunk->read<char>(i);
            *(char *) iter = val; iter += sizeof(val);
        }
}

void
Wavefront::setContext(const void *in)
{
    uint8_t *iter = (uint8_t *)in;
    for (int i = 0; i < barCnt.size(); i++) {
        barCnt[i] = *(int *)iter; iter += sizeof(barCnt[i]);
    }
    wfId = *(int *)iter; iter += sizeof(wfId);
    maxBarCnt = *(int *)iter; iter += sizeof(maxBarCnt);
    oldBarrierCnt = *(int *)iter; iter += sizeof(oldBarrierCnt);
    barrierCnt = *(int *)iter; iter += sizeof(barrierCnt);
    computeUnit->cu_id = *(int *)iter; iter += sizeof(computeUnit->cu_id);
    wgId = *(uint32_t *)iter; iter += sizeof(wgId);
    barrierId = *(uint32_t *)iter; iter += sizeof(barrierId);
    initMask = VectorMask(*(uint64_t *)iter); iter += sizeof(initMask);
    privBase = *(Addr *)iter; iter += sizeof(privBase);
    spillBase = *(Addr *)iter; iter += sizeof(spillBase);

    for (int i = 0; i < workItemId[0].size(); i++) {
        ReconvergenceStackEntry newEntry = *(ReconvergenceStackEntry *)iter;
        iter += sizeof(ReconvergenceStackEntry);
        if (newEntry.pc != std::numeric_limits<uint32_t>::max()) {
            pushToReconvergenceStack(newEntry.pc, newEntry.rpc,
                                     newEntry.execMask);
        }
    }
    int wf_size = computeUnit->wfSize();

    for (int i = 0; i < maxSpVgprs; i++) {
        uint32_t vgprIdx = remap(i, sizeof(uint32_t), 1);
        for (int lane = 0; lane < wf_size; lane++) {
            uint32_t regVal = *(uint32_t *)iter; iter += sizeof(regVal);
            computeUnit->vrf[simdId]->write<uint32_t>(vgprIdx, regVal, lane);
        }
    }

    for (int i = 0; i < maxDpVgprs; i++) {
        uint32_t vgprIdx = remap(i, sizeof(uint64_t), 1);
        for (int lane = 0; lane < wf_size; lane++) {
            uint64_t regVal = *(uint64_t *)iter; iter += sizeof(regVal);
            computeUnit->vrf[simdId]->write<uint64_t>(vgprIdx, regVal, lane);
        }
    }

    for (int i = 0; i < condRegState->numRegs(); i++) {
        for (int lane = 0; lane < wf_size; lane++) {
            uint64_t regVal = *(uint64_t *)iter; iter += sizeof(regVal);
            condRegState->write<uint64_t>(i, lane, regVal);
        }
    }
    /** Restoring LDS contents */
    if (ldsChunk)
        for (int i = 0; i < ldsChunk->size(); i++) {
            char val = *(char *) iter; iter += sizeof(val);
            ldsChunk->write<char>(i, val);
        }
}