-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathPrinterCapstone.cpp
More file actions
4330 lines (3837 loc) · 158 KB
/
Copy pathPrinterCapstone.cpp
File metadata and controls
4330 lines (3837 loc) · 158 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===------------- PrinterCapstone.cpp - Printer Capstone -------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Emits the generated decoder C code for the Capstone.
//
//===----------------------------------------------------------------------===//
#include "Printer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/MC/MCInst.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/TableGen/TableGenBackend.h"
#include <algorithm>
#include <bitset>
#include <unordered_map>
static void emitDefaultSourceFileHeader(raw_ostream &OS) {
OS << "/* Capstone Disassembly Engine, https://www.capstone-engine.org */\n"
<< "/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2022, */\n"
<< "/* Rot127 <unisono@quyllur.org> 2022-2024 */\n"
<< "/* Automatically generated file by Capstone's LLVM TableGen "
"Disassembler "
"Backend. */\n\n"
<< "/* LLVM-commit: <commit> */\n"
<< "/* LLVM-tag: <tag> */\n\n"
<< "/* Do not edit. */\n\n"
<< "/* Capstone's LLVM TableGen Backends: */\n"
<< "/* https://github.com/capstone-engine/llvm-capstone */\n\n";
}
namespace llvm {
/// Prints `namespace <name> {` and `} // end namespace <name>` to the output
/// stream. If Name == "" it emits an anonymous namespace.
void PrinterCapstone::emitNamespace(std::string const &Name, bool Begin,
std::string const &Comment,
bool Newline) const {
return;
}
/// Prints
/// ```
/// #if <ARG>
/// ```
/// and
/// `#endif // <ARG>`
/// Used to control inclusion of a code block via a macro definition.
void PrinterCapstone::emitPPIf(std::string const &Arg, bool Begin,
bool Newline) const {
if (Begin) {
OS << "#if " << Arg << "\n";
} else {
OS << "#endif // " << Arg << (Newline ? "\n\n" : "\n");
}
}
/// Prints
/// ```
/// #ifdef <Name>
/// #undef <Name>
/// ```
/// and
/// `#endif // <Name>`
/// Used to control inclusion of a code block via a macro definition.
void PrinterCapstone::emitIncludeToggle(std::string const &Name, bool Begin,
bool Newline, bool UndefAtEnd) const {
std::set<std::string> Ignore = {"GET_REGINFO_TARGET_DESC",
"GET_REGINFO_HEADER",
"GET_MNEMONIC_CHECKER",
"GET_MNEMONIC_SPELL_CHECKER",
"GET_MATCHER_IMPLEMENTATION",
"GET_SUBTARGET_FEATURE_NAME",
"GET_REGISTER_MATCHER",
"GET_OPERAND_DIAGNOSTIC_TYPES",
"GET_ASSEMBLER_HEADER",
"GET_INSTRINFO_HEADER",
"GET_INSTRINFO_HELPER_DECLS",
"GET_INSTRINFO_HELPERS",
"GET_INSTRINFO_CTOR_DTOR",
"GET_INSTRINFO_OPERAND_ENUM",
"GET_INSTRINFO_NAMED_OPS",
"GET_INSTRINFO_OPERAND_TYPES_ENUM",
"GET_INSTRINFO_OPERAND_TYPE",
"GET_INSTRINFO_MEM_OPERAND_SIZE",
"GET_INSTRINFO_LOGICAL_OPERAND_SIZE_MAP",
"GET_INSTRINFO_LOGICAL_OPERAND_TYPE_MAP",
"GET_INSTRINFO_MC_HELPER_DECLS",
"GET_INSTRINFO_MC_HELPERS",
"ENABLE_INSTR_PREDICATE_VERIFIER",
"GET_GENISTRINFO_MC_HELPERS",
"GET_SUBTARGETINFO_MC_DESC",
"GET_SUBTARGETINFO_TARGET_DESC",
"GET_SUBTARGETINFO_HEADER",
"GET_SUBTARGETINFO_CTOR",
"GET_STIPREDICATE_DECLS_FOR_MC_ANALYSIS",
"GET_STIPREDICATE_DEFS_FOR_MC_ANALYSIS",
"GET_SUBTARGETINFO_MACRO"};
if (Ignore.find(Name) != Ignore.end())
return;
if (Begin) {
OS << "#ifdef " << Name << "\n";
if (!UndefAtEnd)
OS << "#undef " << Name << "\n\n";
} else {
if (UndefAtEnd)
OS << "#undef " << Name << "\n";
OS << "#endif // " << Name << (Newline ? "\n\n" : "\n");
}
}
void PrinterCapstone::emitIfNotDef(std::string const &Name, bool Begin) const {
if (Name == "NDEBUG")
return;
if (Begin) {
OS << "#ifndef " << Name << "\n";
} else {
OS << "#endif // " << Name << "\n\n";
}
}
void PrinterCapstone::regInfoEmitSourceFileHeader(
std::string const &Desc) const {
static unsigned Count = 0;
if (Count > 0) {
// Only emit it once at the beginning.
return;
}
emitDefaultSourceFileHeader(OS);
++Count;
}
void writeFile(std::string Filename, std::string const &Str) {
std::error_code EC;
ToolOutputFile InsnMapFile(Filename, EC, sys::fs::OF_Text);
if (EC)
PrintFatalNote("Could no write \"" + Filename + "\" Error:\n" +
EC.message());
InsnMapFile.os() << Str;
InsnMapFile.keep();
}
// runEnums - Print out enum values for all of the registers.
void PrinterCapstone::regInfoEmitEnums(CodeGenTarget const &Target,
CodeGenRegBank const &Bank) const {
std::string CSRegEnumStr;
raw_string_ostream CSRegEnum(CSRegEnumStr);
emitDefaultSourceFileHeader(CSRegEnum);
const auto &Registers = Bank.getRegisters();
// Register enums are stored as uint16_t in the tables. Make sure we'll fit.
assert(Registers.size() <= 0xffff && "Too many regs to fit in tables");
emitIncludeToggle("GET_REGINFO_ENUM", true);
StringRef TargetName = Target.getName();
OS << "enum {\n " << TargetName << "_NoRegister,\n";
CSRegEnum << "\t" << TargetName.upper() << "_REG_INVALID = 0,\n";
for (const auto &Reg : Registers) {
OS << " " << TargetName << "_" << Reg.getName() << " = " << Reg.EnumValue
<< ",\n";
CSRegEnum << "\t" << TargetName.upper() << "_REG_" << Reg.getName().upper()
<< " = " << Reg.EnumValue << ",\n";
}
assert(Registers.size() == Registers.back().EnumValue &&
"Register enum value mismatch!");
OS << " NUM_TARGET_REGS // " << Registers.size() + 1 << "\n";
OS << "};\n";
CSRegEnum << "\t" << TargetName.upper() << "_REG_ENDING, // "
<< Registers.size() + 1 << "\n";
writeFile(TargetName.str() + "GenCSRegEnum.inc", CSRegEnumStr);
const auto &RegisterClasses = Bank.getRegClasses();
if (!RegisterClasses.empty()) {
// RegisterClass enums are stored as uint16_t in the tables.
assert(RegisterClasses.size() <= 0xffff &&
"Too many register classes to fit in tables");
OS << "\n// Register classes\n\n";
OS << "enum {\n";
for (const auto &RC : RegisterClasses)
OS << " " << TargetName << "_" << RC.getName() << "RegClassID"
<< " = " << RC.EnumValue << ",\n";
OS << "\n};\n";
}
const std::vector<Record *> &RegAltNameIndices =
Target.getRegAltNameIndices();
// If the only definition is the default NoRegAltName, we don't need to
// emit anything.
if (RegAltNameIndices.size() > 1) {
OS << "\n// Register alternate name indices\n\n";
OS << "enum {\n";
for (unsigned I = 0, E = RegAltNameIndices.size(); I != E; ++I)
OS << " " << TargetName << "_" << RegAltNameIndices[I]->getName()
<< ",\t// " << I << "\n";
OS << " NUM_TARGET_REG_ALT_NAMES = " << RegAltNameIndices.size() << "\n";
OS << "};\n";
}
auto &SubRegIndices = Bank.getSubRegIndices();
if (!SubRegIndices.empty()) {
OS << "\n// Subregister indices\n\n";
std::string const Namespace = SubRegIndices.front().getNamespace();
OS << "enum {\n " << TargetName << "_NoSubRegister,\n";
unsigned I = 0;
for (const auto &Idx : SubRegIndices)
OS << " " << TargetName << "_" << Idx.getName() << ",\t// " << ++I
<< "\n";
OS << " " << TargetName << "_NUM_TARGET_SUBREGS\n};\n";
}
emitIncludeToggle("GET_REGINFO_ENUM", false);
}
static void printDiff16(raw_ostream &OS, int16_t Val) { OS << Val; }
void PrinterCapstone::regInfoEmitRegDiffLists(
std::string const TargetName,
SequenceToOffsetTable<DiffVec> const &DiffSeqs) const {
OS << "static const MCPhysReg " << TargetName << "RegDiffLists[] = {\n";
DiffSeqs.emit(OS, printDiff16);
OS << "};\n\n";
}
void PrinterCapstone::regInfoEmitLaneMaskLists(
std::string const TargetName,
SequenceToOffsetTable<MaskVec> const &LaneMaskSeqs) const {
return;
}
void PrinterCapstone::regInfoEmitSubRegIdxLists(
std::string const TargetName,
SequenceToOffsetTable<SubRegIdxVec, deref<std::less<>>> const
&SubRegIdxSeqs) const {
OS << "static const uint16_t " << TargetName << "SubRegIdxLists[] = {\n";
SubRegIdxSeqs.emit(OS, [](raw_ostream &OS, const CodeGenSubRegIndex *Idx) {
OS << Idx->EnumValue;
});
OS << "};\n\n";
}
void PrinterCapstone::regInfoEmitSubRegIdxSizes(
std::string const TargetName,
std::deque<CodeGenSubRegIndex> const &SubRegIndices) const {
return;
}
void PrinterCapstone::regInfoEmitSubRegStrTable(
std::string const TargetName,
SequenceToOffsetTable<std::string> const &RegStrings) const {
OS << "static const MCRegisterDesc " << TargetName
<< "RegDesc[] = { // Descriptors\n";
OS << " { " << RegStrings.get("") << ", 0, 0, 0, 0, 0 },\n";
}
void PrinterCapstone::regInfoEmitRegDesc(
SequenceToOffsetTable<MaskVec> const &LaneMaskSeqs,
std::deque<CodeGenRegister> const &Regs,
SequenceToOffsetTable<SubRegIdxVec, deref<std::less<>>> const
&SubRegIdxSeqs,
SequenceToOffsetTable<DiffVec> const &DiffSeqs,
SmallVector<SubRegIdxVec, 4> const &SubRegIdxLists,
SmallVector<DiffVec, 4> const &SubRegLists,
SmallVector<DiffVec, 4> const &SuperRegLists,
SmallVector<DiffVec, 4> const &RegUnitLists,
SmallVector<MaskVec, 4> const &RegUnitLaneMasks,
SequenceToOffsetTable<std::string> const &RegStrings) const {
unsigned i = 0;
for (const auto &Reg : Regs) {
unsigned FirstRU = Reg.getNativeRegUnits().find_first();
unsigned Offset = DiffSeqs.get(RegUnitLists[i]);
// The value must be kept in sync with MCRegisterInfo.h.
constexpr unsigned RegUnitBits = 12;
assert(isUInt<RegUnitBits>(FirstRU) && "Too many regunits");
assert(isUInt<32 - RegUnitBits>(Offset) && "Offset is too big");
OS << " { " << RegStrings.get(std::string(Reg.getName())) << ", "
<< DiffSeqs.get(SubRegLists[i]) << ", " << DiffSeqs.get(SuperRegLists[i])
<< ", " << SubRegIdxSeqs.get(SubRegIdxLists[i]) << ", "
<< (Offset << RegUnitBits | FirstRU) << ", "
<< LaneMaskSeqs.get(RegUnitLaneMasks[i]) << " },\n";
++i;
}
OS << "};\n\n";
}
void PrinterCapstone::regInfoEmitRegUnitRoots(
std::string const TargetName, CodeGenRegBank const &RegBank) const {
return;
}
static std::string getQualifiedNameCCS(const Record *R) {
StringRef TargetName;
if (R->getValue("Namespace"))
TargetName = R->getValueAsString("Namespace");
if (TargetName.empty())
return std::string(R->getName());
return TargetName.str() + "_" + R->getName().str();
}
void PrinterCapstone::regInfoEmitRegClasses(
std::list<CodeGenRegisterClass> const &RegClasses,
SequenceToOffsetTable<std::string> &RegClassStrings,
CodeGenTarget const &Target) const {
for (const auto &RC : RegClasses) {
ArrayRef<Record *> const Order = RC.getOrder();
// Give the register class a legal C name if it's anonymous.
const std::string &Name = RC.getName();
RegClassStrings.add(Name);
// Emit the register list now (unless it would be a zero-length array).
if (!Order.empty()) {
OS << " // " << Name << " Register Class...\n"
<< " static const MCPhysReg " << Name << "[] = {\n ";
for (Record *Reg : Order) {
OS << getQualifiedNameCCS(Reg) << ", ";
}
OS << "\n };\n\n";
OS << " // " << Name << " Bit set.\n"
<< " static const uint8_t " << Name << "Bits[] = {\n ";
PrinterBitVectorEmitter BVE;
for (Record *Reg : Order) {
BVE.add(Target.getRegBank().getReg(Reg)->EnumValue);
}
BVE.print(OS);
OS << "\n };\n\n";
}
}
}
void PrinterCapstone::regInfoEmitStrLiteralRegClasses(
std::string const TargetName,
SequenceToOffsetTable<std::string> const &RegClassStrings) const {
return;
}
void PrinterCapstone::regInfoEmitMCRegClassesTable(
std::string const TargetName,
std::list<CodeGenRegisterClass> const &RegClasses,
SequenceToOffsetTable<std::string> &RegClassStrings) const {
OS << "static const MCRegisterClass " << TargetName
<< "MCRegisterClasses[] = {\n";
for (const auto &RC : RegClasses) {
ArrayRef<Record *> const Order = RC.getOrder();
std::string const RCName = Order.empty() ? "nullptr" : RC.getName();
std::string const RCBitsName =
Order.empty() ? "nullptr" : RC.getName() + "Bits";
std::string const RCBitsSize =
Order.empty() ? "0" : "sizeof(" + RCBitsName + ")";
assert(isInt<8>(RC.CopyCost) && "Copy cost too large.");
// For Capstone we are only interested in:
// RegClass Name, Size group and bit size
OS << " { " << RCName << ", " << RCBitsName << ", " << RCBitsSize
<< " },\n";
}
OS << "};\n\n";
}
void PrinterCapstone::regInfoEmitRegEncodingTable(
std::string const TargetName,
std::deque<CodeGenRegister> const &Regs) const {
OS << "static const uint16_t " << TargetName;
OS << "RegEncodingTable[] = {\n";
// Add entry for NoRegister
OS << " 0,\n";
for (const auto &RE : Regs) {
Record *Reg = RE.TheDef;
BitsInit *BI = Reg->getValueAsBitsInit("HWEncoding");
uint64_t Value = 0;
for (unsigned I = 0, Ie = BI->getNumBits(); I != Ie; ++I) {
if (BitInit *B = dyn_cast<BitInit>(BI->getBit(I)))
Value |= (uint64_t)B->getValue() << I;
}
OS << " " << Value << ",\n";
}
OS << "};\n"; // End of HW encoding table
return;
}
void PrinterCapstone::regInfoEmitMCRegInfoInit(
std::string const TargetName, CodeGenRegBank const &RegBank,
std::deque<CodeGenRegister> const &Regs,
std::list<CodeGenRegisterClass> const &RegClasses,
std::deque<CodeGenSubRegIndex> const &SubRegIndices) const {
return;
}
void PrinterCapstone::regInfoEmitInfoDwarfRegsRev(
StringRef const &Namespace, DwarfRegNumsVecTy &DwarfRegNums,
unsigned MaxLength, bool IsCtor) const {
return;
}
void PrinterCapstone::regInfoEmitInfoDwarfRegs(StringRef const &Namespace,
DwarfRegNumsVecTy &DwarfRegNums,
unsigned MaxLength,
bool IsCtor) const {
return;
}
void PrinterCapstone::regInfoEmitInfoRegMapping(StringRef const &Namespace,
unsigned MaxLength,
bool IsCtor) const {
return;
}
void PrinterCapstone::regInfoEmitHeaderIncludes() const { return; }
void PrinterCapstone::regInfoEmitHeaderExternRegClasses(
std::list<CodeGenRegisterClass> const &RegClasses) const {
return;
}
void PrinterCapstone::regInfoEmitHeaderDecl(
std::string const &TargetName, std::string const &ClassName,
bool SubRegsPresent, bool DeclareGetPhysRegBaseClass) const {
return;
}
void PrinterCapstone::regInfoEmitExternRegClassesArr(
std::string const &TargetName) const {
return;
}
void PrinterCapstone::regInfoEmitVTSeqs(
SequenceToOffsetTable<std::vector<MVT::SimpleValueType>> const &VTSeqs)
const {
return;
}
void PrinterCapstone::regInfoEmitSubRegIdxTable(
std::deque<CodeGenSubRegIndex> const &SubRegIndices) const {
return;
}
void PrinterCapstone::regInfoEmitRegClassInfoTable(
std::list<CodeGenRegisterClass> const &RegClasses,
SequenceToOffsetTable<std::vector<MVT::SimpleValueType>> const &VTSeqs,
CodeGenHwModes const &CGH, unsigned NumModes) const {
return;
}
void PrinterCapstone::regInfoEmitSubClassMaskTable(
std::list<CodeGenRegisterClass> const &RegClasses,
SmallVector<IdxList, 8> &SuperRegIdxLists,
SequenceToOffsetTable<IdxList, deref<std::less<>>> &SuperRegIdxSeqs,
std::deque<CodeGenSubRegIndex> const &SubRegIndices,
BitVector &MaskBV) const {
return;
}
void PrinterCapstone::regInfoEmitSuperRegIdxSeqsTable(
SequenceToOffsetTable<IdxList, deref<std::less<>>> const &SuperRegIdxSeqs)
const {
return;
}
void PrinterCapstone::regInfoEmitSuperClassesTable(
std::list<CodeGenRegisterClass> const &RegClasses) const {
return;
}
void PrinterCapstone::regInfoEmitRegClassMethods(
std::list<CodeGenRegisterClass> const &RegClasses,
std::string const &TargetName) const {
return;
}
void PrinterCapstone::regInfomitRegClassInstances(
std::list<CodeGenRegisterClass> const &RegClasses,
SequenceToOffsetTable<IdxList, deref<std::less<>>> const &SuperRegIdxSeqs,
SmallVector<IdxList, 8> const &SuperRegIdxLists,
std::string const &TargetName) const {
return;
}
void PrinterCapstone::regInfoEmitRegClassTable(
std::list<CodeGenRegisterClass> const &RegClasses) const {
return;
}
void PrinterCapstone::regInfoEmitCostPerUseTable(
std::vector<unsigned> const &AllRegCostPerUse, unsigned NumRegCosts) const {
return;
}
void PrinterCapstone::regInfoEmitInAllocatableClassTable(
llvm::BitVector const &InAllocClass) const {
return;
}
void PrinterCapstone::regInfoEmitRegExtraDesc(std::string const &TargetName,
unsigned NumRegCosts) const {
return;
}
void PrinterCapstone::regInfoEmitSubClassSubRegGetter(
std::string const &ClassName, unsigned SubRegIndicesSize,
std::deque<CodeGenSubRegIndex> const &SubRegIndices,
std::list<CodeGenRegisterClass> const &RegClasses,
CodeGenRegBank &RegBank) const {
return;
}
void PrinterCapstone::regInfoEmitRegClassWeight(
CodeGenRegBank const &RegBank, std::string const &ClassName) const {
return;
}
void PrinterCapstone::regInfoEmitRegUnitWeight(
CodeGenRegBank const &RegBank, std::string const &ClassName,
bool RegUnitsHaveUnitWeight) const {
return;
}
void PrinterCapstone::regInfoEmitGetNumRegPressureSets(
std::string const &ClassName, unsigned NumSets) const {
return;
}
void PrinterCapstone::regInfoEmitGetRegPressureTables(
CodeGenRegBank const &RegBank, std::string const &ClassName,
unsigned NumSets) const {
return;
}
void PrinterCapstone::regInfoEmitRCSetsTable(
std::string const &ClassName, unsigned NumRCs,
SequenceToOffsetTable<std::vector<int>> const &PSetsSeqs,
std::vector<std::vector<int>> const &PSets) const {
return;
}
void PrinterCapstone::regInfoEmitGetRegUnitPressureSets(
SequenceToOffsetTable<std::vector<int>> const &PSetsSeqs,
CodeGenRegBank const &RegBank, std::string const &ClassName,
std::vector<std::vector<int>> const &PSets) const {
return;
}
void PrinterCapstone::regInfoEmitExternTableDecl(
std::string const &TargetName) const {
return;
}
void PrinterCapstone::regInfoEmitRegClassInit(
std::string const &TargetName, std::string const &ClassName,
CodeGenRegBank const &RegBank,
std::list<CodeGenRegisterClass> const &RegClasses,
std::deque<CodeGenRegister> const &Regs, unsigned SubRegIndicesSize) const {
return;
}
void PrinterCapstone::regInfoEmitSaveListTable(
Record const *CSRSet, SetTheory::RecVec const *Regs) const {
return;
}
void PrinterCapstone::regInfoEmitRegMaskTable(std::string const &CSRSetName,
BitVector &Covered) const {
return;
}
void PrinterCapstone::regInfoEmitGetRegMasks(
std::vector<Record *> const &CSRSets, std::string const &ClassName) const {
return;
}
void PrinterCapstone::regInfoEmitGPRCheck(
std::string const &ClassName,
std::list<CodeGenRegisterCategory> const &RegCategories) const {
return;
}
void PrinterCapstone::regInfoEmitFixedRegCheck(
std::string const &ClassName,
std::list<CodeGenRegisterCategory> const &RegCategories) const {
return;
}
void PrinterCapstone::regInfoEmitArgRegCheck(
std::string const &ClassName,
std::list<CodeGenRegisterCategory> const &RegCategories) const {
return;
}
void PrinterCapstone::regInfoEmitGetRegMaskNames(
std::vector<Record *> const &CSRSets, std::string const &ClassName) const {
return;
}
void PrinterCapstone::regInfoEmitGetFrameLowering(
std::string const &TargetName) const {
return;
}
void PrinterCapstone::regInfoEmitComposeSubRegIndicesImplHead(
std::string const &ClName) const {
return;
}
void PrinterCapstone::regInfoEmitComposeSubRegIndicesImplBody(
SmallVector<SmallVector<CodeGenSubRegIndex *, 4>, 4> const &Rows,
unsigned SubRegIndicesSize, SmallVector<unsigned, 4> const &RowMap) const {
return;
}
void PrinterCapstone::regInfoEmitLaneMaskComposeSeq(
SmallVector<SmallVector<MaskRolPair, 1>, 4> const &Sequences,
SmallVector<unsigned, 4> const &SubReg2SequenceIndexMap,
std::deque<CodeGenSubRegIndex> const &SubRegIndices) const {
return;
}
void PrinterCapstone::regInfoEmitComposeSubRegIdxLaneMask(
std::string const &ClName,
std::deque<CodeGenSubRegIndex> const &SubRegIndices) const {
return;
}
void PrinterCapstone::regInfoEmitComposeSubRegIdxLaneMaskRev(
std::string const &ClName,
std::deque<CodeGenSubRegIndex> const &SubRegIndices) const {
return;
}
void PrinterCapstone::regInfoEmitIsConstantPhysReg(
std::deque<CodeGenRegister> const &Regs,
std::string const &ClassName) const {}
void patchQualifier(std::string &Code) {
while (Code.find("::") != std::string::npos)
Code = Regex("::").sub("_", Code);
}
void patchNullptr(std::string &Code) {
while (Code.find("nullptr") != std::string::npos)
Code = Regex("nullptr").sub("NULL", Code);
}
void patchIsGetImmReg(std::string &Code) {
Regex Pattern = Regex("[a-zA-Z0-9_]+\\.(get|is)(Imm|Reg)\\(\\)");
SmallVector<StringRef> Matches;
while (Pattern.match(Code, &Matches)) {
StringRef Match = Matches[0];
StringRef Op = Match.split(".").first;
StringRef Func = Match.split(".").second.trim(")");
Code = Code.replace(Code.find(Match), Match.size(),
"MCOperand_" + Func.str() + Op.str() + ")");
}
}
static std::string handleDefaultArg(const std::string &TargetName,
std::string &Code) {
// Default values of the template function arguments.
// Tuple is (function name, default argument, number of arguments)
static SmallVector<std::string> Default0 = {"0"};
static SmallVector<std::string> Default1 = {"1"};
static SmallVector<std::string> Default01 = {"0", "1"};
static SmallVector<std::tuple<std::string, SmallVector<std::string> &, int>>
AArch64TemplFuncWithDefaults = {// Default is 1
{"printVectorIndex", Default1, 1},
// Default is false == 0
{"printPrefetchOp", Default0, 1},
// Default is 0
{"printSVERegOp", Default0, 1},
{"printMatrixIndex", Default1, 1}};
static SmallVector<std::tuple<std::string, SmallVector<std::string> &, int>>
LoongArchTemplFuncWithDefaults = {
// Default is 0
{"decodeSImmOperand", Default0, 2},
{"decodeUImmOperand", Default0, 2},
};
static SmallVector<std::tuple<std::string, SmallVector<std::string> &, int>>
MipsTemplFuncWithDefaults = {
{"DecodeSImmWithOffsetAndScale", Default01, 3},
{"printUImm", Default0, 2},
};
SmallVector<std::tuple<std::string, SmallVector<std::string> &, int>>
*TemplFuncWithDefaults;
if (StringRef(TargetName).upper() == "AARCH64")
TemplFuncWithDefaults = &AArch64TemplFuncWithDefaults;
else if (StringRef(TargetName).upper() == "LOONGARCH")
TemplFuncWithDefaults = &LoongArchTemplFuncWithDefaults;
else if (StringRef(TargetName).upper() == "MIPS")
TemplFuncWithDefaults = &MipsTemplFuncWithDefaults;
else
return Code;
for (std::tuple Func : *TemplFuncWithDefaults) {
// Search for function where default argument is not passed
// e.g. printVectorIndex -> printVectorIndex_1
// e.g. decodeSImmOperand<1> -> decodeSImmOperand_1_0
auto Name = std::get<0>(Func);
auto DefaultArg = std::get<1>(Func);
auto ExpectedArgCount = std::get<2>(Func);
SmallVector<StringRef> Matches;
while (Regex(Name + "(<[0-9a-zA-Z,]*>)?($|\\()").match(Code, &Matches)) {
StringRef Arg = Matches[1];
// Count the number of passed arguments
int ActualArgCount = 0;
unsigned DefIdx = 0;
if (!Arg.empty() && Arg != "<>") {
ActualArgCount = Arg.count(',') + 1;
if (ActualArgCount == ExpectedArgCount) {
break;
}
}
std::string NewArg;
NewArg = Regex("<").sub("", Arg);
NewArg = Regex(">").sub("", NewArg);
NewArg = Regex(",").sub("_", NewArg);
while (ActualArgCount < ExpectedArgCount) {
assert(DefIdx < DefaultArg.size() &&
"Out of bounds for predefined template arguments");
// Add default argument
if (NewArg.empty()) {
// e.g. printVectorIndex -> printVectorIndex_1
NewArg += DefaultArg[DefIdx++];
ActualArgCount++;
} else {
// e.g. decodeSImmOperand<1> -> decodeSimmOperand_1_0
NewArg += "_";
NewArg += DefaultArg[DefIdx++];
ActualArgCount++;
}
}
assert(ActualArgCount == ExpectedArgCount &&
"Inconsistent template arg patching.");
StringRef Match = Matches[0];
if (Match.ends_with("(")) {
Code = Regex(Name + "(<[0-9a-zA-Z,]*>)?\\(")
.sub(Name + "_" + NewArg + "(", Code);
} else {
Code =
Regex(Name + "(<[0-9a-zA-Z,]*>)?$").sub(Name + "_" + NewArg, Code);
}
}
}
return Code;
}
/// @brief Replaces template arguments of the form <arg, arg, ...> and similar.
/// It also handles default arguments for certain hard-coded function names.
///
/// @param TargetName The current target name
/// @param Code The C++ code.
static void patchTemplateArgs(const std::string &TargetName,
std::string &Code) {
Code = handleDefaultArg(TargetName, Code);
size_t B = Code.find_first_of("<");
size_t E = Code.find(">");
while (B != std::string::npos && E != std::string::npos) {
std::string const &DecName = Code.substr(0, B);
std::string Args = Code.substr(B + 1, E - B - 1);
std::string Rest = Code.substr(E + 1);
if (Args.empty()) {
return;
}
while ((Args.find("true") != std::string::npos) ||
(Args.find("false") != std::string::npos) ||
(Args.find(",") != std::string::npos) ||
(Args.find("'") != std::string::npos) ||
(Args.find("-") != std::string::npos)) {
Args = Regex("true").sub("1", Args);
Args = Regex("false").sub("0", Args);
Args = Regex(" *, *").sub("_", Args);
Args = Regex("'").sub("", Args);
Args = Regex("-").sub("minus", Args);
}
Code = DecName + "_" + Args + Rest;
E = Code.find(">");
B = Code.find_first_of("<");
}
}
static void patchPrintOperandAddr(std::string &Decoder) {
bool ContainsAddress = Decoder.find("Address") != std::string::npos;
bool PrintOperand = Decoder.find("printOperand(") != std::string::npos;
bool PrintAdrLabelOperand =
Decoder.find("printAdrLabelOperand") != std::string::npos;
if (!ContainsAddress) {
return;
}
StringRef Find;
StringRef Replace;
if (PrintOperand) {
Find = "printOperand\\(([^\n]+Address.+)";
Replace = "printOperandAddr(\\1";
} else if (PrintAdrLabelOperand) {
Find = "printAdrLabelOperand([^\n]+Address.+)";
Replace = "printAdrLabelOperandAddr\\1";
} else {
llvm_unreachable("Unhandled printOperand function.");
}
Decoder = Regex(Find).sub(Replace, Decoder);
}
std::string PrinterCapstone::translateToC(std::string const &TargetName,
std::string const &Code) {
std::string PatchedCode(Code);
patchQualifier(PatchedCode);
patchNullptr(PatchedCode);
patchIsGetImmReg(PatchedCode);
patchTemplateArgs(TargetName, PatchedCode);
if (TargetName == "ARM" || TargetName == "Alpha") {
patchPrintOperandAddr(PatchedCode);
}
return PatchedCode;
}
void PrinterCapstone::decoderEmitterEmitOpDecoder(raw_ostream &DecoderOS,
const OperandInfo &Op) const {
unsigned const Indent = 4;
DecoderOS.indent(Indent) << GuardPrefix;
DecoderOS << translateToC(TargetName, Op.Decoder);
DecoderOS << "(MI, insn, Address, Decoder)" << GuardPostfix << " { "
<< (Op.HasCompleteDecoder ? "" : "*DecodeComplete = false; ")
<< "return " << ReturnFail << "; } \\\n";
}
void PrinterCapstone::decoderEmitterEmitOpBinaryParser(
raw_ostream &DecOS, const OperandInfo &OpInfo) const {
unsigned const Indent = 4;
const std::string &Decoder = translateToC(TargetName, OpInfo.Decoder);
bool const UseInsertBits = OpInfo.numFields() != 1 || OpInfo.InitValue != 0;
if (UseInsertBits) {
DecOS.indent(Indent) << "tmp = 0x";
DecOS.write_hex(OpInfo.InitValue);
DecOS << "; \\\n";
}
for (const EncodingField &EF : OpInfo) {
DecOS.indent(Indent);
if (UseInsertBits)
DecOS << "tmp |= ";
else
DecOS << "tmp = ";
DecOS << "fieldname(insn, " << EF.Base << ", " << EF.Width << ')';
if (UseInsertBits)
DecOS << " << " << EF.Offset;
else if (EF.Offset != 0)
DecOS << " << " << EF.Offset;
DecOS << "; \\\n";
}
if (Decoder != "") {
DecOS.indent(Indent) << GuardPrefix << Decoder
<< "(MI, tmp, Address, Decoder)" << GuardPostfix
<< " { "
<< (OpInfo.HasCompleteDecoder
? ""
: "*DecodeComplete = false; ")
<< "return " << ReturnFail << "; } \\\n";
} else {
DecOS.indent(Indent) << "MCOperand_CreateImm0(MI, tmp); \\\n";
}
}
bool PrinterCapstone::decoderEmitterEmitPredicateMatchAux(
const Init &Val, bool ParenIfBinOp, raw_ostream &PredOS) const {
if (auto *D = dyn_cast<DefInit>(&Val)) {
if (!D->getDef()->isSubClassOf("SubtargetFeature"))
return true;
std::string Subtarget =
StringRef(PredicateNamespace).str() + "_" + D->getAsString();
PredOS << PredicateNamespace << "_getFeatureBits(Inst->csh->mode, "
<< Subtarget << ")";
return false;
}
if (auto *D = dyn_cast<DagInit>(&Val)) {
std::string const Op = D->getOperator()->getAsString();
if (Op == "not" && D->getNumArgs() == 1) {
PredOS << '!';
return decoderEmitterEmitPredicateMatchAux(*D->getArg(0), true, PredOS);
}
if ((Op == "any_of" || Op == "all_of") && D->getNumArgs() > 0) {
bool const Paren =
D->getNumArgs() > 1 && std::exchange(ParenIfBinOp, true);
if (Paren)
PredOS << '(';
ListSeparator LS(Op == "any_of" ? " || " : " && ");
for (auto *Arg : D->getArgs()) {
PredOS << LS;
if (decoderEmitterEmitPredicateMatchAux(*Arg, ParenIfBinOp, PredOS))
return true;
}
if (Paren)
PredOS << ')';
return false;
}
}
return true;
}
bool PrinterCapstone::decoderEmitterEmitPredicateMatch(
raw_ostream &PredOS, const ListInit *Predicates, unsigned Opc) const {
bool IsFirstEmission = true;
for (unsigned I = 0; I < Predicates->size(); ++I) {
Record *Pred = Predicates->getElementAsRecord(I);
if (!Pred->getValue("AssemblerMatcherPredicate"))
continue;
if (!isa<DagInit>(Pred->getValue("AssemblerCondDag")->getValue()))
continue;
if (!IsFirstEmission)
PredOS << " && ";
if (decoderEmitterEmitPredicateMatchAux(
*Pred->getValueAsDag("AssemblerCondDag"), Predicates->size() > 1,
PredOS))
PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!");
IsFirstEmission = false;
}
return !Predicates->empty();
}
void PrinterCapstone::decoderEmitterEmitFieldFromInstruction() const {
OS << "// Helper function for extracting fields from encoded instructions.\n"
<< "#define FieldFromInstruction(fname, InsnType) \\\n"
<< "static InsnType fname(InsnType insn, unsigned startBit, unsigned "
"numBits) \\\n"
<< "{ \\\n"
<< " InsnType fieldMask; \\\n"
<< " if (numBits == sizeof(InsnType) * 8) \\\n"
<< " fieldMask = (InsnType)(-1LL); \\\n"
<< " else \\\n"
<< " fieldMask = (((InsnType)1 << numBits) - 1) << startBit; \\\n"
<< " return (insn & fieldMask) >> startBit; \\\n"
<< "}\n\n";
}
void PrinterCapstone::decoderEmitterEmitInsertBits() const { return; }
// Helper to propagate SoftFail status. Returns false if the status is Fail;
// callers are expected to early-exit in that condition. (Note, the '&' operator
// is correct to propagate the values of this enum; see comment on 'enum
// DecodeStatus'.)
void PrinterCapstone::decoderEmitterEmitCheck() const {
OS << "static bool Check(DecodeStatus *Out, const DecodeStatus In) {\n"
<< " *Out = (DecodeStatus) (*Out & In);\n"
<< " return *Out != MCDisassembler_Fail;\n"
<< "}\n\n";
}
void PrinterCapstone::decoderEmitterEmitDecodeInstruction(
bool IsVarLenInst) const {
OS << "#define DecodeInstruction(fname, fieldname, decoder, InsnType) \\\n"
<< "static DecodeStatus fname(const uint8_t DecodeTable[], "
"MCInst *MI, \\\n"
<< " InsnType insn, uint64_t "
"Address, const void *Decoder) { \\\n"
<< " const uint8_t *Ptr = DecodeTable; \\\n"
<< " uint64_t CurFieldValue = 0; \\\n"
<< " DecodeStatus S = MCDisassembler_Success; \\\n"
<< " while (true) { \\\n"
<< " switch (*Ptr) { \\\n"
<< " default: \\\n"
<< " return MCDisassembler_Fail; \\\n"
<< " case MCD_OPC_ExtractField: { \\\n"
<< " unsigned Start = *++Ptr; \\\n"
<< " unsigned Len = *++Ptr; \\\n"
<< " ++Ptr; \\\n";
if (IsVarLenInst) {
OS << " makeUp(insn, Start + Len); \\\n";
}
OS << " CurFieldValue = fieldname(insn, Start, Len); \\\n"
<< " break; \\\n"
<< " } \\\n"
<< " case MCD_OPC_FilterValue: { \\\n"
<< " /* Decode the field value. */ \\\n"
<< " unsigned Len; \\\n"
<< " uint64_t Val = decodeULEB128(++Ptr, &Len); \\\n"
<< " Ptr += Len; \\\n"
<< " /* NumToSkip is a plain 24-bit integer. */ \\\n"
<< " unsigned NumToSkip = *Ptr++; \\\n"
<< " NumToSkip |= (*Ptr++) << 8; \\\n"