GVN.cpp revision b70a571c99932464ed828fa425ea1e2783d08fab
1//===- GVN.cpp - Eliminate redundant values and loads ------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// 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// Note that this pass does the value numbering itself, it does not use the 14// ValueNumbering analysis passes. 15// 16//===----------------------------------------------------------------------===// 17 18#define DEBUG_TYPE "gvn" 19#include "llvm/Transforms/Scalar.h" 20#include "llvm/BasicBlock.h" 21#include "llvm/Constants.h" 22#include "llvm/DerivedTypes.h" 23#include "llvm/Function.h" 24#include "llvm/Instructions.h" 25#include "llvm/Value.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/Dominators.h" 32#include "llvm/Analysis/AliasAnalysis.h" 33#include "llvm/Analysis/MemoryDependenceAnalysis.h" 34#include "llvm/Support/CFG.h" 35#include "llvm/Support/CommandLine.h" 36#include "llvm/Support/Compiler.h" 37#include "llvm/Support/Debug.h" 38#include "llvm/Transforms/Utils/BasicBlockUtils.h" 39using namespace llvm; 40 41STATISTIC(NumGVNInstr, "Number of instructions deleted"); 42STATISTIC(NumGVNLoad, "Number of loads deleted"); 43STATISTIC(NumGVNPRE, "Number of instructions PRE'd"); 44 45static cl::opt<bool> EnablePRE("enable-pre", 46 cl::init(true), cl::Hidden); 47 48//===----------------------------------------------------------------------===// 49// ValueTable Class 50//===----------------------------------------------------------------------===// 51 52/// This class holds the mapping between values and value numbers. It is used 53/// as an efficient mechanism to determine the expression-wise equivalence of 54/// two values. 55namespace { 56 struct VISIBILITY_HIDDEN Expression { 57 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 58 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 59 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 60 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 61 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 62 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 63 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT, 64 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI, 65 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 66 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT, 67 EMPTY, TOMBSTONE }; 68 69 ExpressionOpcode opcode; 70 const Type* type; 71 uint32_t firstVN; 72 uint32_t secondVN; 73 uint32_t thirdVN; 74 SmallVector<uint32_t, 4> varargs; 75 Value* function; 76 77 Expression() { } 78 Expression(ExpressionOpcode o) : opcode(o) { } 79 80 bool operator==(const Expression &other) const { 81 if (opcode != other.opcode) 82 return false; 83 else if (opcode == EMPTY || opcode == TOMBSTONE) 84 return true; 85 else if (type != other.type) 86 return false; 87 else if (function != other.function) 88 return false; 89 else if (firstVN != other.firstVN) 90 return false; 91 else if (secondVN != other.secondVN) 92 return false; 93 else if (thirdVN != other.thirdVN) 94 return false; 95 else { 96 if (varargs.size() != other.varargs.size()) 97 return false; 98 99 for (size_t i = 0; i < varargs.size(); ++i) 100 if (varargs[i] != other.varargs[i]) 101 return false; 102 103 return true; 104 } 105 } 106 107 bool operator!=(const Expression &other) const { 108 if (opcode != other.opcode) 109 return true; 110 else if (opcode == EMPTY || opcode == TOMBSTONE) 111 return false; 112 else if (type != other.type) 113 return true; 114 else if (function != other.function) 115 return true; 116 else if (firstVN != other.firstVN) 117 return true; 118 else if (secondVN != other.secondVN) 119 return true; 120 else if (thirdVN != other.thirdVN) 121 return true; 122 else { 123 if (varargs.size() != other.varargs.size()) 124 return true; 125 126 for (size_t i = 0; i < varargs.size(); ++i) 127 if (varargs[i] != other.varargs[i]) 128 return true; 129 130 return false; 131 } 132 } 133 }; 134 135 class VISIBILITY_HIDDEN ValueTable { 136 private: 137 DenseMap<Value*, uint32_t> valueNumbering; 138 DenseMap<Expression, uint32_t> expressionNumbering; 139 AliasAnalysis* AA; 140 MemoryDependenceAnalysis* MD; 141 DominatorTree* DT; 142 143 uint32_t nextValueNumber; 144 145 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO); 146 Expression::ExpressionOpcode getOpcode(CmpInst* C); 147 Expression::ExpressionOpcode getOpcode(CastInst* C); 148 Expression create_expression(BinaryOperator* BO); 149 Expression create_expression(CmpInst* C); 150 Expression create_expression(ShuffleVectorInst* V); 151 Expression create_expression(ExtractElementInst* C); 152 Expression create_expression(InsertElementInst* V); 153 Expression create_expression(SelectInst* V); 154 Expression create_expression(CastInst* C); 155 Expression create_expression(GetElementPtrInst* G); 156 Expression create_expression(CallInst* C); 157 Expression create_expression(Constant* C); 158 public: 159 ValueTable() : nextValueNumber(1) { } 160 uint32_t lookup_or_add(Value* V); 161 uint32_t lookup(Value* V) const; 162 void add(Value* V, uint32_t num); 163 void clear(); 164 void erase(Value* v); 165 unsigned size(); 166 void setAliasAnalysis(AliasAnalysis* A) { AA = A; } 167 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; } 168 void setDomTree(DominatorTree* D) { DT = D; } 169 }; 170} 171 172namespace llvm { 173template <> struct DenseMapInfo<Expression> { 174 static inline Expression getEmptyKey() { 175 return Expression(Expression::EMPTY); 176 } 177 178 static inline Expression getTombstoneKey() { 179 return Expression(Expression::TOMBSTONE); 180 } 181 182 static unsigned getHashValue(const Expression e) { 183 unsigned hash = e.opcode; 184 185 hash = e.firstVN + hash * 37; 186 hash = e.secondVN + hash * 37; 187 hash = e.thirdVN + hash * 37; 188 189 hash = ((unsigned)((uintptr_t)e.type >> 4) ^ 190 (unsigned)((uintptr_t)e.type >> 9)) + 191 hash * 37; 192 193 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(), 194 E = e.varargs.end(); I != E; ++I) 195 hash = *I + hash * 37; 196 197 hash = ((unsigned)((uintptr_t)e.function >> 4) ^ 198 (unsigned)((uintptr_t)e.function >> 9)) + 199 hash * 37; 200 201 return hash; 202 } 203 static bool isEqual(const Expression &LHS, const Expression &RHS) { 204 return LHS == RHS; 205 } 206 static bool isPod() { return true; } 207}; 208} 209 210//===----------------------------------------------------------------------===// 211// ValueTable Internal Functions 212//===----------------------------------------------------------------------===// 213Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) { 214 switch(BO->getOpcode()) { 215 default: // THIS SHOULD NEVER HAPPEN 216 assert(0 && "Binary operator with unknown opcode?"); 217 case Instruction::Add: return Expression::ADD; 218 case Instruction::Sub: return Expression::SUB; 219 case Instruction::Mul: return Expression::MUL; 220 case Instruction::UDiv: return Expression::UDIV; 221 case Instruction::SDiv: return Expression::SDIV; 222 case Instruction::FDiv: return Expression::FDIV; 223 case Instruction::URem: return Expression::UREM; 224 case Instruction::SRem: return Expression::SREM; 225 case Instruction::FRem: return Expression::FREM; 226 case Instruction::Shl: return Expression::SHL; 227 case Instruction::LShr: return Expression::LSHR; 228 case Instruction::AShr: return Expression::ASHR; 229 case Instruction::And: return Expression::AND; 230 case Instruction::Or: return Expression::OR; 231 case Instruction::Xor: return Expression::XOR; 232 } 233} 234 235Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) { 236 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) { 237 switch (C->getPredicate()) { 238 default: // THIS SHOULD NEVER HAPPEN 239 assert(0 && "Comparison with unknown predicate?"); 240 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ; 241 case ICmpInst::ICMP_NE: return Expression::ICMPNE; 242 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT; 243 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE; 244 case ICmpInst::ICMP_ULT: return Expression::ICMPULT; 245 case ICmpInst::ICMP_ULE: return Expression::ICMPULE; 246 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT; 247 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE; 248 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT; 249 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE; 250 } 251 } 252 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare"); 253 switch (C->getPredicate()) { 254 default: // THIS SHOULD NEVER HAPPEN 255 assert(0 && "Comparison with unknown predicate?"); 256 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ; 257 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT; 258 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE; 259 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT; 260 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE; 261 case FCmpInst::FCMP_ONE: return Expression::FCMPONE; 262 case FCmpInst::FCMP_ORD: return Expression::FCMPORD; 263 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO; 264 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ; 265 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT; 266 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE; 267 case FCmpInst::FCMP_ULT: return Expression::FCMPULT; 268 case FCmpInst::FCMP_ULE: return Expression::FCMPULE; 269 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE; 270 } 271} 272 273Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) { 274 switch(C->getOpcode()) { 275 default: // THIS SHOULD NEVER HAPPEN 276 assert(0 && "Cast operator with unknown opcode?"); 277 case Instruction::Trunc: return Expression::TRUNC; 278 case Instruction::ZExt: return Expression::ZEXT; 279 case Instruction::SExt: return Expression::SEXT; 280 case Instruction::FPToUI: return Expression::FPTOUI; 281 case Instruction::FPToSI: return Expression::FPTOSI; 282 case Instruction::UIToFP: return Expression::UITOFP; 283 case Instruction::SIToFP: return Expression::SITOFP; 284 case Instruction::FPTrunc: return Expression::FPTRUNC; 285 case Instruction::FPExt: return Expression::FPEXT; 286 case Instruction::PtrToInt: return Expression::PTRTOINT; 287 case Instruction::IntToPtr: return Expression::INTTOPTR; 288 case Instruction::BitCast: return Expression::BITCAST; 289 } 290} 291 292Expression ValueTable::create_expression(CallInst* C) { 293 Expression e; 294 295 e.type = C->getType(); 296 e.firstVN = 0; 297 e.secondVN = 0; 298 e.thirdVN = 0; 299 e.function = C->getCalledFunction(); 300 e.opcode = Expression::CALL; 301 302 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end(); 303 I != E; ++I) 304 e.varargs.push_back(lookup_or_add(*I)); 305 306 return e; 307} 308 309Expression ValueTable::create_expression(BinaryOperator* BO) { 310 Expression e; 311 312 e.firstVN = lookup_or_add(BO->getOperand(0)); 313 e.secondVN = lookup_or_add(BO->getOperand(1)); 314 e.thirdVN = 0; 315 e.function = 0; 316 e.type = BO->getType(); 317 e.opcode = getOpcode(BO); 318 319 return e; 320} 321 322Expression ValueTable::create_expression(CmpInst* C) { 323 Expression e; 324 325 e.firstVN = lookup_or_add(C->getOperand(0)); 326 e.secondVN = lookup_or_add(C->getOperand(1)); 327 e.thirdVN = 0; 328 e.function = 0; 329 e.type = C->getType(); 330 e.opcode = getOpcode(C); 331 332 return e; 333} 334 335Expression ValueTable::create_expression(CastInst* C) { 336 Expression e; 337 338 e.firstVN = lookup_or_add(C->getOperand(0)); 339 e.secondVN = 0; 340 e.thirdVN = 0; 341 e.function = 0; 342 e.type = C->getType(); 343 e.opcode = getOpcode(C); 344 345 return e; 346} 347 348Expression ValueTable::create_expression(ShuffleVectorInst* S) { 349 Expression e; 350 351 e.firstVN = lookup_or_add(S->getOperand(0)); 352 e.secondVN = lookup_or_add(S->getOperand(1)); 353 e.thirdVN = lookup_or_add(S->getOperand(2)); 354 e.function = 0; 355 e.type = S->getType(); 356 e.opcode = Expression::SHUFFLE; 357 358 return e; 359} 360 361Expression ValueTable::create_expression(ExtractElementInst* E) { 362 Expression e; 363 364 e.firstVN = lookup_or_add(E->getOperand(0)); 365 e.secondVN = lookup_or_add(E->getOperand(1)); 366 e.thirdVN = 0; 367 e.function = 0; 368 e.type = E->getType(); 369 e.opcode = Expression::EXTRACT; 370 371 return e; 372} 373 374Expression ValueTable::create_expression(InsertElementInst* I) { 375 Expression e; 376 377 e.firstVN = lookup_or_add(I->getOperand(0)); 378 e.secondVN = lookup_or_add(I->getOperand(1)); 379 e.thirdVN = lookup_or_add(I->getOperand(2)); 380 e.function = 0; 381 e.type = I->getType(); 382 e.opcode = Expression::INSERT; 383 384 return e; 385} 386 387Expression ValueTable::create_expression(SelectInst* I) { 388 Expression e; 389 390 e.firstVN = lookup_or_add(I->getCondition()); 391 e.secondVN = lookup_or_add(I->getTrueValue()); 392 e.thirdVN = lookup_or_add(I->getFalseValue()); 393 e.function = 0; 394 e.type = I->getType(); 395 e.opcode = Expression::SELECT; 396 397 return e; 398} 399 400Expression ValueTable::create_expression(GetElementPtrInst* G) { 401 Expression e; 402 403 e.firstVN = lookup_or_add(G->getPointerOperand()); 404 e.secondVN = 0; 405 e.thirdVN = 0; 406 e.function = 0; 407 e.type = G->getType(); 408 e.opcode = Expression::GEP; 409 410 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end(); 411 I != E; ++I) 412 e.varargs.push_back(lookup_or_add(*I)); 413 414 return e; 415} 416 417//===----------------------------------------------------------------------===// 418// ValueTable External Functions 419//===----------------------------------------------------------------------===// 420 421/// add - Insert a value into the table with a specified value number. 422void ValueTable::add(Value* V, uint32_t num) { 423 valueNumbering.insert(std::make_pair(V, num)); 424} 425 426/// lookup_or_add - Returns the value number for the specified value, assigning 427/// it a new number if it did not have one before. 428uint32_t ValueTable::lookup_or_add(Value* V) { 429 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V); 430 if (VI != valueNumbering.end()) 431 return VI->second; 432 433 if (CallInst* C = dyn_cast<CallInst>(V)) { 434 if (AA->doesNotAccessMemory(C)) { 435 Expression e = create_expression(C); 436 437 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 438 if (EI != expressionNumbering.end()) { 439 valueNumbering.insert(std::make_pair(V, EI->second)); 440 return EI->second; 441 } else { 442 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 443 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 444 445 return nextValueNumber++; 446 } 447 } else if (AA->onlyReadsMemory(C)) { 448 Expression e = create_expression(C); 449 450 if (expressionNumbering.find(e) == expressionNumbering.end()) { 451 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 452 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 453 return nextValueNumber++; 454 } 455 456 Instruction* local_dep = MD->getDependency(C); 457 458 if (local_dep == MemoryDependenceAnalysis::None) { 459 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 460 return nextValueNumber++; 461 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) { 462 if (!isa<CallInst>(local_dep)) { 463 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 464 return nextValueNumber++; 465 } 466 467 CallInst* local_cdep = cast<CallInst>(local_dep); 468 469 if (local_cdep->getCalledFunction() != C->getCalledFunction() || 470 local_cdep->getNumOperands() != C->getNumOperands()) { 471 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 472 return nextValueNumber++; 473 } else if (!C->getCalledFunction()) { 474 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 475 return nextValueNumber++; 476 } else { 477 for (unsigned i = 1; i < C->getNumOperands(); ++i) { 478 uint32_t c_vn = lookup_or_add(C->getOperand(i)); 479 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i)); 480 if (c_vn != cd_vn) { 481 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 482 return nextValueNumber++; 483 } 484 } 485 486 uint32_t v = lookup_or_add(local_cdep); 487 valueNumbering.insert(std::make_pair(V, v)); 488 return v; 489 } 490 } 491 492 493 DenseMap<BasicBlock*, Value*> deps; 494 MD->getNonLocalDependency(C, deps); 495 CallInst* cdep = 0; 496 497 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), 498 E = deps.end(); I != E; ++I) { 499 if (I->second == MemoryDependenceAnalysis::None) { 500 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 501 502 return nextValueNumber++; 503 } else if (I->second != MemoryDependenceAnalysis::NonLocal) { 504 if (DT->properlyDominates(I->first, C->getParent())) { 505 if (CallInst* CD = dyn_cast<CallInst>(I->second)) 506 cdep = CD; 507 else { 508 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 509 return nextValueNumber++; 510 } 511 } else { 512 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 513 return nextValueNumber++; 514 } 515 } 516 } 517 518 if (!cdep) { 519 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 520 return nextValueNumber++; 521 } 522 523 if (cdep->getCalledFunction() != C->getCalledFunction() || 524 cdep->getNumOperands() != C->getNumOperands()) { 525 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 526 return nextValueNumber++; 527 } else if (!C->getCalledFunction()) { 528 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 529 return nextValueNumber++; 530 } else { 531 for (unsigned i = 1; i < C->getNumOperands(); ++i) { 532 uint32_t c_vn = lookup_or_add(C->getOperand(i)); 533 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i)); 534 if (c_vn != cd_vn) { 535 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 536 return nextValueNumber++; 537 } 538 } 539 540 uint32_t v = lookup_or_add(cdep); 541 valueNumbering.insert(std::make_pair(V, v)); 542 return v; 543 } 544 545 } else { 546 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 547 return nextValueNumber++; 548 } 549 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) { 550 Expression e = create_expression(BO); 551 552 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 553 if (EI != expressionNumbering.end()) { 554 valueNumbering.insert(std::make_pair(V, EI->second)); 555 return EI->second; 556 } else { 557 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 558 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 559 560 return nextValueNumber++; 561 } 562 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) { 563 Expression e = create_expression(C); 564 565 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 566 if (EI != expressionNumbering.end()) { 567 valueNumbering.insert(std::make_pair(V, EI->second)); 568 return EI->second; 569 } else { 570 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 571 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 572 573 return nextValueNumber++; 574 } 575 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) { 576 Expression e = create_expression(U); 577 578 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 579 if (EI != expressionNumbering.end()) { 580 valueNumbering.insert(std::make_pair(V, EI->second)); 581 return EI->second; 582 } else { 583 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 584 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 585 586 return nextValueNumber++; 587 } 588 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) { 589 Expression e = create_expression(U); 590 591 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 592 if (EI != expressionNumbering.end()) { 593 valueNumbering.insert(std::make_pair(V, EI->second)); 594 return EI->second; 595 } else { 596 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 597 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 598 599 return nextValueNumber++; 600 } 601 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) { 602 Expression e = create_expression(U); 603 604 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 605 if (EI != expressionNumbering.end()) { 606 valueNumbering.insert(std::make_pair(V, EI->second)); 607 return EI->second; 608 } else { 609 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 610 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 611 612 return nextValueNumber++; 613 } 614 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) { 615 Expression e = create_expression(U); 616 617 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 618 if (EI != expressionNumbering.end()) { 619 valueNumbering.insert(std::make_pair(V, EI->second)); 620 return EI->second; 621 } else { 622 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 623 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 624 625 return nextValueNumber++; 626 } 627 } else if (CastInst* U = dyn_cast<CastInst>(V)) { 628 Expression e = create_expression(U); 629 630 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 631 if (EI != expressionNumbering.end()) { 632 valueNumbering.insert(std::make_pair(V, EI->second)); 633 return EI->second; 634 } else { 635 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 636 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 637 638 return nextValueNumber++; 639 } 640 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) { 641 Expression e = create_expression(U); 642 643 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e); 644 if (EI != expressionNumbering.end()) { 645 valueNumbering.insert(std::make_pair(V, EI->second)); 646 return EI->second; 647 } else { 648 expressionNumbering.insert(std::make_pair(e, nextValueNumber)); 649 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 650 651 return nextValueNumber++; 652 } 653 } else { 654 valueNumbering.insert(std::make_pair(V, nextValueNumber)); 655 return nextValueNumber++; 656 } 657} 658 659/// lookup - Returns the value number of the specified value. Fails if 660/// the value has not yet been numbered. 661uint32_t ValueTable::lookup(Value* V) const { 662 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V); 663 assert(VI != valueNumbering.end() && "Value not numbered?"); 664 return VI->second; 665} 666 667/// clear - Remove all entries from the ValueTable 668void ValueTable::clear() { 669 valueNumbering.clear(); 670 expressionNumbering.clear(); 671 nextValueNumber = 1; 672} 673 674/// erase - Remove a value from the value numbering 675void ValueTable::erase(Value* V) { 676 valueNumbering.erase(V); 677} 678 679//===----------------------------------------------------------------------===// 680// GVN Pass 681//===----------------------------------------------------------------------===// 682 683namespace llvm { 684 template<> struct DenseMapInfo<uint32_t> { 685 static inline uint32_t getEmptyKey() { return ~0; } 686 static inline uint32_t getTombstoneKey() { return ~0 - 1; } 687 static unsigned getHashValue(const uint32_t& Val) { return Val * 37; } 688 static bool isPod() { return true; } 689 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) { 690 return LHS == RHS; 691 } 692 }; 693} 694 695namespace { 696 struct VISIBILITY_HIDDEN ValueNumberScope { 697 ValueNumberScope* parent; 698 DenseMap<uint32_t, Value*> table; 699 700 ValueNumberScope(ValueNumberScope* p) : parent(p) { } 701 }; 702} 703 704namespace { 705 706 class VISIBILITY_HIDDEN GVN : public FunctionPass { 707 bool runOnFunction(Function &F); 708 public: 709 static char ID; // Pass identification, replacement for typeid 710 GVN() : FunctionPass((intptr_t)&ID) { } 711 712 private: 713 ValueTable VN; 714 DenseMap<BasicBlock*, ValueNumberScope*> localAvail; 715 716 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType; 717 PhiMapType phiMap; 718 719 720 // This transformation requires dominator postdominator info 721 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 722 AU.addRequired<DominatorTree>(); 723 AU.addRequired<MemoryDependenceAnalysis>(); 724 AU.addRequired<AliasAnalysis>(); 725 726 AU.addPreserved<DominatorTree>(); 727 AU.addPreserved<AliasAnalysis>(); 728 AU.addPreserved<MemoryDependenceAnalysis>(); 729 } 730 731 // Helper fuctions 732 // FIXME: eliminate or document these better 733 bool processLoad(LoadInst* L, 734 DenseMap<Value*, LoadInst*> &lastLoad, 735 SmallVectorImpl<Instruction*> &toErase); 736 bool processInstruction(Instruction* I, 737 DenseMap<Value*, LoadInst*>& lastSeenLoad, 738 SmallVectorImpl<Instruction*> &toErase); 739 bool processNonLocalLoad(LoadInst* L, 740 SmallVectorImpl<Instruction*> &toErase); 741 bool processBlock(DomTreeNode* DTN); 742 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig, 743 DenseMap<BasicBlock*, Value*> &Phis, 744 bool top_level = false); 745 void dump(DenseMap<uint32_t, Value*>& d); 746 bool iterateOnFunction(Function &F); 747 Value* CollapsePhi(PHINode* p); 748 bool isSafeReplacement(PHINode* p, Instruction* inst); 749 bool performPRE(Function& F); 750 Value* lookupNumber(BasicBlock* BB, uint32_t num); 751 }; 752 753 char GVN::ID = 0; 754} 755 756// createGVNPass - The public interface to this file... 757FunctionPass *llvm::createGVNPass() { return new GVN(); } 758 759static RegisterPass<GVN> X("gvn", 760 "Global Value Numbering"); 761 762void GVN::dump(DenseMap<uint32_t, Value*>& d) { 763 printf("{\n"); 764 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(), 765 E = d.end(); I != E; ++I) { 766 printf("%d\n", I->first); 767 I->second->dump(); 768 } 769 printf("}\n"); 770} 771 772Value* GVN::CollapsePhi(PHINode* p) { 773 DominatorTree &DT = getAnalysis<DominatorTree>(); 774 Value* constVal = p->hasConstantValue(); 775 776 if (!constVal) return 0; 777 778 Instruction* inst = dyn_cast<Instruction>(constVal); 779 if (!inst) 780 return constVal; 781 782 if (DT.dominates(inst, p)) 783 if (isSafeReplacement(p, inst)) 784 return inst; 785 return 0; 786} 787 788bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) { 789 if (!isa<PHINode>(inst)) 790 return true; 791 792 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end(); 793 UI != E; ++UI) 794 if (PHINode* use_phi = dyn_cast<PHINode>(UI)) 795 if (use_phi->getParent() == inst->getParent()) 796 return false; 797 798 return true; 799} 800 801/// GetValueForBlock - Get the value to use within the specified basic block. 802/// available values are in Phis. 803Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig, 804 DenseMap<BasicBlock*, Value*> &Phis, 805 bool top_level) { 806 807 // If we have already computed this value, return the previously computed val. 808 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB); 809 if (V != Phis.end() && !top_level) return V->second; 810 811 BasicBlock* singlePred = BB->getSinglePredecessor(); 812 if (singlePred) { 813 Value *ret = GetValueForBlock(singlePred, orig, Phis); 814 Phis[BB] = ret; 815 return ret; 816 } 817 818 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so 819 // now, then get values to fill in the incoming values for the PHI. 820 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle", 821 BB->begin()); 822 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB))); 823 824 if (Phis.count(BB) == 0) 825 Phis.insert(std::make_pair(BB, PN)); 826 827 // Fill in the incoming values for the block. 828 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 829 Value* val = GetValueForBlock(*PI, orig, Phis); 830 PN->addIncoming(val, *PI); 831 } 832 833 AliasAnalysis& AA = getAnalysis<AliasAnalysis>(); 834 AA.copyValue(orig, PN); 835 836 // Attempt to collapse PHI nodes that are trivially redundant 837 Value* v = CollapsePhi(PN); 838 if (!v) { 839 // Cache our phi construction results 840 phiMap[orig->getPointerOperand()].insert(PN); 841 return PN; 842 } 843 844 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); 845 846 MD.removeInstruction(PN); 847 PN->replaceAllUsesWith(v); 848 849 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(), 850 E = Phis.end(); I != E; ++I) 851 if (I->second == PN) 852 I->second = v; 853 854 PN->eraseFromParent(); 855 856 Phis[BB] = v; 857 return v; 858} 859 860/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are 861/// non-local by performing PHI construction. 862bool GVN::processNonLocalLoad(LoadInst* L, 863 SmallVectorImpl<Instruction*> &toErase) { 864 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); 865 866 // Find the non-local dependencies of the load 867 DenseMap<BasicBlock*, Value*> deps; 868 MD.getNonLocalDependency(L, deps); 869 870 DenseMap<BasicBlock*, Value*> repl; 871 872 // Filter out useless results (non-locals, etc) 873 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end(); 874 I != E; ++I) { 875 if (I->second == MemoryDependenceAnalysis::None) 876 return false; 877 878 if (I->second == MemoryDependenceAnalysis::NonLocal) 879 continue; 880 881 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) { 882 if (S->getPointerOperand() != L->getPointerOperand()) 883 return false; 884 repl[I->first] = S->getOperand(0); 885 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) { 886 if (LD->getPointerOperand() != L->getPointerOperand()) 887 return false; 888 repl[I->first] = LD; 889 } else { 890 return false; 891 } 892 } 893 894 // Use cached PHI construction information from previous runs 895 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()]; 896 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end(); 897 I != E; ++I) { 898 if ((*I)->getParent() == L->getParent()) { 899 MD.removeInstruction(L); 900 L->replaceAllUsesWith(*I); 901 toErase.push_back(L); 902 NumGVNLoad++; 903 return true; 904 } 905 906 repl.insert(std::make_pair((*I)->getParent(), *I)); 907 } 908 909 // Perform PHI construction 910 SmallPtrSet<BasicBlock*, 4> visited; 911 Value* v = GetValueForBlock(L->getParent(), L, repl, true); 912 913 MD.removeInstruction(L); 914 L->replaceAllUsesWith(v); 915 toErase.push_back(L); 916 NumGVNLoad++; 917 918 return true; 919} 920 921/// processLoad - Attempt to eliminate a load, first by eliminating it 922/// locally, and then attempting non-local elimination if that fails. 923bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad, 924 SmallVectorImpl<Instruction*> &toErase) { 925 if (L->isVolatile()) { 926 lastLoad[L->getPointerOperand()] = L; 927 return false; 928 } 929 930 Value* pointer = L->getPointerOperand(); 931 LoadInst*& last = lastLoad[pointer]; 932 933 // ... to a pointer that has been loaded from before... 934 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); 935 bool removedNonLocal = false; 936 Instruction* dep = MD.getDependency(L); 937 if (dep == MemoryDependenceAnalysis::NonLocal && 938 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) { 939 removedNonLocal = processNonLocalLoad(L, toErase); 940 941 if (!removedNonLocal) 942 last = L; 943 944 return removedNonLocal; 945 } 946 947 948 bool deletedLoad = false; 949 950 // Walk up the dependency chain until we either find 951 // a dependency we can use, or we can't walk any further 952 while (dep != MemoryDependenceAnalysis::None && 953 dep != MemoryDependenceAnalysis::NonLocal && 954 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) { 955 // ... that depends on a store ... 956 if (StoreInst* S = dyn_cast<StoreInst>(dep)) { 957 if (S->getPointerOperand() == pointer) { 958 // Remove it! 959 MD.removeInstruction(L); 960 961 L->replaceAllUsesWith(S->getOperand(0)); 962 toErase.push_back(L); 963 deletedLoad = true; 964 NumGVNLoad++; 965 } 966 967 // Whether we removed it or not, we can't 968 // go any further 969 break; 970 } else if (!last) { 971 // If we don't depend on a store, and we haven't 972 // been loaded before, bail. 973 break; 974 } else if (dep == last) { 975 // Remove it! 976 MD.removeInstruction(L); 977 978 L->replaceAllUsesWith(last); 979 toErase.push_back(L); 980 deletedLoad = true; 981 NumGVNLoad++; 982 983 break; 984 } else { 985 dep = MD.getDependency(L, dep); 986 } 987 } 988 989 if (dep != MemoryDependenceAnalysis::None && 990 dep != MemoryDependenceAnalysis::NonLocal && 991 isa<AllocationInst>(dep)) { 992 // Check that this load is actually from the 993 // allocation we found 994 Value* v = L->getOperand(0); 995 while (true) { 996 if (BitCastInst *BC = dyn_cast<BitCastInst>(v)) 997 v = BC->getOperand(0); 998 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v)) 999 v = GEP->getOperand(0); 1000 else 1001 break; 1002 } 1003 if (v == dep) { 1004 // If this load depends directly on an allocation, there isn't 1005 // anything stored there; therefore, we can optimize this load 1006 // to undef. 1007 MD.removeInstruction(L); 1008 1009 L->replaceAllUsesWith(UndefValue::get(L->getType())); 1010 toErase.push_back(L); 1011 deletedLoad = true; 1012 NumGVNLoad++; 1013 } 1014 } 1015 1016 if (!deletedLoad) 1017 last = L; 1018 1019 return deletedLoad; 1020} 1021 1022Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) { 1023 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB); 1024 if (I == localAvail.end()) 1025 return 0; 1026 1027 ValueNumberScope* locals = I->second; 1028 1029 while (locals) { 1030 DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num); 1031 if (I != locals->table.end()) 1032 return I->second; 1033 else 1034 locals = locals->parent; 1035 } 1036 1037 return 0; 1038} 1039 1040/// processInstruction - When calculating availability, handle an instruction 1041/// by inserting it into the appropriate sets 1042bool GVN::processInstruction(Instruction *I, 1043 DenseMap<Value*, LoadInst*> &lastSeenLoad, 1044 SmallVectorImpl<Instruction*> &toErase) { 1045 if (LoadInst* L = dyn_cast<LoadInst>(I)) { 1046 bool changed = processLoad(L, lastSeenLoad, toErase); 1047 1048 if (!changed) { 1049 unsigned num = VN.lookup_or_add(L); 1050 localAvail[I->getParent()]->table.insert(std::make_pair(num, L)); 1051 } 1052 1053 return changed; 1054 } 1055 1056 unsigned num = VN.lookup_or_add(I); 1057 1058 // Allocations are always uniquely numbered, so we can save time and memory 1059 // by fast failing them. 1060 if (isa<AllocationInst>(I)) { 1061 localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); 1062 return false; 1063 } 1064 1065 // Collapse PHI nodes 1066 if (PHINode* p = dyn_cast<PHINode>(I)) { 1067 Value* constVal = CollapsePhi(p); 1068 1069 if (constVal) { 1070 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end(); 1071 PI != PE; ++PI) 1072 if (PI->second.count(p)) 1073 PI->second.erase(p); 1074 1075 p->replaceAllUsesWith(constVal); 1076 toErase.push_back(p); 1077 } else { 1078 localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); 1079 } 1080 // Perform value-number based elimination 1081 } else if (Value* repl = lookupNumber(I->getParent(), num)) { 1082 // Remove it! 1083 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>(); 1084 MD.removeInstruction(I); 1085 1086 VN.erase(I); 1087 I->replaceAllUsesWith(repl); 1088 toErase.push_back(I); 1089 return true; 1090 } else if (!I->isTerminator()) { 1091 localAvail[I->getParent()]->table.insert(std::make_pair(num, I)); 1092 } 1093 1094 return false; 1095} 1096 1097// GVN::runOnFunction - This is the main transformation entry point for a 1098// function. 1099// 1100bool GVN::runOnFunction(Function& F) { 1101 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>()); 1102 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>()); 1103 VN.setDomTree(&getAnalysis<DominatorTree>()); 1104 1105 bool changed = false; 1106 bool shouldContinue = true; 1107 1108 while (shouldContinue) { 1109 shouldContinue = iterateOnFunction(F); 1110 changed |= shouldContinue; 1111 } 1112 1113 return changed; 1114} 1115 1116 1117bool GVN::processBlock(DomTreeNode* DTN) { 1118 BasicBlock* BB = DTN->getBlock(); 1119 1120 SmallVector<Instruction*, 8> toErase; 1121 DenseMap<Value*, LoadInst*> lastSeenLoad; 1122 bool changed_function = false; 1123 1124 if (DTN->getIDom()) 1125 localAvail[BB] = 1126 new ValueNumberScope(localAvail[DTN->getIDom()->getBlock()]); 1127 else 1128 localAvail[BB] = new ValueNumberScope(0); 1129 1130 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); 1131 BI != BE;) { 1132 changed_function |= processInstruction(BI, lastSeenLoad, toErase); 1133 if (toErase.empty()) { 1134 ++BI; 1135 continue; 1136 } 1137 1138 // If we need some instructions deleted, do it now. 1139 NumGVNInstr += toErase.size(); 1140 1141 // Avoid iterator invalidation. 1142 bool AtStart = BI == BB->begin(); 1143 if (!AtStart) 1144 --BI; 1145 1146 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(), 1147 E = toErase.end(); I != E; ++I) 1148 (*I)->eraseFromParent(); 1149 1150 if (AtStart) 1151 BI = BB->begin(); 1152 else 1153 ++BI; 1154 1155 toErase.clear(); 1156 } 1157 1158 return changed_function; 1159} 1160 1161/// performPRE - Perform a purely local form of PRE that looks for diamond 1162/// control flow patterns and attempts to perform simple PRE at the join point. 1163bool GVN::performPRE(Function& F) { 1164 bool changed = false; 1165 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit; 1166 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()), 1167 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) { 1168 BasicBlock* CurrentBlock = *DI; 1169 1170 // Nothing to PRE in the entry block. 1171 if (CurrentBlock == &F.getEntryBlock()) continue; 1172 1173 for (BasicBlock::iterator BI = CurrentBlock->begin(), 1174 BE = CurrentBlock->end(); BI != BE; ) { 1175 if (isa<AllocationInst>(BI) || isa<TerminatorInst>(BI) || 1176 isa<PHINode>(BI) || BI->mayReadFromMemory() || 1177 BI->mayWriteToMemory()) { 1178 BI++; 1179 continue; 1180 } 1181 1182 uint32_t valno = VN.lookup(BI); 1183 1184 // Look for the predecessors for PRE opportunities. We're 1185 // only trying to solve the basic diamond case, where 1186 // a value is computed in the successor and one predecessor, 1187 // but not the other. We also explicitly disallow cases 1188 // where the successor is its own predecessor, because they're 1189 // more complicated to get right. 1190 unsigned numWith = 0; 1191 unsigned numWithout = 0; 1192 BasicBlock* PREPred = 0; 1193 DenseMap<BasicBlock*, Value*> predMap; 1194 for (pred_iterator PI = pred_begin(CurrentBlock), 1195 PE = pred_end(CurrentBlock); PI != PE; ++PI) { 1196 // We're not interested in PRE where the block is its 1197 // own predecessor, on in blocks with predecessors 1198 // that are not reachable. 1199 if (*PI == CurrentBlock) { 1200 numWithout = 2; 1201 break; 1202 } else if (!localAvail.count(*PI)) { 1203 numWithout = 2; 1204 break; 1205 } 1206 1207 DenseMap<uint32_t, Value*>::iterator predV = 1208 localAvail[*PI]->table.find(valno); 1209 if (predV == localAvail[*PI]->table.end()) { 1210 PREPred = *PI; 1211 numWithout++; 1212 } else if (predV->second == BI) { 1213 numWithout = 2; 1214 } else { 1215 predMap[*PI] = predV->second; 1216 numWith++; 1217 } 1218 } 1219 1220 // Don't do PRE when it might increase code size, i.e. when 1221 // we would need to insert instructions in more than one pred. 1222 if (numWithout != 1 || numWith == 0) { 1223 BI++; 1224 continue; 1225 } 1226 1227 // We can't do PRE safely on a critical edge, so instead we schedule 1228 // the edge to be split and perform the PRE the next time we iterate 1229 // on the function. 1230 unsigned succNum = 0; 1231 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors(); 1232 i != e; ++i) 1233 if (PREPred->getTerminator()->getSuccessor(i) == PREPred) { 1234 succNum = i; 1235 break; 1236 } 1237 1238 if (isCriticalEdge(PREPred->getTerminator(), succNum)) { 1239 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum)); 1240 changed = true; 1241 BI++; 1242 continue; 1243 } 1244 1245 // Instantiate the expression the in predecessor that lacked it. 1246 // Because we are going top-down through the block, all value numbers 1247 // will be available in the predecessor by the time we need them. Any 1248 // that weren't original present will have been instantiated earlier 1249 // in this loop. 1250 Instruction* PREInstr = BI->clone(); 1251 bool success = true; 1252 for (unsigned i = 0; i < BI->getNumOperands(); ++i) { 1253 Value* op = BI->getOperand(i); 1254 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op)) 1255 PREInstr->setOperand(i, op); 1256 else if (!lookupNumber(PREPred, VN.lookup(op))) { 1257 success = false; 1258 break; 1259 } else 1260 PREInstr->setOperand(i, lookupNumber(PREPred, VN.lookup(op))); 1261 } 1262 1263 // Fail out if we encounter an operand that is not available in 1264 // the PRE predecessor. This is typically because of loads which 1265 // are not value numbered precisely. 1266 if (!success) { 1267 delete PREInstr; 1268 BI++; 1269 continue; 1270 } 1271 1272 PREInstr->insertBefore(PREPred->getTerminator()); 1273 PREInstr->setName(BI->getName() + ".pre"); 1274 predMap[PREPred] = PREInstr; 1275 VN.add(PREInstr, valno); 1276 NumGVNPRE++; 1277 1278 // Update the availability map to include the new instruction. 1279 localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr)); 1280 1281 // Create a PHI to make the value available in this block. 1282 PHINode* Phi = PHINode::Create(BI->getType(), 1283 BI->getName() + ".pre-phi", 1284 CurrentBlock->begin()); 1285 for (pred_iterator PI = pred_begin(CurrentBlock), 1286 PE = pred_end(CurrentBlock); PI != PE; ++PI) 1287 Phi->addIncoming(predMap[*PI], *PI); 1288 1289 VN.add(Phi, valno); 1290 localAvail[CurrentBlock]->table[valno] = Phi; 1291 1292 BI->replaceAllUsesWith(Phi); 1293 VN.erase(BI); 1294 1295 Instruction* erase = BI; 1296 BI++; 1297 erase->eraseFromParent(); 1298 1299 changed = true; 1300 } 1301 } 1302 1303 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator 1304 I = toSplit.begin(), E = toSplit.end(); I != E; ++I) 1305 SplitCriticalEdge(I->first, I->second, this); 1306 1307 return changed; 1308} 1309 1310// GVN::iterateOnFunction - Executes one iteration of GVN 1311bool GVN::iterateOnFunction(Function &F) { 1312 // Clean out global sets from any previous functions 1313 VN.clear(); 1314 phiMap.clear(); 1315 1316 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator 1317 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) 1318 delete I->second; 1319 localAvail.clear(); 1320 1321 DominatorTree &DT = getAnalysis<DominatorTree>(); 1322 1323 // Top-down walk of the dominator tree 1324 bool changed = false; 1325 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()), 1326 DE = df_end(DT.getRootNode()); DI != DE; ++DI) 1327 changed |= processBlock(*DI); 1328 1329 if (EnablePRE) 1330 changed |= performPRE(F); 1331 1332 return changed; 1333} 1334