-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathCounterCompiler.cs
2499 lines (2181 loc) · 111 KB
/
CounterCompiler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// =====================================================================
// <copyright file="CounterCompiler.cs" company="Advanced Micro Devices, Inc.">
// Copyright (c) 2011-2023 Advanced Micro Devices, Inc. All rights reserved.
// </copyright>
// <author>
// AMD Developer Tools Team
// </author>
// <summary>
// Given an ordered internal counter definition file and the derived (e.g.: public)
// definitions, produces c++ code to define them for the run-time.
// </summary>
// =====================================================================
namespace PublicCounterCompiler
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using GpaTools;
using static GpaTools.Gpa;
using CounterGroup = System.String;
using CounterName = System.String;
using CounterDescription = System.String;
/// <summary>
/// Compiles the derived counters definitions into C++ files.
/// </summary>
public class CounterCompiler
{
/// <summary>
/// Derived counter input file
/// </summary>
public class DerivedCounterFileInput
{
/// <summary>
/// Root filename
/// </summary>
public string rootFilename;
/// <summary>
/// compiler type string
/// </summary>
public string compiler_type_str;
/// <summary>
/// Compiler input path
/// </summary>
public string compilerInputPath;
/// <summary>
/// Auto-generated compiler file input path
/// </summary>
public string autoGenCompilerInputFilePath;
/// <summary>
/// Derived counter h/cpp file output directory
/// </summary>
public string outputDirectory;
/// <summary>
/// Counter list output directory
/// </summary>
public string counterListOutputDirectory;
/// <summary>
/// Test output directory
/// </summary>
public string testOutputDirectory;
}
/// <summary>
/// Derived counter file input
/// </summary>
public DerivedCounterFileInput derivedCounterFileInput = null;
/// <summary>
/// A map of Counter Group to a map of counter name to documentation info for Graphics Counters
/// </summary>
private Dictionary<GfxGeneration, Dictionary<CounterGroup, Dictionary<string, DerivedCounterDef>>>
docInfoMapGraphicsByGeneration =
new Dictionary<GfxGeneration, Dictionary<CounterGroup, Dictionary<string, DerivedCounterDef>>>();
/// <summary>
/// A map of Counter Group to a map of counter name to documentation info for Graphics Counters
/// </summary>
private Dictionary<GfxGeneration, Dictionary<CounterGroup, Dictionary<string, DerivedCounterDef>>>
docInfoMapComputeByGeneration =
new Dictionary<GfxGeneration, Dictionary<CounterGroup, Dictionary<string, DerivedCounterDef>>>();
/// <summary>
/// Indicates if this app is being run as a console app (true) or UI app (false)
/// </summary>
public bool isConsoleApp = true;
/// <summary>
/// List of global GPU generation internal counters
/// </summary>
private List<InternalCounterDef> globalInternalCounterList = null;
/// <summary>
/// Gets a value indicating whether invalid counters should be considered errors, or if they should be ignored.
/// </summary>
/// <returns>True to ignore the invalid counters; false if they should be considered errors.</returns>
public bool IgnoreInvalidCounters()
{
if (isConsoleApp)
{
// by default, running from the console will ignore invalid counters
return true;
}
return Form1.GetIgnoreInvalidCounters;
}
/// <summary>
/// Sets directories based on the supplied API and generation and
/// compiles the derived counters
/// </summary>
/// <param name="api">The API to compile counters for</param>
/// <param name="generation">The HW generation</param>
/// <param name="infoHandler">Called in response to an informational message</param>
/// <param name="errorHandler">Called in response to a error condition</param>
/// <returns>true on success, false if there were any errors</returns>
public bool CompileCounters(
string api,
string generation,
Func<string, bool> infoHandler,
Func<string, bool> errorHandler
)
{
try
{
string baseGfxFileName = derivedCounterFileInput.rootFilename + GpaTools.Gpa.counterFileNamePrefix + api.ToLower() + "_" + generation.ToLower() + ".txt";
string[] baseGfxFileNames = Directory.GetFiles(derivedCounterFileInput.autoGenCompilerInputFilePath, baseGfxFileName);
// Iterate over files that match the base of the counter name's generation file
string searchForAsicFilename = derivedCounterFileInput.rootFilename + GpaTools.Gpa.counterFileNamePrefix + api.ToLower() + "_" + generation.ToLower() + "_*.txt";
string[] asicfileNames = Directory.GetFiles(derivedCounterFileInput.autoGenCompilerInputFilePath, searchForAsicFilename);
List<String> fileNames = new List<string>();
foreach (string counterNamesFile in baseGfxFileNames)
{
fileNames.Add(counterNamesFile);
}
foreach (string counterNamesFile in asicfileNames)
{
fileNames.Add(counterNamesFile);
}
if (fileNames.Count == 0)
{
infoHandler("No files found at:" + derivedCounterFileInput.compilerInputPath + " matching:" + baseGfxFileName);
return false;
}
List<string> asicSpecificFiles = new List<string>();
string baseCounterDefFile = "";
foreach (string counterNamesFile in fileNames)
{
// Determine the specific ASIC, if any
string baseFilename = Path.GetFileNameWithoutExtension(counterNamesFile);
bool isBaseDeriveCounterDefFileParsing = false;
int asicIndex = baseFilename.IndexOf(generation.ToLower());
string asic = baseFilename.Substring(asicIndex + generation.Length);
if (!string.IsNullOrEmpty(asic))
{
asic = asic.Substring(1, asic.Length - 1);
asicSpecificFiles.Add(asic);
isBaseDeriveCounterDefFileParsing = false;
}
else
{
isBaseDeriveCounterDefFileParsing = true;
}
// Suffix
string suffix = string.Empty;
if (api.ToLower() == "cl")
{
suffix = "compute_";
}
string derivedCounterDefsFile = derivedCounterFileInput.compilerInputPath +
derivedCounterFileInput.rootFilename +
GpaTools.Gpa.counterDefinitionsStr +
suffix +
generation.ToLower() +
(!String.IsNullOrEmpty(asic) ? "_" + asic.ToLower() : "") +
".txt";
string section = api + generation;
if (isBaseDeriveCounterDefFileParsing && String.IsNullOrEmpty(baseCounterDefFile))
{
baseCounterDefFile = derivedCounterDefsFile;
}
// Some files may not exist for certain combinations of APIs and architectures
if (!File.Exists(derivedCounterDefsFile))
{
if (!isBaseDeriveCounterDefFileParsing && !String.IsNullOrEmpty(baseCounterDefFile))
{
infoHandler("Info: Unable to find file " + derivedCounterDefsFile + " Using base counter def file.");
derivedCounterDefsFile = baseCounterDefFile;
}
else
{
infoHandler("Info: Unable to find file " + derivedCounterDefsFile);
return true;
}
}
if (LoadFilesAndGenerateOutput(derivedCounterFileInput.rootFilename,
counterNamesFile,
derivedCounterDefsFile,
derivedCounterFileInput.outputDirectory,
derivedCounterFileInput.counterListOutputDirectory,
derivedCounterFileInput.testOutputDirectory,
api,
generation,
asic,
infoHandler,
errorHandler))
{
infoHandler(derivedCounterFileInput.rootFilename + Gpa.counterDefinitionsStr + section + asic + ".cpp / .h written out to:" + derivedCounterFileInput.outputDirectory);
}
else
{
return false;
}
}
// Generate section + ASIC file
bool retVal = GenerateSectionAsicFiles(derivedCounterFileInput.rootFilename, api, generation, derivedCounterFileInput.outputDirectory, asicSpecificFiles, infoHandler, errorHandler);
if (retVal)
{
infoHandler("Counter generation completed successfully");
}
else
{
errorHandler("Counter generation failed");
}
return retVal;
}
catch (Exception e)
{
errorHandler(e.ToString());
return false;
}
}
/// <summary>
/// Generates ASIC files
/// </summary>
/// <param name="rootFilename">Root filename for ASIC files.</param>
/// <param name="api">API being generated.</param>
/// <param name="generation">GPU generation.</param>
/// <param name="outputDirectory">Output directory.</param>
/// <param name="asicSpecificFiles">List of ASIC-specific files.</param>
/// <param name="infoHandler">Called in response to an informational message</param>
/// <param name="errorHandler">Called in response to a error condition</param>
/// <returns>True is files are successfully loaded and generated.</returns>
private bool GenerateSectionAsicFiles(
string rootFilename,
string api,
string generation,
string outputDirectory,
List<string> asicSpecificFiles,
Func<string, bool> infoHandler,
Func<string, bool> errorHandler
)
{
string section = api + "_" + generation;
string filename = outputDirectory + rootFilename + Gpa.counterDefinitionsStr +
api.ToLower() + "_" + generation.ToLower() + "_" + "asics.h";
// Write header file
infoHandler("Writing ASIC header to " + filename);
StreamWriter includeFile = null;
try
{
includeFile = new StreamWriter(filename);
}
catch
{
errorHandler("Failed to open file for writing: " + filename);
return false;
}
string baseDirForHeaderGuard = "GPA";
includeFile.WriteLine("//==============================================================================");
includeFile.WriteLine("// Copyright (c) 2010-{0} Advanced Micro Devices, Inc. All rights reserved.", DateTime.Today.Year);
includeFile.WriteLine("/// @author AMD Developer Tools Team");
includeFile.WriteLine("/// @file");
includeFile.WriteLine("/// @brief {0} Counter Definitions ASIC file for {1}", derivedCounterFileInput.compiler_type_str, section.ToUpper());
includeFile.WriteLine("//==============================================================================");
includeFile.WriteLine();
includeFile.WriteLine("#ifndef {0}_AUTO_GEN_COUNTER_GEN_{1}COUNTER_DEFINITIONS_{2}_ASICS_H_", baseDirForHeaderGuard, rootFilename.ToUpper(), section.ToUpper());
includeFile.WriteLine("#define {0}_AUTO_GEN_COUNTER_GEN_{1}COUNTER_DEFINITIONS_{2}_ASICS_H_", baseDirForHeaderGuard, rootFilename.ToUpper(), section.ToUpper());
includeFile.WriteLine();
includeFile.WriteLine("//*** Note, this is an auto-generated file. Do not edit. Execute {0}CounterCompiler to rebuild.", derivedCounterFileInput.compiler_type_str);
includeFile.WriteLine();
includeFile.WriteLine("#include \"gpu_perf_api_counter_generator/gpa_derived_counter.h\"");
includeFile.WriteLine();
includeFile.WriteLine("#include \"auto_generated/gpu_perf_api_counter_generator/gpa_hw_counter_{0}_{1}.h\"", api.ToLower(), generation.ToLower());
includeFile.WriteLine();
foreach (string asic in asicSpecificFiles)
{
includeFile.WriteLine("#include \"auto_generated/gpu_perf_api_counter_generator/{0}{1}{2}_{3}_{4}.h\"", rootFilename, counterDefinitionsStr, api.ToLower(), generation.ToLower(), asic.ToLower());
}
if (0 != asicSpecificFiles.Count)
{
includeFile.WriteLine();
}
includeFile.WriteLine("namespace {0}_asics", section.ToLower());
includeFile.WriteLine("{");
includeFile.WriteLine(" /// @brief Updates default GPU generation derived counters with ASIC specific derived counters if available.");
includeFile.WriteLine(" ///");
includeFile.WriteLine(" /// @param [in] desired_generation Hardware generation currently in use.");
includeFile.WriteLine(" /// @param [in] asic_type The ASIC type that is currently in use.");
includeFile.WriteLine(" /// @param [out] c Returned set of derived counters, if available.");
includeFile.WriteLine(" ///");
includeFile.WriteLine(" /// @return True if the ASIC matched one available, and c was updated.");
includeFile.WriteLine(" inline void Update{0}AsicSpecificCounters(GDT_HW_GENERATION desired_generation, GDT_HW_ASIC_TYPE asic_type, GpaDerivedCounters& c)", derivedCounterFileInput.compiler_type_str);
includeFile.WriteLine(" {");
if (asicSpecificFiles.Count == 0)
{
includeFile.WriteLine(" UNREFERENCED_PARAMETER(desired_generation);");
includeFile.WriteLine(" UNREFERENCED_PARAMETER(asic_type);");
includeFile.WriteLine(" UNREFERENCED_PARAMETER(c);");
}
else
{
includeFile.WriteLine(" // Override max block events first so we could chain these if we want");
includeFile.WriteLine(" counter_{0}::OverrideMaxBlockEvents(asic_type);", section.ToLower());
includeFile.WriteLine();
for (int i = 0; i < asicSpecificFiles.Count; ++i)
{
includeFile.WriteLine(" if ({0}_{1}::Update{2}AsicSpecificCounters(desired_generation, asic_type, c))", section.ToLower(), asicSpecificFiles[i].ToLower(), derivedCounterFileInput.compiler_type_str);
includeFile.WriteLine(" {");
includeFile.WriteLine(" return;");
includeFile.WriteLine(" }");
includeFile.WriteLine();
}
}
includeFile.WriteLine(" }");
includeFile.WriteLine();
includeFile.WriteLine("} // namespace " + section.ToLower() + "asics");
includeFile.WriteLine();
includeFile.WriteLine("#endif // {0}_AUTO_GEN_COUNTER_GEN_{1}COUNTER_DEFINITIONS_{2}_ASICS_H_", baseDirForHeaderGuard, rootFilename.ToUpper(), section.ToUpper());
includeFile.Close();
return true;
}
/// <summary>
/// Formats a counter error for output
/// </summary>
/// <param name="counterName">Derived counter name</param>
/// <param name="component">Component of the formula that is referenced</param>
/// <param name="index">Index of the component of the formula that is referenced</param>
/// <param name="errorMessage">Error message</param>
private void OutputCounterError(string counterName, string component, int index, string errorMessage, Func<string, bool> errorHandler)
{
errorHandler(counterName + " - " + errorMessage + " " + component + " at index " + index);
}
/// <summary>
/// Validates the counter formula and referenced hardware counters
/// </summary>
/// <param name="counter">Derived counter to validate</param>
/// <returns>True if the formula and referenced counters are correct, otherwise false.</returns>
private bool ValidateFormulaAndReferencedCounter(DerivedCounterDef counter, Func<string, bool> infoHandler, Func<string, bool> errorHandler)
{
bool retVal = true;
string comp = counter.Comp.ToLower();
string[] components = comp.Split(',');
// Basic validation of comp formula
// Validate count of counters vs. those referenced in formula
// Validate that all counter references are 1, or multiple of 4
Stack<string> rpnStack = new Stack<string>();
int componentIndex = -1;
foreach (string component in components)
{
++componentIndex;
// Empty
if (string.IsNullOrEmpty(component))
{
OutputCounterError(counter.Name, component, componentIndex, "empty comp component", errorHandler);
retVal = false;
break;
}
// Range hardware counter reference
bool isNumeric = false;
if (component.Contains(".."))
{
int startingCounter = 0;
isNumeric = int.TryParse(component, out startingCounter);
if (!isNumeric)
{
OutputCounterError(counter.Name, component, componentIndex, "invalid hardware counter range", errorHandler);
retVal = false;
break;
}
int ellipsisIndex = component.IndexOf("..");
if (ellipsisIndex < 0)
{
OutputCounterError(counter.Name, component, componentIndex, "invalid hardware counter range", errorHandler);
retVal = false;
break;
}
int endingCounter = 0;
isNumeric = int.TryParse(component.Substring(ellipsisIndex + 2), out endingCounter);
if (!isNumeric)
{
OutputCounterError(counter.Name, component, componentIndex, "invalid hardware counter range", errorHandler);
retVal = false;
break;
}
if (endingCounter <= startingCounter)
{
OutputCounterError(counter.Name, component, componentIndex, "invalid hardware counter range", errorHandler);
retVal = false;
break;
}
if (((endingCounter - startingCounter) + 1) % 4 != 0)
{
OutputCounterError(counter.Name, component, componentIndex, "hardware counter range is not a multiple of 4", errorHandler);
retVal = false;
break;
}
for (int i = startingCounter; i <= endingCounter; ++i)
{
rpnStack.Push(i.ToString());
var hardwareCounter = counter.GetCounter(i);
if (hardwareCounter == null)
{
OutputCounterError(counter.Name, component, componentIndex, "reference to undefined hardware counter index", errorHandler);
retVal = false;
break;
}
hardwareCounter.Referenced = true;
}
continue;
}
// Singleton hardware counter reference
int index;
isNumeric = int.TryParse(component, out index);
if (isNumeric)
{
rpnStack.Push(component);
if (index < 0 || index >= counter.GetCounterCount())
{
OutputCounterError(counter.Name, component, componentIndex, "reference to out of range hardware counter index", errorHandler);
retVal = false;
break;
}
var hardwareCounter = counter.GetCounter(index);
if (hardwareCounter == null)
{
OutputCounterError(counter.Name, component, componentIndex, "reference to undefined hardware counter index", errorHandler);
retVal = false;
break;
}
hardwareCounter.Referenced = true;
continue;
}
// Numeric
if (component.Substring(0, 1) == "(")
{
string n = component.Substring(1, component.Length - 2);
float value = 0;
isNumeric = float.TryParse(n, out value);
if (!isNumeric)
{
OutputCounterError(counter.Name, component, componentIndex, "invalid numeric value", errorHandler);
retVal = false;
break;
}
rpnStack.Push(component);
continue;
}
// Operator
switch (component)
{
case "+":
case "-":
case "*":
case "/":
{
if (rpnStack.Count < 2)
{
OutputCounterError(counter.Name, component, componentIndex, "stack has insufficient entries (pop 2) for", errorHandler);
retVal = false;
break;
}
string result = rpnStack.Pop();
result = component + result;
result = rpnStack.Pop() + result;
rpnStack.Push(result);
}
continue;
case "ifnotzero":
{
if (rpnStack.Count < 3)
{
OutputCounterError(counter.Name, component, componentIndex, "stack has insufficient entries (pop 3) for", errorHandler);
retVal = false;
break;
}
string result = rpnStack.Pop();
// the format is: false,true,condition,ifnotzero
// detect if condition is a constant value
if (result.Contains("("))
{
OutputCounterError(counter.Name, component, componentIndex, "ifnotzero conditional expression is constant", errorHandler);
retVal = false;
break;
}
result += "!=0 ? ";
result += rpnStack.Pop();
result += " : ";
result += rpnStack.Pop();
rpnStack.Push(result);
}
continue;
case "comparemax6":
{
if (rpnStack.Count < 12)
{
OutputCounterError(counter.Name, component, componentIndex, "stack has insufficient entries (pop 12) for", errorHandler);
retVal = false;
break;
}
string result = string.Empty;
result = "max(";
for (int i = 0; i < 6; ++i)
{
result = rpnStack.Pop();
if (i != 5)
{
result += ", ";
}
}
result = ") ? ret(";
for (int i = 0; i < 6; ++i)
{
result = rpnStack.Pop();
if (i != 5)
{
result += ", ";
}
}
result = ")";
rpnStack.Push(result);
}
continue;
case "comparemax4":
{
if (rpnStack.Count < 8)
{
OutputCounterError(counter.Name, component, componentIndex, "stack has insufficient entries (pop 8) for", errorHandler);
retVal = false;
break;
}
string result = string.Empty;
result = "max(";
for (int i = 0; i < 4; ++i)
{
result = rpnStack.Pop();
if (i != 3)
{
result += ", ";
}
}
result = ") ? ret(";
for (int i = 0; i < 4; ++i)
{
result = rpnStack.Pop();
if (i != 3)
{
result += ", ";
}
}
result = ")";
rpnStack.Push(result);
}
continue;
case "comparemax2":
{
if (rpnStack.Count < 4)
{
OutputCounterError(counter.Name, component, componentIndex, "stack has insufficient entries (pop 4) for", errorHandler);
retVal = false;
break;
}
string result = string.Empty;
result = "max(";
for (int i = 0; i < 2; ++i)
{
result = rpnStack.Pop();
if (i != 1)
{
result += ", ";
}
}
result = ") ? ret(";
for (int i = 0; i < 2; ++i)
{
result = rpnStack.Pop();
if (i != 1)
{
result += ", ";
}
}
result = ")";
rpnStack.Push(result);
}
continue;
case "num_shader_engines":
case "num_shader_arrays":
case "num_simds":
case "su_clocks_prim":
case "num_prim_pipes":
case "ts_freq":
case "num_cus":
rpnStack.Push(component);
continue;
}
// Special handling for [sum, min, max, avg, mul, div]{N}
if (component.Length >= 3)
{
var prefix3 = component.Substring(0, 3);
if ("sum" == prefix3
|| "sub" == prefix3
|| "max" == prefix3
|| "min" == prefix3
|| "avg" == prefix3)
{
int popCount = 0;
string strCount = component.Substring(3);
if (string.IsNullOrEmpty(strCount))
{
popCount = 2;
}
else
{
isNumeric = int.TryParse(strCount, out popCount);
if (!isNumeric)
{
OutputCounterError(counter.Name, component, componentIndex, prefix3 + " operator with invalid component count", errorHandler);
retVal = false;
break;
}
if (rpnStack.Count < popCount)
{
OutputCounterError(counter.Name, component, componentIndex, "attempt to " + prefix3 + " more components than exist on stack", errorHandler);
retVal = false;
break;
}
}
for (int i = 0; i < popCount; ++i)
{
rpnStack.Pop();
}
rpnStack.Push("result:" + component);
continue;
}
// Special handling for vector multiply and divide [vecMul, vecDiv, vecSum, vecSub]{N}
prefix3 = component.Substring(0, 3);
if ("vec" == prefix3)
{
int popCount = 0;
string strCount = component.Substring(6);
if (string.IsNullOrEmpty(strCount))
{
popCount = 2;
}
else
{
isNumeric = int.TryParse(strCount, out popCount);
if (!isNumeric)
{
OutputCounterError(counter.Name, component, componentIndex, prefix3 + " operator with invalid component count", errorHandler);
retVal = false;
break;
}
if (rpnStack.Count < popCount)
{
OutputCounterError(counter.Name, component, componentIndex, "attempt to " + prefix3 + " more components than exist on stack", errorHandler);
retVal = false;
break;
}
}
for (int i = 0; i < (2 * popCount); ++i)
{
rpnStack.Pop();
}
for (int i = 0; i < popCount; ++i)
{
rpnStack.Push("result:" + component + i.ToString());
}
continue;
}
}
// Special handling for dividesum{N}
if (component.StartsWith("dividesum"))
{
int popCount = 0;
string strCount = component.Substring(9);
if (string.IsNullOrEmpty(strCount))
{
OutputCounterError(counter.Name, component, componentIndex, "dividesum operator missing number of components", errorHandler);
retVal = false;
break;
}
isNumeric = int.TryParse(strCount, out popCount);
if (!isNumeric)
{
OutputCounterError(counter.Name, component, componentIndex, "dividesum operator with invalid component count", errorHandler);
retVal = false;
break;
}
if (rpnStack.Count < popCount)
{
OutputCounterError(counter.Name, component, componentIndex, "attempt to dividesum more components than exist on stack", errorHandler);
retVal = false;
break;
}
for (int i = 0; i < popCount; ++i)
{
rpnStack.Pop();
}
rpnStack.Push("result:" + component);
continue;
}
// scalarSub[n], scalarMul[n] scalarDiv[n]
if (component.StartsWith("scalarmul")
|| component.StartsWith("scalardiv")
|| component.StartsWith("scalarsub"))
{
int popCount = 0;
string strCount = component.Substring(9);
if (string.IsNullOrEmpty(strCount))
{
OutputCounterError(counter.Name, component, componentIndex, "scalar operator missing number of components", errorHandler);
retVal = false;
break;
}
isNumeric = int.TryParse(strCount, out popCount);
if (!isNumeric)
{
OutputCounterError(counter.Name, component, componentIndex, "scalar operator with invalid component count", errorHandler);
retVal = false;
break;
}
popCount += 1;
if (rpnStack.Count < popCount)
{
OutputCounterError(counter.Name, component, componentIndex, "not enough components on the stack for the specified scalar operator", errorHandler);
retVal = false;
break;
}
for (int i = 0; i < popCount; ++i)
{
rpnStack.Pop();
}
for (int i = 0; i < (popCount - 1); ++i)
{
rpnStack.Push("result:" + component + i.ToString());
}
continue;
}
// Unknown component - error
OutputCounterError(counter.Name, component, componentIndex, "unknown formula component", errorHandler);
return false;
}
// Validate stack contains a single result
if (rpnStack.Count != 1)
{
errorHandler(counter.Name + " stack incorrectly contains " + rpnStack.Count.ToString() + " entries instead a single result");
retVal = false;
}
// Validate all hardware counters were referenced
int counterIndex = 0;
foreach (var hardwareCounter in counter.GetCounters())
{
if (hardwareCounter.Referenced == false)
{
if (hardwareCounter.Name.StartsWith("SPI") && (hardwareCounter.Name.Contains("PERF_PS_CTL_BUSY")
|| hardwareCounter.Name.Contains("PERF_PS_BUSY")))
{
infoHandler("Warning:" + counter.Name + " unreferenced block instance counter " + hardwareCounter.Name + " at index "
+ counterIndex + ". This is required for some counter definitions.");
}
else
{
errorHandler(counter.Name + " unreferenced block instance counter " + hardwareCounter.Name + " at index " + counterIndex);
retVal = false;
}
}
++counterIndex;
}
return retVal;
}
/// <summary>
/// Validates the formula and referenced counters
/// </summary>
/// <param name="publicCounterList">List of public counter to validate</param>
/// <returns>True if the formula and referenced counters are correct, otherwise false.</returns>
private bool ValidateFormulaAndReferencedCounters(ref List<DerivedCounterDef> counters, Func<string, bool> infoHandler, Func<string, bool> errorHandler)
{
bool retVal = true;
foreach (DerivedCounterDef counter in counters)
{
retVal &= ValidateFormulaAndReferencedCounter(counter, infoHandler, errorHandler);
}
return retVal;
}
/// <summary>
/// Generates output file of GPU counter data by API and ASIC for use in documentation, etc.
/// </summary>
/// <param name="outputCsv">True to output the counter name and description only.</param>
/// <param name="derivedCounterList">List of derived counters.</param>
/// <param name="internalCounterList">List of internal counters.</param>
/// <param name="outputDir">Output directory.</param>
/// <param name="api">API being generated.</param>
/// <param name="generation">GPU generation.</param>
/// <param name="asic">Optional ASIC name.</param>
/// <returns>True is files are successfully loaded and generated.</returns>
private void GenerateDerivedCounterDocFile(
bool outputCsv,
ref List<DerivedCounterDef> derivedCounterList,
ref List<InternalCounterDef> internalCounterList,
string outputDir,
string api,
string generation,
string asic,
Func<string, bool> infoHandler,
Func<string, bool> errorHandler
)
{
// Ignore generating ASIC-specific docs for now, as the public counters are identical for the user.
bool asicSpecific = !string.IsNullOrEmpty(asic);
if (asicSpecific)
{
return;
}
StreamWriter docStream = null;
string docFilePath;
docFilePath = outputDir + api + generation + asic + (outputCsv ? ".csv" : ".txt");
try
{
docStream = new StreamWriter(docFilePath);
}
catch
{
errorHandler("Failed to open file for writing: " + docStream);
return;
}
docStream.WriteLine("API: " + api);
docStream.WriteLine("GPU: " + generation + asic);
docStream.WriteLine("Counters: " + derivedCounterList.Count);
docStream.WriteLine("Date: " + String.Format("{0:d MMM yyyy h:mm tt}", DateTime.Now));
docStream.WriteLine();
foreach (var counter in derivedCounterList)
{
if (asicSpecific && !DerivedCounterReferencesAsicRegisters(ref internalCounterList, counter))
{
continue;
}
if (outputCsv)
{
string desc = counter.Desc.Replace(',', ' ');
docStream.WriteLine(counter.Name + "," + counter.Usage + "," + desc);
}
else
{
docStream.WriteLine(counter.Name);
docStream.WriteLine(counter.Usage);
docStream.WriteLine(counter.Desc);
docStream.WriteLine(counter.CompReadable);
docStream.WriteLine();
}
}
docStream.Close();
infoHandler("Counter Doc file written: " + docFilePath);
}
/// <summary>
/// Adds information to the counter info structure that will be used to generate counter documentation.
/// </summary>
/// <param name="derivedCounterList">List of public counters.</param>
/// <param name="generation">GPU generation.</param>
/// <param name="docInfoMap">the counter info structure in which to add information</param>
private void AddInfoToRSTDocInfo(
ref List<DerivedCounterDef> derivedCounterList,
string generation,
Dictionary<GfxGeneration, Dictionary<CounterGroup, Dictionary<string, DerivedCounterDef>>> docInfoMap,
Func<string, bool> infoHandler
)
{
GfxGeneration gfxGen = GfxGeneration.Unknown;
if ("Gfx11" == generation)
{
gfxGen = GfxGeneration.Gfx11;
}
else if ("Gfx103" == generation)