blob: c6b50a4002d4735e7bedc9038d7d44850f48e759 [file] [log] [blame]
Owen Anderson85c40642007-07-24 17:55:58 +00001//===- GVN.cpp - Eliminate redundant values and loads ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions. It also performs simple dead load elimination.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "gvn"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000016
Owen Anderson85c40642007-07-24 17:55:58 +000017#include "llvm/Transforms/Scalar.h"
Owen Anderson5d72a422007-07-25 19:57:03 +000018#include "llvm/BasicBlock.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000019#include "llvm/Constants.h"
Owen Anderson85c40642007-07-24 17:55:58 +000020#include "llvm/DerivedTypes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000021#include "llvm/Function.h"
22#include "llvm/Instructions.h"
23#include "llvm/Value.h"
Owen Anderson85c40642007-07-24 17:55:58 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/ADT/BitVector.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/Analysis/MemoryDependenceAnalysis.h"
32#include "llvm/Support/CFG.h"
33#include "llvm/Support/Compiler.h"
34using namespace llvm;
35
36//===----------------------------------------------------------------------===//
37// ValueTable Class
38//===----------------------------------------------------------------------===//
39
40/// This class holds the mapping between values and value numbers. It is used
41/// as an efficient mechanism to determine the expression-wise equivalence of
42/// two values.
43namespace {
44 struct VISIBILITY_HIDDEN Expression {
45 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
46 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
47 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
48 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
49 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
50 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
51 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
52 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
53 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
54 PTRTOINT, INTTOPTR, BITCAST, GEP, EMPTY,
55 TOMBSTONE };
56
57 ExpressionOpcode opcode;
58 const Type* type;
59 uint32_t firstVN;
60 uint32_t secondVN;
61 uint32_t thirdVN;
62 SmallVector<uint32_t, 4> varargs;
63
64 Expression() { }
65 Expression(ExpressionOpcode o) : opcode(o) { }
66
67 bool operator==(const Expression &other) const {
68 if (opcode != other.opcode)
69 return false;
70 else if (opcode == EMPTY || opcode == TOMBSTONE)
71 return true;
72 else if (type != other.type)
73 return false;
74 else if (firstVN != other.firstVN)
75 return false;
76 else if (secondVN != other.secondVN)
77 return false;
78 else if (thirdVN != other.thirdVN)
79 return false;
80 else {
81 if (varargs.size() != other.varargs.size())
82 return false;
83
84 for (size_t i = 0; i < varargs.size(); ++i)
85 if (varargs[i] != other.varargs[i])
86 return false;
87
88 return true;
89 }
90 }
91
92 bool operator!=(const Expression &other) const {
93 if (opcode != other.opcode)
94 return true;
95 else if (opcode == EMPTY || opcode == TOMBSTONE)
96 return false;
97 else if (type != other.type)
98 return true;
99 else if (firstVN != other.firstVN)
100 return true;
101 else if (secondVN != other.secondVN)
102 return true;
103 else if (thirdVN != other.thirdVN)
104 return true;
105 else {
106 if (varargs.size() != other.varargs.size())
107 return true;
108
109 for (size_t i = 0; i < varargs.size(); ++i)
110 if (varargs[i] != other.varargs[i])
111 return true;
112
113 return false;
114 }
115 }
116 };
117
118 class VISIBILITY_HIDDEN ValueTable {
119 private:
120 DenseMap<Value*, uint32_t> valueNumbering;
121 DenseMap<Expression, uint32_t> expressionNumbering;
122
123 uint32_t nextValueNumber;
124
125 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
126 Expression::ExpressionOpcode getOpcode(CmpInst* C);
127 Expression::ExpressionOpcode getOpcode(CastInst* C);
128 Expression create_expression(BinaryOperator* BO);
129 Expression create_expression(CmpInst* C);
130 Expression create_expression(ShuffleVectorInst* V);
131 Expression create_expression(ExtractElementInst* C);
132 Expression create_expression(InsertElementInst* V);
133 Expression create_expression(SelectInst* V);
134 Expression create_expression(CastInst* C);
135 Expression create_expression(GetElementPtrInst* G);
136 public:
137 ValueTable() { nextValueNumber = 1; }
138 uint32_t lookup_or_add(Value* V);
139 uint32_t lookup(Value* V) const;
140 void add(Value* V, uint32_t num);
141 void clear();
142 void erase(Value* v);
143 unsigned size();
144 };
145}
146
147namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000148template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000149 static inline Expression getEmptyKey() {
150 return Expression(Expression::EMPTY);
151 }
152
153 static inline Expression getTombstoneKey() {
154 return Expression(Expression::TOMBSTONE);
155 }
Owen Anderson85c40642007-07-24 17:55:58 +0000156
157 static unsigned getHashValue(const Expression e) {
158 unsigned hash = e.opcode;
159
160 hash = e.firstVN + hash * 37;
161 hash = e.secondVN + hash * 37;
162 hash = e.thirdVN + hash * 37;
163
164 hash = (unsigned)((uintptr_t)e.type >> 4) ^
165 (unsigned)((uintptr_t)e.type >> 9) +
166 hash * 37;
167
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000168 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
169 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000170 hash = *I + hash * 37;
171
172 return hash;
173 }
Chris Lattner92eea072007-09-17 18:34:04 +0000174 static bool isEqual(const Expression &LHS, const Expression &RHS) {
175 return LHS == RHS;
176 }
Owen Anderson85c40642007-07-24 17:55:58 +0000177 static bool isPod() { return true; }
178};
179}
180
181//===----------------------------------------------------------------------===//
182// ValueTable Internal Functions
183//===----------------------------------------------------------------------===//
184Expression::ExpressionOpcode
185 ValueTable::getOpcode(BinaryOperator* BO) {
186 switch(BO->getOpcode()) {
187 case Instruction::Add:
188 return Expression::ADD;
189 case Instruction::Sub:
190 return Expression::SUB;
191 case Instruction::Mul:
192 return Expression::MUL;
193 case Instruction::UDiv:
194 return Expression::UDIV;
195 case Instruction::SDiv:
196 return Expression::SDIV;
197 case Instruction::FDiv:
198 return Expression::FDIV;
199 case Instruction::URem:
200 return Expression::UREM;
201 case Instruction::SRem:
202 return Expression::SREM;
203 case Instruction::FRem:
204 return Expression::FREM;
205 case Instruction::Shl:
206 return Expression::SHL;
207 case Instruction::LShr:
208 return Expression::LSHR;
209 case Instruction::AShr:
210 return Expression::ASHR;
211 case Instruction::And:
212 return Expression::AND;
213 case Instruction::Or:
214 return Expression::OR;
215 case Instruction::Xor:
216 return Expression::XOR;
217
218 // THIS SHOULD NEVER HAPPEN
219 default:
220 assert(0 && "Binary operator with unknown opcode?");
221 return Expression::ADD;
222 }
223}
224
225Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
226 if (C->getOpcode() == Instruction::ICmp) {
227 switch (C->getPredicate()) {
228 case ICmpInst::ICMP_EQ:
229 return Expression::ICMPEQ;
230 case ICmpInst::ICMP_NE:
231 return Expression::ICMPNE;
232 case ICmpInst::ICMP_UGT:
233 return Expression::ICMPUGT;
234 case ICmpInst::ICMP_UGE:
235 return Expression::ICMPUGE;
236 case ICmpInst::ICMP_ULT:
237 return Expression::ICMPULT;
238 case ICmpInst::ICMP_ULE:
239 return Expression::ICMPULE;
240 case ICmpInst::ICMP_SGT:
241 return Expression::ICMPSGT;
242 case ICmpInst::ICMP_SGE:
243 return Expression::ICMPSGE;
244 case ICmpInst::ICMP_SLT:
245 return Expression::ICMPSLT;
246 case ICmpInst::ICMP_SLE:
247 return Expression::ICMPSLE;
248
249 // THIS SHOULD NEVER HAPPEN
250 default:
251 assert(0 && "Comparison with unknown predicate?");
252 return Expression::ICMPEQ;
253 }
254 } else {
255 switch (C->getPredicate()) {
256 case FCmpInst::FCMP_OEQ:
257 return Expression::FCMPOEQ;
258 case FCmpInst::FCMP_OGT:
259 return Expression::FCMPOGT;
260 case FCmpInst::FCMP_OGE:
261 return Expression::FCMPOGE;
262 case FCmpInst::FCMP_OLT:
263 return Expression::FCMPOLT;
264 case FCmpInst::FCMP_OLE:
265 return Expression::FCMPOLE;
266 case FCmpInst::FCMP_ONE:
267 return Expression::FCMPONE;
268 case FCmpInst::FCMP_ORD:
269 return Expression::FCMPORD;
270 case FCmpInst::FCMP_UNO:
271 return Expression::FCMPUNO;
272 case FCmpInst::FCMP_UEQ:
273 return Expression::FCMPUEQ;
274 case FCmpInst::FCMP_UGT:
275 return Expression::FCMPUGT;
276 case FCmpInst::FCMP_UGE:
277 return Expression::FCMPUGE;
278 case FCmpInst::FCMP_ULT:
279 return Expression::FCMPULT;
280 case FCmpInst::FCMP_ULE:
281 return Expression::FCMPULE;
282 case FCmpInst::FCMP_UNE:
283 return Expression::FCMPUNE;
284
285 // THIS SHOULD NEVER HAPPEN
286 default:
287 assert(0 && "Comparison with unknown predicate?");
288 return Expression::FCMPOEQ;
289 }
290 }
291}
292
293Expression::ExpressionOpcode
294 ValueTable::getOpcode(CastInst* C) {
295 switch(C->getOpcode()) {
296 case Instruction::Trunc:
297 return Expression::TRUNC;
298 case Instruction::ZExt:
299 return Expression::ZEXT;
300 case Instruction::SExt:
301 return Expression::SEXT;
302 case Instruction::FPToUI:
303 return Expression::FPTOUI;
304 case Instruction::FPToSI:
305 return Expression::FPTOSI;
306 case Instruction::UIToFP:
307 return Expression::UITOFP;
308 case Instruction::SIToFP:
309 return Expression::SITOFP;
310 case Instruction::FPTrunc:
311 return Expression::FPTRUNC;
312 case Instruction::FPExt:
313 return Expression::FPEXT;
314 case Instruction::PtrToInt:
315 return Expression::PTRTOINT;
316 case Instruction::IntToPtr:
317 return Expression::INTTOPTR;
318 case Instruction::BitCast:
319 return Expression::BITCAST;
320
321 // THIS SHOULD NEVER HAPPEN
322 default:
323 assert(0 && "Cast operator with unknown opcode?");
324 return Expression::BITCAST;
325 }
326}
327
328Expression ValueTable::create_expression(BinaryOperator* BO) {
329 Expression e;
330
331 e.firstVN = lookup_or_add(BO->getOperand(0));
332 e.secondVN = lookup_or_add(BO->getOperand(1));
333 e.thirdVN = 0;
334 e.type = BO->getType();
335 e.opcode = getOpcode(BO);
336
337 return e;
338}
339
340Expression ValueTable::create_expression(CmpInst* C) {
341 Expression e;
342
343 e.firstVN = lookup_or_add(C->getOperand(0));
344 e.secondVN = lookup_or_add(C->getOperand(1));
345 e.thirdVN = 0;
346 e.type = C->getType();
347 e.opcode = getOpcode(C);
348
349 return e;
350}
351
352Expression ValueTable::create_expression(CastInst* C) {
353 Expression e;
354
355 e.firstVN = lookup_or_add(C->getOperand(0));
356 e.secondVN = 0;
357 e.thirdVN = 0;
358 e.type = C->getType();
359 e.opcode = getOpcode(C);
360
361 return e;
362}
363
364Expression ValueTable::create_expression(ShuffleVectorInst* S) {
365 Expression e;
366
367 e.firstVN = lookup_or_add(S->getOperand(0));
368 e.secondVN = lookup_or_add(S->getOperand(1));
369 e.thirdVN = lookup_or_add(S->getOperand(2));
370 e.type = S->getType();
371 e.opcode = Expression::SHUFFLE;
372
373 return e;
374}
375
376Expression ValueTable::create_expression(ExtractElementInst* E) {
377 Expression e;
378
379 e.firstVN = lookup_or_add(E->getOperand(0));
380 e.secondVN = lookup_or_add(E->getOperand(1));
381 e.thirdVN = 0;
382 e.type = E->getType();
383 e.opcode = Expression::EXTRACT;
384
385 return e;
386}
387
388Expression ValueTable::create_expression(InsertElementInst* I) {
389 Expression e;
390
391 e.firstVN = lookup_or_add(I->getOperand(0));
392 e.secondVN = lookup_or_add(I->getOperand(1));
393 e.thirdVN = lookup_or_add(I->getOperand(2));
394 e.type = I->getType();
395 e.opcode = Expression::INSERT;
396
397 return e;
398}
399
400Expression ValueTable::create_expression(SelectInst* I) {
401 Expression e;
402
403 e.firstVN = lookup_or_add(I->getCondition());
404 e.secondVN = lookup_or_add(I->getTrueValue());
405 e.thirdVN = lookup_or_add(I->getFalseValue());
406 e.type = I->getType();
407 e.opcode = Expression::SELECT;
408
409 return e;
410}
411
412Expression ValueTable::create_expression(GetElementPtrInst* G) {
413 Expression e;
414
415 e.firstVN = lookup_or_add(G->getPointerOperand());
416 e.secondVN = 0;
417 e.thirdVN = 0;
418 e.type = G->getType();
419 e.opcode = Expression::GEP;
420
421 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
422 I != E; ++I)
423 e.varargs.push_back(lookup_or_add(*I));
424
425 return e;
426}
427
428//===----------------------------------------------------------------------===//
429// ValueTable External Functions
430//===----------------------------------------------------------------------===//
431
432/// lookup_or_add - Returns the value number for the specified value, assigning
433/// it a new number if it did not have one before.
434uint32_t ValueTable::lookup_or_add(Value* V) {
435 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
436 if (VI != valueNumbering.end())
437 return VI->second;
438
439
440 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
441 Expression e = create_expression(BO);
442
443 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
444 if (EI != expressionNumbering.end()) {
445 valueNumbering.insert(std::make_pair(V, EI->second));
446 return EI->second;
447 } else {
448 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
449 valueNumbering.insert(std::make_pair(V, nextValueNumber));
450
451 return nextValueNumber++;
452 }
453 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
454 Expression e = create_expression(C);
455
456 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
457 if (EI != expressionNumbering.end()) {
458 valueNumbering.insert(std::make_pair(V, EI->second));
459 return EI->second;
460 } else {
461 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
462 valueNumbering.insert(std::make_pair(V, nextValueNumber));
463
464 return nextValueNumber++;
465 }
466 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
467 Expression e = create_expression(U);
468
469 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
470 if (EI != expressionNumbering.end()) {
471 valueNumbering.insert(std::make_pair(V, EI->second));
472 return EI->second;
473 } else {
474 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
475 valueNumbering.insert(std::make_pair(V, nextValueNumber));
476
477 return nextValueNumber++;
478 }
479 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
480 Expression e = create_expression(U);
481
482 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
483 if (EI != expressionNumbering.end()) {
484 valueNumbering.insert(std::make_pair(V, EI->second));
485 return EI->second;
486 } else {
487 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
488 valueNumbering.insert(std::make_pair(V, nextValueNumber));
489
490 return nextValueNumber++;
491 }
492 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
493 Expression e = create_expression(U);
494
495 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
496 if (EI != expressionNumbering.end()) {
497 valueNumbering.insert(std::make_pair(V, EI->second));
498 return EI->second;
499 } else {
500 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
501 valueNumbering.insert(std::make_pair(V, nextValueNumber));
502
503 return nextValueNumber++;
504 }
505 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
506 Expression e = create_expression(U);
507
508 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
509 if (EI != expressionNumbering.end()) {
510 valueNumbering.insert(std::make_pair(V, EI->second));
511 return EI->second;
512 } else {
513 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
514 valueNumbering.insert(std::make_pair(V, nextValueNumber));
515
516 return nextValueNumber++;
517 }
518 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
519 Expression e = create_expression(U);
520
521 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
522 if (EI != expressionNumbering.end()) {
523 valueNumbering.insert(std::make_pair(V, EI->second));
524 return EI->second;
525 } else {
526 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
528
529 return nextValueNumber++;
530 }
531 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
532 Expression e = create_expression(U);
533
534 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
535 if (EI != expressionNumbering.end()) {
536 valueNumbering.insert(std::make_pair(V, EI->second));
537 return EI->second;
538 } else {
539 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
540 valueNumbering.insert(std::make_pair(V, nextValueNumber));
541
542 return nextValueNumber++;
543 }
544 } else {
545 valueNumbering.insert(std::make_pair(V, nextValueNumber));
546 return nextValueNumber++;
547 }
548}
549
550/// lookup - Returns the value number of the specified value. Fails if
551/// the value has not yet been numbered.
552uint32_t ValueTable::lookup(Value* V) const {
553 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
554 if (VI != valueNumbering.end())
555 return VI->second;
556 else
557 assert(0 && "Value not numbered?");
558
559 return 0;
560}
561
562/// clear - Remove all entries from the ValueTable
563void ValueTable::clear() {
564 valueNumbering.clear();
565 expressionNumbering.clear();
566 nextValueNumber = 1;
567}
568
Owen Anderson5aff8002007-07-31 23:27:13 +0000569/// erase - Remove a value from the value numbering
570void ValueTable::erase(Value* V) {
571 valueNumbering.erase(V);
572}
573
Owen Anderson85c40642007-07-24 17:55:58 +0000574//===----------------------------------------------------------------------===//
575// ValueNumberedSet Class
576//===----------------------------------------------------------------------===//
577namespace {
578class ValueNumberedSet {
579 private:
580 SmallPtrSet<Value*, 8> contents;
581 BitVector numbers;
582 public:
583 ValueNumberedSet() { numbers.resize(1); }
584 ValueNumberedSet(const ValueNumberedSet& other) {
585 numbers = other.numbers;
586 contents = other.contents;
587 }
588
589 typedef SmallPtrSet<Value*, 8>::iterator iterator;
590
591 iterator begin() { return contents.begin(); }
592 iterator end() { return contents.end(); }
593
594 bool insert(Value* v) { return contents.insert(v); }
595 void insert(iterator I, iterator E) { contents.insert(I, E); }
596 void erase(Value* v) { contents.erase(v); }
597 unsigned count(Value* v) { return contents.count(v); }
598 size_t size() { return contents.size(); }
599
600 void set(unsigned i) {
601 if (i >= numbers.size())
602 numbers.resize(i+1);
603
604 numbers.set(i);
605 }
606
607 void operator=(const ValueNumberedSet& other) {
608 contents = other.contents;
609 numbers = other.numbers;
610 }
611
612 void reset(unsigned i) {
613 if (i < numbers.size())
614 numbers.reset(i);
615 }
616
617 bool test(unsigned i) {
618 if (i >= numbers.size())
619 return false;
620
621 return numbers.test(i);
622 }
623
624 void clear() {
625 contents.clear();
626 numbers.clear();
627 }
628};
629}
630
631//===----------------------------------------------------------------------===//
632// GVN Pass
633//===----------------------------------------------------------------------===//
634
635namespace {
636
637 class VISIBILITY_HIDDEN GVN : public FunctionPass {
638 bool runOnFunction(Function &F);
639 public:
640 static char ID; // Pass identification, replacement for typeid
641 GVN() : FunctionPass((intptr_t)&ID) { }
642
643 private:
644 ValueTable VN;
645
646 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
647
Owen Anderson5b299672007-08-07 23:12:31 +0000648 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
649 PhiMapType phiMap;
650
651
Owen Anderson85c40642007-07-24 17:55:58 +0000652 // This transformation requires dominator postdominator info
653 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
654 AU.setPreservesCFG();
655 AU.addRequired<DominatorTree>();
656 AU.addRequired<MemoryDependenceAnalysis>();
657 AU.addPreserved<MemoryDependenceAnalysis>();
658 }
659
660 // Helper fuctions
661 // FIXME: eliminate or document these better
662 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
663 void val_insert(ValueNumberedSet& s, Value* v);
664 bool processLoad(LoadInst* L,
665 DenseMap<Value*, LoadInst*>& lastLoad,
666 SmallVector<Instruction*, 4>& toErase);
667 bool processInstruction(Instruction* I,
668 ValueNumberedSet& currAvail,
669 DenseMap<Value*, LoadInst*>& lastSeenLoad,
670 SmallVector<Instruction*, 4>& toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000671 bool processNonLocalLoad(LoadInst* L,
672 SmallVector<Instruction*, 4>& toErase);
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000673 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000674 DenseMap<BasicBlock*, Value*> &Phis,
675 bool top_level = false);
Owen Anderson5d72a422007-07-25 19:57:03 +0000676 void dump(DenseMap<BasicBlock*, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000677 bool iterateOnFunction(Function &F);
Owen Andersone02ad522007-08-16 22:51:56 +0000678 Value* CollapsePhi(PHINode* p);
Owen Anderson19625972007-09-16 08:04:16 +0000679 bool isSafeReplacement(PHINode* p, Instruction* inst);
Owen Anderson85c40642007-07-24 17:55:58 +0000680 };
681
682 char GVN::ID = 0;
683
684}
685
686// createGVNPass - The public interface to this file...
687FunctionPass *llvm::createGVNPass() { return new GVN(); }
688
689static RegisterPass<GVN> X("gvn",
690 "Global Value Numbering");
691
692STATISTIC(NumGVNInstr, "Number of instructions deleted");
693STATISTIC(NumGVNLoad, "Number of loads deleted");
694
695/// find_leader - Given a set and a value number, return the first
696/// element of the set with that value number, or 0 if no such element
697/// is present
698Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
699 if (!vals.test(v))
700 return 0;
701
702 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
703 I != E; ++I)
704 if (v == VN.lookup(*I))
705 return *I;
706
707 assert(0 && "No leader found, but present bit is set?");
708 return 0;
709}
710
711/// val_insert - Insert a value into a set only if there is not a value
712/// with the same value number already in the set
713void GVN::val_insert(ValueNumberedSet& s, Value* v) {
714 uint32_t num = VN.lookup(v);
715 if (!s.test(num))
716 s.insert(v);
717}
718
Owen Anderson5d72a422007-07-25 19:57:03 +0000719void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
720 printf("{\n");
721 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
722 E = d.end(); I != E; ++I) {
723 if (I->second == MemoryDependenceAnalysis::None)
724 printf("None\n");
725 else
726 I->second->dump();
727 }
728 printf("}\n");
729}
730
Owen Andersone02ad522007-08-16 22:51:56 +0000731Value* GVN::CollapsePhi(PHINode* p) {
732 DominatorTree &DT = getAnalysis<DominatorTree>();
733 Value* constVal = p->hasConstantValue();
734
735 if (constVal) {
736 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
737 if (DT.dominates(inst, p))
Owen Anderson19625972007-09-16 08:04:16 +0000738 if (isSafeReplacement(p, inst))
739 return inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000740 } else {
741 return constVal;
742 }
743 }
744
745 return 0;
746}
Owen Anderson5d72a422007-07-25 19:57:03 +0000747
Owen Anderson19625972007-09-16 08:04:16 +0000748bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
749 if (!isa<PHINode>(inst))
750 return true;
751
752 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
753 UI != E; ++UI)
754 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
755 if (use_phi->getParent() == inst->getParent())
756 return false;
757
758 return true;
759}
760
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000761/// GetValueForBlock - Get the value to use within the specified basic block.
762/// available values are in Phis.
763Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000764 DenseMap<BasicBlock*, Value*> &Phis,
765 bool top_level) {
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000766
767 // If we have already computed this value, return the previously computed val.
Owen Andersoned7f9932007-08-03 19:59:35 +0000768 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
769 if (V != Phis.end() && !top_level) return V->second;
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000770
Owen Anderson3f75d122007-08-01 22:01:54 +0000771 BasicBlock* singlePred = BB->getSinglePredecessor();
Owen Anderson30463f12007-08-03 11:03:26 +0000772 if (singlePred) {
Owen Andersoned7f9932007-08-03 19:59:35 +0000773 Value *ret = GetValueForBlock(singlePred, orig, Phis);
774 Phis[BB] = ret;
775 return ret;
Owen Anderson30463f12007-08-03 11:03:26 +0000776 }
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000777 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
778 // now, then get values to fill in the incoming values for the PHI.
779 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
780 BB->begin());
781 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
Owen Andersoned7f9932007-08-03 19:59:35 +0000782
783 if (Phis.count(BB) == 0)
784 Phis.insert(std::make_pair(BB, PN));
Owen Anderson48a2c562007-07-30 16:57:08 +0000785
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000786 // Fill in the incoming values for the block.
Owen Anderson9f577412007-07-31 17:43:14 +0000787 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
788 Value* val = GetValueForBlock(*PI, orig, Phis);
Owen Anderson9f577412007-07-31 17:43:14 +0000789
790 PN->addIncoming(val, *PI);
791 }
792
Owen Andersone0143452007-08-16 22:02:55 +0000793 // Attempt to collapse PHI nodes that are trivially redundant
Owen Andersone02ad522007-08-16 22:51:56 +0000794 Value* v = CollapsePhi(PN);
Owen Andersonf631bb62007-08-14 18:16:29 +0000795 if (v) {
Owen Andersone02ad522007-08-16 22:51:56 +0000796 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersonf631bb62007-08-14 18:16:29 +0000797
Owen Andersone02ad522007-08-16 22:51:56 +0000798 MD.removeInstruction(PN);
799 PN->replaceAllUsesWith(v);
Owen Andersonf631bb62007-08-14 18:16:29 +0000800
Owen Andersone02ad522007-08-16 22:51:56 +0000801 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
802 E = Phis.end(); I != E; ++I)
803 if (I->second == PN)
804 I->second = v;
Owen Andersonf631bb62007-08-14 18:16:29 +0000805
Owen Andersone02ad522007-08-16 22:51:56 +0000806 PN->eraseFromParent();
Owen Andersonf631bb62007-08-14 18:16:29 +0000807
Owen Andersone02ad522007-08-16 22:51:56 +0000808 Phis[BB] = v;
Owen Andersonf631bb62007-08-14 18:16:29 +0000809
Owen Andersone02ad522007-08-16 22:51:56 +0000810 return v;
Owen Anderson9f577412007-07-31 17:43:14 +0000811 }
812
Owen Andersone0143452007-08-16 22:02:55 +0000813 // Cache our phi construction results
Owen Anderson5b299672007-08-07 23:12:31 +0000814 phiMap[orig->getPointerOperand()].insert(PN);
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000815 return PN;
Owen Anderson5d72a422007-07-25 19:57:03 +0000816}
817
Owen Andersone0143452007-08-16 22:02:55 +0000818/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
819/// non-local by performing PHI construction.
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000820bool GVN::processNonLocalLoad(LoadInst* L,
821 SmallVector<Instruction*, 4>& toErase) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000822 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
823
Owen Andersone0143452007-08-16 22:02:55 +0000824 // Find the non-local dependencies of the load
Owen Anderson5d72a422007-07-25 19:57:03 +0000825 DenseMap<BasicBlock*, Value*> deps;
Owen Anderson3f75d122007-08-01 22:01:54 +0000826 MD.getNonLocalDependency(L, deps);
Owen Anderson5d72a422007-07-25 19:57:03 +0000827
828 DenseMap<BasicBlock*, Value*> repl;
Owen Anderson5b299672007-08-07 23:12:31 +0000829
Owen Andersone0143452007-08-16 22:02:55 +0000830 // Filter out useless results (non-locals, etc)
Owen Anderson5d72a422007-07-25 19:57:03 +0000831 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
832 I != E; ++I)
833 if (I->second == MemoryDependenceAnalysis::None) {
834 return false;
Owen Andersonb484d1f2007-07-30 17:29:24 +0000835 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
836 continue;
Owen Anderson935e39b2007-08-09 04:42:44 +0000837 }else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000838 if (S->getPointerOperand() == L->getPointerOperand())
Owen Anderson5b299672007-08-07 23:12:31 +0000839 repl[I->first] = S->getOperand(0);
Owen Anderson5d72a422007-07-25 19:57:03 +0000840 else
841 return false;
842 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
843 if (LD->getPointerOperand() == L->getPointerOperand())
Owen Anderson5b299672007-08-07 23:12:31 +0000844 repl[I->first] = LD;
Owen Anderson5d72a422007-07-25 19:57:03 +0000845 else
846 return false;
847 } else {
848 return false;
849 }
850
Owen Andersone0143452007-08-16 22:02:55 +0000851 // Use cached PHI construction information from previous runs
Owen Anderson5b299672007-08-07 23:12:31 +0000852 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
853 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
854 I != E; ++I) {
855 if ((*I)->getParent() == L->getParent()) {
856 MD.removeInstruction(L);
857 L->replaceAllUsesWith(*I);
858 toErase.push_back(L);
859 NumGVNLoad++;
860
861 return true;
862 } else {
863 repl.insert(std::make_pair((*I)->getParent(), *I));
864 }
865 }
866
Owen Andersone0143452007-08-16 22:02:55 +0000867 // Perform PHI construction
Owen Anderson6ce3ae22007-07-25 22:03:06 +0000868 SmallPtrSet<BasicBlock*, 4> visited;
Owen Andersonc6a31b92007-08-02 17:56:05 +0000869 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
Owen Anderson5d72a422007-07-25 19:57:03 +0000870
871 MD.removeInstruction(L);
872 L->replaceAllUsesWith(v);
873 toErase.push_back(L);
Owen Anderson5b299672007-08-07 23:12:31 +0000874 NumGVNLoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +0000875
876 return true;
877}
878
Owen Andersone0143452007-08-16 22:02:55 +0000879/// processLoad - Attempt to eliminate a load, first by eliminating it
880/// locally, and then attempting non-local elimination if that fails.
Owen Anderson85c40642007-07-24 17:55:58 +0000881bool GVN::processLoad(LoadInst* L,
882 DenseMap<Value*, LoadInst*>& lastLoad,
883 SmallVector<Instruction*, 4>& toErase) {
884 if (L->isVolatile()) {
885 lastLoad[L->getPointerOperand()] = L;
886 return false;
887 }
888
889 Value* pointer = L->getPointerOperand();
890 LoadInst*& last = lastLoad[pointer];
891
892 // ... to a pointer that has been loaded from before...
893 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000894 bool removedNonLocal = false;
Owen Anderson935e39b2007-08-09 04:42:44 +0000895 Instruction* dep = MD.getDependency(L);
Owen Anderson5d72a422007-07-25 19:57:03 +0000896 if (dep == MemoryDependenceAnalysis::NonLocal &&
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000897 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
898 removedNonLocal = processNonLocalLoad(L, toErase);
899
900 if (!removedNonLocal)
901 last = L;
902
903 return removedNonLocal;
904 }
905
906
Owen Anderson85c40642007-07-24 17:55:58 +0000907 bool deletedLoad = false;
908
Owen Andersone0143452007-08-16 22:02:55 +0000909 // Walk up the dependency chain until we either find
910 // a dependency we can use, or we can't walk any further
Owen Anderson85c40642007-07-24 17:55:58 +0000911 while (dep != MemoryDependenceAnalysis::None &&
912 dep != MemoryDependenceAnalysis::NonLocal &&
913 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
914 // ... that depends on a store ...
915 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
916 if (S->getPointerOperand() == pointer) {
917 // Remove it!
918 MD.removeInstruction(L);
919
920 L->replaceAllUsesWith(S->getOperand(0));
921 toErase.push_back(L);
922 deletedLoad = true;
923 NumGVNLoad++;
924 }
925
926 // Whether we removed it or not, we can't
927 // go any further
928 break;
929 } else if (!last) {
930 // If we don't depend on a store, and we haven't
931 // been loaded before, bail.
932 break;
933 } else if (dep == last) {
934 // Remove it!
935 MD.removeInstruction(L);
936
937 L->replaceAllUsesWith(last);
938 toErase.push_back(L);
939 deletedLoad = true;
940 NumGVNLoad++;
941
942 break;
943 } else {
Owen Anderson935e39b2007-08-09 04:42:44 +0000944 dep = MD.getDependency(L, dep);
Owen Anderson85c40642007-07-24 17:55:58 +0000945 }
946 }
947
948 if (!deletedLoad)
949 last = L;
950
951 return deletedLoad;
952}
953
Owen Andersonf631bb62007-08-14 18:16:29 +0000954/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +0000955/// by inserting it into the appropriate sets
956bool GVN::processInstruction(Instruction* I,
957 ValueNumberedSet& currAvail,
958 DenseMap<Value*, LoadInst*>& lastSeenLoad,
959 SmallVector<Instruction*, 4>& toErase) {
960 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
961 return processLoad(L, lastSeenLoad, toErase);
962 }
963
964 unsigned num = VN.lookup_or_add(I);
965
Owen Andersone0143452007-08-16 22:02:55 +0000966 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +0000967 if (PHINode* p = dyn_cast<PHINode>(I)) {
Owen Andersone02ad522007-08-16 22:51:56 +0000968 Value* constVal = CollapsePhi(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +0000969
970 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +0000971 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
972 PI != PE; ++PI)
973 if (PI->second.count(p))
974 PI->second.erase(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +0000975
Owen Andersone02ad522007-08-16 22:51:56 +0000976 p->replaceAllUsesWith(constVal);
977 toErase.push_back(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +0000978 }
Owen Andersone0143452007-08-16 22:02:55 +0000979 // Perform value-number based elimination
Owen Anderson98f6a6b2007-08-14 18:33:27 +0000980 } else if (currAvail.test(num)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000981 Value* repl = find_leader(currAvail, num);
982
Owen Anderson5aff8002007-07-31 23:27:13 +0000983 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +0000984 I->replaceAllUsesWith(repl);
985 toErase.push_back(I);
986 return true;
987 } else if (!I->isTerminator()) {
988 currAvail.set(num);
989 currAvail.insert(I);
990 }
991
992 return false;
993}
994
995// GVN::runOnFunction - This is the main transformation entry point for a
996// function.
997//
Owen Andersonbe168b32007-08-14 18:04:11 +0000998bool GVN::runOnFunction(Function& F) {
999 bool changed = false;
1000 bool shouldContinue = true;
1001
1002 while (shouldContinue) {
1003 shouldContinue = iterateOnFunction(F);
1004 changed |= shouldContinue;
1005 }
1006
1007 return changed;
1008}
1009
1010
1011// GVN::iterateOnFunction - Executes one iteration of GVN
1012bool GVN::iterateOnFunction(Function &F) {
Owen Anderson85c40642007-07-24 17:55:58 +00001013 // Clean out global sets from any previous functions
1014 VN.clear();
1015 availableOut.clear();
Owen Anderson5b299672007-08-07 23:12:31 +00001016 phiMap.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001017
1018 bool changed_function = false;
1019
1020 DominatorTree &DT = getAnalysis<DominatorTree>();
1021
1022 SmallVector<Instruction*, 4> toErase;
1023
1024 // Top-down walk of the dominator tree
1025 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1026 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1027
1028 // Get the set to update for this block
1029 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1030 DenseMap<Value*, LoadInst*> lastSeenLoad;
1031
1032 BasicBlock* BB = DI->getBlock();
1033
1034 // A block inherits AVAIL_OUT from its dominator
1035 if (DI->getIDom() != 0)
1036 currAvail = availableOut[DI->getIDom()->getBlock()];
1037
1038 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
Owen Andersonc0403802007-07-30 21:26:39 +00001039 BI != BE; ) {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +00001040 changed_function |= processInstruction(BI, currAvail,
1041 lastSeenLoad, toErase);
Owen Anderson5d72a422007-07-25 19:57:03 +00001042
1043 NumGVNInstr += toErase.size();
1044
Owen Andersonc0403802007-07-30 21:26:39 +00001045 // Avoid iterator invalidation
1046 ++BI;
1047
Owen Anderson5d72a422007-07-25 19:57:03 +00001048 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1049 E = toErase.end(); I != E; ++I)
1050 (*I)->eraseFromParent();
1051
1052 toErase.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001053 }
1054 }
1055
Owen Anderson85c40642007-07-24 17:55:58 +00001056 return changed_function;
1057}