1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs a hybrid of global value numbering and partial redundancy
11 // elimination, known as GVN-PRE. It performs partial redundancy elimination on
12 // values, rather than lexical expressions, allowing a more comprehensive view
13 // the optimization. It replaces redundant values with uses of earlier
14 // occurences of the same value. While this is beneficial in that it eliminates
15 // unneeded computation, it also increases register pressure by creating large
16 // live ranges, and should be used with caution on platforms that are very
17 // sensitive to register pressure.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "gvnpre"
22 #include "llvm/Value.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Function.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/PostOrderIterator.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// This class holds the mapping between values and value numbers. It is used
50 /// as an efficient mechanism to determine the expression-wise equivalence of
54 class VISIBILITY_HIDDEN ValueTable {
57 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
58 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
59 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
60 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
61 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
62 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
63 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
64 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
65 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
66 PTRTOINT, INTTOPTR, BITCAST, GEP};
68 ExpressionOpcode opcode;
73 std::vector<uint32_t> varargs;
75 bool operator< (const Expression& other) const {
76 if (opcode < other.opcode)
78 else if (opcode > other.opcode)
80 else if (type < other.type)
82 else if (type > other.type)
84 else if (firstVN < other.firstVN)
86 else if (firstVN > other.firstVN)
88 else if (secondVN < other.secondVN)
90 else if (secondVN > other.secondVN)
92 else if (thirdVN < other.thirdVN)
94 else if (thirdVN > other.thirdVN)
97 if (varargs.size() < other.varargs.size())
99 else if (varargs.size() > other.varargs.size())
102 for (size_t i = 0; i < varargs.size(); ++i)
103 if (varargs[i] < other.varargs[i])
105 else if (varargs[i] > other.varargs[i])
114 DenseMap<Value*, uint32_t> valueNumbering;
115 std::map<Expression, uint32_t> expressionNumbering;
117 uint32_t nextValueNumber;
119 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
120 Expression::ExpressionOpcode getOpcode(CmpInst* C);
121 Expression::ExpressionOpcode getOpcode(CastInst* C);
122 Expression create_expression(BinaryOperator* BO);
123 Expression create_expression(CmpInst* C);
124 Expression create_expression(ShuffleVectorInst* V);
125 Expression create_expression(ExtractElementInst* C);
126 Expression create_expression(InsertElementInst* V);
127 Expression create_expression(SelectInst* V);
128 Expression create_expression(CastInst* C);
129 Expression create_expression(GetElementPtrInst* G);
131 ValueTable() { nextValueNumber = 1; }
132 uint32_t lookup_or_add(Value* V);
133 uint32_t lookup(Value* V) const;
134 void add(Value* V, uint32_t num);
136 void erase(Value* v);
141 //===----------------------------------------------------------------------===//
142 // ValueTable Internal Functions
143 //===----------------------------------------------------------------------===//
144 ValueTable::Expression::ExpressionOpcode
145 ValueTable::getOpcode(BinaryOperator* BO) {
146 switch(BO->getOpcode()) {
147 case Instruction::Add:
148 return Expression::ADD;
149 case Instruction::Sub:
150 return Expression::SUB;
151 case Instruction::Mul:
152 return Expression::MUL;
153 case Instruction::UDiv:
154 return Expression::UDIV;
155 case Instruction::SDiv:
156 return Expression::SDIV;
157 case Instruction::FDiv:
158 return Expression::FDIV;
159 case Instruction::URem:
160 return Expression::UREM;
161 case Instruction::SRem:
162 return Expression::SREM;
163 case Instruction::FRem:
164 return Expression::FREM;
165 case Instruction::Shl:
166 return Expression::SHL;
167 case Instruction::LShr:
168 return Expression::LSHR;
169 case Instruction::AShr:
170 return Expression::ASHR;
171 case Instruction::And:
172 return Expression::AND;
173 case Instruction::Or:
174 return Expression::OR;
175 case Instruction::Xor:
176 return Expression::XOR;
178 // THIS SHOULD NEVER HAPPEN
180 assert(0 && "Binary operator with unknown opcode?");
181 return Expression::ADD;
185 ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
186 if (C->getOpcode() == Instruction::ICmp) {
187 switch (C->getPredicate()) {
188 case ICmpInst::ICMP_EQ:
189 return Expression::ICMPEQ;
190 case ICmpInst::ICMP_NE:
191 return Expression::ICMPNE;
192 case ICmpInst::ICMP_UGT:
193 return Expression::ICMPUGT;
194 case ICmpInst::ICMP_UGE:
195 return Expression::ICMPUGE;
196 case ICmpInst::ICMP_ULT:
197 return Expression::ICMPULT;
198 case ICmpInst::ICMP_ULE:
199 return Expression::ICMPULE;
200 case ICmpInst::ICMP_SGT:
201 return Expression::ICMPSGT;
202 case ICmpInst::ICMP_SGE:
203 return Expression::ICMPSGE;
204 case ICmpInst::ICMP_SLT:
205 return Expression::ICMPSLT;
206 case ICmpInst::ICMP_SLE:
207 return Expression::ICMPSLE;
209 // THIS SHOULD NEVER HAPPEN
211 assert(0 && "Comparison with unknown predicate?");
212 return Expression::ICMPEQ;
215 switch (C->getPredicate()) {
216 case FCmpInst::FCMP_OEQ:
217 return Expression::FCMPOEQ;
218 case FCmpInst::FCMP_OGT:
219 return Expression::FCMPOGT;
220 case FCmpInst::FCMP_OGE:
221 return Expression::FCMPOGE;
222 case FCmpInst::FCMP_OLT:
223 return Expression::FCMPOLT;
224 case FCmpInst::FCMP_OLE:
225 return Expression::FCMPOLE;
226 case FCmpInst::FCMP_ONE:
227 return Expression::FCMPONE;
228 case FCmpInst::FCMP_ORD:
229 return Expression::FCMPORD;
230 case FCmpInst::FCMP_UNO:
231 return Expression::FCMPUNO;
232 case FCmpInst::FCMP_UEQ:
233 return Expression::FCMPUEQ;
234 case FCmpInst::FCMP_UGT:
235 return Expression::FCMPUGT;
236 case FCmpInst::FCMP_UGE:
237 return Expression::FCMPUGE;
238 case FCmpInst::FCMP_ULT:
239 return Expression::FCMPULT;
240 case FCmpInst::FCMP_ULE:
241 return Expression::FCMPULE;
242 case FCmpInst::FCMP_UNE:
243 return Expression::FCMPUNE;
245 // THIS SHOULD NEVER HAPPEN
247 assert(0 && "Comparison with unknown predicate?");
248 return Expression::FCMPOEQ;
253 ValueTable::Expression::ExpressionOpcode
254 ValueTable::getOpcode(CastInst* C) {
255 switch(C->getOpcode()) {
256 case Instruction::Trunc:
257 return Expression::TRUNC;
258 case Instruction::ZExt:
259 return Expression::ZEXT;
260 case Instruction::SExt:
261 return Expression::SEXT;
262 case Instruction::FPToUI:
263 return Expression::FPTOUI;
264 case Instruction::FPToSI:
265 return Expression::FPTOSI;
266 case Instruction::UIToFP:
267 return Expression::UITOFP;
268 case Instruction::SIToFP:
269 return Expression::SITOFP;
270 case Instruction::FPTrunc:
271 return Expression::FPTRUNC;
272 case Instruction::FPExt:
273 return Expression::FPEXT;
274 case Instruction::PtrToInt:
275 return Expression::PTRTOINT;
276 case Instruction::IntToPtr:
277 return Expression::INTTOPTR;
278 case Instruction::BitCast:
279 return Expression::BITCAST;
281 // THIS SHOULD NEVER HAPPEN
283 assert(0 && "Cast operator with unknown opcode?");
284 return Expression::BITCAST;
288 ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
291 e.firstVN = lookup_or_add(BO->getOperand(0));
292 e.secondVN = lookup_or_add(BO->getOperand(1));
294 e.type = BO->getType();
295 e.opcode = getOpcode(BO);
300 ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
303 e.firstVN = lookup_or_add(C->getOperand(0));
304 e.secondVN = lookup_or_add(C->getOperand(1));
306 e.type = C->getType();
307 e.opcode = getOpcode(C);
312 ValueTable::Expression ValueTable::create_expression(CastInst* C) {
315 e.firstVN = lookup_or_add(C->getOperand(0));
318 e.type = C->getType();
319 e.opcode = getOpcode(C);
324 ValueTable::Expression ValueTable::create_expression(ShuffleVectorInst* S) {
327 e.firstVN = lookup_or_add(S->getOperand(0));
328 e.secondVN = lookup_or_add(S->getOperand(1));
329 e.thirdVN = lookup_or_add(S->getOperand(2));
330 e.type = S->getType();
331 e.opcode = Expression::SHUFFLE;
336 ValueTable::Expression ValueTable::create_expression(ExtractElementInst* E) {
339 e.firstVN = lookup_or_add(E->getOperand(0));
340 e.secondVN = lookup_or_add(E->getOperand(1));
342 e.type = E->getType();
343 e.opcode = Expression::EXTRACT;
348 ValueTable::Expression ValueTable::create_expression(InsertElementInst* I) {
351 e.firstVN = lookup_or_add(I->getOperand(0));
352 e.secondVN = lookup_or_add(I->getOperand(1));
353 e.thirdVN = lookup_or_add(I->getOperand(2));
354 e.type = I->getType();
355 e.opcode = Expression::INSERT;
360 ValueTable::Expression ValueTable::create_expression(SelectInst* I) {
363 e.firstVN = lookup_or_add(I->getCondition());
364 e.secondVN = lookup_or_add(I->getTrueValue());
365 e.thirdVN = lookup_or_add(I->getFalseValue());
366 e.type = I->getType();
367 e.opcode = Expression::SELECT;
372 ValueTable::Expression ValueTable::create_expression(GetElementPtrInst* G) {
375 e.firstVN = lookup_or_add(G->getPointerOperand());
378 e.type = G->getType();
379 e.opcode = Expression::SELECT;
381 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
383 e.varargs.push_back(lookup_or_add(*I));
388 //===----------------------------------------------------------------------===//
389 // ValueTable External Functions
390 //===----------------------------------------------------------------------===//
392 /// lookup_or_add - Returns the value number for the specified value, assigning
393 /// it a new number if it did not have one before.
394 uint32_t ValueTable::lookup_or_add(Value* V) {
395 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
396 if (VI != valueNumbering.end())
400 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
401 Expression e = create_expression(BO);
403 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
404 if (EI != expressionNumbering.end()) {
405 valueNumbering.insert(std::make_pair(V, EI->second));
408 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
409 valueNumbering.insert(std::make_pair(V, nextValueNumber));
411 return nextValueNumber++;
413 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
414 Expression e = create_expression(C);
416 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
417 if (EI != expressionNumbering.end()) {
418 valueNumbering.insert(std::make_pair(V, EI->second));
421 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
422 valueNumbering.insert(std::make_pair(V, nextValueNumber));
424 return nextValueNumber++;
426 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
427 Expression e = create_expression(U);
429 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
430 if (EI != expressionNumbering.end()) {
431 valueNumbering.insert(std::make_pair(V, EI->second));
434 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
435 valueNumbering.insert(std::make_pair(V, nextValueNumber));
437 return nextValueNumber++;
439 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
440 Expression e = create_expression(U);
442 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
443 if (EI != expressionNumbering.end()) {
444 valueNumbering.insert(std::make_pair(V, EI->second));
447 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448 valueNumbering.insert(std::make_pair(V, nextValueNumber));
450 return nextValueNumber++;
452 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
453 Expression e = create_expression(U);
455 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
456 if (EI != expressionNumbering.end()) {
457 valueNumbering.insert(std::make_pair(V, EI->second));
460 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
461 valueNumbering.insert(std::make_pair(V, nextValueNumber));
463 return nextValueNumber++;
465 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
466 Expression e = create_expression(U);
468 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
469 if (EI != expressionNumbering.end()) {
470 valueNumbering.insert(std::make_pair(V, EI->second));
473 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
474 valueNumbering.insert(std::make_pair(V, nextValueNumber));
476 return nextValueNumber++;
478 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
479 Expression e = create_expression(U);
481 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
482 if (EI != expressionNumbering.end()) {
483 valueNumbering.insert(std::make_pair(V, EI->second));
486 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
487 valueNumbering.insert(std::make_pair(V, nextValueNumber));
489 return nextValueNumber++;
491 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
492 Expression e = create_expression(U);
494 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
495 if (EI != expressionNumbering.end()) {
496 valueNumbering.insert(std::make_pair(V, EI->second));
499 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
500 valueNumbering.insert(std::make_pair(V, nextValueNumber));
502 return nextValueNumber++;
505 valueNumbering.insert(std::make_pair(V, nextValueNumber));
506 return nextValueNumber++;
510 /// lookup - Returns the value number of the specified value. Fails if
511 /// the value has not yet been numbered.
512 uint32_t ValueTable::lookup(Value* V) const {
513 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
514 if (VI != valueNumbering.end())
517 assert(0 && "Value not numbered?");
522 /// add - Add the specified value with the given value number, removing
523 /// its old number, if any
524 void ValueTable::add(Value* V, uint32_t num) {
525 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
526 if (VI != valueNumbering.end())
527 valueNumbering.erase(VI);
528 valueNumbering.insert(std::make_pair(V, num));
531 /// clear - Remove all entries from the ValueTable
532 void ValueTable::clear() {
533 valueNumbering.clear();
534 expressionNumbering.clear();
538 /// erase - Remove a value from the value numbering
539 void ValueTable::erase(Value* V) {
540 valueNumbering.erase(V);
543 /// size - Return the number of assigned value numbers
544 unsigned ValueTable::size() {
545 // NOTE: zero is never assigned
546 return nextValueNumber;
549 //===----------------------------------------------------------------------===//
551 //===----------------------------------------------------------------------===//
555 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
556 bool runOnFunction(Function &F);
558 static char ID; // Pass identification, replacement for typeid
559 GVNPRE() : FunctionPass((intptr_t)&ID) { }
563 std::vector<Instruction*> createdExpressions;
565 std::map<BasicBlock*, SmallPtrSet<Value*, 16> > availableOut;
566 std::map<BasicBlock*, SmallPtrSet<Value*, 16> > anticipatedIn;
568 // This transformation requires dominator postdominator info
569 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
570 AU.setPreservesCFG();
571 AU.addRequired<UnifyFunctionExitNodes>();
572 AU.addRequired<DominatorTree>();
576 // FIXME: eliminate or document these better
577 void dump(const SmallPtrSet<Value*, 16>& s) const;
578 void clean(SmallPtrSet<Value*, 16>& set, BitVector& presentInSet);
579 Value* find_leader(SmallPtrSet<Value*, 16>& vals,
581 Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ);
582 void phi_translate_set(SmallPtrSet<Value*, 16>& anticIn, BasicBlock* pred,
583 BasicBlock* succ, SmallPtrSet<Value*, 16>& out);
585 void topo_sort(SmallPtrSet<Value*, 16>& set,
586 std::vector<Value*>& vec);
591 void val_insert(SmallPtrSet<Value*, 16>& s, Value* v);
592 void val_replace(SmallPtrSet<Value*, 16>& s, Value* v);
593 bool dependsOnInvoke(Value* V);
594 void buildsets_availout(BasicBlock::iterator I,
595 SmallPtrSet<Value*, 16>& currAvail,
596 SmallPtrSet<PHINode*, 16>& currPhis,
597 SmallPtrSet<Value*, 16>& currExps,
598 SmallPtrSet<Value*, 16>& currTemps,
599 BitVector& availNumbers,
600 BitVector& expNumbers);
601 bool buildsets_anticout(BasicBlock* BB,
602 SmallPtrSet<Value*, 16>& anticOut,
603 std::set<BasicBlock*>& visited);
604 unsigned buildsets_anticin(BasicBlock* BB,
605 SmallPtrSet<Value*, 16>& anticOut,
606 SmallPtrSet<Value*, 16>& currExps,
607 SmallPtrSet<Value*, 16>& currTemps,
608 std::set<BasicBlock*>& visited);
609 void buildsets(Function& F);
611 void insertion_pre(Value* e, BasicBlock* BB,
612 std::map<BasicBlock*, Value*>& avail,
613 std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_set);
614 unsigned insertion_mergepoint(std::vector<Value*>& workList,
615 df_iterator<DomTreeNode*>& D,
616 std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_set);
617 bool insertion(Function& F);
625 // createGVNPREPass - The public interface to this file...
626 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
628 RegisterPass<GVNPRE> X("gvnpre",
629 "Global Value Numbering/Partial Redundancy Elimination");
632 STATISTIC(NumInsertedVals, "Number of values inserted");
633 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
634 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
636 /// find_leader - Given a set and a value number, return the first
637 /// element of the set with that value number, or 0 if no such element
639 Value* GVNPRE::find_leader(SmallPtrSet<Value*, 16>& vals, uint32_t v) {
640 for (SmallPtrSet<Value*, 16>::iterator I = vals.begin(), E = vals.end();
642 if (v == VN.lookup(*I))
648 /// val_insert - Insert a value into a set only if there is not a value
649 /// with the same value number already in the set
650 void GVNPRE::val_insert(SmallPtrSet<Value*, 16>& s, Value* v) {
651 uint32_t num = VN.lookup(v);
652 Value* leader = find_leader(s, num);
657 /// val_replace - Insert a value into a set, replacing any values already in
658 /// the set that have the same value number
659 void GVNPRE::val_replace(SmallPtrSet<Value*, 16>& s, Value* v) {
660 uint32_t num = VN.lookup(v);
661 Value* leader = find_leader(s, num);
662 while (leader != 0) {
664 leader = find_leader(s, num);
669 /// phi_translate - Given a value, its parent block, and a predecessor of its
670 /// parent, translate the value into legal for the predecessor block. This
671 /// means translating its operands (and recursively, their operands) through
672 /// any phi nodes in the parent into values available in the predecessor
673 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
678 if (CastInst* U = dyn_cast<CastInst>(V)) {
680 if (isa<Instruction>(U->getOperand(0)))
681 newOp1 = phi_translate(U->getOperand(0), pred, succ);
683 newOp1 = U->getOperand(0);
688 if (newOp1 != U->getOperand(0)) {
689 Instruction* newVal = 0;
690 if (CastInst* C = dyn_cast<CastInst>(U))
691 newVal = CastInst::create(C->getOpcode(),
692 newOp1, C->getType(),
693 C->getName()+".expr");
695 uint32_t v = VN.lookup_or_add(newVal);
697 Value* leader = find_leader(availableOut[pred], v);
699 createdExpressions.push_back(newVal);
709 } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) ||
710 isa<ExtractElementInst>(V)) {
711 User* U = cast<User>(V);
714 if (isa<Instruction>(U->getOperand(0)))
715 newOp1 = phi_translate(U->getOperand(0), pred, succ);
717 newOp1 = U->getOperand(0);
723 if (isa<Instruction>(U->getOperand(1)))
724 newOp2 = phi_translate(U->getOperand(1), pred, succ);
726 newOp2 = U->getOperand(1);
731 if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
732 Instruction* newVal = 0;
733 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
734 newVal = BinaryOperator::create(BO->getOpcode(),
736 BO->getName()+".expr");
737 else if (CmpInst* C = dyn_cast<CmpInst>(U))
738 newVal = CmpInst::create(C->getOpcode(),
741 C->getName()+".expr");
742 else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
743 newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
745 uint32_t v = VN.lookup_or_add(newVal);
747 Value* leader = find_leader(availableOut[pred], v);
749 createdExpressions.push_back(newVal);
758 // Ternary Operations
759 } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
760 isa<SelectInst>(V)) {
761 User* U = cast<User>(V);
764 if (isa<Instruction>(U->getOperand(0)))
765 newOp1 = phi_translate(U->getOperand(0), pred, succ);
767 newOp1 = U->getOperand(0);
773 if (isa<Instruction>(U->getOperand(1)))
774 newOp2 = phi_translate(U->getOperand(1), pred, succ);
776 newOp2 = U->getOperand(1);
782 if (isa<Instruction>(U->getOperand(2)))
783 newOp3 = phi_translate(U->getOperand(2), pred, succ);
785 newOp3 = U->getOperand(2);
790 if (newOp1 != U->getOperand(0) ||
791 newOp2 != U->getOperand(1) ||
792 newOp3 != U->getOperand(2)) {
793 Instruction* newVal = 0;
794 if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
795 newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
796 S->getName()+".expr");
797 else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
798 newVal = new InsertElementInst(newOp1, newOp2, newOp3,
799 I->getName()+".expr");
800 else if (SelectInst* I = dyn_cast<SelectInst>(U))
801 newVal = new SelectInst(newOp1, newOp2, newOp3, I->getName()+".expr");
803 uint32_t v = VN.lookup_or_add(newVal);
805 Value* leader = find_leader(availableOut[pred], v);
807 createdExpressions.push_back(newVal);
817 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
819 if (isa<Instruction>(U->getPointerOperand()))
820 newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
822 newOp1 = U->getPointerOperand();
827 bool changed_idx = false;
828 std::vector<Value*> newIdx;
829 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
831 if (isa<Instruction>(*I)) {
832 Value* newVal = phi_translate(*I, pred, succ);
833 newIdx.push_back(newVal);
837 newIdx.push_back(*I);
840 if (newOp1 != U->getPointerOperand() || changed_idx) {
841 Instruction* newVal = new GetElementPtrInst(newOp1,
842 &newIdx[0], newIdx.size(),
843 U->getName()+".expr");
845 uint32_t v = VN.lookup_or_add(newVal);
847 Value* leader = find_leader(availableOut[pred], v);
849 createdExpressions.push_back(newVal);
859 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
860 if (P->getParent() == succ)
861 return P->getIncomingValueForBlock(pred);
867 /// phi_translate_set - Perform phi translation on every element of a set
868 void GVNPRE::phi_translate_set(SmallPtrSet<Value*, 16>& anticIn,
869 BasicBlock* pred, BasicBlock* succ,
870 SmallPtrSet<Value*, 16>& out) {
871 for (SmallPtrSet<Value*, 16>::iterator I = anticIn.begin(),
872 E = anticIn.end(); I != E; ++I) {
873 Value* V = phi_translate(*I, pred, succ);
879 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of
880 /// whose inputs is an invoke instruction. If this is true, we cannot safely
881 /// PRE the instruction or anything that depends on it.
882 bool GVNPRE::dependsOnInvoke(Value* V) {
883 if (PHINode* p = dyn_cast<PHINode>(V)) {
884 for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
885 if (isa<InvokeInst>(*I))
893 /// clean - Remove all non-opaque values from the set whose operands are not
894 /// themselves in the set, as well as all values that depend on invokes (see
896 void GVNPRE::clean(SmallPtrSet<Value*, 16>& set, BitVector& presentInSet) {
897 std::vector<Value*> worklist;
898 worklist.reserve(set.size());
899 topo_sort(set, worklist);
901 for (unsigned i = 0; i < worklist.size(); ++i) {
902 Value* v = worklist[i];
905 if (CastInst* U = dyn_cast<CastInst>(v)) {
906 bool lhsValid = !isa<Instruction>(U->getOperand(0));
907 lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
909 lhsValid = !dependsOnInvoke(U->getOperand(0));
913 presentInSet.flip(VN.lookup(U));
917 } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
918 isa<ExtractElementInst>(v)) {
919 User* U = cast<User>(v);
921 bool lhsValid = !isa<Instruction>(U->getOperand(0));
922 lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
924 lhsValid = !dependsOnInvoke(U->getOperand(0));
926 bool rhsValid = !isa<Instruction>(U->getOperand(1));
927 rhsValid |= presentInSet.test(VN.lookup(U->getOperand(1)));
929 rhsValid = !dependsOnInvoke(U->getOperand(1));
931 if (!lhsValid || !rhsValid) {
933 presentInSet.flip(VN.lookup(U));
936 // Handle ternary ops
937 } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
938 isa<SelectInst>(v)) {
939 User* U = cast<User>(v);
941 bool lhsValid = !isa<Instruction>(U->getOperand(0));
942 lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
944 lhsValid = !dependsOnInvoke(U->getOperand(0));
946 bool rhsValid = !isa<Instruction>(U->getOperand(1));
947 rhsValid |= presentInSet.test(VN.lookup(U->getOperand(1)));
949 rhsValid = !dependsOnInvoke(U->getOperand(1));
951 bool thirdValid = !isa<Instruction>(U->getOperand(2));
952 thirdValid |= presentInSet.test(VN.lookup(U->getOperand(2)));
954 thirdValid = !dependsOnInvoke(U->getOperand(2));
956 if (!lhsValid || !rhsValid || !thirdValid) {
958 presentInSet.flip(VN.lookup(U));
961 // Handle varargs ops
962 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
963 bool ptrValid = !isa<Instruction>(U->getPointerOperand());
964 ptrValid |= presentInSet.test(VN.lookup(U->getPointerOperand()));
966 ptrValid = !dependsOnInvoke(U->getPointerOperand());
968 bool varValid = true;
969 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
972 varValid &= !isa<Instruction>(*I) || presentInSet.test(VN.lookup(*I));
973 varValid &= !dependsOnInvoke(*I);
976 if (!ptrValid || !varValid) {
978 presentInSet.flip(VN.lookup(U));
984 /// topo_sort - Given a set of values, sort them by topological
985 /// order into the provided vector.
986 void GVNPRE::topo_sort(SmallPtrSet<Value*, 16>& set, std::vector<Value*>& vec) {
987 SmallPtrSet<Value*, 16> visited;
988 std::vector<Value*> stack;
989 for (SmallPtrSet<Value*, 16>::iterator I = set.begin(), E = set.end();
991 if (visited.count(*I) == 0)
994 while (!stack.empty()) {
995 Value* e = stack.back();
998 if (CastInst* U = dyn_cast<CastInst>(e)) {
999 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1001 if (l != 0 && isa<Instruction>(l) &&
1002 visited.count(l) == 0)
1010 // Handle binary ops
1011 } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1012 isa<ExtractElementInst>(e)) {
1013 User* U = cast<User>(e);
1014 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1015 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1017 if (l != 0 && isa<Instruction>(l) &&
1018 visited.count(l) == 0)
1020 else if (r != 0 && isa<Instruction>(r) &&
1021 visited.count(r) == 0)
1029 // Handle ternary ops
1030 } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1031 isa<SelectInst>(e)) {
1032 User* U = cast<User>(e);
1033 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1034 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1035 Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1037 if (l != 0 && isa<Instruction>(l) &&
1038 visited.count(l) == 0)
1040 else if (r != 0 && isa<Instruction>(r) &&
1041 visited.count(r) == 0)
1043 else if (m != 0 && isa<Instruction>(m) &&
1044 visited.count(m) == 0)
1052 // Handle vararg ops
1053 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1054 Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1056 if (p != 0 && isa<Instruction>(p) &&
1057 visited.count(p) == 0)
1060 bool push_va = false;
1061 for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1062 E = U->idx_end(); I != E; ++I) {
1063 Value * v = find_leader(set, VN.lookup(*I));
1064 if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1077 // Handle opaque ops
1089 /// dump - Dump a set of values to standard error
1090 void GVNPRE::dump(const SmallPtrSet<Value*, 16>& s) const {
1092 for (SmallPtrSet<Value*, 16>::iterator I = s.begin(), E = s.end();
1094 DOUT << "" << VN.lookup(*I) << ": ";
1095 DEBUG((*I)->dump());
1100 /// elimination - Phase 3 of the main algorithm. Perform full redundancy
1101 /// elimination by walking the dominator tree and removing any instruction that
1102 /// is dominated by another instruction with the same value number.
1103 bool GVNPRE::elimination() {
1104 DOUT << "\n\nPhase 3: Elimination\n\n";
1106 bool changed_function = false;
1108 std::vector<std::pair<Instruction*, Value*> > replace;
1109 std::vector<Instruction*> erase;
1111 DominatorTree& DT = getAnalysis<DominatorTree>();
1113 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1114 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1115 BasicBlock* BB = DI->getBlock();
1117 //DOUT << "Block: " << BB->getName() << "\n";
1118 //dump(availableOut[BB]);
1121 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1124 if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1125 isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1126 isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1127 isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1128 Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1131 if (Instruction* Instr = dyn_cast<Instruction>(leader))
1132 if (Instr->getParent() != 0 && Instr != BI) {
1133 replace.push_back(std::make_pair(BI, leader));
1134 erase.push_back(BI);
1141 while (!replace.empty()) {
1142 std::pair<Instruction*, Value*> rep = replace.back();
1144 rep.first->replaceAllUsesWith(rep.second);
1145 changed_function = true;
1148 for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
1150 (*I)->eraseFromParent();
1152 return changed_function;
1155 /// cleanup - Delete any extraneous values that were created to represent
1156 /// expressions without leaders.
1157 void GVNPRE::cleanup() {
1158 while (!createdExpressions.empty()) {
1159 Instruction* I = createdExpressions.back();
1160 createdExpressions.pop_back();
1166 /// buildsets_availout - When calculating availability, handle an instruction
1167 /// by inserting it into the appropriate sets
1168 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1169 SmallPtrSet<Value*, 16>& currAvail,
1170 SmallPtrSet<PHINode*, 16>& currPhis,
1171 SmallPtrSet<Value*, 16>& currExps,
1172 SmallPtrSet<Value*, 16>& currTemps,
1173 BitVector& availNumbers,
1174 BitVector& expNumbers) {
1176 if (PHINode* p = dyn_cast<PHINode>(I)) {
1177 VN.lookup_or_add(p);
1178 expNumbers.resize(VN.size());
1179 availNumbers.resize(VN.size());
1184 } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1185 Value* leftValue = U->getOperand(0);
1187 unsigned num = VN.lookup_or_add(U);
1188 expNumbers.resize(VN.size());
1189 availNumbers.resize(VN.size());
1191 if (isa<Instruction>(leftValue))
1192 if (!expNumbers.test(VN.lookup(leftValue))) {
1193 currExps.insert(leftValue);
1194 expNumbers.set(VN.lookup(leftValue));
1197 if (!expNumbers.test(VN.lookup(U))) {
1199 expNumbers.set(num);
1202 // Handle binary ops
1203 } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1204 isa<ExtractElementInst>(I)) {
1205 User* U = cast<User>(I);
1206 Value* leftValue = U->getOperand(0);
1207 Value* rightValue = U->getOperand(1);
1209 unsigned num = VN.lookup_or_add(U);
1210 expNumbers.resize(VN.size());
1211 availNumbers.resize(VN.size());
1213 if (isa<Instruction>(leftValue))
1214 if (!expNumbers.test(VN.lookup(leftValue))) {
1215 currExps.insert(leftValue);
1216 expNumbers.set(VN.lookup(leftValue));
1219 if (isa<Instruction>(rightValue))
1220 if (!expNumbers.test(VN.lookup(rightValue))) {
1221 currExps.insert(rightValue);
1222 expNumbers.set(VN.lookup(rightValue));
1225 if (!expNumbers.test(VN.lookup(U))) {
1227 expNumbers.set(num);
1230 // Handle ternary ops
1231 } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1232 isa<SelectInst>(I)) {
1233 User* U = cast<User>(I);
1234 Value* leftValue = U->getOperand(0);
1235 Value* rightValue = U->getOperand(1);
1236 Value* thirdValue = U->getOperand(2);
1238 VN.lookup_or_add(U);
1240 unsigned num = VN.lookup_or_add(U);
1241 expNumbers.resize(VN.size());
1242 availNumbers.resize(VN.size());
1244 if (isa<Instruction>(leftValue))
1245 if (!expNumbers.test(VN.lookup(leftValue))) {
1246 currExps.insert(leftValue);
1247 expNumbers.set(VN.lookup(leftValue));
1249 if (isa<Instruction>(rightValue))
1250 if (!expNumbers.test(VN.lookup(rightValue))) {
1251 currExps.insert(rightValue);
1252 expNumbers.set(VN.lookup(rightValue));
1254 if (isa<Instruction>(thirdValue))
1255 if (!expNumbers.test(VN.lookup(thirdValue))) {
1256 currExps.insert(thirdValue);
1257 expNumbers.set(VN.lookup(thirdValue));
1260 if (!expNumbers.test(VN.lookup(U))) {
1262 expNumbers.set(num);
1265 // Handle vararg ops
1266 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1267 Value* ptrValue = U->getPointerOperand();
1269 VN.lookup_or_add(U);
1271 unsigned num = VN.lookup_or_add(U);
1272 expNumbers.resize(VN.size());
1273 availNumbers.resize(VN.size());
1275 if (isa<Instruction>(ptrValue))
1276 if (!expNumbers.test(VN.lookup(ptrValue))) {
1277 currExps.insert(ptrValue);
1278 expNumbers.set(VN.lookup(ptrValue));
1281 for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1283 if (isa<Instruction>(*OI) && !expNumbers.test(VN.lookup(*OI))) {
1284 currExps.insert(*OI);
1285 expNumbers.set(VN.lookup(*OI));
1288 if (!expNumbers.test(VN.lookup(U))) {
1290 expNumbers.set(num);
1293 // Handle opaque ops
1294 } else if (!I->isTerminator()){
1295 VN.lookup_or_add(I);
1296 expNumbers.resize(VN.size());
1297 availNumbers.resize(VN.size());
1299 currTemps.insert(I);
1302 if (!I->isTerminator())
1303 if (!availNumbers.test(VN.lookup(I))) {
1304 currAvail.insert(I);
1305 availNumbers.set(VN.lookup(I));
1309 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1310 /// set as a function of the ANTIC_IN set of the block's predecessors
1311 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1312 SmallPtrSet<Value*, 16>& anticOut,
1313 std::set<BasicBlock*>& visited) {
1314 if (BB->getTerminator()->getNumSuccessors() == 1) {
1315 if (BB->getTerminator()->getSuccessor(0) != BB &&
1316 visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1317 DOUT << "DEFER: " << BB->getName() << "\n";
1321 phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1322 BB, BB->getTerminator()->getSuccessor(0), anticOut);
1324 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1325 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1326 anticOut.insert(anticipatedIn[first].begin(), anticipatedIn[first].end());
1328 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1329 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1330 SmallPtrSet<Value*, 16>& succAnticIn = anticipatedIn[currSucc];
1332 std::vector<Value*> temp;
1334 for (SmallPtrSet<Value*, 16>::iterator I = anticOut.begin(),
1335 E = anticOut.end(); I != E; ++I)
1336 if (find_leader(succAnticIn, VN.lookup(*I)) == 0)
1339 for (std::vector<Value*>::iterator I = temp.begin(), E = temp.end();
1348 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1349 /// each block. ANTIC_IN is then a function of ANTIC_OUT and the GEN
1350 /// sets populated in buildsets_availout
1351 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1352 SmallPtrSet<Value*, 16>& anticOut,
1353 SmallPtrSet<Value*, 16>& currExps,
1354 SmallPtrSet<Value*, 16>& currTemps,
1355 std::set<BasicBlock*>& visited) {
1356 SmallPtrSet<Value*, 16>& anticIn = anticipatedIn[BB];
1357 unsigned old = anticIn.size();
1359 bool defer = buildsets_anticout(BB, anticOut, visited);
1365 BitVector numbers(VN.size());
1366 for (SmallPtrSet<Value*, 16>::iterator I = anticOut.begin(),
1367 E = anticOut.end(); I != E; ++I) {
1368 unsigned num = VN.lookup_or_add(*I);
1369 numbers.resize(VN.size());
1371 if (isa<Instruction>(*I)) {
1376 for (SmallPtrSet<Value*, 16>::iterator I = currExps.begin(),
1377 E = currExps.end(); I != E; ++I) {
1378 if (!numbers.test(VN.lookup_or_add(*I))) {
1380 numbers.set(VN.lookup(*I));
1384 for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1385 E = currTemps.end(); I != E; ++I) {
1387 numbers.flip(VN.lookup(*I));
1390 clean(anticIn, numbers);
1393 if (old != anticIn.size())
1399 /// buildsets - Phase 1 of the main algorithm. Construct the AVAIL_OUT
1400 /// and the ANTIC_IN sets.
1401 void GVNPRE::buildsets(Function& F) {
1402 std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedExpressions;
1403 std::map<BasicBlock*, SmallPtrSet<PHINode*, 16> > generatedPhis;
1404 std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1406 DominatorTree &DT = getAnalysis<DominatorTree>();
1408 // Phase 1, Part 1: calculate AVAIL_OUT
1410 // Top-down walk of the dominator tree
1411 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1412 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1414 // Get the sets to update for this block
1415 SmallPtrSet<Value*, 16>& currExps = generatedExpressions[DI->getBlock()];
1416 SmallPtrSet<PHINode*, 16>& currPhis = generatedPhis[DI->getBlock()];
1417 SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1418 SmallPtrSet<Value*, 16>& currAvail = availableOut[DI->getBlock()];
1420 BasicBlock* BB = DI->getBlock();
1422 // A block inherits AVAIL_OUT from its dominator
1423 if (DI->getIDom() != 0)
1424 currAvail.insert(availableOut[DI->getIDom()->getBlock()].begin(),
1425 availableOut[DI->getIDom()->getBlock()].end());
1427 BitVector availNumbers(VN.size());
1428 for (SmallPtrSet<Value*, 16>::iterator I = currAvail.begin(),
1429 E = currAvail.end(); I != E; ++I)
1430 availNumbers.set(VN.lookup(*I));
1432 BitVector expNumbers(VN.size());
1433 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1435 buildsets_availout(BI, currAvail, currPhis, currExps,
1436 currTemps, availNumbers, expNumbers);
1440 // Phase 1, Part 2: calculate ANTIC_IN
1442 std::set<BasicBlock*> visited;
1443 SmallPtrSet<BasicBlock*, 4> block_changed;
1444 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1445 block_changed.insert(FI);
1447 bool changed = true;
1448 unsigned iterations = 0;
1452 SmallPtrSet<Value*, 16> anticOut;
1454 // Postorder walk of the CFG
1455 for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1456 BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1457 BasicBlock* BB = *BBI;
1459 if (block_changed.count(BB) != 0) {
1460 unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1461 generatedTemporaries[BB], visited);
1470 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1472 block_changed.insert(*PI);
1475 block_changed.erase(BB);
1477 changed |= (ret == 2);
1485 DOUT << "ITERATIONS: " << iterations << "\n";
1488 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1489 /// by inserting appropriate values into the predecessors and a phi node in
1491 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1492 std::map<BasicBlock*, Value*>& avail,
1493 std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_sets) {
1494 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1495 DOUT << "PRED: " << (*PI)->getName() << "\n";
1496 Value* e2 = avail[*PI];
1497 if (!find_leader(availableOut[*PI], VN.lookup(e2))) {
1498 User* U = cast<User>(e2);
1501 if (isa<BinaryOperator>(U->getOperand(0)) ||
1502 isa<CmpInst>(U->getOperand(0)) ||
1503 isa<ShuffleVectorInst>(U->getOperand(0)) ||
1504 isa<ExtractElementInst>(U->getOperand(0)) ||
1505 isa<InsertElementInst>(U->getOperand(0)) ||
1506 isa<SelectInst>(U->getOperand(0)) ||
1507 isa<CastInst>(U->getOperand(0)) ||
1508 isa<GetElementPtrInst>(U->getOperand(0)))
1509 s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1511 s1 = U->getOperand(0);
1515 if (isa<BinaryOperator>(U) ||
1517 isa<ShuffleVectorInst>(U) ||
1518 isa<ExtractElementInst>(U) ||
1519 isa<InsertElementInst>(U) ||
1521 if (isa<BinaryOperator>(U->getOperand(1)) ||
1522 isa<CmpInst>(U->getOperand(1)) ||
1523 isa<ShuffleVectorInst>(U->getOperand(1)) ||
1524 isa<ExtractElementInst>(U->getOperand(1)) ||
1525 isa<InsertElementInst>(U->getOperand(1)) ||
1526 isa<SelectInst>(U->getOperand(1)) ||
1527 isa<CastInst>(U->getOperand(1)) ||
1528 isa<GetElementPtrInst>(U->getOperand(1))) {
1529 s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1531 s2 = U->getOperand(1);
1534 // Ternary Operators
1536 if (isa<ShuffleVectorInst>(U) ||
1537 isa<InsertElementInst>(U) ||
1539 if (isa<BinaryOperator>(U->getOperand(2)) ||
1540 isa<CmpInst>(U->getOperand(2)) ||
1541 isa<ShuffleVectorInst>(U->getOperand(2)) ||
1542 isa<ExtractElementInst>(U->getOperand(2)) ||
1543 isa<InsertElementInst>(U->getOperand(2)) ||
1544 isa<SelectInst>(U->getOperand(2)) ||
1545 isa<CastInst>(U->getOperand(2)) ||
1546 isa<GetElementPtrInst>(U->getOperand(2))) {
1547 s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1549 s3 = U->getOperand(2);
1553 std::vector<Value*> sVarargs;
1554 if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1555 for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1556 OE = G->idx_end(); OI != OE; ++OI) {
1557 if (isa<BinaryOperator>(*OI) ||
1558 isa<CmpInst>(*OI) ||
1559 isa<ShuffleVectorInst>(*OI) ||
1560 isa<ExtractElementInst>(*OI) ||
1561 isa<InsertElementInst>(*OI) ||
1562 isa<SelectInst>(*OI) ||
1563 isa<CastInst>(*OI) ||
1564 isa<GetElementPtrInst>(*OI)) {
1565 sVarargs.push_back(find_leader(availableOut[*PI],
1568 sVarargs.push_back(*OI);
1574 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1575 newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1576 BO->getName()+".gvnpre",
1577 (*PI)->getTerminator());
1578 else if (CmpInst* C = dyn_cast<CmpInst>(U))
1579 newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1580 C->getName()+".gvnpre",
1581 (*PI)->getTerminator());
1582 else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1583 newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1584 (*PI)->getTerminator());
1585 else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1586 newVal = new InsertElementInst(s1, s2, s3, S->getName()+".gvnpre",
1587 (*PI)->getTerminator());
1588 else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1589 newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1590 (*PI)->getTerminator());
1591 else if (SelectInst* S = dyn_cast<SelectInst>(U))
1592 newVal = new SelectInst(s1, s2, s3, S->getName()+".gvnpre",
1593 (*PI)->getTerminator());
1594 else if (CastInst* C = dyn_cast<CastInst>(U))
1595 newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1596 C->getName()+".gvnpre",
1597 (*PI)->getTerminator());
1598 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
1599 newVal = new GetElementPtrInst(s1, &sVarargs[0], sVarargs.size(),
1600 G->getName()+".gvnpre",
1601 (*PI)->getTerminator());
1604 VN.add(newVal, VN.lookup(U));
1606 SmallPtrSet<Value*, 16>& predAvail = availableOut[*PI];
1607 val_replace(predAvail, newVal);
1608 val_replace(new_sets[*PI], newVal);
1610 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1611 if (av != avail.end())
1613 avail.insert(std::make_pair(*PI, newVal));
1621 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1623 p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1625 p->addIncoming(avail[*PI], *PI);
1628 VN.add(p, VN.lookup(e));
1629 val_replace(availableOut[BB], p);
1630 new_sets[BB].insert(p);
1635 /// insertion_mergepoint - When walking the dom tree, check at each merge
1636 /// block for the possibility of a partial redundancy. If present, eliminate it
1637 unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
1638 df_iterator<DomTreeNode*>& D,
1639 std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_sets) {
1640 bool changed_function = false;
1641 bool new_stuff = false;
1643 BasicBlock* BB = D->getBlock();
1644 for (unsigned i = 0; i < workList.size(); ++i) {
1645 Value* e = workList[i];
1647 if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1648 isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1649 isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1650 isa<GetElementPtrInst>(e)) {
1651 if (find_leader(availableOut[D->getIDom()->getBlock()],
1655 std::map<BasicBlock*, Value*> avail;
1656 bool by_some = false;
1659 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1661 Value *e2 = phi_translate(e, *PI, BB);
1662 Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1665 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1666 if (av != avail.end())
1668 avail.insert(std::make_pair(*PI, e2));
1670 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1671 if (av != avail.end())
1673 avail.insert(std::make_pair(*PI, e3));
1680 if (by_some && num_avail < std::distance(pred_begin(BB), pred_end(BB))) {
1681 insertion_pre(e, BB, avail, new_sets);
1683 changed_function = true;
1689 unsigned retval = 0;
1690 if (changed_function)
1698 /// insert - Phase 2 of the main algorithm. Walk the dominator tree looking for
1699 /// merge points. When one is found, check for a partial redundancy. If one is
1700 /// present, eliminate it. Repeat this walk until no changes are made.
1701 bool GVNPRE::insertion(Function& F) {
1702 bool changed_function = false;
1704 DominatorTree &DT = getAnalysis<DominatorTree>();
1706 std::map<BasicBlock*, SmallPtrSet<Value*, 16> > new_sets;
1707 bool new_stuff = true;
1710 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1711 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1712 BasicBlock* BB = DI->getBlock();
1717 SmallPtrSet<Value*, 16>& availOut = availableOut[BB];
1718 SmallPtrSet<Value*, 16>& anticIn = anticipatedIn[BB];
1720 // Replace leaders with leaders inherited from dominator
1721 if (DI->getIDom() != 0) {
1722 SmallPtrSet<Value*, 16>& dom_set = new_sets[DI->getIDom()->getBlock()];
1723 for (SmallPtrSet<Value*, 16>::iterator I = dom_set.begin(),
1724 E = dom_set.end(); I != E; ++I) {
1725 val_replace(new_sets[BB], *I);
1726 val_replace(availOut, *I);
1730 // If there is more than one predecessor...
1731 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1732 std::vector<Value*> workList;
1733 workList.reserve(anticIn.size());
1734 topo_sort(anticIn, workList);
1736 unsigned result = insertion_mergepoint(workList, DI, new_sets);
1738 changed_function = true;
1745 return changed_function;
1748 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1751 bool GVNPRE::runOnFunction(Function &F) {
1752 // Clean out global sets from any previous functions
1754 createdExpressions.clear();
1755 availableOut.clear();
1756 anticipatedIn.clear();
1758 bool changed_function = false;
1760 // Phase 1: BuildSets
1761 // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1764 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1765 DOUT << "ANTIC_IN: " << FI->getName() << "\n";
1766 dump(anticipatedIn[FI]);
1771 // This phase inserts values to make partially redundant values
1773 changed_function |= insertion(F);
1775 // Phase 3: Eliminate
1776 // This phase performs trivial full redundancy elimination
1777 changed_function |= elimination();
1780 // This phase cleans up values that were created solely
1781 // as leaders for expressions
1784 return changed_function;