forked from novt-vtable-less-compiler/novt-llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNoVTAbiBuilder.cpp
2170 lines (1971 loc) · 92.7 KB
/
NoVTAbiBuilder.cpp
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
#include "llvm/Transforms/IPO/NoVTAbiBuilder.h"
#include <utility>
#include <set>
#include <algorithm>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/Format.h>
#include <queue>
#include <fstream>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Linker/Linker.h>
using namespace llvm;
#define with_debug_output 0
#define dout if (with_debug_output) llvm::errs()
#define advanced_loop_detection 0
#define seconds_since(start) (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start).count())
namespace {
const bool BUILD_TRAPS = true;
const bool BUILD_TRAPS_VBASE_OFFSET = false;
const bool BUILD_NOINLINE = false;
const bool BUILD_NOOPT_TRAMPOLINES = BUILD_NOINLINE && false;
const bool BUILD_OPTIMIZE = true;
const int BUILD_INSTRUMENTATION = 0; // 0=off, 1=lite, 2=full, 3=counting sizes
std::chrono::high_resolution_clock::time_point compilerStart = std::chrono::high_resolution_clock::now();
class DefClass;
class DefClassIdent;
std::vector<DefClass *> getInheritancePath(DefClassIdent *ident);
raw_ostream &operator<<(raw_ostream &OS, const DefClassIdent &ident);
struct InheritanceDefinition {
DefClass *cls;
int offset;
int tmp_scratch; // used by different algorithms, non-permanent
InheritanceDefinition(DefClass *cls, int offset) : cls(cls), offset(offset) {}
};
void parseIntToIntMap(std::map<int, int> &map, const std::string &idmap) {
std::string buffer = idmap;
size_t pos = 0;
int key = 0;
bool parseKey = true;
while (!buffer.empty()) {
if (parseKey) {
key = std::stoi(buffer, &pos, 10);
} else {
map[key] = std::stoi(buffer, &pos, 10);
}
buffer = buffer.substr(pos + 1);
parseKey = !parseKey;
}
}
struct CVtable {
std::vector<std::string> symbols;
DefClass *base;
DefClass *layout;
int offset;
std::map<int, int> cvtableIndexToLayoutClassOffset;
CVtable(const std::string &symbol, DefClass *base, DefClass *layout, int offset, const std::string &idmap)
: symbols({symbol}), base(base), layout(layout), offset(offset) {
parseIntToIntMap(cvtableIndexToLayoutClassOffset, idmap);
}
};
class DefClass {
public:
std::string name;
std::vector<InheritanceDefinition> bases;
std::vector<InheritanceDefinition> children;
std::vector<InheritanceDefinition> vbases;
std::vector<InheritanceDefinition> vchildren;
std::vector<DefClassIdent *> idents;
std::vector<DefClassIdent *> construction_idents;
std::map<DefClass *, std::pair<int, int>> virtualIdentRanges; // [from, to) index in "idents"
std::map<std::pair<std::string, int>, Function *> definitions; // (function name, thunk offset) => definition
std::string vtableSymbol = "";
std::map<int, int> vtableIdMap;
std::vector<CVtable> cvtables;
bool has_virtual_functions = false;
explicit DefClass(std::string name) : name(std::move(name)) {}
void addBase(DefClass *base, int offset) {
for (auto b: bases) {
if (b.cls == base)
return;
}
bases.emplace_back(base, offset);
base->children.emplace_back(this, -offset);
}
void addVBase(DefClass *base, int offset) {
for (auto b: vbases) {
if (b.cls == base)
return;
}
vbases.emplace_back(base, offset);
base->vchildren.emplace_back(this, -offset);
}
void sortThings() {
auto comp = [](InheritanceDefinition d1, InheritanceDefinition d2) {
if (d1.offset == d2.offset)
return d1.tmp_scratch < d2.tmp_scratch;
return d1.offset < d2.offset;
};
for (size_t i = 0; i < vbases.size(); i++) {
vbases[i].tmp_scratch = i;
}
std::sort(vbases.begin(), vbases.end(), comp);
for (size_t i = 0; i < bases.size(); i++) {
bases[i].tmp_scratch = i;
}
std::sort(bases.begin(), bases.end(), comp);
}
void setVtable(const std::string &symbol, const std::string &idmap) {
vtableSymbol = symbol;
parseIntToIntMap(vtableIdMap, idmap);
}
/**
* symbol = "base-in-layout"
* @param symbol
* @param base
* @param layout
* @param offset
*/
void addCVTable(const std::string &symbol, DefClass *base, DefClass *layout, int offset,
const std::string &idmap) {
for (auto &cvtable: cvtables) {
if (cvtable.base == base && cvtable.layout == layout && cvtable.offset == offset) {
cvtable.symbols.push_back(symbol);
return;
}
}
cvtables.emplace_back(symbol, base, layout, offset, idmap);
}
bool isVirtual() {
if (!definitions.empty() || !vbases.empty() || has_virtual_functions)
return true;
for (auto &base: bases) {
if (base.cls->isVirtual())
return true;
}
return false;
}
/**
*
* @param funcname
* @param path
* @param offset offset from the current position in the class to this class beginning
* @param layoutClass (optional) class used to calculate the layout of vbases (for cvtables)
* @param offsetToLayoutClass offset from beginning of my current class (this) to the beginning of the layout class
* @return
*/
std::tuple<DefClass *, int, std::set<DefClass *>>
getDefinitionInternal(const std::string &funcname, const std::vector<DefClass *> &path, int offset = 0,
DefClass *layoutClass = nullptr, int offsetToLayoutClass = 0) {
// return type (nearest definition class, offset to this class, set of superseded definitions)
std::vector<std::pair<DefClass *, int>> candidates;
std::set<DefClass *> superseded;
for (auto b: vbases) {
auto baseOffset = b.offset;
if (layoutClass) {
baseOffset = offsetToLayoutClass + *layoutClass->getOffsetToBase(b.cls);
}
auto x = b.cls->getDefinitionInternal(funcname, path, offset + baseOffset, layoutClass,
offsetToLayoutClass - baseOffset);
if (std::get<0>(x)) {
candidates.emplace_back(std::get<0>(x), std::get<1>(x));
for (auto c: std::get<2>(x)) superseded.insert(c);
}
}
for (auto b: bases) {
auto x = b.cls->getDefinitionInternal(funcname, path, offset + b.offset, layoutClass,
offsetToLayoutClass - b.offset);
if (std::get<0>(x)) {
candidates.emplace_back(std::get<0>(x), std::get<1>(x));
for (auto c: std::get<2>(x)) superseded.insert(c);
}
}
// if we override this function - supersede everything we saw so far
auto it1 = definitions.find({funcname, offset});
auto it2 = definitions.find({funcname, 0});
if (it1 != definitions.end() || it2 != definitions.end()) {
for (auto b: bases) superseded.insert(b.cls);
for (auto b: vbases) superseded.insert(b.cls);
return {this, offset, superseded};
}
// if we do not override this function - take the best candidate
std::pair<DefClass *, int> bestCandidate = {nullptr, 0};
int bestIndex = -1;
for (const auto candidate: candidates) {
if (superseded.find(candidate.first) == superseded.end()) {
int index = std::find(path.begin(), path.end(), candidate.first) - path.begin();
if (bestIndex < 0 || bestIndex > index) {
bestCandidate = candidate;
bestIndex = index;
}
}
}
return {bestCandidate.first, bestCandidate.second, superseded};
}
std::pair<Function *, int>
getDefinition(const std::string &funcname, int offset, DefClassIdent *ident, DefClass *layoutClass = nullptr,
int layoutClassOffset = 0) {
std::vector<DefClass *> inheritancePath = getInheritancePath(ident);
auto result = getDefinitionInternal(funcname, inheritancePath, offset, layoutClass, layoutClassOffset);
if (std::get<0>(result)) {
auto cls = std::get<0>(result);
auto cls_offset = std::get<1>(result);
auto it = cls->definitions.find({funcname, cls_offset});
if (it != cls->definitions.end())
return {it->second, 0};
it = cls->definitions.find({funcname, 0});
if (it != cls->definitions.end())
return {it->second, cls_offset};
}
return {nullptr, 0};
}
Optional<int> getOffsetToBase(DefClass *base) {
if (base == this)
return 0;
for (auto b: vbases) {
if (b.cls == base)
return b.offset;
}
for (auto b: bases) {
auto off = b.cls->getOffsetToBase(base);
if (off) {
return *off + b.offset;
}
}
return {};
}
void print() {
llvm::errs() << "class " << name << " : ";
for (auto b: bases) llvm::errs() << b.cls->name << "(" << b.offset << ") ";
for (auto b: vbases) llvm::errs() << "virtual " << b.cls->name << "(" << b.offset << ") ";
llvm::errs() << "{\n";
for (const auto &it: definitions)
llvm::errs() << " " << it.first.first << " +" << it.first.second << "\n";
// llvm::errs() << " " << it.first.first << " +" << it.first.second << " (symbol " << it.second->getName() << ")\n";
if (!vtableSymbol.empty()) {
llvm::errs() << " vtable " << vtableSymbol << "\n";
llvm::errs() << " vtable index map: ";
for (const auto &it: vtableIdMap) llvm::errs() << it.first << ":" << it.second << " ";
llvm::errs() << "\n";
}
for (const auto ident: idents) {
llvm::errs() << " ident " << *ident << "\n";
}
for (const auto ident: construction_idents) {
llvm::errs() << " construction ident " << *ident << "\n";
}
llvm::errs() << "}\n";
}
Optional<DefClassIdent *> getIdentToOffset(int offset);
};
class DefClassIdent {
public:
DefClass *cls;
int offsetToCls;
// only for construction vtables
DefClass *layout_cls = nullptr;
int offsetToLayoutCls = 0;
bool abstract = true;
bool is_virtual = false;
int vtable_index = 0;
int base_index = 0;
uint32_t number = 0xffffffff;
std::set<DefClassIdent *> bases;
std::set<DefClassIdent *> children;
DefClassIdent *firstBase = nullptr;
DefClassIdent *replacedBy = nullptr;
bool removed = false;
bool in_cluster = false;
std::vector<User *> users;
// storage for optimization passes
std::set<DefClassIdent *> unequal;
std::set<DefClassIdent *> equalCandidates;
DefClassIdent(DefClass *cls, int offsetToCls, int vtableIndex, int baseIndex)
: cls(cls), offsetToCls(offsetToCls), vtable_index(vtableIndex), base_index(baseIndex) {}
DefClassIdent(DefClass *cls, int offsetToCls, int vtableIndex, int baseIndex, DefClass *layoutCls,
int offsetToLayoutCls)
: cls(cls), offsetToCls(offsetToCls), layout_cls(layoutCls), offsetToLayoutCls(offsetToLayoutCls),
vtable_index(vtableIndex), base_index(baseIndex) {}
void addChild(DefClassIdent *ident) {
for (auto child: children) {
if (child == ident) return;
}
this->children.insert(ident);
ident->bases.insert(this);
if (ident->firstBase == nullptr)
ident->firstBase = this;
}
void replaceChild(DefClassIdent *identOld, DefClassIdent *identNew) {
if (children.erase(identOld) > 0) {
children.insert(identNew);
identNew->bases.insert(this);
}
}
void replaceBase(DefClassIdent *identOld, DefClassIdent *identNew) {
if (bases.erase(identOld) > 0) {
bases.insert(identNew);
identNew->children.insert(this);
}
if (firstBase == identOld)
firstBase = identNew;
}
Optional<DefClassIdent *> getBaseForClass(DefClass *cls) {
for (auto &b: bases) {
if (b->cls == cls)
return b;
}
return {};
}
Optional<DefClassIdent *> getBaseForClassRecursive(DefClass *cls, bool only_virtuals = false,
std::set<DefClassIdent *> *additionalBases = nullptr) {
Optional<DefClassIdent *> result;
for (auto &b: bases) {
if (b->cls == cls) {
if (additionalBases) {
if (!result)
result = b;
additionalBases->insert(b);
} else {
return b;
}
}
}
for (auto &b: bases) {
if (only_virtuals && !b->is_virtual) continue;
auto opt = b->getBaseForClassRecursive(cls, only_virtuals, additionalBases);
if (opt) {
if (!additionalBases)
return opt;
else if (!result)
result = opt;
}
}
return result;
}
Optional<DefClassIdent *>
getSimilarIdentForClass(const DefClass *cls, std::set<DefClassIdent *> *additionalBases) {
std::set<DefClassIdent *> seen;
std::queue<DefClassIdent *> queue;
queue.push(this);
seen.insert(this);
Optional<DefClassIdent *> result;
while (!queue.empty()) {
auto ident = queue.front();
queue.pop();
if (ident->cls == cls && ident->layout_cls == nullptr) {
if (!additionalBases)
return ident;
if (result)
additionalBases->insert(ident);
else
result = ident;
}
for (auto i2: ident->children) {
if (seen.find(i2) == seen.end()) {
queue.push(i2);
seen.insert(i2);
}
}
for (auto i2: ident->bases) {
if (seen.find(i2) == seen.end()) {
queue.push(i2);
seen.insert(i2);
}
}
}
return result;
}
void joinFrom(DefClassIdent *ident2) {
assert(cls == ident2->cls);
assert(offsetToCls == ident2->offsetToCls);
assert(layout_cls == ident2->layout_cls);
for (auto baseIdent: ident2->bases) {
baseIdent->replaceChild(ident2, this);
}
for (auto childIdent: ident2->children) {
childIdent->replaceBase(ident2, this);
}
abstract = abstract && ident2->abstract;
users.insert(users.end(), ident2->users.begin(), ident2->users.end());
}
void toDot(llvm::raw_ostream &out) {
out << "\"" << this << "\" [label=\"" << *this << "\"];\n";
for (auto child: children) {
out << "\"" << this << "\" -> \"" << child << "\";\n";
}
}
int getNumber() {
DefClassIdent *ident = this;
while (ident->replacedBy) ident = ident->replacedBy;
return ident->number;
}
void optReplaceBy(DefClassIdent *&ident) {
replacedBy = ident;
for (auto ue: unequal) {
ident->unequal.insert(ue);
ue->unequal.insert(ident);
}
}
inline void remove() {
removed = true;
}
};
std::vector<DefClass *> getInheritancePath(DefClassIdent *ident) {
std::vector<DefClass *> result;
while (ident) {
result.push_back(ident->cls);
if (ident->bases.empty()) break;
ident = ident->firstBase;
}
return result;
}
raw_ostream &operator<<(raw_ostream &OS, const DefClassIdent &ident) {
OS << "#" << ident.vtable_index;
if (ident.base_index != ident.vtable_index) OS << "/#" << ident.base_index;
OS << " of " << ident.cls->name;
if (ident.layout_cls) OS << " in " << ident.layout_cls->name;
OS << ", cls@" << ident.offsetToCls;
if (ident.layout_cls) OS << ", layoutCls@" << ident.offsetToLayoutCls;
if (ident.is_virtual && ident.abstract) OS << " (virtual abstract)";
else if (ident.is_virtual) OS << " (virtual)";
else if (ident.abstract) OS << " (abstract)";
if (ident.number != 0xffffffff) {
OS << " // ID " << ident.number << " (" << format_hex(ident.number, 1) << ")";
}
return OS;
}
Optional<DefClassIdent *> DefClass::getIdentToOffset(int offset) {
for (auto ident: idents) {
if (ident->offsetToCls == offset) {
return ident;
}
}
return {};
}
enum SwitchFunctionType {
DISPATCHER = 0,
VBASE_OFFSET = 1,
DYNAMIC_CAST = 2,
DYNAMIC_VOID_CAST = 3,
RTTI_GET = 4
};
class SwitchFunction {
public:
const SwitchFunctionType type;
Function *const function;
SwitchInst *const switchInst;
const bool defaultIsImportant;
bool removed = false;
std::map<DefClassIdent *, BasicBlock *> cases;
std::set<BasicBlock *> blocks;
std::set<DefClassIdent *> idents;
std::set<DefClassIdent *> defaultIdents; // idents that go to the "default" case (if "defaultIsImportant")
SwitchFunction(const SwitchFunctionType type, Function *function, SwitchInst *switchInst,
bool defaultIsImportant)
: type(type), function(function), switchInst(switchInst), defaultIsImportant(defaultIsImportant) {}
void addCase(DefClassIdent *ident, BasicBlock *block) {
cases[ident] = block;
blocks.insert(block);
idents.insert(ident);
}
void addDefaultCase(DefClassIdent *ident) {
defaultIdents.insert(ident);
}
void replaceSwitchInst(BasicBlock *bb) {
IRBuilder<> builder((Instruction *) switchInst);
builder.CreateBr(bb);
switchInst->eraseFromParent();
function->removeFnAttr(Attribute::NoInline);
function->removeFnAttr(Attribute::OptimizeNone);
function->addFnAttr(Attribute::AlwaysInline);
cases.clear();
blocks.clear();
idents.clear();
removed = true;
}
void buildCases() {
if (removed)
return;
auto IntPtr = cast<IntegerType>(function->getParent()->getDataLayout().getIntPtrType(function->getContext()));
for (const auto it: cases) {
switchInst->addCase(ConstantInt::get(IntPtr, it.first->number), it.second);
}
}
void assertIdentNumbers() {
if (removed)
return;
std::set<uint32_t> seenNumbers;
for (const auto it: cases) {
assert(it.first->number != 0xffffffff);
auto result = seenNumbers.insert(it.first->number);
assert(result.second);
}
}
};
class AbiBuilder {
Module &M;
LLVMContext &C;
std::map<std::string, std::unique_ptr<DefClass>> classes;
std::vector<std::unique_ptr<DefClassIdent>> idents;
std::vector<std::unique_ptr<SwitchFunction>> createdFunctions;
IntegerType *Int32;
Type *IntPtr;
PointerType *Int8Ptr;
long count_dispatchers = 0;
long count_dispatcher_usages = 0;
long count_rtti = 0;
long count_dynamic_cast = 0;
long count_dynamic_cast_void = 0;
long count_vbase_offset_getter = 0;
public:
explicit AbiBuilder(Module &m) : M(m), C(M.getContext()), Int32(Type::getInt32Ty(M.getContext())),
IntPtr(m.getDataLayout().getIntPtrType(M.getContext())),
Int8Ptr(Type::getInt8PtrTy(M.getContext())) {}
DefClass *getClass(const std::string &name) {
auto it = classes.find(name);
if (it != classes.end())
return it->second.get();
return classes.insert({name, std::make_unique<DefClass>(name)}).first->second.get();
}
static bool isConstant(Value *v, uint64_t c) {
auto x = dyn_cast<ConstantInt>(v);
if (!x) return false;
return x->getValue().getZExtValue() == c;
}
static uint64_t getConstant(Value *v, uint64_t def = -1) {
auto x = dyn_cast<ConstantInt>(v);
if (!x) return def;
return x->getValue().getZExtValue();
}
/**
* Parse the metadata from LLVM and initialize all these "Class" structs
*/
void buildClassHierarchy() {
for (auto &md: M.getNamedMDList()) {
if (!md.getName().startswith("novt.")) continue;
if (md.getName().endswith(".bases")) {
auto cls = getClass(md.getName().substr(5, md.getName().size() - 11));
for (unsigned i = 0; i < md.getNumOperands(); i++) {
if (md.getOperand(i)->getNumOperands() > 1) {
auto basename = cast<MDString>(md.getOperand(i)->getOperand(0))->getString();
auto offset = std::stoi(cast<MDString>(md.getOperand(i)->getOperand(1))->getString());
cls->addBase(getClass(basename), offset);
}
}
} else if (md.getName().endswith(".vbases")) {
auto cls = getClass(md.getName().substr(5, md.getName().size() - 12));
for (unsigned i = 0; i < md.getNumOperands(); i++) {
if (md.getOperand(i)->getNumOperands() > 1) {
auto basename = cast<MDString>(md.getOperand(i)->getOperand(0))->getString();
auto offset = std::stoi(cast<MDString>(md.getOperand(i)->getOperand(1))->getString());
cls->addVBase(getClass(basename), offset);
}
}
} else if (md.getName().endswith(".methods")) {
auto cls = getClass(md.getName().substr(5, md.getName().size() - 13));
for (unsigned i = 0; i < md.getNumOperands(); i++) {
if (md.getOperand(i)->getNumOperands() > 0) {
// Format: {function name, function symbol, ["thunkoffset:thunksymbol"]...}
auto funcname = cast<MDString>(md.getOperand(i)->getOperand(0))->getString();
auto funcRef = dyn_cast_or_null<ValueAsMetadata>(md.getOperand(i)->getOperand(2));
if (funcRef && funcRef->getValue()) {
auto f = dyn_cast<Function>(funcRef->getValue());
if (f)
cls->definitions.insert({{funcname, 0}, f});
} else {
auto implname = cast<MDString>(md.getOperand(i)->getOperand(1))->getString();
auto f = M.getFunction(implname);
if (!f && funcname.equals("D1v") && implname.endswith("D2Ev")) {
std::string newName = implname;
newName[newName.size() - 3] = '1';
f = M.getFunction(newName);
}
if (f) {
cls->definitions.insert({{funcname, 0}, f});
} else {
dout << "[NOTFOUND] Could not find function " << implname << " (from " << *md.getOperand(i)
<< " class " << cls->name << ")\n";
}
}
// parse thunk definitions for this method
int thunkOffset = 0;
for (unsigned int j = 3; j < md.getOperand(i)->getNumOperands(); j++) {
auto thunkspec = dyn_cast_or_null<MDString>(md.getOperand(i)->getOperand(j));
if (thunkspec) {
thunkOffset = std::stoi(thunkspec->getString());
} else {
auto thunkFunction = dyn_cast_or_null<ValueAsMetadata>(md.getOperand(i)->getOperand(j));
if (thunkFunction && thunkFunction->getValue()) {
auto f = dyn_cast<Function>(thunkFunction->getValue());
if (f)
cls->definitions.insert({{funcname, thunkOffset}, f});
} else {
// llvm::errs() << "Could not find thunk " << thunkspec << " (from " << *md.getOperand(i) << ")\n";
}
}
}
cls->has_virtual_functions = true;
}
}
} else if (md.getName().endswith(".vtable")) {
auto cls = getClass(md.getName().substr(5, md.getName().size() - 12));
for (unsigned int i = 0; i < md.getNumOperands(); i++) {
std::string idmap;
if (md.getOperand(i)->getNumOperands() > 1) {
idmap = cast<MDString>(md.getOperand(i)->getOperand(1))->getString();
}
const auto &op0 = md.getOperand(i)->getOperand(0);
auto vtable = dyn_cast_or_null<ValueAsMetadata>(op0);
if (vtable) {
assert(vtable->getValue() && "vtable symbol without value");
cls->setVtable(vtable->getValue()->getName(), idmap);
break;
} else if (op0) {
cls->setVtable(cast<MDString>(op0)->getString(), idmap);
}
}
// dout << "class " << md.getName().substr(5, md.getName().size() - 12) << " has vtable named "
// << vtable << " '" << md.getName() << "'" << "\n";
} else if (md.getName().endswith(".cvtables")) {
auto cls = getClass(md.getName().substr(5, md.getName().size() - 14));
for (unsigned i = 0; i < md.getNumOperands(); i++) {
if (md.getOperand(i)->getNumOperands() > 1) {
auto symbolStr = cast<MDString>(md.getOperand(i)->getOperand(0))->getString();
auto base = getClass(cast<MDString>(md.getOperand(i)->getOperand(1))->getString());
auto layout = getClass(cast<MDString>(md.getOperand(i)->getOperand(2))->getString());
auto offset = std::stoi(cast<MDString>(md.getOperand(i)->getOperand(3))->getString());
auto idMapString = dyn_cast<MDString>(md.getOperand(i)->getOperand(4));
if (md.getOperand(i)->getNumOperands() > 5 && md.getOperand(i)->getOperand(5)) {
auto symbolGlobal = dyn_cast_or_null<ValueAsMetadata>(md.getOperand(i)->getOperand(5));
if (symbolGlobal && symbolGlobal->getValue())
symbolStr = symbolGlobal->getValue()->getName();
}
cls->addCVTable(symbolStr, base, layout, offset, idMapString ? idMapString->getString() : "");
}
}
}
}
for (const auto &cls: classes) {
cls.second->sortThings();
}
}
void printClasses() {
llvm::errs() << "\n\n";
for (auto &it: classes) {
it.second->print();
}
llvm::errs() << "\n\n";
}
void printIdents() {
llvm::errs() << "\n\n";
llvm::errs() << "digraph G{\n";
for (auto &it: classes) {
for (auto ident: it.second->idents) {
ident->toDot(llvm::errs());
}
for (auto ident: it.second->construction_idents) {
ident->toDot(llvm::errs());
}
}
llvm::errs() << "}\n";
llvm::errs() << "\n\n";
}
/**
* Add identifiers (numbers) to all classes
*/
void buildClassNumbers() {
uint32_t i = 0;
for (auto &it: classes) {
for (auto ident: it.second->idents) {
if (!ident->abstract)
ident->number = i++;
}
for (auto ident: it.second->construction_idents) {
if (!ident->abstract)
ident->number = i++;
}
}
}
std::set<DefClass *> loopDetectionClasses;
void buildIdentsForClass(DefClass *cls) {
if (!cls->idents.empty())
return;
if (advanced_loop_detection) {
auto it = loopDetectionClasses.insert(cls);
if (!it.second) {
llvm::errs() << "This class is part of a loop: " << cls->name << "\n";
}
}
int next_ident_index = 0;
for (auto it: cls->bases) {
buildIdentsForClass(it.cls);
for (auto baseIdent: it.cls->idents) {
if (!baseIdent->is_virtual) {
auto index = next_ident_index++;
auto new_ident = new DefClassIdent(cls, -it.offset + baseIdent->offsetToCls, index, index);
idents.emplace_back(new_ident);
cls->idents.push_back(new_ident);
baseIdent->addChild(new_ident);
}
}
}
for (auto it: cls->bases) {
// Copy over virtual idents from this base
for (auto it2: it.cls->vbases) {
if (cls->virtualIdentRanges.find(it2.cls) == cls->virtualIdentRanges.end()) {
auto start_index = next_ident_index;
auto startstop = it.cls->virtualIdentRanges[it2.cls];
for (int i = startstop.first; i < startstop.second; i++) {
auto index = next_ident_index++;
idents.emplace_back(new DefClassIdent(cls, 0, index, index));
auto new_ident = idents[idents.size() - 1].get();
cls->idents.push_back(new_ident);
it.cls->idents[i]->addChild(new_ident);
new_ident->is_virtual = true;
}
cls->virtualIdentRanges[it2.cls] = {start_index, next_ident_index};
}
}
}
// Give this class at least one non-virtual ident (if it is virtual)
if (cls->idents.empty() && cls->isVirtual()) {
auto index = next_ident_index++;
idents.emplace_back(new DefClassIdent(cls, 0, index, index));
cls->idents.push_back(idents[idents.size() - 1].get());
}
// Create virtual idents for new bases
for (auto it: cls->vbases) {
if (cls->virtualIdentRanges.find(it.cls) == cls->virtualIdentRanges.end()) {
buildIdentsForClass(it.cls);
auto start_index = next_ident_index;
for (auto baseIdent: it.cls->idents) {
if (!baseIdent->is_virtual) {
auto index = next_ident_index++;
idents.emplace_back(new DefClassIdent(cls, 0, index, index));
auto new_ident = idents[idents.size() - 1].get();
cls->idents.push_back(new_ident);
baseIdent->addChild(new_ident);
new_ident->is_virtual = true;
}
}
cls->virtualIdentRanges[it.cls] = {start_index, next_ident_index};
}
}
// Compute virtual offsets
for (auto it: cls->vbases) {
if (cls->virtualIdentRanges.find(it.cls) != cls->virtualIdentRanges.end()) {
auto startstop = cls->virtualIdentRanges[it.cls];
for (int i = startstop.first; i < startstop.second; i++) {
cls->idents[i]->offsetToCls = -it.offset + it.cls->idents[i - startstop.first]->offsetToCls;
}
}
}
if (advanced_loop_detection) {
loopDetectionClasses.erase(cls);
}
}
void buildIdentHierarchy() {
// build identifiers
for (auto &it: classes) {
// dout << "buildIdentsForClass(" << it.second->name << ") ...\n";
buildIdentsForClass(it.second.get());
}
dout << "all idents built, now postprocessing ...\n";
// join identifiers where only one vtable exists (classes without data)
for (auto &it: classes) {
auto &classIdents = it.second->idents;
int sub = 0;
std::map<int, int> offsetToIndex;
for (size_t i = 0; i < classIdents.size();) {
classIdents[i]->vtable_index -= sub;
auto offsetAlreadyTaken = offsetToIndex.find(classIdents[i]->offsetToCls);
if (offsetAlreadyTaken != offsetToIndex.end()) {
classIdents[offsetAlreadyTaken->second]->joinFrom(classIdents[i]);
classIdents.erase(classIdents.begin() + i);
sub++;
} else {
offsetToIndex[classIdents[i]->offsetToCls] = i;
i++;
}
}
}
// Iterate all vtables and set corresponding identifiers non-abstract / add users
for (auto &it: classes) {
auto vtable = M.getNamedGlobal(it.second->vtableSymbol);
if (vtable) {
auto numVtables = vtable->getType()->getPointerElementType()->getStructNumElements();
// error handling
if (numVtables != it.second->idents.size()) {
printClasses();
llvm::errs() << "Class " << it.second->name << "\n";
llvm::errs() << "vtables: " << numVtables << " (" << *vtable->getType() << ")\n";
llvm::errs() << "idents: " << it.second->idents.size() << "\n";
for (auto ident: it.second->idents) {
llvm::errs() << "- ident for " << ident->cls->name << " " << ident->abstract << ident->is_virtual
<< "\n";
}
}
assert(numVtables == it.second->idents.size() && "VTable count did not match identifier count");
// end error handling
for (auto user: vtable->users()) {
// store i32 (...)** bitcast (i8** getelementptr inbounds ({ [5 x i8*] }, { [5 x i8*] }* @_ZTV1A, i64 0, inrange i32 0, i64 2) to i32 (...)**), i32 (...)*** %2, align 8, !tbaa !26
auto gep = dyn_cast<GEPOperator>(user);
if (gep && gep->getNumOperands() == 4 && isConstant(gep->getOperand(1), 0) &&
getConstant(gep->getOperand(2)) < numVtables && gep->getNumUses() > 0) {
auto numUsedVtable = getConstant(gep->getOperand(2));
// get the correct ident
auto tableIdent = it.second->idents[numUsedVtable];
auto offsetToClass = it.second->vtableIdMap.find(numUsedVtable);
if (offsetToClass != it.second->vtableIdMap.end()) {
auto tableIdentOpt = it.second->getIdentToOffset(-offsetToClass->second);
if (!tableIdentOpt) {
llvm::errs() << "[ERR] No ident found for offset " << offsetToClass->second << " in class "
<< it.second->name << "\n";
} else {
tableIdent = *tableIdentOpt;
}
}
tableIdent->abstract = false;
tableIdent->users.push_back(user);
} else {
llvm::errs() << "[WARNING] Can't remove usage of vtable " << *user << "\n";
}
}
}
for (const auto &cvtable: it.second->cvtables) {
dout << " --- new cvtable --- // and offsetCurrentClassToLayout for grep\n";
int offsetCurrentClassToLayout = -cvtable.offset;
dout << "Start with offsetCurrentClassToLayout = " << offsetCurrentClassToLayout << "\n";
for (auto &symbol: cvtable.symbols) {
vtable = M.getNamedGlobal(symbol);
if (vtable) {
std::map<int, DefClassIdent *> usedTables;
auto numVtables = vtable->getType()->getPointerElementType()->getStructNumElements();
for (auto user: vtable->users()) {
// store i32 (...)** bitcast (i8** getelementptr inbounds ({ [5 x i8*] }, { [5 x i8*] }* @_ZTV1A, i64 0, inrange i32 0, i64 2) to i32 (...)**), i32 (...)*** %2, align 8, !tbaa !26
auto gep = dyn_cast<GEPOperator>(user);
if (gep && gep->getNumOperands() == 4 && isConstant(gep->getOperand(1), 0) &&
getConstant(gep->getOperand(2)) < numVtables && gep->getNumUses() > 0) {
auto numOfUsedVtable = getConstant(gep->getOperand(2));
if (usedTables.count(numOfUsedVtable) == 0) {
// resolve shit - get the parent ident from the given offset.
// we end up with the ident that should store the vtable - from the "base" class.
// we use the layout class ident as fallback.
dout << "CVtable index " << numOfUsedVtable << "\n";
auto offset = cvtable.cvtableIndexToLayoutClassOffset.find(numOfUsedVtable);
auto baseIdent = numOfUsedVtable < cvtable.base->idents.size()
? cvtable.base->idents[numOfUsedVtable] : nullptr;
std::set<DefClassIdent *> additionalBases;
auto offsetInLayout = -cvtable.offset;
auto offsetInCurrent = baseIdent ? baseIdent->offsetToCls : 0;
if (offset == cvtable.cvtableIndexToLayoutClassOffset.end()) {
llvm::errs() << "[ERRS] No offset found for cvtable " << cvtable.base->name << " in "
<< cvtable.layout->name << ": index " << numOfUsedVtable << "\n";
} else {
auto identInLayout = cvtable.layout->getIdentToOffset(-offset->second);
if (!identInLayout) {
llvm::errs() << "[ERRS] No offset ident found for cvtable " << cvtable.base->name << " in "
<< cvtable.layout->name << ": index " << numOfUsedVtable << " offset "
<< offset->second << " + " << cvtable.offset << "\n";
} else {
offsetInLayout = (*identInLayout)->offsetToCls;
auto baseIdentOpt = (*identInLayout)->getBaseForClassRecursive(cvtable.base,
(*identInLayout)->is_virtual,
&additionalBases);
if (!baseIdentOpt) {
baseIdentOpt = (*identInLayout)->getSimilarIdentForClass(cvtable.base, &additionalBases);
if (baseIdentOpt)
dout << "getBaseForClassRecursive did not find, but baseIdentOpt found = "
<< **baseIdentOpt << "\n";
}
if (!baseIdentOpt) {
llvm::errs() << "[ERRS] No base ident found for cvtable " << cvtable.base->name << " in "
<< cvtable.layout->name << ": index " << numOfUsedVtable << " offset "
<< offset->second << " + " << cvtable.offset << " layout-ident "
<< **identInLayout << "\n";
baseIdent = *identInLayout;
} else {
baseIdent = *baseIdentOpt;
if ((*identInLayout)->is_virtual || true) {
offsetInCurrent = offsetInLayout - offsetCurrentClassToLayout;
dout << "using offsetCurrentClassToLayout=" << offsetCurrentClassToLayout
<< " set offsetInCurrent to " << offsetInCurrent << " - identInLayout="
<< **identInLayout << " v=" << (*identInLayout)->is_virtual << "\n";
} else {
/*offsetInCurrent = baseIdent->offsetToCls;
offsetCurrentClassToLayout = offsetInLayout - offsetInCurrent;
dout << "offsetCurrentClassToLayout = " << offsetCurrentClassToLayout
<< " for cvtable (because " << offsetInLayout << " - (" << offsetInCurrent
<< ") identInLayout=" << **identInLayout << "\n";*/
}
}
}
}
assert(baseIdent && "no base ident found");
dout << "baseIdent = " << *baseIdent << " layoutclass = " << cvtable.layout->name
<< " // offsetCurrentClassToLayout\n";
auto new_ident = new DefClassIdent(cvtable.base, offsetInCurrent, numOfUsedVtable,
baseIdent->base_index, cvtable.layout, offsetInLayout);
idents.emplace_back(new_ident);
baseIdent->addChild(new_ident);
new_ident->abstract = false;
new_ident->is_virtual = baseIdent->is_virtual;
cvtable.base->construction_idents.push_back(new_ident);
for (auto additionalBase: additionalBases) {
additionalBase->addChild(new_ident);
}
usedTables[numOfUsedVtable] = new_ident;
dout << " => " << *new_ident << "\n";
}
usedTables[numOfUsedVtable]->users.push_back(user);