blob: b164873763a1b618a32f0a795d102933241d4aad [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
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 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.
18//
19//===----------------------------------------------------------------------===//
20
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"
Owen Anderson16780522007-07-19 06:13:15 +000033#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
36#include "llvm/Support/CFG.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/Debug.h"
39#include <algorithm>
40#include <deque>
41#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042using namespace llvm;
43
44//===----------------------------------------------------------------------===//
45// ValueTable Class
46//===----------------------------------------------------------------------===//
47
48/// This class holds the mapping between values and value numbers. It is used
49/// as an efficient mechanism to determine the expression-wise equivalence of
50/// two values.
51
Owen Anderson16780522007-07-19 06:13:15 +000052struct Expression {
53 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
54 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
55 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
56 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
57 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
58 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
59 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
60 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
61 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
62 PTRTOINT, INTTOPTR, BITCAST, GEP, EMPTY,
63 TOMBSTONE };
64
65 ExpressionOpcode opcode;
66 const Type* type;
67 uint32_t firstVN;
68 uint32_t secondVN;
69 uint32_t thirdVN;
70 SmallVector<uint32_t, 4> varargs;
71
72 Expression() { }
Dan Gohman26247f02007-09-24 15:48:49 +000073 explicit Expression(ExpressionOpcode o) : opcode(o) { }
Owen Anderson16780522007-07-19 06:13:15 +000074
75 bool operator==(const Expression &other) const {
76 if (opcode != other.opcode)
77 return false;
78 else if (opcode == EMPTY || opcode == TOMBSTONE)
79 return true;
80 else if (type != other.type)
81 return false;
82 else if (firstVN != other.firstVN)
83 return false;
84 else if (secondVN != other.secondVN)
85 return false;
86 else if (thirdVN != other.thirdVN)
87 return false;
88 else {
89 if (varargs.size() != other.varargs.size())
90 return false;
91
92 for (size_t i = 0; i < varargs.size(); ++i)
93 if (varargs[i] != other.varargs[i])
94 return false;
95
96 return true;
97 }
98 }
99
100 bool operator!=(const Expression &other) const {
101 if (opcode != other.opcode)
102 return true;
103 else if (opcode == EMPTY || opcode == TOMBSTONE)
104 return false;
105 else if (type != other.type)
106 return true;
107 else if (firstVN != other.firstVN)
108 return true;
109 else if (secondVN != other.secondVN)
110 return true;
111 else if (thirdVN != other.thirdVN)
112 return true;
113 else {
114 if (varargs.size() != other.varargs.size())
115 return true;
116
117 for (size_t i = 0; i < varargs.size(); ++i)
118 if (varargs[i] != other.varargs[i])
119 return true;
120
121 return false;
122 }
123 }
124};
125
126
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127namespace {
128 class VISIBILITY_HIDDEN ValueTable {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 private:
130 DenseMap<Value*, uint32_t> valueNumbering;
Owen Anderson16780522007-07-19 06:13:15 +0000131 DenseMap<Expression, uint32_t> expressionNumbering;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132
133 uint32_t nextValueNumber;
134
135 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
136 Expression::ExpressionOpcode getOpcode(CmpInst* C);
137 Expression::ExpressionOpcode getOpcode(CastInst* C);
138 Expression create_expression(BinaryOperator* BO);
139 Expression create_expression(CmpInst* C);
140 Expression create_expression(ShuffleVectorInst* V);
141 Expression create_expression(ExtractElementInst* C);
142 Expression create_expression(InsertElementInst* V);
143 Expression create_expression(SelectInst* V);
144 Expression create_expression(CastInst* C);
145 Expression create_expression(GetElementPtrInst* G);
146 public:
147 ValueTable() { nextValueNumber = 1; }
148 uint32_t lookup_or_add(Value* V);
149 uint32_t lookup(Value* V) const;
150 void add(Value* V, uint32_t num);
151 void clear();
152 void erase(Value* v);
153 unsigned size();
154 };
155}
156
Owen Anderson16780522007-07-19 06:13:15 +0000157namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000158template <> struct DenseMapInfo<Expression> {
Owen Anderson0b7ad4b2007-08-02 18:20:52 +0000159 static inline Expression getEmptyKey() {
160 return Expression(Expression::EMPTY);
161 }
162
163 static inline Expression getTombstoneKey() {
164 return Expression(Expression::TOMBSTONE);
165 }
Owen Anderson16780522007-07-19 06:13:15 +0000166
167 static unsigned getHashValue(const Expression e) {
168 unsigned hash = e.opcode;
169
170 hash = e.firstVN + hash * 37;
171 hash = e.secondVN + hash * 37;
172 hash = e.thirdVN + hash * 37;
173
174 hash = (unsigned)((uintptr_t)e.type >> 4) ^
175 (unsigned)((uintptr_t)e.type >> 9) +
176 hash * 37;
177
Owen Anderson0b7ad4b2007-08-02 18:20:52 +0000178 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
179 E = e.varargs.end(); I != E; ++I)
Owen Anderson16780522007-07-19 06:13:15 +0000180 hash = *I + hash * 37;
181
182 return hash;
183 }
Chris Lattner92eea072007-09-17 18:34:04 +0000184 static bool isEqual(const Expression &LHS, const Expression &RHS) {
185 return LHS == RHS;
186 }
Owen Anderson16780522007-07-19 06:13:15 +0000187 static bool isPod() { return true; }
188};
189}
190
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191//===----------------------------------------------------------------------===//
192// ValueTable Internal Functions
193//===----------------------------------------------------------------------===//
Owen Anderson16780522007-07-19 06:13:15 +0000194Expression::ExpressionOpcode
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 ValueTable::getOpcode(BinaryOperator* BO) {
196 switch(BO->getOpcode()) {
197 case Instruction::Add:
198 return Expression::ADD;
199 case Instruction::Sub:
200 return Expression::SUB;
201 case Instruction::Mul:
202 return Expression::MUL;
203 case Instruction::UDiv:
204 return Expression::UDIV;
205 case Instruction::SDiv:
206 return Expression::SDIV;
207 case Instruction::FDiv:
208 return Expression::FDIV;
209 case Instruction::URem:
210 return Expression::UREM;
211 case Instruction::SRem:
212 return Expression::SREM;
213 case Instruction::FRem:
214 return Expression::FREM;
215 case Instruction::Shl:
216 return Expression::SHL;
217 case Instruction::LShr:
218 return Expression::LSHR;
219 case Instruction::AShr:
220 return Expression::ASHR;
221 case Instruction::And:
222 return Expression::AND;
223 case Instruction::Or:
224 return Expression::OR;
225 case Instruction::Xor:
226 return Expression::XOR;
227
228 // THIS SHOULD NEVER HAPPEN
229 default:
230 assert(0 && "Binary operator with unknown opcode?");
231 return Expression::ADD;
232 }
233}
234
Owen Anderson16780522007-07-19 06:13:15 +0000235Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 if (C->getOpcode() == Instruction::ICmp) {
237 switch (C->getPredicate()) {
238 case ICmpInst::ICMP_EQ:
239 return Expression::ICMPEQ;
240 case ICmpInst::ICMP_NE:
241 return Expression::ICMPNE;
242 case ICmpInst::ICMP_UGT:
243 return Expression::ICMPUGT;
244 case ICmpInst::ICMP_UGE:
245 return Expression::ICMPUGE;
246 case ICmpInst::ICMP_ULT:
247 return Expression::ICMPULT;
248 case ICmpInst::ICMP_ULE:
249 return Expression::ICMPULE;
250 case ICmpInst::ICMP_SGT:
251 return Expression::ICMPSGT;
252 case ICmpInst::ICMP_SGE:
253 return Expression::ICMPSGE;
254 case ICmpInst::ICMP_SLT:
255 return Expression::ICMPSLT;
256 case ICmpInst::ICMP_SLE:
257 return Expression::ICMPSLE;
258
259 // THIS SHOULD NEVER HAPPEN
260 default:
261 assert(0 && "Comparison with unknown predicate?");
262 return Expression::ICMPEQ;
263 }
264 } else {
265 switch (C->getPredicate()) {
266 case FCmpInst::FCMP_OEQ:
267 return Expression::FCMPOEQ;
268 case FCmpInst::FCMP_OGT:
269 return Expression::FCMPOGT;
270 case FCmpInst::FCMP_OGE:
271 return Expression::FCMPOGE;
272 case FCmpInst::FCMP_OLT:
273 return Expression::FCMPOLT;
274 case FCmpInst::FCMP_OLE:
275 return Expression::FCMPOLE;
276 case FCmpInst::FCMP_ONE:
277 return Expression::FCMPONE;
278 case FCmpInst::FCMP_ORD:
279 return Expression::FCMPORD;
280 case FCmpInst::FCMP_UNO:
281 return Expression::FCMPUNO;
282 case FCmpInst::FCMP_UEQ:
283 return Expression::FCMPUEQ;
284 case FCmpInst::FCMP_UGT:
285 return Expression::FCMPUGT;
286 case FCmpInst::FCMP_UGE:
287 return Expression::FCMPUGE;
288 case FCmpInst::FCMP_ULT:
289 return Expression::FCMPULT;
290 case FCmpInst::FCMP_ULE:
291 return Expression::FCMPULE;
292 case FCmpInst::FCMP_UNE:
293 return Expression::FCMPUNE;
294
295 // THIS SHOULD NEVER HAPPEN
296 default:
297 assert(0 && "Comparison with unknown predicate?");
298 return Expression::FCMPOEQ;
299 }
300 }
301}
302
Owen Anderson16780522007-07-19 06:13:15 +0000303Expression::ExpressionOpcode
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 ValueTable::getOpcode(CastInst* C) {
305 switch(C->getOpcode()) {
306 case Instruction::Trunc:
307 return Expression::TRUNC;
308 case Instruction::ZExt:
309 return Expression::ZEXT;
310 case Instruction::SExt:
311 return Expression::SEXT;
312 case Instruction::FPToUI:
313 return Expression::FPTOUI;
314 case Instruction::FPToSI:
315 return Expression::FPTOSI;
316 case Instruction::UIToFP:
317 return Expression::UITOFP;
318 case Instruction::SIToFP:
319 return Expression::SITOFP;
320 case Instruction::FPTrunc:
321 return Expression::FPTRUNC;
322 case Instruction::FPExt:
323 return Expression::FPEXT;
324 case Instruction::PtrToInt:
325 return Expression::PTRTOINT;
326 case Instruction::IntToPtr:
327 return Expression::INTTOPTR;
328 case Instruction::BitCast:
329 return Expression::BITCAST;
330
331 // THIS SHOULD NEVER HAPPEN
332 default:
333 assert(0 && "Cast operator with unknown opcode?");
334 return Expression::BITCAST;
335 }
336}
337
Owen Anderson16780522007-07-19 06:13:15 +0000338Expression ValueTable::create_expression(BinaryOperator* BO) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 Expression e;
340
341 e.firstVN = lookup_or_add(BO->getOperand(0));
342 e.secondVN = lookup_or_add(BO->getOperand(1));
343 e.thirdVN = 0;
344 e.type = BO->getType();
345 e.opcode = getOpcode(BO);
346
347 return e;
348}
349
Owen Anderson16780522007-07-19 06:13:15 +0000350Expression ValueTable::create_expression(CmpInst* C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 Expression e;
352
353 e.firstVN = lookup_or_add(C->getOperand(0));
354 e.secondVN = lookup_or_add(C->getOperand(1));
355 e.thirdVN = 0;
356 e.type = C->getType();
357 e.opcode = getOpcode(C);
358
359 return e;
360}
361
Owen Anderson16780522007-07-19 06:13:15 +0000362Expression ValueTable::create_expression(CastInst* C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 Expression e;
364
365 e.firstVN = lookup_or_add(C->getOperand(0));
366 e.secondVN = 0;
367 e.thirdVN = 0;
368 e.type = C->getType();
369 e.opcode = getOpcode(C);
370
371 return e;
372}
373
Owen Anderson16780522007-07-19 06:13:15 +0000374Expression ValueTable::create_expression(ShuffleVectorInst* S) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 Expression e;
376
377 e.firstVN = lookup_or_add(S->getOperand(0));
378 e.secondVN = lookup_or_add(S->getOperand(1));
379 e.thirdVN = lookup_or_add(S->getOperand(2));
380 e.type = S->getType();
381 e.opcode = Expression::SHUFFLE;
382
383 return e;
384}
385
Owen Anderson16780522007-07-19 06:13:15 +0000386Expression ValueTable::create_expression(ExtractElementInst* E) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387 Expression e;
388
389 e.firstVN = lookup_or_add(E->getOperand(0));
390 e.secondVN = lookup_or_add(E->getOperand(1));
391 e.thirdVN = 0;
392 e.type = E->getType();
393 e.opcode = Expression::EXTRACT;
394
395 return e;
396}
397
Owen Anderson16780522007-07-19 06:13:15 +0000398Expression ValueTable::create_expression(InsertElementInst* I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 Expression e;
400
401 e.firstVN = lookup_or_add(I->getOperand(0));
402 e.secondVN = lookup_or_add(I->getOperand(1));
403 e.thirdVN = lookup_or_add(I->getOperand(2));
404 e.type = I->getType();
405 e.opcode = Expression::INSERT;
406
407 return e;
408}
409
Owen Anderson16780522007-07-19 06:13:15 +0000410Expression ValueTable::create_expression(SelectInst* I) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 Expression e;
412
413 e.firstVN = lookup_or_add(I->getCondition());
414 e.secondVN = lookup_or_add(I->getTrueValue());
415 e.thirdVN = lookup_or_add(I->getFalseValue());
416 e.type = I->getType();
417 e.opcode = Expression::SELECT;
418
419 return e;
420}
421
Owen Anderson16780522007-07-19 06:13:15 +0000422Expression ValueTable::create_expression(GetElementPtrInst* G) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 Expression e;
424
425 e.firstVN = lookup_or_add(G->getPointerOperand());
426 e.secondVN = 0;
427 e.thirdVN = 0;
428 e.type = G->getType();
Owen Anderson0c1f6c92007-07-20 08:19:20 +0000429 e.opcode = Expression::GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430
431 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
432 I != E; ++I)
433 e.varargs.push_back(lookup_or_add(*I));
434
435 return e;
436}
437
438//===----------------------------------------------------------------------===//
439// ValueTable External Functions
440//===----------------------------------------------------------------------===//
441
442/// lookup_or_add - Returns the value number for the specified value, assigning
443/// it a new number if it did not have one before.
444uint32_t ValueTable::lookup_or_add(Value* V) {
445 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
446 if (VI != valueNumbering.end())
447 return VI->second;
448
449
450 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
451 Expression e = create_expression(BO);
452
Owen Anderson16780522007-07-19 06:13:15 +0000453 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 if (EI != expressionNumbering.end()) {
455 valueNumbering.insert(std::make_pair(V, EI->second));
456 return EI->second;
457 } else {
458 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
459 valueNumbering.insert(std::make_pair(V, nextValueNumber));
460
461 return nextValueNumber++;
462 }
463 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
464 Expression e = create_expression(C);
465
Owen Anderson16780522007-07-19 06:13:15 +0000466 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 if (EI != expressionNumbering.end()) {
468 valueNumbering.insert(std::make_pair(V, EI->second));
469 return EI->second;
470 } else {
471 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
472 valueNumbering.insert(std::make_pair(V, nextValueNumber));
473
474 return nextValueNumber++;
475 }
476 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
477 Expression e = create_expression(U);
478
Owen Anderson16780522007-07-19 06:13:15 +0000479 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 if (EI != expressionNumbering.end()) {
481 valueNumbering.insert(std::make_pair(V, EI->second));
482 return EI->second;
483 } else {
484 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
485 valueNumbering.insert(std::make_pair(V, nextValueNumber));
486
487 return nextValueNumber++;
488 }
489 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
490 Expression e = create_expression(U);
491
Owen Anderson16780522007-07-19 06:13:15 +0000492 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 if (EI != expressionNumbering.end()) {
494 valueNumbering.insert(std::make_pair(V, EI->second));
495 return EI->second;
496 } else {
497 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
498 valueNumbering.insert(std::make_pair(V, nextValueNumber));
499
500 return nextValueNumber++;
501 }
502 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
503 Expression e = create_expression(U);
504
Owen Anderson16780522007-07-19 06:13:15 +0000505 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 if (EI != expressionNumbering.end()) {
507 valueNumbering.insert(std::make_pair(V, EI->second));
508 return EI->second;
509 } else {
510 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
511 valueNumbering.insert(std::make_pair(V, nextValueNumber));
512
513 return nextValueNumber++;
514 }
515 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
516 Expression e = create_expression(U);
517
Owen Anderson16780522007-07-19 06:13:15 +0000518 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 if (EI != expressionNumbering.end()) {
520 valueNumbering.insert(std::make_pair(V, EI->second));
521 return EI->second;
522 } else {
523 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
524 valueNumbering.insert(std::make_pair(V, nextValueNumber));
525
526 return nextValueNumber++;
527 }
528 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
529 Expression e = create_expression(U);
530
Owen Anderson16780522007-07-19 06:13:15 +0000531 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 if (EI != expressionNumbering.end()) {
533 valueNumbering.insert(std::make_pair(V, EI->second));
534 return EI->second;
535 } else {
536 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
538
539 return nextValueNumber++;
540 }
541 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
542 Expression e = create_expression(U);
543
Owen Anderson16780522007-07-19 06:13:15 +0000544 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 if (EI != expressionNumbering.end()) {
546 valueNumbering.insert(std::make_pair(V, EI->second));
547 return EI->second;
548 } else {
549 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
550 valueNumbering.insert(std::make_pair(V, nextValueNumber));
551
552 return nextValueNumber++;
553 }
554 } else {
555 valueNumbering.insert(std::make_pair(V, nextValueNumber));
556 return nextValueNumber++;
557 }
558}
559
560/// lookup - Returns the value number of the specified value. Fails if
561/// the value has not yet been numbered.
562uint32_t ValueTable::lookup(Value* V) const {
563 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
564 if (VI != valueNumbering.end())
565 return VI->second;
566 else
567 assert(0 && "Value not numbered?");
568
569 return 0;
570}
571
572/// add - Add the specified value with the given value number, removing
573/// its old number, if any
574void ValueTable::add(Value* V, uint32_t num) {
575 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
576 if (VI != valueNumbering.end())
577 valueNumbering.erase(VI);
578 valueNumbering.insert(std::make_pair(V, num));
579}
580
581/// clear - Remove all entries from the ValueTable
582void ValueTable::clear() {
583 valueNumbering.clear();
584 expressionNumbering.clear();
585 nextValueNumber = 1;
586}
587
588/// erase - Remove a value from the value numbering
589void ValueTable::erase(Value* V) {
590 valueNumbering.erase(V);
591}
592
593/// size - Return the number of assigned value numbers
594unsigned ValueTable::size() {
595 // NOTE: zero is never assigned
596 return nextValueNumber;
597}
598
599//===----------------------------------------------------------------------===//
600// ValueNumberedSet Class
601//===----------------------------------------------------------------------===//
602
603class ValueNumberedSet {
604 private:
605 SmallPtrSet<Value*, 8> contents;
606 BitVector numbers;
607 public:
608 ValueNumberedSet() { numbers.resize(1); }
609 ValueNumberedSet(const ValueNumberedSet& other) {
610 numbers = other.numbers;
611 contents = other.contents;
612 }
613
614 typedef SmallPtrSet<Value*, 8>::iterator iterator;
615
616 iterator begin() { return contents.begin(); }
617 iterator end() { return contents.end(); }
618
619 bool insert(Value* v) { return contents.insert(v); }
620 void insert(iterator I, iterator E) { contents.insert(I, E); }
621 void erase(Value* v) { contents.erase(v); }
622 unsigned count(Value* v) { return contents.count(v); }
623 size_t size() { return contents.size(); }
624
625 void set(unsigned i) {
626 if (i >= numbers.size())
627 numbers.resize(i+1);
628
629 numbers.set(i);
630 }
631
632 void operator=(const ValueNumberedSet& other) {
633 contents = other.contents;
634 numbers = other.numbers;
635 }
636
637 void reset(unsigned i) {
638 if (i < numbers.size())
639 numbers.reset(i);
640 }
641
642 bool test(unsigned i) {
643 if (i >= numbers.size())
644 return false;
645
646 return numbers.test(i);
647 }
648
649 void clear() {
650 contents.clear();
651 numbers.clear();
652 }
653};
654
655//===----------------------------------------------------------------------===//
656// GVNPRE Pass
657//===----------------------------------------------------------------------===//
658
659namespace {
660
661 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
662 bool runOnFunction(Function &F);
663 public:
664 static char ID; // Pass identification, replacement for typeid
665 GVNPRE() : FunctionPass((intptr_t)&ID) { }
666
667 private:
668 ValueTable VN;
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000669 SmallVector<Instruction*, 8> createdExpressions;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670
671 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
672 DenseMap<BasicBlock*, ValueNumberedSet> anticipatedIn;
673 DenseMap<BasicBlock*, ValueNumberedSet> generatedPhis;
674
675 // This transformation requires dominator postdominator info
676 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
677 AU.setPreservesCFG();
678 AU.addRequiredID(BreakCriticalEdgesID);
679 AU.addRequired<UnifyFunctionExitNodes>();
680 AU.addRequired<DominatorTree>();
681 }
682
683 // Helper fuctions
684 // FIXME: eliminate or document these better
685 void dump(ValueNumberedSet& s) const ;
686 void clean(ValueNumberedSet& set) ;
687 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
688 Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) ;
689 void phi_translate_set(ValueNumberedSet& anticIn, BasicBlock* pred,
690 BasicBlock* succ, ValueNumberedSet& out) ;
691
692 void topo_sort(ValueNumberedSet& set,
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000693 SmallVector<Value*, 8>& vec) ;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694
695 void cleanup() ;
696 bool elimination() ;
697
698 void val_insert(ValueNumberedSet& s, Value* v) ;
699 void val_replace(ValueNumberedSet& s, Value* v) ;
700 bool dependsOnInvoke(Value* V) ;
701 void buildsets_availout(BasicBlock::iterator I,
702 ValueNumberedSet& currAvail,
703 ValueNumberedSet& currPhis,
704 ValueNumberedSet& currExps,
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000705 SmallPtrSet<Value*, 16>& currTemps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 bool buildsets_anticout(BasicBlock* BB,
707 ValueNumberedSet& anticOut,
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000708 SmallPtrSet<BasicBlock*, 8>& visited);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 unsigned buildsets_anticin(BasicBlock* BB,
710 ValueNumberedSet& anticOut,
711 ValueNumberedSet& currExps,
712 SmallPtrSet<Value*, 16>& currTemps,
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000713 SmallPtrSet<BasicBlock*, 8>& visited);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 void buildsets(Function& F) ;
715
716 void insertion_pre(Value* e, BasicBlock* BB,
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000717 DenseMap<BasicBlock*, Value*>& avail,
718 std::map<BasicBlock*,ValueNumberedSet>& new_set);
719 unsigned insertion_mergepoint(SmallVector<Value*, 8>& workList,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 df_iterator<DomTreeNode*>& D,
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000721 std::map<BasicBlock*, ValueNumberedSet>& new_set);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 bool insertion(Function& F) ;
723
724 };
725
726 char GVNPRE::ID = 0;
727
728}
729
730// createGVNPREPass - The public interface to this file...
731FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
732
733static RegisterPass<GVNPRE> X("gvnpre",
Owen Anderson0b7ad4b2007-08-02 18:20:52 +0000734 "Global Value Numbering/Partial Redundancy Elimination");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735
736
737STATISTIC(NumInsertedVals, "Number of values inserted");
738STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
739STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
740
741/// find_leader - Given a set and a value number, return the first
742/// element of the set with that value number, or 0 if no such element
743/// is present
744Value* GVNPRE::find_leader(ValueNumberedSet& vals, uint32_t v) {
745 if (!vals.test(v))
746 return 0;
747
748 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
749 I != E; ++I)
750 if (v == VN.lookup(*I))
751 return *I;
752
753 assert(0 && "No leader found, but present bit is set?");
754 return 0;
755}
756
757/// val_insert - Insert a value into a set only if there is not a value
758/// with the same value number already in the set
759void GVNPRE::val_insert(ValueNumberedSet& s, Value* v) {
760 uint32_t num = VN.lookup(v);
761 if (!s.test(num))
762 s.insert(v);
763}
764
765/// val_replace - Insert a value into a set, replacing any values already in
766/// the set that have the same value number
767void GVNPRE::val_replace(ValueNumberedSet& s, Value* v) {
Owen Anderson437d5a92007-07-19 19:57:13 +0000768 if (s.count(v)) return;
769
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 uint32_t num = VN.lookup(v);
771 Value* leader = find_leader(s, num);
772 if (leader != 0)
773 s.erase(leader);
774 s.insert(v);
775 s.set(num);
776}
777
778/// phi_translate - Given a value, its parent block, and a predecessor of its
779/// parent, translate the value into legal for the predecessor block. This
780/// means translating its operands (and recursively, their operands) through
781/// any phi nodes in the parent into values available in the predecessor
782Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
783 if (V == 0)
784 return 0;
785
786 // Unary Operations
787 if (CastInst* U = dyn_cast<CastInst>(V)) {
788 Value* newOp1 = 0;
789 if (isa<Instruction>(U->getOperand(0)))
790 newOp1 = phi_translate(U->getOperand(0), pred, succ);
791 else
792 newOp1 = U->getOperand(0);
793
794 if (newOp1 == 0)
795 return 0;
796
797 if (newOp1 != U->getOperand(0)) {
798 Instruction* newVal = 0;
799 if (CastInst* C = dyn_cast<CastInst>(U))
800 newVal = CastInst::create(C->getOpcode(),
801 newOp1, C->getType(),
802 C->getName()+".expr");
803
804 uint32_t v = VN.lookup_or_add(newVal);
805
806 Value* leader = find_leader(availableOut[pred], v);
807 if (leader == 0) {
808 createdExpressions.push_back(newVal);
809 return newVal;
810 } else {
811 VN.erase(newVal);
812 delete newVal;
813 return leader;
814 }
815 }
816
817 // Binary Operations
818 } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) ||
819 isa<ExtractElementInst>(V)) {
820 User* U = cast<User>(V);
821
822 Value* newOp1 = 0;
823 if (isa<Instruction>(U->getOperand(0)))
824 newOp1 = phi_translate(U->getOperand(0), pred, succ);
825 else
826 newOp1 = U->getOperand(0);
827
828 if (newOp1 == 0)
829 return 0;
830
831 Value* newOp2 = 0;
832 if (isa<Instruction>(U->getOperand(1)))
833 newOp2 = phi_translate(U->getOperand(1), pred, succ);
834 else
835 newOp2 = U->getOperand(1);
836
837 if (newOp2 == 0)
838 return 0;
839
840 if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
841 Instruction* newVal = 0;
842 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
843 newVal = BinaryOperator::create(BO->getOpcode(),
844 newOp1, newOp2,
845 BO->getName()+".expr");
846 else if (CmpInst* C = dyn_cast<CmpInst>(U))
847 newVal = CmpInst::create(C->getOpcode(),
848 C->getPredicate(),
849 newOp1, newOp2,
850 C->getName()+".expr");
851 else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
852 newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
853
854 uint32_t v = VN.lookup_or_add(newVal);
855
856 Value* leader = find_leader(availableOut[pred], v);
857 if (leader == 0) {
858 createdExpressions.push_back(newVal);
859 return newVal;
860 } else {
861 VN.erase(newVal);
862 delete newVal;
863 return leader;
864 }
865 }
866
867 // Ternary Operations
868 } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
869 isa<SelectInst>(V)) {
870 User* U = cast<User>(V);
871
872 Value* newOp1 = 0;
873 if (isa<Instruction>(U->getOperand(0)))
874 newOp1 = phi_translate(U->getOperand(0), pred, succ);
875 else
876 newOp1 = U->getOperand(0);
877
878 if (newOp1 == 0)
879 return 0;
880
881 Value* newOp2 = 0;
882 if (isa<Instruction>(U->getOperand(1)))
883 newOp2 = phi_translate(U->getOperand(1), pred, succ);
884 else
885 newOp2 = U->getOperand(1);
886
887 if (newOp2 == 0)
888 return 0;
889
890 Value* newOp3 = 0;
891 if (isa<Instruction>(U->getOperand(2)))
892 newOp3 = phi_translate(U->getOperand(2), pred, succ);
893 else
894 newOp3 = U->getOperand(2);
895
896 if (newOp3 == 0)
897 return 0;
898
899 if (newOp1 != U->getOperand(0) ||
900 newOp2 != U->getOperand(1) ||
901 newOp3 != U->getOperand(2)) {
902 Instruction* newVal = 0;
903 if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
904 newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
905 S->getName()+".expr");
906 else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
907 newVal = new InsertElementInst(newOp1, newOp2, newOp3,
908 I->getName()+".expr");
909 else if (SelectInst* I = dyn_cast<SelectInst>(U))
910 newVal = new SelectInst(newOp1, newOp2, newOp3, I->getName()+".expr");
911
912 uint32_t v = VN.lookup_or_add(newVal);
913
914 Value* leader = find_leader(availableOut[pred], v);
915 if (leader == 0) {
916 createdExpressions.push_back(newVal);
917 return newVal;
918 } else {
919 VN.erase(newVal);
920 delete newVal;
921 return leader;
922 }
923 }
924
925 // Varargs operators
926 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
927 Value* newOp1 = 0;
928 if (isa<Instruction>(U->getPointerOperand()))
929 newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
930 else
931 newOp1 = U->getPointerOperand();
932
933 if (newOp1 == 0)
934 return 0;
935
936 bool changed_idx = false;
Owen Anderson9f1f2d42007-07-19 06:37:56 +0000937 SmallVector<Value*, 4> newIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
939 I != E; ++I)
940 if (isa<Instruction>(*I)) {
941 Value* newVal = phi_translate(*I, pred, succ);
942 newIdx.push_back(newVal);
943 if (newVal != *I)
944 changed_idx = true;
945 } else {
946 newIdx.push_back(*I);
947 }
948
949 if (newOp1 != U->getPointerOperand() || changed_idx) {
950 Instruction* newVal = new GetElementPtrInst(newOp1,
David Greene393be882007-09-04 15:46:09 +0000951 newIdx.begin(), newIdx.end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952 U->getName()+".expr");
953
954 uint32_t v = VN.lookup_or_add(newVal);
955
956 Value* leader = find_leader(availableOut[pred], v);
957 if (leader == 0) {
958 createdExpressions.push_back(newVal);
959 return newVal;
960 } else {
961 VN.erase(newVal);
962 delete newVal;
963 return leader;
964 }
965 }
966
967 // PHI Nodes
968 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
969 if (P->getParent() == succ)
970 return P->getIncomingValueForBlock(pred);
971 }
972
973 return V;
974}
975
976/// phi_translate_set - Perform phi translation on every element of a set
977void GVNPRE::phi_translate_set(ValueNumberedSet& anticIn,
978 BasicBlock* pred, BasicBlock* succ,
979 ValueNumberedSet& out) {
980 for (ValueNumberedSet::iterator I = anticIn.begin(),
981 E = anticIn.end(); I != E; ++I) {
982 Value* V = phi_translate(*I, pred, succ);
983 if (V != 0 && !out.test(VN.lookup_or_add(V))) {
984 out.insert(V);
985 out.set(VN.lookup(V));
986 }
987 }
988}
989
990/// dependsOnInvoke - Test if a value has an phi node as an operand, any of
991/// whose inputs is an invoke instruction. If this is true, we cannot safely
992/// PRE the instruction or anything that depends on it.
993bool GVNPRE::dependsOnInvoke(Value* V) {
994 if (PHINode* p = dyn_cast<PHINode>(V)) {
995 for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
996 if (isa<InvokeInst>(*I))
997 return true;
998 return false;
999 } else {
1000 return false;
1001 }
1002}
1003
1004/// clean - Remove all non-opaque values from the set whose operands are not
1005/// themselves in the set, as well as all values that depend on invokes (see
1006/// above)
1007void GVNPRE::clean(ValueNumberedSet& set) {
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001008 SmallVector<Value*, 8> worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 worklist.reserve(set.size());
1010 topo_sort(set, worklist);
1011
1012 for (unsigned i = 0; i < worklist.size(); ++i) {
1013 Value* v = worklist[i];
1014
1015 // Handle unary ops
1016 if (CastInst* U = dyn_cast<CastInst>(v)) {
1017 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1018 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1019 if (lhsValid)
1020 lhsValid = !dependsOnInvoke(U->getOperand(0));
1021
1022 if (!lhsValid) {
1023 set.erase(U);
1024 set.reset(VN.lookup(U));
1025 }
1026
1027 // Handle binary ops
1028 } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
1029 isa<ExtractElementInst>(v)) {
1030 User* U = cast<User>(v);
1031
1032 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1033 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1034 if (lhsValid)
1035 lhsValid = !dependsOnInvoke(U->getOperand(0));
1036
1037 bool rhsValid = !isa<Instruction>(U->getOperand(1));
1038 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1039 if (rhsValid)
1040 rhsValid = !dependsOnInvoke(U->getOperand(1));
1041
1042 if (!lhsValid || !rhsValid) {
1043 set.erase(U);
1044 set.reset(VN.lookup(U));
1045 }
1046
1047 // Handle ternary ops
1048 } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
1049 isa<SelectInst>(v)) {
1050 User* U = cast<User>(v);
1051
1052 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1053 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1054 if (lhsValid)
1055 lhsValid = !dependsOnInvoke(U->getOperand(0));
1056
1057 bool rhsValid = !isa<Instruction>(U->getOperand(1));
1058 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1059 if (rhsValid)
1060 rhsValid = !dependsOnInvoke(U->getOperand(1));
1061
1062 bool thirdValid = !isa<Instruction>(U->getOperand(2));
1063 thirdValid |= set.test(VN.lookup(U->getOperand(2)));
1064 if (thirdValid)
1065 thirdValid = !dependsOnInvoke(U->getOperand(2));
1066
1067 if (!lhsValid || !rhsValid || !thirdValid) {
1068 set.erase(U);
1069 set.reset(VN.lookup(U));
1070 }
1071
1072 // Handle varargs ops
1073 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
1074 bool ptrValid = !isa<Instruction>(U->getPointerOperand());
1075 ptrValid |= set.test(VN.lookup(U->getPointerOperand()));
1076 if (ptrValid)
1077 ptrValid = !dependsOnInvoke(U->getPointerOperand());
1078
1079 bool varValid = true;
1080 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
1081 I != E; ++I)
1082 if (varValid) {
1083 varValid &= !isa<Instruction>(*I) || set.test(VN.lookup(*I));
1084 varValid &= !dependsOnInvoke(*I);
1085 }
1086
1087 if (!ptrValid || !varValid) {
1088 set.erase(U);
1089 set.reset(VN.lookup(U));
1090 }
1091 }
1092 }
1093}
1094
1095/// topo_sort - Given a set of values, sort them by topological
1096/// order into the provided vector.
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001097void GVNPRE::topo_sort(ValueNumberedSet& set, SmallVector<Value*, 8>& vec) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 SmallPtrSet<Value*, 16> visited;
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001099 SmallVector<Value*, 8> stack;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 for (ValueNumberedSet::iterator I = set.begin(), E = set.end();
1101 I != E; ++I) {
1102 if (visited.count(*I) == 0)
1103 stack.push_back(*I);
1104
1105 while (!stack.empty()) {
1106 Value* e = stack.back();
1107
1108 // Handle unary ops
1109 if (CastInst* U = dyn_cast<CastInst>(e)) {
1110 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1111
1112 if (l != 0 && isa<Instruction>(l) &&
1113 visited.count(l) == 0)
1114 stack.push_back(l);
1115 else {
1116 vec.push_back(e);
1117 visited.insert(e);
1118 stack.pop_back();
1119 }
1120
1121 // Handle binary ops
1122 } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1123 isa<ExtractElementInst>(e)) {
1124 User* U = cast<User>(e);
1125 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1126 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1127
1128 if (l != 0 && isa<Instruction>(l) &&
1129 visited.count(l) == 0)
1130 stack.push_back(l);
1131 else if (r != 0 && isa<Instruction>(r) &&
1132 visited.count(r) == 0)
1133 stack.push_back(r);
1134 else {
1135 vec.push_back(e);
1136 visited.insert(e);
1137 stack.pop_back();
1138 }
1139
1140 // Handle ternary ops
1141 } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1142 isa<SelectInst>(e)) {
1143 User* U = cast<User>(e);
1144 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1145 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1146 Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1147
1148 if (l != 0 && isa<Instruction>(l) &&
1149 visited.count(l) == 0)
1150 stack.push_back(l);
1151 else if (r != 0 && isa<Instruction>(r) &&
1152 visited.count(r) == 0)
1153 stack.push_back(r);
1154 else if (m != 0 && isa<Instruction>(m) &&
1155 visited.count(m) == 0)
1156 stack.push_back(m);
1157 else {
1158 vec.push_back(e);
1159 visited.insert(e);
1160 stack.pop_back();
1161 }
1162
1163 // Handle vararg ops
1164 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1165 Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1166
1167 if (p != 0 && isa<Instruction>(p) &&
1168 visited.count(p) == 0)
1169 stack.push_back(p);
1170 else {
1171 bool push_va = false;
1172 for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1173 E = U->idx_end(); I != E; ++I) {
1174 Value * v = find_leader(set, VN.lookup(*I));
1175 if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1176 stack.push_back(v);
1177 push_va = true;
1178 }
1179 }
1180
1181 if (!push_va) {
1182 vec.push_back(e);
1183 visited.insert(e);
1184 stack.pop_back();
1185 }
1186 }
1187
1188 // Handle opaque ops
1189 } else {
1190 visited.insert(e);
1191 vec.push_back(e);
1192 stack.pop_back();
1193 }
1194 }
1195
1196 stack.clear();
1197 }
1198}
1199
1200/// dump - Dump a set of values to standard error
1201void GVNPRE::dump(ValueNumberedSet& s) const {
1202 DOUT << "{ ";
1203 for (ValueNumberedSet::iterator I = s.begin(), E = s.end();
1204 I != E; ++I) {
1205 DOUT << "" << VN.lookup(*I) << ": ";
1206 DEBUG((*I)->dump());
1207 }
1208 DOUT << "}\n\n";
1209}
1210
1211/// elimination - Phase 3 of the main algorithm. Perform full redundancy
1212/// elimination by walking the dominator tree and removing any instruction that
1213/// is dominated by another instruction with the same value number.
1214bool GVNPRE::elimination() {
1215 bool changed_function = false;
1216
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001217 SmallVector<std::pair<Instruction*, Value*>, 8> replace;
1218 SmallVector<Instruction*, 8> erase;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219
1220 DominatorTree& DT = getAnalysis<DominatorTree>();
1221
1222 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1223 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1224 BasicBlock* BB = DI->getBlock();
1225
1226 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1227 BI != BE; ++BI) {
1228
1229 if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1230 isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1231 isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1232 isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1233
Owen Anderson0b7ad4b2007-08-02 18:20:52 +00001234 if (availableOut[BB].test(VN.lookup(BI)) &&
1235 !availableOut[BB].count(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1237 if (Instruction* Instr = dyn_cast<Instruction>(leader))
1238 if (Instr->getParent() != 0 && Instr != BI) {
1239 replace.push_back(std::make_pair(BI, leader));
1240 erase.push_back(BI);
1241 ++NumEliminated;
1242 }
1243 }
1244 }
1245 }
1246 }
1247
1248 while (!replace.empty()) {
1249 std::pair<Instruction*, Value*> rep = replace.back();
1250 replace.pop_back();
1251 rep.first->replaceAllUsesWith(rep.second);
1252 changed_function = true;
1253 }
1254
Owen Anderson0b7ad4b2007-08-02 18:20:52 +00001255 for (SmallVector<Instruction*, 8>::iterator I = erase.begin(),
1256 E = erase.end(); I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 (*I)->eraseFromParent();
1258
1259 return changed_function;
1260}
1261
1262/// cleanup - Delete any extraneous values that were created to represent
1263/// expressions without leaders.
1264void GVNPRE::cleanup() {
1265 while (!createdExpressions.empty()) {
1266 Instruction* I = createdExpressions.back();
1267 createdExpressions.pop_back();
1268
1269 delete I;
1270 }
1271}
1272
1273/// buildsets_availout - When calculating availability, handle an instruction
1274/// by inserting it into the appropriate sets
1275void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1276 ValueNumberedSet& currAvail,
1277 ValueNumberedSet& currPhis,
1278 ValueNumberedSet& currExps,
1279 SmallPtrSet<Value*, 16>& currTemps) {
1280 // Handle PHI nodes
1281 if (PHINode* p = dyn_cast<PHINode>(I)) {
1282 unsigned num = VN.lookup_or_add(p);
1283
1284 currPhis.insert(p);
1285 currPhis.set(num);
1286
1287 // Handle unary ops
1288 } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1289 Value* leftValue = U->getOperand(0);
1290
1291 unsigned num = VN.lookup_or_add(U);
1292
1293 if (isa<Instruction>(leftValue))
1294 if (!currExps.test(VN.lookup(leftValue))) {
1295 currExps.insert(leftValue);
1296 currExps.set(VN.lookup(leftValue));
1297 }
1298
1299 if (!currExps.test(num)) {
1300 currExps.insert(U);
1301 currExps.set(num);
1302 }
1303
1304 // Handle binary ops
1305 } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1306 isa<ExtractElementInst>(I)) {
1307 User* U = cast<User>(I);
1308 Value* leftValue = U->getOperand(0);
1309 Value* rightValue = U->getOperand(1);
1310
1311 unsigned num = VN.lookup_or_add(U);
1312
1313 if (isa<Instruction>(leftValue))
1314 if (!currExps.test(VN.lookup(leftValue))) {
1315 currExps.insert(leftValue);
1316 currExps.set(VN.lookup(leftValue));
1317 }
1318
1319 if (isa<Instruction>(rightValue))
1320 if (!currExps.test(VN.lookup(rightValue))) {
1321 currExps.insert(rightValue);
1322 currExps.set(VN.lookup(rightValue));
1323 }
1324
1325 if (!currExps.test(num)) {
1326 currExps.insert(U);
1327 currExps.set(num);
1328 }
1329
1330 // Handle ternary ops
1331 } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1332 isa<SelectInst>(I)) {
1333 User* U = cast<User>(I);
1334 Value* leftValue = U->getOperand(0);
1335 Value* rightValue = U->getOperand(1);
1336 Value* thirdValue = U->getOperand(2);
1337
1338 VN.lookup_or_add(U);
1339
1340 unsigned num = VN.lookup_or_add(U);
1341
1342 if (isa<Instruction>(leftValue))
1343 if (!currExps.test(VN.lookup(leftValue))) {
1344 currExps.insert(leftValue);
1345 currExps.set(VN.lookup(leftValue));
1346 }
1347 if (isa<Instruction>(rightValue))
1348 if (!currExps.test(VN.lookup(rightValue))) {
1349 currExps.insert(rightValue);
1350 currExps.set(VN.lookup(rightValue));
1351 }
1352 if (isa<Instruction>(thirdValue))
1353 if (!currExps.test(VN.lookup(thirdValue))) {
1354 currExps.insert(thirdValue);
1355 currExps.set(VN.lookup(thirdValue));
1356 }
1357
1358 if (!currExps.test(num)) {
1359 currExps.insert(U);
1360 currExps.set(num);
1361 }
1362
1363 // Handle vararg ops
1364 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1365 Value* ptrValue = U->getPointerOperand();
1366
1367 VN.lookup_or_add(U);
1368
1369 unsigned num = VN.lookup_or_add(U);
1370
1371 if (isa<Instruction>(ptrValue))
1372 if (!currExps.test(VN.lookup(ptrValue))) {
1373 currExps.insert(ptrValue);
1374 currExps.set(VN.lookup(ptrValue));
1375 }
1376
1377 for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1378 OI != OE; ++OI)
1379 if (isa<Instruction>(*OI) && !currExps.test(VN.lookup(*OI))) {
1380 currExps.insert(*OI);
1381 currExps.set(VN.lookup(*OI));
1382 }
1383
1384 if (!currExps.test(VN.lookup(U))) {
1385 currExps.insert(U);
1386 currExps.set(num);
1387 }
1388
1389 // Handle opaque ops
1390 } else if (!I->isTerminator()){
1391 VN.lookup_or_add(I);
1392
1393 currTemps.insert(I);
1394 }
1395
1396 if (!I->isTerminator())
1397 if (!currAvail.test(VN.lookup(I))) {
1398 currAvail.insert(I);
1399 currAvail.set(VN.lookup(I));
1400 }
1401}
1402
1403/// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1404/// set as a function of the ANTIC_IN set of the block's predecessors
1405bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1406 ValueNumberedSet& anticOut,
Owen Andersonc2ae87b2007-07-19 03:32:44 +00001407 SmallPtrSet<BasicBlock*, 8>& visited) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001408 if (BB->getTerminator()->getNumSuccessors() == 1) {
1409 if (BB->getTerminator()->getSuccessor(0) != BB &&
1410 visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1411 return true;
1412 }
1413 else {
1414 phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1415 BB, BB->getTerminator()->getSuccessor(0), anticOut);
1416 }
1417 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1418 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1419 for (ValueNumberedSet::iterator I = anticipatedIn[first].begin(),
1420 E = anticipatedIn[first].end(); I != E; ++I) {
1421 anticOut.insert(*I);
1422 anticOut.set(VN.lookup(*I));
1423 }
1424
1425 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1426 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1427 ValueNumberedSet& succAnticIn = anticipatedIn[currSucc];
1428
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001429 SmallVector<Value*, 16> temp;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430
1431 for (ValueNumberedSet::iterator I = anticOut.begin(),
1432 E = anticOut.end(); I != E; ++I)
1433 if (!succAnticIn.test(VN.lookup(*I)))
1434 temp.push_back(*I);
1435
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001436 for (SmallVector<Value*, 16>::iterator I = temp.begin(), E = temp.end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 I != E; ++I) {
1438 anticOut.erase(*I);
1439 anticOut.reset(VN.lookup(*I));
1440 }
1441 }
1442 }
1443
1444 return false;
1445}
1446
1447/// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1448/// each block. ANTIC_IN is then a function of ANTIC_OUT and the GEN
1449/// sets populated in buildsets_availout
1450unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1451 ValueNumberedSet& anticOut,
1452 ValueNumberedSet& currExps,
1453 SmallPtrSet<Value*, 16>& currTemps,
Owen Andersonc2ae87b2007-07-19 03:32:44 +00001454 SmallPtrSet<BasicBlock*, 8>& visited) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 ValueNumberedSet& anticIn = anticipatedIn[BB];
1456 unsigned old = anticIn.size();
1457
1458 bool defer = buildsets_anticout(BB, anticOut, visited);
1459 if (defer)
1460 return 0;
1461
1462 anticIn.clear();
1463
1464 for (ValueNumberedSet::iterator I = anticOut.begin(),
1465 E = anticOut.end(); I != E; ++I) {
1466 anticIn.insert(*I);
1467 anticIn.set(VN.lookup(*I));
1468 }
1469 for (ValueNumberedSet::iterator I = currExps.begin(),
1470 E = currExps.end(); I != E; ++I) {
1471 if (!anticIn.test(VN.lookup(*I))) {
1472 anticIn.insert(*I);
1473 anticIn.set(VN.lookup(*I));
1474 }
1475 }
1476
1477 for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1478 E = currTemps.end(); I != E; ++I) {
1479 anticIn.erase(*I);
1480 anticIn.reset(VN.lookup(*I));
1481 }
1482
1483 clean(anticIn);
1484 anticOut.clear();
1485
1486 if (old != anticIn.size())
1487 return 2;
1488 else
1489 return 1;
1490}
1491
1492/// buildsets - Phase 1 of the main algorithm. Construct the AVAIL_OUT
1493/// and the ANTIC_IN sets.
1494void GVNPRE::buildsets(Function& F) {
Owen Andersonc2ae87b2007-07-19 03:32:44 +00001495 DenseMap<BasicBlock*, ValueNumberedSet> generatedExpressions;
1496 DenseMap<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001497
1498 DominatorTree &DT = getAnalysis<DominatorTree>();
1499
1500 // Phase 1, Part 1: calculate AVAIL_OUT
1501
1502 // Top-down walk of the dominator tree
1503 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1504 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1505
1506 // Get the sets to update for this block
1507 ValueNumberedSet& currExps = generatedExpressions[DI->getBlock()];
1508 ValueNumberedSet& currPhis = generatedPhis[DI->getBlock()];
1509 SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1510 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1511
1512 BasicBlock* BB = DI->getBlock();
1513
1514 // A block inherits AVAIL_OUT from its dominator
1515 if (DI->getIDom() != 0)
1516 currAvail = availableOut[DI->getIDom()->getBlock()];
1517
1518 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1519 BI != BE; ++BI)
1520 buildsets_availout(BI, currAvail, currPhis, currExps,
1521 currTemps);
1522
1523 }
1524
1525 // Phase 1, Part 2: calculate ANTIC_IN
1526
Owen Andersonc2ae87b2007-07-19 03:32:44 +00001527 SmallPtrSet<BasicBlock*, 8> visited;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528 SmallPtrSet<BasicBlock*, 4> block_changed;
1529 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1530 block_changed.insert(FI);
1531
1532 bool changed = true;
1533 unsigned iterations = 0;
1534
1535 while (changed) {
1536 changed = false;
1537 ValueNumberedSet anticOut;
1538
1539 // Postorder walk of the CFG
1540 for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1541 BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1542 BasicBlock* BB = *BBI;
1543
1544 if (block_changed.count(BB) != 0) {
1545 unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1546 generatedTemporaries[BB], visited);
1547
1548 if (ret == 0) {
1549 changed = true;
1550 continue;
1551 } else {
1552 visited.insert(BB);
1553
1554 if (ret == 2)
1555 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1556 PI != PE; ++PI) {
1557 block_changed.insert(*PI);
1558 }
1559 else
1560 block_changed.erase(BB);
1561
1562 changed |= (ret == 2);
1563 }
1564 }
1565 }
1566
1567 iterations++;
1568 }
1569}
1570
1571/// insertion_pre - When a partial redundancy has been identified, eliminate it
1572/// by inserting appropriate values into the predecessors and a phi node in
1573/// the main block
1574void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001575 DenseMap<BasicBlock*, Value*>& avail,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576 std::map<BasicBlock*, ValueNumberedSet>& new_sets) {
1577 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1578 Value* e2 = avail[*PI];
1579 if (!availableOut[*PI].test(VN.lookup(e2))) {
1580 User* U = cast<User>(e2);
1581
1582 Value* s1 = 0;
1583 if (isa<BinaryOperator>(U->getOperand(0)) ||
1584 isa<CmpInst>(U->getOperand(0)) ||
1585 isa<ShuffleVectorInst>(U->getOperand(0)) ||
1586 isa<ExtractElementInst>(U->getOperand(0)) ||
1587 isa<InsertElementInst>(U->getOperand(0)) ||
1588 isa<SelectInst>(U->getOperand(0)) ||
1589 isa<CastInst>(U->getOperand(0)) ||
1590 isa<GetElementPtrInst>(U->getOperand(0)))
1591 s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1592 else
1593 s1 = U->getOperand(0);
1594
1595 Value* s2 = 0;
1596
1597 if (isa<BinaryOperator>(U) ||
1598 isa<CmpInst>(U) ||
1599 isa<ShuffleVectorInst>(U) ||
1600 isa<ExtractElementInst>(U) ||
1601 isa<InsertElementInst>(U) ||
1602 isa<SelectInst>(U))
1603 if (isa<BinaryOperator>(U->getOperand(1)) ||
1604 isa<CmpInst>(U->getOperand(1)) ||
1605 isa<ShuffleVectorInst>(U->getOperand(1)) ||
1606 isa<ExtractElementInst>(U->getOperand(1)) ||
1607 isa<InsertElementInst>(U->getOperand(1)) ||
1608 isa<SelectInst>(U->getOperand(1)) ||
1609 isa<CastInst>(U->getOperand(1)) ||
1610 isa<GetElementPtrInst>(U->getOperand(1))) {
1611 s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1612 } else {
1613 s2 = U->getOperand(1);
1614 }
1615
1616 // Ternary Operators
1617 Value* s3 = 0;
1618 if (isa<ShuffleVectorInst>(U) ||
1619 isa<InsertElementInst>(U) ||
1620 isa<SelectInst>(U))
1621 if (isa<BinaryOperator>(U->getOperand(2)) ||
1622 isa<CmpInst>(U->getOperand(2)) ||
1623 isa<ShuffleVectorInst>(U->getOperand(2)) ||
1624 isa<ExtractElementInst>(U->getOperand(2)) ||
1625 isa<InsertElementInst>(U->getOperand(2)) ||
1626 isa<SelectInst>(U->getOperand(2)) ||
1627 isa<CastInst>(U->getOperand(2)) ||
1628 isa<GetElementPtrInst>(U->getOperand(2))) {
1629 s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1630 } else {
1631 s3 = U->getOperand(2);
1632 }
1633
1634 // Vararg operators
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001635 SmallVector<Value*, 4> sVarargs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1637 for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1638 OE = G->idx_end(); OI != OE; ++OI) {
1639 if (isa<BinaryOperator>(*OI) ||
1640 isa<CmpInst>(*OI) ||
1641 isa<ShuffleVectorInst>(*OI) ||
1642 isa<ExtractElementInst>(*OI) ||
1643 isa<InsertElementInst>(*OI) ||
1644 isa<SelectInst>(*OI) ||
1645 isa<CastInst>(*OI) ||
1646 isa<GetElementPtrInst>(*OI)) {
1647 sVarargs.push_back(find_leader(availableOut[*PI],
1648 VN.lookup(*OI)));
1649 } else {
1650 sVarargs.push_back(*OI);
1651 }
1652 }
1653 }
1654
1655 Value* newVal = 0;
1656 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1657 newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1658 BO->getName()+".gvnpre",
1659 (*PI)->getTerminator());
1660 else if (CmpInst* C = dyn_cast<CmpInst>(U))
1661 newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1662 C->getName()+".gvnpre",
1663 (*PI)->getTerminator());
1664 else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1665 newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1666 (*PI)->getTerminator());
1667 else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1668 newVal = new InsertElementInst(s1, s2, s3, S->getName()+".gvnpre",
1669 (*PI)->getTerminator());
1670 else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1671 newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1672 (*PI)->getTerminator());
1673 else if (SelectInst* S = dyn_cast<SelectInst>(U))
1674 newVal = new SelectInst(s1, s2, s3, S->getName()+".gvnpre",
1675 (*PI)->getTerminator());
1676 else if (CastInst* C = dyn_cast<CastInst>(U))
1677 newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1678 C->getName()+".gvnpre",
1679 (*PI)->getTerminator());
1680 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
David Greene393be882007-09-04 15:46:09 +00001681 newVal = new GetElementPtrInst(s1, sVarargs.begin(), sVarargs.end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 G->getName()+".gvnpre",
1683 (*PI)->getTerminator());
1684
1685
1686 VN.add(newVal, VN.lookup(U));
1687
1688 ValueNumberedSet& predAvail = availableOut[*PI];
1689 val_replace(predAvail, newVal);
1690 val_replace(new_sets[*PI], newVal);
1691 predAvail.set(VN.lookup(newVal));
1692
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001693 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 if (av != avail.end())
1695 avail.erase(av);
1696 avail.insert(std::make_pair(*PI, newVal));
1697
1698 ++NumInsertedVals;
1699 }
1700 }
1701
1702 PHINode* p = 0;
1703
1704 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1705 if (p == 0)
1706 p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1707
1708 p->addIncoming(avail[*PI], *PI);
1709 }
1710
1711 VN.add(p, VN.lookup(e));
1712 val_replace(availableOut[BB], p);
1713 availableOut[BB].set(VN.lookup(e));
1714 generatedPhis[BB].insert(p);
1715 generatedPhis[BB].set(VN.lookup(e));
1716 new_sets[BB].insert(p);
1717 new_sets[BB].set(VN.lookup(e));
1718
1719 ++NumInsertedPhis;
1720}
1721
1722/// insertion_mergepoint - When walking the dom tree, check at each merge
1723/// block for the possibility of a partial redundancy. If present, eliminate it
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001724unsigned GVNPRE::insertion_mergepoint(SmallVector<Value*, 8>& workList,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725 df_iterator<DomTreeNode*>& D,
1726 std::map<BasicBlock*, ValueNumberedSet >& new_sets) {
1727 bool changed_function = false;
1728 bool new_stuff = false;
1729
1730 BasicBlock* BB = D->getBlock();
1731 for (unsigned i = 0; i < workList.size(); ++i) {
1732 Value* e = workList[i];
1733
1734 if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1735 isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1736 isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1737 isa<GetElementPtrInst>(e)) {
1738 if (availableOut[D->getIDom()->getBlock()].test(VN.lookup(e)))
1739 continue;
1740
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001741 DenseMap<BasicBlock*, Value*> avail;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742 bool by_some = false;
1743 bool all_same = true;
1744 Value * first_s = 0;
1745
1746 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1747 ++PI) {
1748 Value *e2 = phi_translate(e, *PI, BB);
1749 Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1750
1751 if (e3 == 0) {
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001752 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001753 if (av != avail.end())
1754 avail.erase(av);
1755 avail.insert(std::make_pair(*PI, e2));
1756 all_same = false;
1757 } else {
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001758 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759 if (av != avail.end())
1760 avail.erase(av);
1761 avail.insert(std::make_pair(*PI, e3));
1762
1763 by_some = true;
1764 if (first_s == 0)
1765 first_s = e3;
1766 else if (first_s != e3)
1767 all_same = false;
1768 }
1769 }
1770
1771 if (by_some && !all_same &&
1772 !generatedPhis[BB].test(VN.lookup(e))) {
1773 insertion_pre(e, BB, avail, new_sets);
1774
1775 changed_function = true;
1776 new_stuff = true;
1777 }
1778 }
1779 }
1780
1781 unsigned retval = 0;
1782 if (changed_function)
1783 retval += 1;
1784 if (new_stuff)
1785 retval += 2;
1786
1787 return retval;
1788}
1789
1790/// insert - Phase 2 of the main algorithm. Walk the dominator tree looking for
1791/// merge points. When one is found, check for a partial redundancy. If one is
1792/// present, eliminate it. Repeat this walk until no changes are made.
1793bool GVNPRE::insertion(Function& F) {
1794 bool changed_function = false;
1795
1796 DominatorTree &DT = getAnalysis<DominatorTree>();
1797
1798 std::map<BasicBlock*, ValueNumberedSet> new_sets;
1799 bool new_stuff = true;
1800 while (new_stuff) {
1801 new_stuff = false;
1802 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1803 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1804 BasicBlock* BB = DI->getBlock();
1805
1806 if (BB == 0)
1807 continue;
1808
1809 ValueNumberedSet& availOut = availableOut[BB];
1810 ValueNumberedSet& anticIn = anticipatedIn[BB];
1811
1812 // Replace leaders with leaders inherited from dominator
1813 if (DI->getIDom() != 0) {
1814 ValueNumberedSet& dom_set = new_sets[DI->getIDom()->getBlock()];
1815 for (ValueNumberedSet::iterator I = dom_set.begin(),
1816 E = dom_set.end(); I != E; ++I) {
1817 val_replace(new_sets[BB], *I);
1818 val_replace(availOut, *I);
1819 }
1820 }
1821
1822 // If there is more than one predecessor...
1823 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
Owen Anderson9f1f2d42007-07-19 06:37:56 +00001824 SmallVector<Value*, 8> workList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001825 workList.reserve(anticIn.size());
1826 topo_sort(anticIn, workList);
1827
1828 unsigned result = insertion_mergepoint(workList, DI, new_sets);
1829 if (result & 1)
1830 changed_function = true;
1831 if (result & 2)
1832 new_stuff = true;
1833 }
1834 }
1835 }
1836
1837 return changed_function;
1838}
1839
1840// GVNPRE::runOnFunction - This is the main transformation entry point for a
1841// function.
1842//
1843bool GVNPRE::runOnFunction(Function &F) {
1844 // Clean out global sets from any previous functions
1845 VN.clear();
1846 createdExpressions.clear();
1847 availableOut.clear();
1848 anticipatedIn.clear();
1849 generatedPhis.clear();
1850
1851 bool changed_function = false;
1852
1853 // Phase 1: BuildSets
1854 // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1855 buildsets(F);
1856
1857 // Phase 2: Insert
1858 // This phase inserts values to make partially redundant values
1859 // fully redundant
1860 changed_function |= insertion(F);
1861
1862 // Phase 3: Eliminate
1863 // This phase performs trivial full redundancy elimination
1864 changed_function |= elimination();
1865
1866 // Phase 4: Cleanup
1867 // This phase cleans up values that were created solely
1868 // as leaders for expressions
1869 cleanup();
1870
1871 return changed_function;
1872}