-
Notifications
You must be signed in to change notification settings - Fork 0
/
GVN.cpp
3359 lines (2867 loc) · 123 KB
/
GVN.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
//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs global value numbering to eliminate fully redundant
// instructions. It also performs simple dead load elimination.
//
// Note that this pass does the value numbering itself; it does not use the
// ValueNumbering analysis passes.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Analysis/PHITransAddr.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include "llvm/Crellvm/ValidationUnit.h"
#include "llvm/Crellvm/Infrules.h"
#include "llvm/Crellvm/Hintgen.h"
#include <vector>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "gvn"
STATISTIC(NumGVNInstr, "Number of instructions deleted");
STATISTIC(NumGVNLoad, "Number of loads deleted");
STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
STATISTIC(NumGVNBlocks, "Number of blocks merged");
STATISTIC(NumGVNSimpl, "Number of instructions simplified");
STATISTIC(NumGVNEqProp, "Number of equalities propagated");
STATISTIC(NumPRELoad, "Number of loads PRE'd");
static cl::opt<bool> EnablePRE("enable-pre",
cl::init(true), cl::Hidden);
static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
// Maximum allowed recursion depth.
static cl::opt<uint32_t>
MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
cl::desc("Max recurse depth (default = 1000)"));
//===----------------------------------------------------------------------===//
// ValueTable Class
//===----------------------------------------------------------------------===//
/// This class holds the mapping between values and value numbers. It is used
/// as an efficient mechanism to determine the expression-wise equivalence of
/// two values.
namespace {
struct Expression {
uint32_t opcode;
Type *type;
SmallVector<uint32_t, 4> varargs;
Expression(uint32_t o = ~2U) : opcode(o) { }
bool operator==(const Expression &other) const {
if (opcode != other.opcode)
return false;
if (opcode == ~0U || opcode == ~1U)
return true;
if (type != other.type)
return false;
if (varargs != other.varargs)
return false;
return true;
}
friend hash_code hash_value(const Expression &Value) {
return hash_combine(Value.opcode, Value.type,
hash_combine_range(Value.varargs.begin(),
Value.varargs.end()));
}
};
class ValueTable {
DenseMap<Value*, uint32_t> valueNumbering;
DenseMap<Expression, uint32_t> expressionNumbering;
AliasAnalysis *AA;
MemoryDependenceAnalysis *MD;
DominatorTree *DT;
uint32_t nextValueNumber;
Expression create_expression(Instruction* I);
Expression create_cmp_expression(unsigned Opcode,
CmpInst::Predicate Predicate,
Value *LHS, Value *RHS);
Expression create_extractvalue_expression(ExtractValueInst* EI);
uint32_t lookup_or_add_call(CallInst* C);
// For Crellvm
void constructVET(Instruction *I, Expression e, uint32_t vn);
public:
ValueTable() : nextValueNumber(1) { }
uint32_t lookup_or_add(Value *V);
uint32_t lookup(Value *V) const;
uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
Value *LHS, Value *RHS);
void add(Value *V, uint32_t num);
void clear();
void erase(Value *v);
void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
AliasAnalysis *getAliasAnalysis() const { return AA; }
void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
void setDomTree(DominatorTree* D) { DT = D; }
uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
void verifyRemoved(const Value *) const;
// For Crellvm
uint32_t lookup_safe (Value *V) const;
DominatorTree *getDomTree() { return DT; }
};
}
namespace llvm {
template <> struct DenseMapInfo<Expression> {
static inline Expression getEmptyKey() {
return ~0U;
}
static inline Expression getTombstoneKey() {
return ~1U;
}
static unsigned getHashValue(const Expression e) {
using llvm::hash_value;
return static_cast<unsigned>(hash_value(e));
}
static bool isEqual(const Expression &LHS, const Expression &RHS) {
return LHS == RHS;
}
};
}
//===----------------------------------------------------------------------===//
// ValueTable Internal Functions
//===----------------------------------------------------------------------===//
// For crellvm
#define GVNDICT(A) crellvm::PassDictionary::GetInstance().get<crellvm::ArgForGVN>()->A
#define INSERT_IF_NOT_EXISTS(dict, key, val) \
if (dict->count(key) == 0) (*dict)[key] = val
#define PUSH_INFRULE(name, ...) \
GVNDICT(infrules).push_back(crellvm::Cons##name::make( __VA_ARGS__ )); \
GVNDICT(infrules).push_back(crellvm::Cons##name##Tgt::make( __VA_ARGS__ ))
#define GVAR(vn) VAR("g" + std::to_string(vn), Ghost)
#define INVARIANT_UNION(set0, set1) \
for (auto I = set1.begin(), E = set1.end(); I != E; ++I) set0.insert(*I);
bool not_supported_floatingTy(Instruction *I) {
for (auto OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
auto ty = (*OI)->getType();
if (ty->isFloatingPointTy() && (!ty->isFloatTy() && !ty->isDoubleTy())) return true;
}
return false;
}
void ValueTable::constructVET(Instruction *I, Expression e, uint32_t vn) {
INSERT_IF_NOT_EXISTS(GVNDICT(VNCnt), vn, 0);
++(*GVNDICT(VNCnt))[vn];
if (crellvm::TyInstruction::isSupported(*I)) {
if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I)) return;
if (not_supported_floatingTy(I)) return;
std::shared_ptr<crellvm::ConsInsn> ginsn = std::static_pointer_cast<crellvm::ConsInsn>(INSN(*I)->get());
if (isa<CmpInst>(I) || I->isCommutative())
if (lookup(I->getOperand(0)) != e.varargs[0]) std::swap(e.varargs[0], e.varargs[1]);
(*GVNDICT(VET))[I] = std::make_pair(e.varargs, SmallSetVector<crellvm::GVNArg::TyInvTKey, 4>());
SmallSetVector<crellvm::GVNArg::TyInvTKey, 4> &invks = (*GVNDICT(VET))[I].second;
for (unsigned i = 0; i < e.varargs.size(); ++i)
if (Instruction *I_op = dyn_cast<Instruction>(I->getOperand(i))) {
// Constructing ginsn
ginsn->replace_op(i, ID("g" + std::to_string(e.varargs[i]), Ghost));
// Constructing VET[I]
if (GVNDICT(VET)->count(I_op) > 0)
INVARIANT_UNION(invks, (*GVNDICT(VET))[I_op].second);
}
// Make own invariant, and insert own inv of VET[I]
std::shared_ptr<crellvm::TyExpr> ginsn_e(new crellvm::TyExpr(ginsn));
bool b = false;
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) b = GEP->isInBounds();
auto key = std::make_pair(vn, b);
INSERT_IF_NOT_EXISTS(GVNDICT(InvT), key, std::make_pair(LESSDEF(ginsn_e, GVAR(vn), SRC),
LESSDEF(GVAR(vn), ginsn_e, TGT)));
invks.insert(key);
}
}
Expression ValueTable::create_expression(Instruction *I) {
Expression e;
e.type = I->getType();
e.opcode = I->getOpcode();
for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
OI != OE; ++OI)
e.varargs.push_back(lookup_or_add(*OI));
if (I->isCommutative()) {
// Ensure that commutative instructions that only differ by a permutation
// of their operands get the same value number by sorting the operand value
// numbers. Since all commutative instructions have two operands it is more
// efficient to sort by hand rather than using, say, std::sort.
assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
if (e.varargs[0] > e.varargs[1])
std::swap(e.varargs[0], e.varargs[1]);
}
if (CmpInst *C = dyn_cast<CmpInst>(I)) {
// Sort the operand value numbers so x<y and y>x get the same value number.
CmpInst::Predicate Predicate = C->getPredicate();
if (e.varargs[0] > e.varargs[1]) {
std::swap(e.varargs[0], e.varargs[1]);
Predicate = CmpInst::getSwappedPredicate(Predicate);
}
e.opcode = (C->getOpcode() << 8) | Predicate;
} else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
II != IE; ++II)
e.varargs.push_back(*II);
}
return e;
}
Expression ValueTable::create_cmp_expression(unsigned Opcode,
CmpInst::Predicate Predicate,
Value *LHS, Value *RHS) {
assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
"Not a comparison!");
Expression e;
e.type = CmpInst::makeCmpResultType(LHS->getType());
e.varargs.push_back(lookup_or_add(LHS));
e.varargs.push_back(lookup_or_add(RHS));
// Sort the operand value numbers so x<y and y>x get the same value number.
if (e.varargs[0] > e.varargs[1]) {
std::swap(e.varargs[0], e.varargs[1]);
Predicate = CmpInst::getSwappedPredicate(Predicate);
}
e.opcode = (Opcode << 8) | Predicate;
return e;
}
Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
assert(EI && "Not an ExtractValueInst?");
Expression e;
e.type = EI->getType();
e.opcode = 0;
IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
// EI might be an extract from one of our recognised intrinsics. If it
// is we'll synthesize a semantically equivalent expression instead on
// an extract value expression.
switch (I->getIntrinsicID()) {
case Intrinsic::sadd_with_overflow:
case Intrinsic::uadd_with_overflow:
e.opcode = Instruction::Add;
break;
case Intrinsic::ssub_with_overflow:
case Intrinsic::usub_with_overflow:
e.opcode = Instruction::Sub;
break;
case Intrinsic::smul_with_overflow:
case Intrinsic::umul_with_overflow:
e.opcode = Instruction::Mul;
break;
default:
break;
}
if (e.opcode != 0) {
// Intrinsic recognized. Grab its args to finish building the expression.
assert(I->getNumArgOperands() == 2 &&
"Expect two args for recognised intrinsics.");
e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
return e;
}
}
// Not a recognised intrinsic. Fall back to producing an extract value
// expression.
e.opcode = EI->getOpcode();
for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
OI != OE; ++OI)
e.varargs.push_back(lookup_or_add(*OI));
for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
II != IE; ++II)
e.varargs.push_back(*II);
return e;
}
//===----------------------------------------------------------------------===//
// ValueTable External Functions
//===----------------------------------------------------------------------===//
/// add - Insert a value into the table with a specified value number.
void ValueTable::add(Value *V, uint32_t num) {
valueNumbering.insert(std::make_pair(V, num));
}
uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
if (AA->doesNotAccessMemory(C)) {
Expression exp = create_expression(C);
uint32_t &e = expressionNumbering[exp];
if (!e) e = nextValueNumber++;
valueNumbering[C] = e;
crellvm::intrude([&C, &exp, e, this]{ constructVET(C, exp, e); });
return e;
} else if (AA->onlyReadsMemory(C)) {
Expression exp = create_expression(C);
uint32_t &e = expressionNumbering[exp];
if (!e) {
e = nextValueNumber++;
valueNumbering[C] = e;
crellvm::intrude([&C, &exp, e, this]{ constructVET(C, exp, e); });
return e;
}
if (!MD) {
e = nextValueNumber++;
valueNumbering[C] = e;
crellvm::intrude([&C, &exp, e, this]{ constructVET(C, exp, e); });
return e;
}
MemDepResult local_dep = MD->getDependency(C);
if (!local_dep.isDef() && !local_dep.isNonLocal()) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
if (local_dep.isDef()) {
CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
if (c_vn != cd_vn) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
}
uint32_t v = lookup_or_add(local_cdep);
valueNumbering[C] = v;
return v;
}
// Non-local case.
const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
MD->getNonLocalCallDependency(CallSite(C));
// FIXME: Move the checking logic to MemDep!
CallInst* cdep = nullptr;
// Check to see if we have a single dominating call instruction that is
// identical to C.
for (unsigned i = 0, e = deps.size(); i != e; ++i) {
const NonLocalDepEntry *I = &deps[i];
if (I->getResult().isNonLocal())
continue;
// We don't handle non-definitions. If we already have a call, reject
// instruction dependencies.
if (!I->getResult().isDef() || cdep != nullptr) {
cdep = nullptr;
break;
}
CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
// FIXME: All duplicated with non-local case.
if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
cdep = NonLocalDepCall;
continue;
}
cdep = nullptr;
break;
}
if (!cdep) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
if (c_vn != cd_vn) {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
}
uint32_t v = lookup_or_add(cdep);
valueNumbering[C] = v;
return v;
} else {
valueNumbering[C] = nextValueNumber;
return nextValueNumber++;
}
}
/// lookup_or_add - Returns the value number for the specified value, assigning
/// it a new number if it did not have one before.
uint32_t ValueTable::lookup_or_add(Value *V) {
DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
if (VI != valueNumbering.end())
return VI->second;
if (!isa<Instruction>(V)) {
valueNumbering[V] = nextValueNumber;
return nextValueNumber++;
}
Instruction* I = cast<Instruction>(V);
Expression exp;
switch (I->getOpcode()) {
case Instruction::Call:
return lookup_or_add_call(cast<CallInst>(I));
case Instruction::Add:
case Instruction::FAdd:
case Instruction::Sub:
case Instruction::FSub:
case Instruction::Mul:
case Instruction::FMul:
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::FDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::FRem:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::ICmp:
case Instruction::FCmp:
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::PtrToInt:
case Instruction::IntToPtr:
case Instruction::BitCast:
case Instruction::Select:
case Instruction::ExtractElement:
case Instruction::InsertElement:
case Instruction::ShuffleVector:
case Instruction::InsertValue:
case Instruction::GetElementPtr:
exp = create_expression(I);
break;
case Instruction::ExtractValue:
exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
break;
default:
valueNumbering[V] = nextValueNumber;
return nextValueNumber++;
}
uint32_t& e = expressionNumbering[exp];
if (!e) e = nextValueNumber++;
valueNumbering[V] = e;
crellvm::intrude([&V, &exp, e, this]{ constructVET(cast<Instruction>(V), exp, e); });
return e;
}
/// Returns the value number of the specified value. Fails if
/// the value has not yet been numbered.
uint32_t ValueTable::lookup(Value *V) const {
DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
assert(VI != valueNumbering.end() && "Value not numbered?");
return VI->second;
}
// For Crellvm
uint32_t ValueTable::lookup_safe(Value *V) const {
DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
if (VI == valueNumbering.end()) return 0;
return VI->second;
}
/// Returns the value number of the given comparison,
/// assigning it a new number if it did not have one before. Useful when
/// we deduced the result of a comparison, but don't immediately have an
/// instruction realizing that comparison to hand.
uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
CmpInst::Predicate Predicate,
Value *LHS, Value *RHS) {
Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
uint32_t& e = expressionNumbering[exp];
if (!e) e = nextValueNumber++;
return e;
}
/// Remove all entries from the ValueTable.
void ValueTable::clear() {
valueNumbering.clear();
expressionNumbering.clear();
nextValueNumber = 1;
}
/// Remove a value from the value numbering.
void ValueTable::erase(Value *V) {
valueNumbering.erase(V);
}
/// verifyRemoved - Verify that the value is removed from all internal data
/// structures.
void ValueTable::verifyRemoved(const Value *V) const {
for (DenseMap<Value*, uint32_t>::const_iterator
I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
assert(I->first != V && "Inst still occurs in value numbering map!");
}
}
//===----------------------------------------------------------------------===//
// GVN Pass
//===----------------------------------------------------------------------===//
namespace {
class GVN;
struct AvailableValueInBlock {
/// BB - The basic block in question.
BasicBlock *BB;
enum ValType {
SimpleVal, // A simple offsetted value that is accessed.
LoadVal, // A value produced by a load.
MemIntrin, // A memory intrinsic which is loaded from.
UndefVal // A UndefValue representing a value from dead block (which
// is not yet physically removed from the CFG).
};
/// V - The value that is live out of the block.
PointerIntPair<Value *, 2, ValType> Val;
/// Offset - The byte offset in Val that is interesting for the load query.
unsigned Offset;
static AvailableValueInBlock get(BasicBlock *BB, Value *V,
unsigned Offset = 0) {
AvailableValueInBlock Res;
Res.BB = BB;
Res.Val.setPointer(V);
Res.Val.setInt(SimpleVal);
Res.Offset = Offset;
return Res;
}
static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
unsigned Offset = 0) {
AvailableValueInBlock Res;
Res.BB = BB;
Res.Val.setPointer(MI);
Res.Val.setInt(MemIntrin);
Res.Offset = Offset;
return Res;
}
static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
unsigned Offset = 0) {
AvailableValueInBlock Res;
Res.BB = BB;
Res.Val.setPointer(LI);
Res.Val.setInt(LoadVal);
Res.Offset = Offset;
return Res;
}
static AvailableValueInBlock getUndef(BasicBlock *BB) {
AvailableValueInBlock Res;
Res.BB = BB;
Res.Val.setPointer(nullptr);
Res.Val.setInt(UndefVal);
Res.Offset = 0;
return Res;
}
bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
bool isUndefValue() const { return Val.getInt() == UndefVal; }
Value *getSimpleValue() const {
assert(isSimpleValue() && "Wrong accessor");
return Val.getPointer();
}
LoadInst *getCoercedLoadValue() const {
assert(isCoercedLoadValue() && "Wrong accessor");
return cast<LoadInst>(Val.getPointer());
}
MemIntrinsic *getMemIntrinValue() const {
assert(isMemIntrinValue() && "Wrong accessor");
return cast<MemIntrinsic>(Val.getPointer());
}
/// Emit code into this block to adjust the value defined here to the
/// specified type. This handles various coercion cases.
Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const;
};
class GVN : public FunctionPass {
bool NoLoads;
MemoryDependenceAnalysis *MD;
DominatorTree *DT;
const TargetLibraryInfo *TLI;
AssumptionCache *AC;
SetVector<BasicBlock *> DeadBlocks;
ValueTable VN;
/// A mapping from value numbers to lists of Value*'s that
/// have that value number. Use findLeader to query it.
struct LeaderTableEntry {
Value *Val;
const BasicBlock *BB;
LeaderTableEntry *Next;
};
DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
BumpPtrAllocator TableAllocator;
SmallVector<Instruction*, 8> InstrsToErase;
typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
public:
static char ID; // Pass identification, replacement for typeid
explicit GVN(bool noloads = false)
: FunctionPass(ID), NoLoads(noloads), MD(nullptr) {
initializeGVNPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
/// This removes the specified instruction from
/// our various maps and marks it for deletion.
void markInstructionForDeletion(Instruction *I) {
VN.erase(I);
InstrsToErase.push_back(I);
}
DominatorTree &getDominatorTree() const { return *DT; }
AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
MemoryDependenceAnalysis &getMemDep() const { return *MD; }
private:
/// Push a new Value to the LeaderTable onto the list for its value number.
void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
LeaderTableEntry &Curr = LeaderTable[N];
if (!Curr.Val) {
Curr.Val = V;
Curr.BB = BB;
return;
}
LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
Node->Val = V;
Node->BB = BB;
Node->Next = Curr.Next;
Curr.Next = Node;
}
/// Scan the list of values corresponding to a given
/// value number, and remove the given instruction if encountered.
void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
LeaderTableEntry* Prev = nullptr;
LeaderTableEntry* Curr = &LeaderTable[N];
while (Curr && (Curr->Val != I || Curr->BB != BB)) {
Prev = Curr;
Curr = Curr->Next;
}
if (!Curr)
return;
if (Prev) {
Prev->Next = Curr->Next;
} else {
if (!Curr->Next) {
Curr->Val = nullptr;
Curr->BB = nullptr;
} else {
LeaderTableEntry* Next = Curr->Next;
Curr->Val = Next->Val;
Curr->BB = Next->BB;
Curr->Next = Next->Next;
}
}
}
// List of critical edges to be split between iterations.
SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
// This transformation requires dominator postdominator info
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
if (!NoLoads)
AU.addRequired<MemoryDependenceAnalysis>();
AU.addRequired<AliasAnalysis>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<AliasAnalysis>();
}
// Helper fuctions of redundant load elimination
bool processLoad(LoadInst *L);
bool processNonLocalLoad(LoadInst *L);
void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
AvailValInBlkVect &ValuesPerBlock,
UnavailBlkVect &UnavailableBlocks);
bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
UnavailBlkVect &UnavailableBlocks);
// Other helper routines
bool processInstruction(Instruction *I);
bool processBlock(BasicBlock *BB);
void dump(DenseMap<uint32_t, Value*> &d);
bool iterateOnFunction(Function &F);
bool performPRE(Function &F);
bool performScalarPRE(Instruction *I);
bool performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
unsigned int ValNo);
Value *findLeader(const BasicBlock *BB, uint32_t num);
void cleanupGlobalSets();
void verifyRemoved(const Instruction *I) const;
bool splitCriticalEdges();
BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
bool processFoldableCondBr(BranchInst *BI);
void addDeadBlock(BasicBlock *BB);
void assignValNumForDeadCode();
};
char GVN::ID = 0;
}
// The public interface to this file...
FunctionPass *llvm::createGVNPass(bool NoLoads) {
return new GVN(NoLoads);
}
INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void GVN::dump(DenseMap<uint32_t, Value*>& d) {
errs() << "{\n";
for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
E = d.end(); I != E; ++I) {
errs() << I->first << "\n";
I->second->dump();
}
errs() << "}\n";
}
#endif
// Crellvm hint generation code
void hintgenLoadOpt(crellvm::CoreHint &hints, Instruction *I, Instruction *pos, Value *ptr, crellvm::TyScope scp) {
std::string id = crellvm::getVariable(*I);
if (I != pos) {
PROPAGATE(LESSDEF(VAR(id), RHS(id, Physical, scp), scp), BOUNDS(INSTPOS(SRC, I), INSTPOS(SRC, pos)));
PROPAGATE(LESSDEF(RHS(id, Physical, scp), VAR(id), scp), BOUNDS(INSTPOS(SRC, I), INSTPOS(SRC, pos)));
}
if (I->getOperand(0) != ptr)
if (Instruction *Iop = dyn_cast<Instruction>(I->getOperand(0)))
hintgenLoadOpt(hints, Iop, pos, ptr, scp);
}
void insertProofForPropEq(crellvm::CoreHint &hints, std::vector<llvm::Instruction*> props,
std::vector<std::shared_ptr<crellvm::TyInfrule>> infrs,
bool is_src, BasicBlock *BB, Instruction *cur_pos) {
auto scp = is_src? SRC : TGT;
TerminatorInst *TI = BB->getSinglePredecessor()->getTerminator();
Instruction *I_cond = nullptr;
ConstantInt *C_cond = nullptr;
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
I_cond = cast<Instruction>(BI->getCondition());
if (BI->getSuccessor(0) == BB) C_cond = ConstantInt::getTrue(BB->getContext());
else if (BI->getSuccessor(1) == BB) C_cond = ConstantInt::getFalse(BB->getContext());
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
I_cond = dyn_cast<Instruction>(SI->getCondition());
for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
if (i.getCaseSuccessor() == BB) C_cond = i.getCaseValue();
} else assert(false && "GVN make_repl_inv: Unexpected terminator.");
std::string id_I_cond = crellvm::getVariable(*I_cond);
PROPAGATE(LESSDEF(EXPR(C_cond, Physical), VAR(id_I_cond), scp), BOUNDS(STARTPOS(SRC, BB->getName()), INSTPOS(SRC, cur_pos)));
PROPAGATE(LESSDEF(VAR(id_I_cond), EXPR(C_cond, Physical), scp), BOUNDS(STARTPOS(SRC, BB->getName()), INSTPOS(SRC, cur_pos)));
// TODO: factor this out to a function
for (auto II = props.begin(), EI = props.end(); II != EI; ++II) {
Instruction *I = *II;
std::string id = crellvm::getVariable(*I);
PROPAGATE(LESSDEF(VAR(id), RHS(id, Physical, scp), scp), BOUNDS(INSTPOS(SRC, I), INSTPOS(SRC, cur_pos)));
PROPAGATE(LESSDEF(RHS(id, Physical, scp), VAR(id), scp), BOUNDS(INSTPOS(SRC, I), INSTPOS(SRC, cur_pos)));
}
for (auto II = infrs.begin(), EI = infrs.end(); II != EI; ++II) {
if (TerminatorInst *TI = dyn_cast<TerminatorInst>(cur_pos))
for (unsigned i = 0; i < TI->getNumSuccessors(); ++i)
INFRULE(PHIPOS(scp, TI->getSuccessor(i)->getName(), TI->getParent()->getName()), *II);
else INFRULE(INSTPOS(scp, cur_pos), *II);
}
}
bool lookupCT(ValueTable &VN, crellvm::GVNArg::TyCT &CT,
crellvm::GVNArg::TyCTElem &elem,
Value *V, uint32_t vn, Instruction *pos) {
DominatorTree *DT = VN.getDomTree();
bool flag = false;
std::vector<crellvm::GVNArg::TyCTElem> &ct_list = DICTMAP(CT, std::make_pair(V, vn));
for (auto II = ct_list.begin(), IE = ct_list.end(); II != IE; ++II) {
elem = *II;
BasicBlock *cur = elem.first;
Instruction *cur_begin = cur->begin();
if (DT->dominates(cur_begin, pos) || cur_begin == pos){
flag = true;
break;
}
}
return flag;
}
void PropagateVETInv(crellvm::CoreHint &hints, crellvm::GVNArg::TyInvT &InvT,
crellvm::GVNArg::TyVNCnt &VNCnt,
SmallSetVector<crellvm::GVNArg::TyInvTKey, 4> &s,
Instruction *from, Instruction *to) {
if (from != to)
for (auto I = s.begin(), E = s.end(); I != E; ++I) {
if ((*VNCnt)[I->first] <= 1) continue;
std::pair<std::shared_ptr<crellvm::TyPropagateObject>,
std::shared_ptr<crellvm::TyPropagateObject>> &prop_pair = (*InvT)[*I];
PROPAGATE(prop_pair.first, BOUNDS(INSTPOS(SRC, from), INSTPOS(SRC, to)));
PROPAGATE(prop_pair.second, BOUNDS(INSTPOS(SRC, from), INSTPOS(SRC, to)));
}
}
static inline Value *src_tgt(bool is_src, Value *src, Value *tgt, Value *v) {
if (!is_src && (src == v)) return tgt;
return v;
}
bool proofGenGVNUnary(crellvm::CoreHint &hints, ValueTable &VN,
crellvm::GVNArg::TyVET &VET, crellvm::GVNArg::TyInvT &InvT,
crellvm::GVNArg::TyCT &CT, crellvm::GVNArg::TyCTInv &CTInv,
crellvm::GVNArg::TyCallPHI &CallPHIs,
crellvm::GVNArg::TyVNCnt &VNCnt,
std::map<uint32_t, Instruction*> &calls,
std::map<uint32_t, LoadInst*> &loads,
Value *V_term, Instruction *l_end, uint32_t vn, bool is_src) {
SmallVector<std::pair<Instruction*, std::pair<Value *, uint32_t>>, 4> worklist;
SmallSetVector<std::pair<Instruction*, std::pair<Value *, uint32_t>>, 4> visited;
worklist.push_back(std::make_pair(l_end, std::make_pair(V_term, vn)));
visited.insert(std::make_pair(l_end, std::make_pair(V_term, vn)));
while(!worklist.empty()) {
Instruction *cur_pos = worklist.back().first;
Value *V = worklist.back().second.first;
uint32_t vn = worklist.back().second.second;
worklist.pop_back();
if (Instruction *I_V = dyn_cast<Instruction>(V)) {
bool is_call = false;
Value *V_t = src_tgt(is_src, l_end, V_term, V);
std::string id_V = crellvm::getVariable(*I_V),
id_V_t = crellvm::getVariable(*V_t);
if (isa<CallInst>(I_V)) is_call = true;
if (PHINode *PN = dyn_cast<PHINode>(I_V))
if (CallPHIs->count(PN) > 0) is_call = true;
if (is_call) {
auto II = calls.find(vn);
if (II != calls.end()) {
if (I_V != II->second) {
// We admit readonly call cases now.
hints.appendToDescription("GVN: Readonly calls.");
hints.setReturnCodeToAdmitted();
return false;
}
} else calls.insert(std::make_pair(vn, I_V));
}
if (vn != VN.lookup_safe(I_V)) {
if (Instruction *TR = dyn_cast<TruncInst>(I_V)) {
if (loads.count(vn) > 0) {
LoadInst *LI = loads[vn];
std::string id_L = crellvm::getVariable(*LI);
PROPAGATE(LESSDEF(RHS(id_L, Physical, SRC), VAR(id_L), SRC), BOUNDS(INSTPOS(SRC, LI), INSTPOS(SRC, TR)));
PROPAGATE(LESSDEF(GVAR(vn), RHS(id_L, Physical, SRC), TGT), BOUNDS(INSTPOS(SRC, LI), INSTPOS(SRC, TR)));
hintgenLoadOpt(hints, TR, TR, LI->getPointerOperand(), TGT);
PROPAGATE(is_src? LESSDEF(VAR(id_V), GVAR(vn), SRC) : LESSDEF(GVAR(vn), VAR(id_V), TGT),
BOUNDS(INSTPOS(SRC, I_V), INSTPOS(SRC, cur_pos)));
}
} else {
PROPAGATE(LESSDEF(VAR(id_V), GVAR(vn), SRC), BOUNDS(INSTPOS(SRC, I_V), INSTPOS(SRC, cur_pos)));
PROPAGATE(LESSDEF(GVAR(vn), VAR(id_V), TGT), BOUNDS(INSTPOS(SRC, I_V), INSTPOS(SRC, cur_pos)));
}
} else {
if (LoadInst *LI = dyn_cast<LoadInst>(I_V)) loads[vn] = LI;
if (I_V != cur_pos) PROPAGATE(is_src? LESSDEF(VAR(id_V), GVAR(vn), SRC) : LESSDEF(GVAR(vn), VAR(id_V_t), TGT),
BOUNDS(INSTPOS(SRC, I_V), INSTPOS(SRC, cur_pos)));
if (((*VNCnt)[vn] > 1) && (VET->count(I_V) > 0)) {
PropagateVETInv(hints, InvT, VNCnt, (*VET)[I_V].second, I_V, cur_pos);
for (unsigned i = 0; i < I_V->getNumOperands(); ++i) {
uint32_t vn_op = (isa<PHINode>(I_V))? vn : (*VET)[I_V].first[i];
Instruction *new_pos = I_V;
if (PHINode *PN = dyn_cast<PHINode>(I_V))
new_pos = PN->getIncomingBlock(i)->getTerminator();