File: IGCMetricImpl.cpp

package info (click to toggle)
intel-graphics-compiler2 2.16.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 106,644 kB
  • sloc: cpp: 805,640; lisp: 287,672; ansic: 16,414; python: 3,952; yacc: 2,588; lex: 1,666; pascal: 313; sh: 186; makefile: 35
file content (1401 lines) | stat: -rw-r--r-- 53,441 bytes parent folder | download
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
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
/*========================== begin_copyright_notice ============================

Copyright (C) 2021-2023 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include <algorithm>
#include <string>
#include <unordered_map>
#include <fstream>

#include <iomanip>
#include <common/igc_regkeys.hpp>
#include <Metrics/IGCMetricImpl.h>
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
#include <Metrics/IGCMetricsVer.h>
#endif

#include <Probe/Assertion.h>
#include <Compiler/CISACodeGen/ShaderCodeGen.hpp>
#include <DebugInfo/VISAModule.hpp>
#include <Compiler/DebugInfo/ScalarVISAModule.h>
#include <visaBuilder_interface.h>
#include <visa/Common_ISA.h>

#include "common/LLVMWarningsPush.hpp"
#include <llvm/IR/Instructions.h>
#include <llvm/Support/Path.h>
#include <llvm/IR/DebugInfo.h>
#include <llvmWrapper/ADT/Optional.h>
#include <optional>
#include <llvmWrapper/Support/TypeSize.h>
#include "common/LLVMWarningsPop.hpp"

// #define DEBUG_METRIC

namespace IGCMetrics {
IGCMetricImpl::IGCMetricImpl() {
  this->isEnabled = false;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  this->countInstInFunc = 0;
  this->pMetricData = nullptr;
#endif
}
IGCMetricImpl::~IGCMetricImpl() {
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  this->map_EmuCalls.clear();
  this->map_Func.clear();
  this->map_Loops.clear();
  if (this->pMetricData != nullptr) {
    free(this->pMetricData);
    this->pMetricData = nullptr;
  }
#endif
}
bool IGCMetricImpl::Enable() {
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  return isEnabled && IGC_GET_FLAG_VALUE(MetricsDumpEnable) > 0;
#else
  return false;
#endif
}

void IGCMetricImpl::Init(ShaderHash *Hash, bool isEnabled) {
  this->isEnabled = isEnabled;
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  std::stringstream ss;

  ss << std::hex << std::setfill('0') << std::setw(sizeof(Hash->asmHash) * CHAR_BIT / 4) << Hash->asmHash;

  oclProgram.set_hash(ss.str());
#endif
}

size_t IGCMetricImpl::getMetricDataSize() {
  if (!Enable())
    return 0;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  // pMetricData = [VerInfo|CollectedMetricsData....]
  return sizeof(int) + oclProgram.ByteSizeLong();
#else
  return 0;
#endif
}

const void *const IGCMetricImpl::getMetricData() {
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  return pMetricData;
#else
  return nullptr;
#endif
}

void IGCMetricImpl::OutputMetrics() {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED

  if (pMetricData == nullptr) {
    // pMetricData = [VerInfo|CollectedMetricsData....]
    pMetricData = malloc(getMetricDataSize());

    // Encode the IGCMetrics version.
    // Currently it's count of commits made for
    // IGC/Metrics/proto_schema folder.
    // Define IGCMetricsVer generated during cmake call.
    // If there was a problem to generate the IGCMetricsVer value,
    // then it will be set to default "0"
    ((int *)pMetricData)[0] = IGCMetricsVer;

    if (oclProgram.ByteSizeLong() > 0) {
      // Copy IGC metrics data into stream
      void *pMetricDataInput = (void *)((char *)pMetricData + sizeof(int));
      oclProgram.SerializeToArray(pMetricDataInput, oclProgram.ByteSizeLong());
    }
  }

  if (IGC_GET_FLAG_VALUE(MetricsDumpEnable) > 0) {
    // Out file with ext OPTRPT - OPTimization RePoT
    std::string fileName = oclProgram.hash() + ".optrpt";

    std::ofstream metric_data;
    metric_data.open(fileName);

    if (metric_data.is_open()) {
      if (IGC_GET_FLAG_VALUE(MetricsDumpEnable) == 1) {
        // Binary format of protobuf
        metric_data.write((const char *)pMetricData, getMetricDataSize());
      } else if (IGC_GET_FLAG_VALUE(MetricsDumpEnable) == 2) {
        // Text readable in JSON format
        google::protobuf::util::JsonPrintOptions jsonConfig;

        jsonConfig.add_whitespace = true;
        jsonConfig.preserve_proto_field_names = true;
        jsonConfig.always_print_primitive_fields = true;

        std::string json;
        google::protobuf::util::MessageToJsonString(oclProgram, &json, jsonConfig);
        metric_data << "IGCMetricsVer : " << IGCMetricsVer << "\n";
        metric_data << json;
      }

      metric_data.close();
    }
  }
#endif
}

void IGCMetricImpl::StatBeginEmuFunc(llvm::Instruction *instruction) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  countInstInFunc = CountInstInFunc(instruction->getParent()->getParent());
#endif
}

bool isDPType(llvm::Instruction *instruction) {
  llvm::Type *type = instruction->getType()->getScalarType();
  if (type->isDoubleTy()) {
    return true;
  }

  for (unsigned int i = 0; i < instruction->getNumOperands(); ++i) {
    type = instruction->getOperand(i)->getType()->getScalarType();
    if (type->isDoubleTy()) {
      return true;
    }
  }

  return false;
}

void IGCMetricImpl::StatEndEmuFunc(llvm::Instruction *emulatedInstruction) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  llvm::DILocation *debLoc = (llvm::DILocation *)emulatedInstruction->getDebugLoc();

  auto func_m = GetFuncMetric(emulatedInstruction);
  if (func_m == nullptr) {
    return;
  }

  IGC_METRICS::InstrStats *stats = func_m->mutable_instruction_stats();
  IGC_METRICS::FuncEmuCalls *emuCall_m = nullptr;

  // Count how many instructions we added
  int extraInstrAdded = CountInstInFunc(emulatedInstruction->getParent()->getParent()) - countInstInFunc;
  // reset counter
  countInstInFunc = 0;

  if (map_EmuCalls.find(debLoc) != map_EmuCalls.end()) {
    // For case when receive extra instruction to already recoreded emu-function
    emuCall_m = map_EmuCalls[debLoc];
  } else {
    // For case if we discover new emulated function
    emuCall_m = func_m->add_emufunctioncalls();
    map_EmuCalls.insert({debLoc, emuCall_m});

    auto emuCall_m_loc = emuCall_m->add_funccallloc();
    FillCodeRef(emuCall_m_loc, debLoc);
    stats->set_countemulatedinst(stats->countemulatedinst() + 1);

    if (IGC_IS_FLAG_ENABLED(ForceDPEmulation) && isDPType(emulatedInstruction)) {
      emuCall_m->set_type(IGC_METRICS::FuncEmuCalls_Reason4FuncEmu_FP_MODEL_MODE);
    } else {
      emuCall_m->set_type(IGC_METRICS::FuncEmuCalls_Reason4FuncEmu_NO_HW_SUPPORT);
    }
  }
  // Count amount of instructions created to emulate not supported instruction
  emuCall_m->set_count(emuCall_m->count() + extraInstrAdded);
#endif
}

void IGCMetricImpl::StatIncCoalesced(llvm::Instruction *coalescedAccess) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  auto func_m = GetFuncMetric(coalescedAccess);
  if (func_m == nullptr) {
    return;
  }

  IGC_METRICS::InstrStats *stats = func_m->mutable_instruction_stats();
  stats->set_countcoalescedaccess(stats->countcoalescedaccess() + 1);
#endif
}

void IGCMetricImpl::CollectRegStats(KERNEL_INFO *kernelInfo, llvm::Function *pFunc) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  if (kernelInfo != nullptr) {
    auto func_m = GetFuncMetric(pFunc);
    if (func_m != nullptr) {
      auto func_reg_stats_m = func_m->mutable_local_reg_stats();
      func_reg_stats_m->set_percentgrfusage(kernelInfo->precentGRFUsage);
      func_reg_stats_m->set_countregspillsallocated(kernelInfo->numSpillReg);
      func_reg_stats_m->set_countregfillsallocated(kernelInfo->numFillReg);
      func_reg_stats_m->set_countregallocated(kernelInfo->numReg);
      func_reg_stats_m->set_countregtmpallocated(kernelInfo->numTmpReg);
      func_reg_stats_m->set_countbytesregtmpallocated(kernelInfo->bytesOfTmpReg);

      auto func_instr_stats_m = func_m->mutable_instruction_stats();

      auto func_instr_simd_stats_m = func_instr_stats_m->mutable_simd_used();
      func_instr_simd_stats_m->set_simd1(kernelInfo->countSIMD1);
      func_instr_simd_stats_m->set_simd2(kernelInfo->countSIMD2);
      func_instr_simd_stats_m->set_simd4(kernelInfo->countSIMD4);
      func_instr_simd_stats_m->set_simd8(kernelInfo->countSIMD8);
      func_instr_simd_stats_m->set_simd16(kernelInfo->countSIMD16);
      func_instr_simd_stats_m->set_simd32(kernelInfo->countSIMD32);

      if (kernelInfo->lscSends.hasAnyLSCSend) {
        auto lsc_sends_stats_m = func_instr_stats_m->mutable_statslscsends();

        // Load
        lsc_sends_stats_m->set_countlsc_load(kernelInfo->lscSends.countLSC_LOAD);
        lsc_sends_stats_m->set_countlsc_load_strided(kernelInfo->lscSends.countLSC_LOAD_STRIDED);
        lsc_sends_stats_m->set_countlsc_load_quad(kernelInfo->lscSends.countLSC_LOAD_QUAD);
        lsc_sends_stats_m->set_countlsc_load_block2d(kernelInfo->lscSends.countLSC_LOAD_BLOCK2D);
        // Store
        lsc_sends_stats_m->set_countlsc_store(kernelInfo->lscSends.countLSC_STORE);
        lsc_sends_stats_m->set_countlsc_store_strided(kernelInfo->lscSends.countLSC_STORE_STRIDED);
        lsc_sends_stats_m->set_countlsc_store_quad(kernelInfo->lscSends.countLSC_STORE_QUAD);
        lsc_sends_stats_m->set_countlsc_store_block2d(kernelInfo->lscSends.countLSC_STORE_BLOCK2D);
        lsc_sends_stats_m->set_countlsc_store_uncompressed(kernelInfo->lscSends.countLSC_STORE_UNCOMPRESSED);
      }

      if (kernelInfo->hdcSends.hasAnyHDCSend) {
        auto hdc_sends_stats_m = func_instr_stats_m->mutable_statshdcsends();
        // Data Cache0 Messages
        // Load
        hdc_sends_stats_m->set_countdc_oword_block_read(kernelInfo->hdcSends.countDC_OWORD_BLOCK_READ);
        hdc_sends_stats_m->set_countdc_aligned_oword_block_read(kernelInfo->hdcSends.countDC_ALIGNED_OWORD_BLOCK_READ);
        hdc_sends_stats_m->set_countdc_dword_scattered_read(kernelInfo->hdcSends.countDC_DWORD_SCATTERED_READ);
        hdc_sends_stats_m->set_countdc_byte_scattered_read(kernelInfo->hdcSends.countDC_BYTE_SCATTERED_READ);
        hdc_sends_stats_m->set_countdc_qword_scattered_read(kernelInfo->hdcSends.countDC_QWORD_SCATTERED_READ);
        // Store
        hdc_sends_stats_m->set_countdc_oword_block_write(kernelInfo->hdcSends.countDC_OWORD_BLOCK_WRITE);
        hdc_sends_stats_m->set_countdc_dword_scattered_write(kernelInfo->hdcSends.countDC_DWORD_SCATTERED_WRITE);
        hdc_sends_stats_m->set_countdc_byte_scattered_write(kernelInfo->hdcSends.countDC_BYTE_SCATTERED_WRITE);
        hdc_sends_stats_m->set_countdc_qword_scattered_write(kernelInfo->hdcSends.countDC_QWORD_SCATTERED_WRITE);

        // Data Cache1 Messages
        // Load
        hdc_sends_stats_m->set_countdc1_untyped_surface_read(kernelInfo->hdcSends.countDC1_UNTYPED_SURFACE_READ);
        hdc_sends_stats_m->set_countdc1_media_block_read(kernelInfo->hdcSends.countDC1_MEDIA_BLOCK_READ);
        hdc_sends_stats_m->set_countdc1_typed_surface_read(kernelInfo->hdcSends.countDC1_TYPED_SURFACE_READ);
        hdc_sends_stats_m->set_countdc1_a64_scattered_read(kernelInfo->hdcSends.countDC1_A64_SCATTERED_READ);
        hdc_sends_stats_m->set_countdc1_a64_untyped_surface_read(
            kernelInfo->hdcSends.countDC1_A64_UNTYPED_SURFACE_READ);
        hdc_sends_stats_m->set_countdc1_a64_block_read(kernelInfo->hdcSends.countDC1_A64_BLOCK_READ);
        // Store
        hdc_sends_stats_m->set_countdc1_untyped_surface_write(kernelInfo->hdcSends.countDC1_UNTYPED_SURFACE_WRITE);
        hdc_sends_stats_m->set_countdc1_media_block_write(kernelInfo->hdcSends.countDC1_MEDIA_BLOCK_WRITE);
        hdc_sends_stats_m->set_countdc1_typed_surface_write(kernelInfo->hdcSends.countDC1_TYPED_SURFACE_WRITE);
        hdc_sends_stats_m->set_countdc1_a64_block_write(kernelInfo->hdcSends.countDC1_A64_BLOCK_WRITE);
        hdc_sends_stats_m->set_countdc1_a64_untyped_surface_write(
            kernelInfo->hdcSends.countDC1_A64_UNTYPED_SURFACE_WRITE);
        hdc_sends_stats_m->set_countdc1_a64_scattered_write(kernelInfo->hdcSends.countDC1_A64_SCATTERED_WRITE);

        // Data Cache2 Messages
        // Load
        hdc_sends_stats_m->set_countdc2_untyped_surface_read(kernelInfo->hdcSends.countDC2_UNTYPED_SURFACE_READ);
        hdc_sends_stats_m->set_countdc2_a64_scattered_read(kernelInfo->hdcSends.countDC2_A64_SCATTERED_READ);
        hdc_sends_stats_m->set_countdc2_a64_untyped_surface_read(
            kernelInfo->hdcSends.countDC2_A64_UNTYPED_SURFACE_READ);
        hdc_sends_stats_m->set_countdc2_byte_scattered_read(kernelInfo->hdcSends.countDC2_BYTE_SCATTERED_READ);
        // Store
        hdc_sends_stats_m->set_countdc2_untyped_surface_write(kernelInfo->hdcSends.countDC2_UNTYPED_SURFACE_WRITE);
        hdc_sends_stats_m->set_countdc2_a64_untyped_surface_write(
            kernelInfo->hdcSends.countDC2_A64_UNTYPED_SURFACE_WRITE);
        hdc_sends_stats_m->set_countdc2_a64_scattered_write(kernelInfo->hdcSends.countDC2_A64_SCATTERED_WRITE);
        hdc_sends_stats_m->set_countdc2_byte_scattered_write(kernelInfo->hdcSends.countDC2_BYTE_SCATTERED_WRITE);

        // URB Messages
        // Load
        hdc_sends_stats_m->set_counturb_read_hword(kernelInfo->hdcSends.countURB_READ_HWORD);
        hdc_sends_stats_m->set_counturb_read_oword(kernelInfo->hdcSends.countURB_READ_OWORD);
        hdc_sends_stats_m->set_counturb_simd8_read(kernelInfo->hdcSends.countURB_SIMD8_READ);
        // Store
        hdc_sends_stats_m->set_counturb_write_hword(kernelInfo->hdcSends.countURB_WRITE_HWORD);
        hdc_sends_stats_m->set_counturb_write_oword(kernelInfo->hdcSends.countURB_WRITE_OWORD);
        hdc_sends_stats_m->set_counturb_simd8_write(kernelInfo->hdcSends.countURB_SIMD8_WRITE);
      }

      if (kernelInfo->spillFills.countBytesSpilled > 0) {
        auto spillFill_m = func_m->mutable_spillfill_stats();

        spillFill_m->set_countbytesspilled(kernelInfo->spillFills.countBytesSpilled);

        for (auto spillOrderInstr : kernelInfo->spillFills.spillInstrOrder) {
          spillFill_m->add_spillinstrvisaid(spillOrderInstr);
        }
        for (auto fillOrderInstr : kernelInfo->spillFills.fillInstrOrder) {
          spillFill_m->add_fillinstrvisaid(fillOrderInstr);
        }
        for (auto virtualVar : kernelInfo->spillFills.virtualVars) {
          spillFill_m->add_virtualvars(virtualVar);
        }
      }
    }
  }
#endif
}

void IGCMetricImpl::CollectFunctions(llvm::Module *pModule) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED

  this->pModule = (IGCLLVM::Module *)pModule;
  fillInstrKindID = pModule->getMDKindID("FillInstr");
  spillInstrKindID = pModule->getMDKindID("SpillInstr");
  for (auto func_i = pModule->begin(); func_i != pModule->end(); ++func_i) {
    llvm::Function &func = *func_i;
    llvm::DISubprogram *func_dbinfo = func.getSubprogram();

    if (func_dbinfo != nullptr) {
      IGC_METRICS::Function *func_m = oclProgram.add_functions();

      func_m->set_name(func.getName().str());

      switch (func.getCallingConv()) {
      case llvm::CallingConv::SPIR_FUNC:
        func_m->set_type(IGC_METRICS::FunctionType::FUNCTION);
        break;
      case llvm::CallingConv::SPIR_KERNEL:
        func_m->set_type(IGC_METRICS::FunctionType::KERNEL);
        break;
      case llvm::CallingConv::C:
        func_m->set_type(IGC_METRICS::FunctionType::FUNCTION);
        break;
      default:
        IGC_ASSERT_MESSAGE(false, "Unknown Function type");
        break;
      }
      map_Func.insert({func_dbinfo, func_m});
      IGC_METRICS::CodeRef *func_m_loc = func_m->mutable_funcloc();
      FillCodeRef(func_m_loc, func_dbinfo);

      GetFunctionData(func_m, func);
    }
  }
#endif
}

void IGCMetricImpl::CollectLoops(llvm::Loop *loop) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  for (auto subLoop : loop->getSubLoops()) {
    CollectLoop(subLoop);
  }
#endif
}

void IGCMetricImpl::CollectLoops(llvm::LoopInfo *loopInfo) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  for (auto loop_i = loopInfo->begin(); loop_i != loopInfo->end(); ++loop_i) {
    llvm::Loop *loop = *loop_i;
    CollectLoop(loop);
    CollectLoops(loop);
  }
#endif
}

void IGCMetricImpl::CollectLoopCyclomaticComplexity(llvm::Function *pFunc, int LoopCyclomaticComplexity,
                                                    int LoopCyclomaticComplexity_Max) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd16cost = costmodel->mutable_simd16();
    simd16cost->set_loopcyclomaticcomplexity(LoopCyclomaticComplexity);
    simd16cost->set_loopcyclomaticcomplexity_max(LoopCyclomaticComplexity_Max);
    simd16cost->set_loopcyclomaticcomplexity_status(
        LoopCyclomaticComplexity < LoopCyclomaticComplexity_Max
            ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
            : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

void IGCMetricImpl::CollectNestedLoopsWithMultipleExits(llvm::Function *pFunc, float NestedLoopsWithMultipleExitsRatio,
                                                        float NestedLoopsWithMultipleExitsRatio_Max) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd16cost = costmodel->mutable_simd16();
    simd16cost->set_nestedloopswithmultipleexitsratio(NestedLoopsWithMultipleExitsRatio);
    simd16cost->set_nestedloopswithmultipleexitsratio_max(NestedLoopsWithMultipleExitsRatio_Max);
    simd16cost->set_nestedloopswithmultipleexitsratio_status(
        NestedLoopsWithMultipleExitsRatio < NestedLoopsWithMultipleExitsRatio_Max
            ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
            : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

void IGCMetricImpl::CollectLongStridedLdStInLoop(llvm::Function *pFunc, llvm::Loop *pProblematicLoop,
                                                 int LongStridedLdStInLoop_LdCnt, int LongStridedLdStInLoop_StCnt,
                                                 int LongStridedLdStInLoop_MaxCntLdOrSt) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd16cost = costmodel->mutable_simd16();

    if (pProblematicLoop == nullptr) {
      simd16cost->set_longstridedldstinloop_status(
          IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK);
    } else {
      simd16cost->set_longstridedldstinloop_status(
          IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
      simd16cost->set_longstridedldstinloop_ldcnt(LongStridedLdStInLoop_LdCnt);
      simd16cost->set_longstridedldstinloop_stcnt(LongStridedLdStInLoop_StCnt);
      simd16cost->set_longstridedldstinloop_maxcntldorst(LongStridedLdStInLoop_MaxCntLdOrSt);

      FillCodeRef(simd16cost->mutable_longstridedldstinloop_problematicloop(), pProblematicLoop->getStartLoc());
    }
  }
#endif
}

void IGCMetricImpl::CollectIsGeminiLakeWithDoubles(llvm::Function *pFunc, bool IsGeminiLakeWithDoubles) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd16cost = costmodel->mutable_simd16();

    simd16cost->set_isgeminilakewithdoubles_status(
        IsGeminiLakeWithDoubles ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
                                : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

void IGCMetricImpl::FinalizeStats() {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  UpdateLoopsInfo();
  UpdateModelCost();
  UpdateFunctionArgumentsList();
  UpdateInstructionStats();
#endif
}

void IGCMetricImpl::CollectDataFromDebugInfo(llvm::Function *pFunc, IGC::DebugInfoData *pDebugInfo,
                                             const IGC::VISADebugInfo *pVisaDbgInfo) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED

  auto pDbgFunc = pFunc->getSubprogram();
  if (!pDbgFunc || map_Func.find(pDbgFunc) == map_Func.end()) {
    // For case if we have debugInfo not for user kernel
    return;
  }

  oclProgram.set_device((IGC_METRICS::DeviceType)pDebugInfo->m_pShader->m_Platform->getPlatformInfo().eProductFamily);

  llvm::DenseMap<llvm::Function *, IGC::VISAModule *> *pListFuncData = &pDebugInfo->m_VISAModules;
  llvm::DenseMap<llvm::DIVariable *, IGC_METRICS::VarInfo *> var_db2metric;

  for (auto pListFuncData_it = pListFuncData->begin(); pListFuncData_it != pListFuncData->end(); ++pListFuncData_it) {
    llvm::Function *pFunc = pListFuncData_it->first;
    IGC::VISAModule *vISAData = pListFuncData_it->second;
    const auto &VDI = vISAData->getVisaObjectDI(*pVisaDbgInfo);
#ifdef DEBUG_METRIC
    std::printf("\nList of symbols:\n");

    for (auto it_dbgInfo = pDebugInfo->m_FunctionSymbols[pFunc].begin();
         it_dbgInfo != pDebugInfo->m_FunctionSymbols[pFunc].end(); ++it_dbgInfo) {
      std::printf("pointer{%p} key{%s} val{%s}\n", it_dbgInfo->first, it_dbgInfo->first->getName().str().c_str(),
                  it_dbgInfo->second->getName().getCString());
      it_dbgInfo->first->dump();
    }
#endif
    UpdateMem2RegStats(vISAData);

    const llvm::Value *pVal = nullptr;

    // Iterate over all instruction ported to vISA
    for (auto instr = vISAData->begin(); instr != vISAData->end(); ++instr) {
      if (const llvm::DbgDeclareInst *pDbgAddrInst = llvm::dyn_cast<llvm::DbgDeclareInst>(*instr)) {
        // Get : call void @llvm.dbg.value
        pVal = pDbgAddrInst->getAddress();
      } else if (const llvm::DbgValueInst *pDbgValInst = llvm::dyn_cast<llvm::DbgValueInst>(*instr)) {
        // Get : call void @llvm.dbg.value

        // Avoid undef values in metadata
        {
          llvm::MetadataAsValue *mdAv = llvm::dyn_cast<llvm::MetadataAsValue>(pDbgValInst->getArgOperand(0));
          if (mdAv != nullptr) {
            llvm::ValueAsMetadata *vAsMD = llvm::dyn_cast<llvm::ValueAsMetadata>(mdAv->getMetadata());
            if (vAsMD != nullptr && llvm::isa<llvm::UndefValue>(vAsMD->getValue())) {
              continue;
            }
          }
        }

        pVal = pDbgValInst->getValue();
      } else {
        continue;
      }

      auto varLoc = vISAData->GetVariableLocation(*instr);

      IGC_METRICS::VarInfo *varInfo_m = GetVarMetric((llvm::Value *)pVal);

      if (varInfo_m == nullptr) {
        continue;
      }

      // Get CVariable data for this user variable
      auto cvar = pDebugInfo->getMapping(*pFunc, pVal);

#ifdef DEBUG_METRIC
      int users_count = (int)std::distance(pVal->user_begin(), pVal->user_end());
      pVal->dump();
      std::printf("\ninstr (varname:%s, pointer:%p, usage count:%d) :\n", varInfo_m->name().c_str(), pVal, users_count);
      (*instr)->dump();
#endif

      if (!varLoc.IsRegister() && !varLoc.IsImmediate() && !varLoc.IsSLM()) {
        continue;
      }
      // As for now support only registers, immediates and slm memory to report

      if (cvar == nullptr && pDebugInfo->m_pShader->GetSymbolMapping().find((llvm::Value *)pVal) !=
                                 pDebugInfo->m_pShader->GetSymbolMapping().end()) {
        cvar = pDebugInfo->m_pShader->GetSymbolMapping()[(llvm::Value *)pVal];
      }

      if (cvar == nullptr && pDebugInfo->m_pShader->GetGlobalMapping().find((llvm::Value *)pVal) !=
                                 pDebugInfo->m_pShader->GetGlobalMapping().end()) {
        cvar = pDebugInfo->m_pShader->GetGlobalMapping()[(llvm::Value *)pVal];
      }

      if (cvar == nullptr) {
        auto cvar_const = llvm::dyn_cast<llvm::Constant>(pVal);
        if (cvar_const != nullptr && pDebugInfo->m_pShader->GetConstantMapping().find((llvm::Constant *)cvar_const) !=
                                         pDebugInfo->m_pShader->GetConstantMapping().end()) {
          cvar = pDebugInfo->m_pShader->GetConstantMapping()[(llvm::Constant *)cvar_const];
        }
      }

      if (cvar == nullptr) {
        // If not found, ignore
        continue;
      }

      varInfo_m->set_size(cvar->GetSize());
      varInfo_m->set_type((IGC_METRICS::VarInfo_VarType)cvar->GetType());

      auto fillRegister = [&](unsigned int reg) {
        const auto *varInfo = vISAData->getVarInfo(VDI, reg);
        auto varInfo_reg_m = varInfo_m->add_reg();

        varInfo_reg_m->set_addrmodel(varLoc.IsInGlobalAddrSpace()
                                         ? IGC_METRICS::VarInfo_AddressModel::VarInfo_AddressModel_GLOBAL
                                         : IGC_METRICS::VarInfo_AddressModel::VarInfo_AddressModel_LOCAL);

        // varInfo_m->set_memoryaccess((IGC_METRICS::VarInfo_MemAccess)varInfo->memoryAccess);

        if (varInfo != nullptr) {
          // check if any?
          varInfo_reg_m->set_isspill(varInfo->lrs[0].isSpill());
          varInfo_reg_m->set_liverangestart(varInfo->lrs[0].start);
          varInfo_reg_m->set_liverangeend(varInfo->lrs[0].end);
        }
        varInfo_reg_m->set_isuniform(cvar->IsUniform());
        varInfo_reg_m->set_isconst(cvar->IsImmediate());
      };

      fillRegister(varLoc.GetRegister());
      // Special case when we have simd32 splitted into two simd16
      if (varLoc.HasLocationSecondReg()) {
        fillRegister(varLoc.GetSecondReg());
      }
    }
  }
#endif
}

void IGCMetricImpl::CollectInstructionCnt(llvm::Function *pFunc, int InstCnt, int InstCntMax) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd32cost = costmodel->mutable_simd32();

    simd32cost->set_instructioncount(InstCnt);
    simd32cost->set_instructioncount_max(InstCntMax);
    simd32cost->set_instructioncount_status(
        InstCnt < InstCntMax ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
                             : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

void IGCMetricImpl::CollectThreadGroupSize(llvm::Function *pFunc, int ThreadGroupSize, int ThreadGroupSizeMax) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd32cost = costmodel->mutable_simd32();

    simd32cost->set_threadgroupsize(ThreadGroupSize);
    simd32cost->set_threadgroupsize_max(ThreadGroupSizeMax);
    simd32cost->set_threadgroupsize_status(ThreadGroupSize < ThreadGroupSizeMax
                                               ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
                                               : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

void IGCMetricImpl::CollectThreadGroupSizeHint(llvm::Function *pFunc, int ThreadGroupSizeHint,
                                               int ThreadGroupSizeHintMax) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd32cost = costmodel->mutable_simd32();

    simd32cost->set_threadgroupsizehint(ThreadGroupSizeHint);
    simd32cost->set_threadgroupsizehint_max(ThreadGroupSizeHintMax);
    simd32cost->set_threadgroupsizehint_status(
        ThreadGroupSizeHint < ThreadGroupSizeHintMax
            ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
            : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

void IGCMetricImpl::CollectIsSubGroupFuncIn(llvm::Function *pFunc, bool flag) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd32cost = costmodel->mutable_simd32();

    simd32cost->set_subgroupfunctionarepresent_status(
        !flag ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
              : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

void IGCMetricImpl::CollectGen9Gen10WithIEEESqrtDivFunc(llvm::Function *pFunc, bool flag) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd32cost = costmodel->mutable_simd32();

    simd32cost->set_gen9orgen10withieeesqrtordivfunc_status(
        !flag ? IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK
              : IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
  }
#endif
}

enum { LOOPCOUNT_LIKELY_SMALL, LOOPCOUNT_LIKELY_LARGE, LOOPCOUNT_UNKNOWN };

void IGCMetricImpl::CollectNonUniformLoop(llvm::Function *pFunc, short LoopCount, llvm::Loop *problematicLoop) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pFunc);

  if (func_metric) {
    auto costmodel = func_metric->mutable_costmodel_stats();
    auto simd32cost = costmodel->mutable_simd32();

    if (problematicLoop == nullptr) {
      simd32cost->set_nonuniformloop_status(IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_OK);
      simd32cost->set_nonuniformloop_count(
          IGC_METRICS::CostModelStats_CostSIMD32_LoopCount::CostModelStats_CostSIMD32_LoopCount_LIKELY_SMALL);
    } else {
      simd32cost->set_nonuniformloop_status(IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD);
      simd32cost->set_nonuniformloop_count((IGC_METRICS::CostModelStats_CostSIMD32_LoopCount)LoopCount);
      auto codeRefloop = simd32cost->mutable_nonuniformloop_problematicloop();
      FillCodeRef(codeRefloop, problematicLoop->getStartLoc());
    }
  }
#endif
}

void IGCMetricImpl::UpdateVariable(llvm::Value *Org, llvm::Value *New) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  auto varData = GetVarData(Org);

  if (varData) {
    auto MDDILocalVariable = varData->varDILocalVariable;
    llvm::MetadataAsValue *MDValue = makeMDasVal(New);

    llvm::Instruction *insertAfter = nullptr;
    if (auto arg = llvm::dyn_cast<llvm::Argument>(New)) {
      insertAfter = &*arg->getParent()->getEntryBlock().begin();
    } else if (auto instruction = llvm::dyn_cast<llvm::Instruction>(New)) {
      insertAfter = instruction;
    } else {
      IGC_ASSERT_MESSAGE(false, "Unknown llvm type");
    }

    makeTrackCall(funcTrackValue, {MDValue, MDDILocalVariable}, insertAfter);
  }
#endif
}

void IGCMetricImpl::CollectMem2Reg(llvm::AllocaInst *pAllocaInst, IGC::StatusPrivArr2Reg status) {
  if (!Enable())
    return;
#ifdef IGC_METRICS__PROTOBUF_ATTACHED
  IGC_METRICS::Function *func_metric = GetFuncMetric(pAllocaInst);
  if (func_metric) {
    auto var_d = GetVarData(pAllocaInst);

    auto reg_stats = func_metric->mutable_local_reg_stats();

    if (status == IGC::StatusPrivArr2Reg::OK) {
      reg_stats->set_countprvarray2grfpromoted(reg_stats->countprvarray2grfpromoted() + 1);
    } else {
      reg_stats->set_countprvarray2grfnotpromoted(reg_stats->countprvarray2grfnotpromoted() + 1);

      if (var_d) {
        // As for now assuming that all store/load associated with
        // alloca will be treated as spill/fill
        std::vector<llvm::LoadInst *> fills;
        std::vector<llvm::StoreInst *> spills;

        std::function<void(llvm::User *, std::vector<llvm::LoadInst *> &, std::vector<llvm::StoreInst *> &)>
            lookForSpillFills = [&](llvm::User *enterUser, std::vector<llvm::LoadInst *> &fills,
                                    std::vector<llvm::StoreInst *> &spills) {
              for (auto user : enterUser->users()) {
                if (auto load = llvm::dyn_cast<llvm::LoadInst>(user)) {
                  fills.push_back(load);
                } else if (auto load = llvm::dyn_cast<llvm::StoreInst>(user)) {
                  spills.push_back(load);
                } else if (llvm::isa<llvm::GetElementPtrInst>(user)) {
                  lookForSpillFills(user, fills, spills);
                }
              }
            };

        // Map in code any refrence to this spill/fills (for metrics)
        // by adding callinstr llvm.igc.metric.trackSpill/Fill in module for tracking
        lookForSpillFills(pAllocaInst, fills, spills);

        for (auto fill : fills) {
          MDNode *N = llvm::cast<DILocalVariable>(var_d->varDILocalVariable->getMetadata());
          fill->setMetadata(fillInstrKindID, N);
        }

        for (auto spill : spills) {
          MDNode *N = llvm::cast<DILocalVariable>(var_d->varDILocalVariable->getMetadata());
          spill->setMetadata(spillInstrKindID, N);
        }

        auto allocated = IGCLLVM::makeOptional(pAllocaInst->getAllocationSizeInBits(pModule->getDataLayout()));

        auto func_m = GetFuncMetric(pAllocaInst);
        auto spillFill_m = func_m->mutable_spillfill_stats();
        // Add amount of bytes spilled
        spillFill_m->set_countbytesspilled(spillFill_m->countbytesspilled() +
                                           (int32_t)(allocated.value_or(IGCLLVM::getTypeSize(0)) / 8));
      }
    }

    if (var_d) {
      var_d->var_m->set_status_privarr2reg((IGC_METRICS::VarInfo_PrivArr2Reg)status);
    }
  }
#endif
}

#ifdef IGC_METRICS__PROTOBUF_ATTACHED

class CollectSpillFills : public llvm::InstVisitor<CollectSpillFills> {
  IGCMetricImpl *metric;
  IGC::VISAModule *CurrentVISA;

public:
  CollectSpillFills(IGCMetricImpl *metric, IGC::VISAModule *CurrentVISA) {
    this->metric = metric;
    this->CurrentVISA = CurrentVISA;
  }

  void visitLoadInst(llvm::LoadInst &instr) {
    auto spillMD = instr.getMetadata(metric->fillInstrKindID);
    if (spillMD != nullptr) {
      // Some instructions dosen't have visa offset
      // that means the instruction is a dead code
      if (CurrentVISA->HasVisaOffset(&instr)) {
        auto func_m = metric->GetFuncMetric(&instr);
        auto spillFill_m = func_m->mutable_spillfill_stats();

        spillFill_m->set_countfillinstr(spillFill_m->countfillinstr() + 1);

        // Add spill instruction to metrics
        spillFill_m->add_fillinstrvisaid(CurrentVISA->GetVisaOffset(&instr));
      }
    }
  }

  void visitStoreInst(llvm::StoreInst &instr) {
    auto fillMD = instr.getMetadata(metric->spillInstrKindID);
    if (fillMD != nullptr) {
      // Some instructions dosen't have visa offset
      // that means the instruction is a dead code
      if (CurrentVISA->HasVisaOffset(&instr)) {
        auto func_m = metric->GetFuncMetric(&instr);
        auto spillFill_m = func_m->mutable_spillfill_stats();

        spillFill_m->set_countspillinstr(spillFill_m->countspillinstr() + 1);

        // Add spill instruction to metrics
        spillFill_m->add_spillinstrvisaid(CurrentVISA->GetVisaOffset(&instr));
      }
    }
  }
};

void IGCMetricImpl::UpdateMem2RegStats(IGC::VISAModule *CurrentVISA) {
  // Now if we have vISA kernel code ready, then we can map
  // spill/fills from IGC to vISA-ID
  CollectSpillFills metricPass(this, CurrentVISA);

  metricPass.visit((llvm::Function *)(CurrentVISA->GetEntryFunction()));
}

void IGCMetricImpl::UpdateFunctionArgumentsList() {
  for (auto func_i = pModule->begin(); func_i != pModule->end(); ++func_i) {
    llvm::Function *func = &*func_i;

    auto func_m = GetFuncMetric(func);

    if (func_m) {
      for (auto arg_i = func->arg_begin(); arg_i != func->arg_end(); ++arg_i) {
        llvm::Argument *arg = &*arg_i;
        bool foundInMetric = false;

        // Check if we are looking on the explicit argument
        // which is already added in the metrics for the function
        if (arg->hasName()) {
          for (int i = 0; i < func_m->arguments_size(); ++i) {
            if (func_m->arguments(i).name() == arg->getName().str()) {
              foundInMetric = true;
              break;
            }
          }
        }

        // Not found - add it as implict argument
        if (!foundInMetric) {
          auto func_arg_m = func_m->add_arguments();
          if (arg->hasName()) {
            func_arg_m->set_name(arg->getName().str());
          }
          func_arg_m->set_compilesize((int32_t)arg->getType()->getPrimitiveSizeInBits());
          func_arg_m->set_type(IGC_METRICS::KernelArg_ArgumentType::KernelArg_ArgumentType_IMPLICIT);
        }
      }
    }
  }
}

void IGCMetricImpl::UpdateModelCost() {
  // Function which checks the overall model cost of kernel status for SIMD16 and SIMD32

  auto isOkStatus = [](IGC_METRICS::CostModelStats_CostStatus Status) {
    return Status != IGC_METRICS::CostModelStats_CostStatus::CostModelStats_CostStatus_BAD;
  };

  for (auto func_m_i = map_Func.begin(); func_m_i != map_Func.end(); ++func_m_i) {
    auto func_m = func_m_i->second;

    if (func_m->has_costmodel_stats()) {
      auto costmodel = func_m->mutable_costmodel_stats();

      if (costmodel->has_simd16()) {
        auto simd16 = costmodel->mutable_simd16();

        simd16->set_overallstatus(isOkStatus(simd16->loopcyclomaticcomplexity_status()) &&
                                  isOkStatus(simd16->nestedloopswithmultipleexitsratio_status()) &&
                                  isOkStatus(simd16->longstridedldstinloop_status()) &&
                                  isOkStatus(simd16->isgeminilakewithdoubles_status()));
      }

      if (costmodel->has_simd32()) {
        auto simd32 = costmodel->mutable_simd32();

        simd32->set_overallstatus(isOkStatus(simd32->instructioncount_status()) &&
                                  isOkStatus(simd32->threadgroupsize_status()) &&
                                  isOkStatus(simd32->threadgroupsizehint_status()) &&
                                  isOkStatus(simd32->subgroupfunctionarepresent_status()) &&
                                  isOkStatus(simd32->gen9orgen10withieeesqrtordivfunc_status()) &&
                                  isOkStatus(simd32->nonuniformloop_status()));
      }
    }
  }
}

void IGCMetricImpl::CollectLoop(llvm::Loop *loop) {
  if (loop->getStartLoc() && loop->getStartLoc()->getScope()) {
    if (map_Loops.find(loop->getStartLoc()->getScope()) == map_Loops.end()) {
      auto func_m = GetFuncMetric(loop);
      if (func_m == nullptr) {
        return;
      }

      auto cfg_stats = func_m->mutable_cfg_stats();
      auto loop_m = cfg_stats->add_loops_stats();
      auto loopLoc = loop_m->mutable_looploc();

      FillCodeRef(loopLoc, loop->getStartLoc());
      loop_m->set_nestinglevel(loop->getLoopDepth());

      map_Loops.insert({loop->getStartLoc()->getScope(), loop_m});
    }
  }
}

void IGCMetricImpl::UpdateLoopsInfo() {}

class CollectInstrData : public llvm::InstVisitor<CollectInstrData> {
  IGCMetricImpl *metric;

public:
  CollectInstrData(IGCMetricImpl *metric) { this->metric = metric; }

  void visitUnaryOperator(llvm::UnaryOperator &unaryOpInst) { AddArithmeticinstCount(unaryOpInst); }

  void visitBinaryOperator(llvm::BinaryOperator &binaryOpInst) { AddArithmeticinstCount(binaryOpInst); }

  void visitCallInst(llvm::CallInst &callInst) {
    /*
    if (GenIntrinsicInst* CI = llvm::dyn_cast<GenIntrinsicInst>(&callInst))
    {
        switch (CI->getIntrinsicID())
        {
        default:
            break;
        }
    }*/
    if (IntrinsicInst *CI = llvm::dyn_cast<IntrinsicInst>(&callInst)) {
      switch (CI->getIntrinsicID()) {
      case Intrinsic::log:
      case Intrinsic::log2:
      case Intrinsic::log10:
      case Intrinsic::cos:
      case Intrinsic::sin:
      case Intrinsic::exp:
      case Intrinsic::exp2:
        AddTranscendentalFuncCount(callInst);
        break;
      case Intrinsic::sqrt:
      case Intrinsic::pow:
      case Intrinsic::floor:
      case Intrinsic::ceil:
      case Intrinsic::trunc:
      case Intrinsic::maxnum:
      case Intrinsic::minnum:
        AddArithmeticinstCount(callInst);
        break;
      default:
        break;
      }
    }
  }

  void AddTranscendentalFuncCount(llvm::Instruction &instr) {
    // Transcendental functions includes:
    // 1.exponential function
    // 2.logarithm
    // 3.trigonometric functions
    auto func_m = metric->GetFuncMetric(&instr);

    if (func_m) {
      auto instr_stats_m = func_m->mutable_instruction_stats();
      instr_stats_m->set_counttranscendentalfunc(instr_stats_m->counttranscendentalfunc() + 1);
    }
  }

  void AddArithmeticinstCount(llvm::Instruction &instr) {
    auto func_m = metric->GetFuncMetric(&instr);

    if (func_m) {
      auto instr_stats_m = func_m->mutable_instruction_stats();
      instr_stats_m->set_countarithmeticinst(instr_stats_m->countarithmeticinst() + 1);
    }
  }
};

void IGCMetricImpl::UpdateInstructionStats() {
  CollectInstrData metricPass(this);

  metricPass.visit(pModule);
}

class CollectFuncData : public llvm::InstVisitor<CollectFuncData> {
  IGCMetricImpl *metric;

public:
  CollectFuncData(IGCMetricImpl *metric) { this->metric = metric; }

  void visitDbgVariableIntrinsic(llvm::DbgVariableIntrinsic &dbValInst) { metric->AddVarMetric(&dbValInst); }

  void visitCallInst(llvm::CallInst &callInst) {
    auto calledFuncName = callInst.getCalledFunction()->getName();
    if (calledFuncName.startswith("llvm.dbg") || calledFuncName.startswith("llvm.genx.GenISA.CatchAllDebugLine")) {
      // Ignore debugInfo calls
      return;
    }

    auto func_m = metric->GetFuncMetric(&callInst);
    auto funcCallType = IGC_METRICS::FuncCalls_FuncCallsType::FuncCalls_FuncCallsType_INLINE;

    if (calledFuncName.startswith("__builtin_IB")) {
      funcCallType = IGC_METRICS::FuncCalls_FuncCallsType::FuncCalls_FuncCallsType_LIBRARY;
    } else if (calledFuncName.startswith("llvm.")) {
      funcCallType = IGC_METRICS::FuncCalls_FuncCallsType::FuncCalls_FuncCallsType_LIBRARY;
    } else if (calledFuncName.startswith("__builtin_spirv")) {
      funcCallType = IGC_METRICS::FuncCalls_FuncCallsType::FuncCalls_FuncCallsType_LIBRARY;
    }

    // Get data about this function call
    IGC_METRICS::FuncCalls *callFunc_m = nullptr;

    for (int i = 0; i < func_m->functioncalls_size(); ++i) {
      if (calledFuncName.equals(func_m->functioncalls(i).name())) {
        // For case if we have already record created
        callFunc_m = (IGC_METRICS::FuncCalls *)&func_m->functioncalls(i);
        callFunc_m->set_count(callFunc_m->count() + 1);
        break;
      }
    }
    if (callFunc_m == nullptr) {
      // For new case
      callFunc_m = func_m->add_functioncalls();
      callFunc_m->set_name(calledFuncName.str());
      callFunc_m->set_count(1);
      callFunc_m->set_type(funcCallType);
    }

    auto instr_call_dbinfo = callInst.getDebugLoc();
    auto callFunc_m_loc = callFunc_m->add_funccallloc();
    metric->FillCodeRef(callFunc_m_loc, instr_call_dbinfo);
  }
};

void IGCMetricImpl::GetFunctionData(IGC_METRICS::Function *func_m, llvm::Function &func) {
  CollectFuncData metricPass(this);

  metricPass.visit(func);

  for (auto bb_i = func.begin(); bb_i != func.end(); ++bb_i) {
    llvm::BasicBlock *bb = &*bb_i;

    if (bb->hasName() && (bb->getName().startswith("if.then") || bb->getName().startswith("if.else"))) {
      auto func_cfg_stats = func_m->mutable_cfg_stats();
      auto ifelse_m = func_cfg_stats->add_ifelsebr_stats();

      ifelse_m->set_countbrtaken((int)std::distance(bb->users().begin(), bb->users().end()));

      llvm::DebugLoc *dbLoc = nullptr;
      auto instr_i = bb->end();

      // Start checking from the terminator instruction
      // then go to the previous one
      do {
        instr_i--;
        // We need to get debug info
        dbLoc = (llvm::DebugLoc *)&instr_i->getDebugLoc();
      } while (*dbLoc && instr_i != bb->begin());

      if (*dbLoc) {
        auto ifelse_block_db = llvm::dyn_cast<DILexicalBlock>(dbLoc->getScope());
        FillCodeRef(ifelse_m->mutable_brloc(), ifelse_block_db);
      }
    }
  }
}

int IGCMetricImpl::CountInstInFunc(llvm::Function *pFunc) {
  unsigned int instCount = 0;
  for (auto bb = pFunc->begin(); bb != pFunc->end(); ++bb) {
    instCount += (unsigned int)std::distance(bb->begin(), bb->end());
  }

  return instCount;
}

llvm::CallInst *IGCMetricImpl::makeTrackCall(const char *const trackCall, ArrayRef<Value *> Args,
                                             llvm::Instruction *insertAfter) {
  auto &ctx = pModule->getContext();
  auto atrr = llvm::AttributeList::get(ctx, {{0, llvm::Attribute::get(ctx, llvm::Attribute::AttrKind::OptimizeNone)},
                                             {1, llvm::Attribute::get(ctx, llvm::Attribute::AttrKind::NoInline)},
                                             {2, llvm::Attribute::get(ctx, llvm::Attribute::AttrKind::ReadNone)},
                                             {3, llvm::Attribute::get(ctx, llvm::Attribute::AttrKind::NoAlias)}});

  auto funcType = llvm::FunctionType::get(llvm::Type::getVoidTy(ctx),
                                          {llvm::Type::getMetadataTy(ctx), llvm::Type::getMetadataTy(ctx)}, false);

  auto funcVal = pModule->getOrInsertFunction(trackCall, funcType, atrr);

  llvm::Function *func = llvm::cast<llvm::Function>(funcVal);

  return llvm::CallInst::Create(func, Args, "", insertAfter->getNextNode());
}

IGC_METRICS::VarInfo *IGCMetricImpl::AddVarMetric(llvm::DbgVariableIntrinsic *pInstr) {
  int DILocalVariableIndex = 1;
  if (llvm::isa<llvm::DbgValueInst>(pInstr) && pInstr->arg_size() == 4) {
    DILocalVariableIndex = 2;
  }

  llvm::MDNode *pNode = nullptr;
  llvm::Value *value = nullptr;
  llvm::MetadataAsValue *MDValue = llvm::dyn_cast<llvm::MetadataAsValue>(pInstr->getArgOperand(0));
  llvm::MetadataAsValue *MDDILocalVariable =
      llvm::dyn_cast<llvm::MetadataAsValue>(pInstr->getArgOperand(DILocalVariableIndex));
  IGC_METRICS::VarInfo *var_m = nullptr;

  if (MDValue != nullptr) {
    llvm::ValueAsMetadata *vAsMD = llvm::dyn_cast<llvm::ValueAsMetadata>(MDValue->getMetadata());
    pNode = llvm::cast<DILocalVariable>(MDDILocalVariable->getMetadata());
    if (vAsMD != nullptr && vAsMD->getValue() != nullptr) {
      value = vAsMD->getValue();
    }
  }

  if (pNode && value) {
    // Map only once user variable in metrics
    if (map_Var.find(MDDILocalVariable) == map_Var.end()) {
      // Extract debuginfo variable data to metrics
      llvm::DIVariable *diVar = llvm::cast<llvm::DIVariable>(pNode);

      std::string varName = diVar->getName().str();

      auto func_m = GetFuncMetric(pInstr);

      var_m = func_m->add_variables();
      var_m->set_name(varName);
      FillCodeRef(var_m->mutable_varloc(), diVar);

      // If variable is an argument of function/kernel
      // make a record of this information in metric too
      if (llvm::isa<llvm::Argument>(value)) {
        auto func_arg_m = func_m->add_arguments();
        func_arg_m->set_name(varName);
        func_arg_m->set_compilesize((int32_t)value->getType()->getPrimitiveSizeInBits());
        func_arg_m->set_type(IGC_METRICS::KernelArg_ArgumentType::KernelArg_ArgumentType_EXPLICIT);
      }

      // The user variables are identified by the MDAsVal,
      // because they are unique in whole module and aren't
      // recreated/changed during compilation of shader (it doesn't change pointer)
      map_Var[MDDILocalVariable].var_m = var_m;

      // Map in code any refrence to this variable (for metrics)
      // by adding callinstr llvm.igc.metric.trackValue in module for tracking
      makeTrackCall(funcTrackValue, {MDValue, MDDILocalVariable}, pInstr);

      map_Var[MDDILocalVariable].varDILocalVariable = MDDILocalVariable;
    } else {
      var_m = map_Var[MDDILocalVariable].var_m;
    }

    return var_m;
  }
  // Cannot find associated user-variable with this instruction
  return nullptr;
}

IGC_METRICS::VarInfo *IGCMetricImpl::GetVarMetric(llvm::Value *pValue) {
  auto data = GetVarData(pValue);
  return data ? data->var_m : nullptr;
}

struct VarData *IGCMetricImpl::GetVarData(llvm::Value *pValue) {
  // iterate over all user variables which we found
  for (auto trackerVal_i = map_Var.begin(); trackerVal_i != map_Var.end(); ++trackerVal_i) {
    // The user variables are identified by the MDAsVal,
    // because they are unique in whole module and aren't
    // recreated/changed during compilation of shader (it doesn't change pointer)
    llvm::MetadataAsValue *tracker = (*trackerVal_i).first;

    for (auto user : tracker->users()) {
      // Check all usage of this MDAsVal and look for the metrics call functions:
      // call void @llvm.igc.metric.trackValue(...)
      if (llvm::CallInst *callInst = dyn_cast<llvm::CallInst>(user)) {
        if (callInst->getCalledFunction()->getName().startswith(funcTrackValue)) {
          llvm::Value *trackedValue = callInst->getArgOperand(0);

          llvm::MetadataAsValue *MDValue = llvm::dyn_cast<llvm::MetadataAsValue>(trackedValue);
          llvm::ValueAsMetadata *vAsMD = llvm::dyn_cast<llvm::ValueAsMetadata>(MDValue->getMetadata());

          // Found tracker which looks at defined user variable
          if (vAsMD && vAsMD->getValue() == pValue) {
            return &map_Var[tracker];
          }
        }
      }
    }
  }
  // Cannot find associated user-variable with this instruction/value
  return nullptr;
}

IGC_METRICS::Function *IGCMetricImpl::GetFuncMetric(const llvm::Instruction *const pInstr) {
  return GetFuncMetric((llvm::Instruction *)pInstr);
}

IGC_METRICS::Function *IGCMetricImpl::GetFuncMetric(llvm::Instruction *pInstr) {
  auto func_m = GetFuncMetric(&pInstr->getDebugLoc());
  if (func_m != nullptr) {
    return func_m;
  }
  return GetFuncMetric(pInstr->getParent()->getParent());
}

IGC_METRICS::Function *IGCMetricImpl::GetFuncMetric(llvm::Loop *pLoop) {
  auto func_m = GetFuncMetric(pLoop->getStartLoc());
  if (func_m != nullptr) {
    return func_m;
  }
  return GetFuncMetric(pLoop->getBlocks()[0]->getParent());
}

IGC_METRICS::Function *IGCMetricImpl::GetFuncMetric(llvm::Function *pFunc) {
  return GetFuncMetric(pFunc->getSubprogram());
}

IGC_METRICS::Function *IGCMetricImpl::GetFuncMetric(const llvm::DebugLoc *pLoc) {
  if (pLoc == nullptr || !pLoc->get()) {
    return nullptr;
  }
  const MDNode *Scope = pLoc->getInlinedAtScope();
  if (auto *SP = llvm::getDISubprogram(Scope)) {
    return GetFuncMetric(SP);
  }
  return nullptr;
}

IGC_METRICS::Function *IGCMetricImpl::GetFuncMetric(const llvm::DebugLoc &pLoc) {
  if (!pLoc.get()) {
    return nullptr;
  }
  const MDNode *Scope = pLoc.getInlinedAtScope();
  if (auto *SP = llvm::getDISubprogram(Scope)) {
    return GetFuncMetric(SP);
  }
  return nullptr;
}

IGC_METRICS::Function *IGCMetricImpl::GetFuncMetric(llvm::DISubprogram *pFunc) {
  if (map_Func.find(pFunc) == map_Func.end()) {
    return nullptr;
  } else {
    return map_Func[pFunc];
  }
}

void IGCMetricImpl::FillCodeRef(IGC_METRICS::CodeRef *codeRef, llvm::DILexicalBlock *Loc) {
  if (Loc == nullptr || Loc->getDirectory().empty() || Loc->getFilename().empty()) {
    return;
  }
  FillCodeRef(codeRef, GetFullPath(Loc->getDirectory().str(), Loc->getFilename().str()), Loc->getLine());
}

void IGCMetricImpl::FillCodeRef(IGC_METRICS::CodeRef *codeRef, llvm::DISubprogram *Loc) {
  if (Loc == nullptr || Loc->getDirectory().empty() || Loc->getFilename().empty()) {
    return;
  }
  FillCodeRef(codeRef, GetFullPath(Loc->getDirectory().str(), Loc->getFilename().str()), Loc->getLine());
}

void IGCMetricImpl::FillCodeRef(IGC_METRICS::CodeRef *codeRef, llvm::DILocation *Loc) {
  if (Loc == nullptr || Loc->getDirectory().empty() || Loc->getFilename().empty()) {
    return;
  }
  FillCodeRef(codeRef, GetFullPath(Loc->getDirectory().str(), Loc->getFilename().str()), Loc->getLine());
}

void IGCMetricImpl::FillCodeRef(IGC_METRICS::CodeRef *codeRef, llvm::DIVariable *Var) {
  if (Var == nullptr || Var->getDirectory().empty() || Var->getFilename().empty()) {
    return;
  }
  FillCodeRef(codeRef, GetFullPath(Var->getDirectory().str(), Var->getFilename().str()), Var->getLine());
}

void IGCMetricImpl::FillCodeRef(IGC_METRICS::CodeRef *codeRef, const std::string &filePathName, int line) {
  if (filePathName.empty()) {
    return;
  }
  codeRef->set_line(line);
  codeRef->set_pathtofile(filePathName);
}

const std::string IGCMetricImpl::GetFullPath(const char *dir, const char *fileName) {
  return GetFullPath(std::string(dir), std::string(fileName));
}

const std::string IGCMetricImpl::GetFullPath(const std::string &dir, const std::string &fileName) {
  llvm::SmallVector<char, 1024> fileNamebuf;
  llvm::sys::path::append(fileNamebuf, dir);
  llvm::sys::path::append(fileNamebuf, fileName);
  std::string fileNameStr(fileNamebuf.begin(), fileNamebuf.end());
  return fileNameStr;
}

llvm::MetadataAsValue *IGCMetricImpl::makeMDasVal(llvm::Value *Value) {
  llvm::MetadataAsValue *MDValue = llvm::MetadataAsValue::get(Value->getContext(), llvm::ValueAsMetadata::get(Value));
  return MDValue;
}

#endif

} // namespace IGCMetrics