1 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass performs global value numbering to eliminate fully redundant 10 // instructions. It also performs simple dead load elimination. 11 // 12 // Note that this pass does the value numbering itself; it does not use the 13 // ValueNumbering analysis passes. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Transforms/Scalar/GVN.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/DepthFirstIterator.h" 20 #include "llvm/ADT/Hashing.h" 21 #include "llvm/ADT/MapVector.h" 22 #include "llvm/ADT/PointerIntPair.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SetVector.h" 26 #include "llvm/ADT/SmallPtrSet.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/AssumeBundleQueries.h" 31 #include "llvm/Analysis/AssumptionCache.h" 32 #include "llvm/Analysis/CFG.h" 33 #include "llvm/Analysis/DomTreeUpdater.h" 34 #include "llvm/Analysis/GlobalsModRef.h" 35 #include "llvm/Analysis/InstructionSimplify.h" 36 #include "llvm/Analysis/LoopInfo.h" 37 #include "llvm/Analysis/MemoryBuiltins.h" 38 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 39 #include "llvm/Analysis/MemorySSA.h" 40 #include "llvm/Analysis/MemorySSAUpdater.h" 41 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 42 #include "llvm/Analysis/PHITransAddr.h" 43 #include "llvm/Analysis/TargetLibraryInfo.h" 44 #include "llvm/Analysis/ValueTracking.h" 45 #include "llvm/Config/llvm-config.h" 46 #include "llvm/IR/Attributes.h" 47 #include "llvm/IR/BasicBlock.h" 48 #include "llvm/IR/Constant.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugInfoMetadata.h" 52 #include "llvm/IR/DebugLoc.h" 53 #include "llvm/IR/Dominators.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/InstrTypes.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/IR/Intrinsics.h" 60 #include "llvm/IR/LLVMContext.h" 61 #include "llvm/IR/Metadata.h" 62 #include "llvm/IR/Module.h" 63 #include "llvm/IR/Operator.h" 64 #include "llvm/IR/PassManager.h" 65 #include "llvm/IR/PatternMatch.h" 66 #include "llvm/IR/Type.h" 67 #include "llvm/IR/Use.h" 68 #include "llvm/IR/Value.h" 69 #include "llvm/InitializePasses.h" 70 #include "llvm/Pass.h" 71 #include "llvm/Support/Casting.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/Debug.h" 75 #include "llvm/Support/raw_ostream.h" 76 #include "llvm/Transforms/Utils.h" 77 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 78 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 79 #include "llvm/Transforms/Utils/Local.h" 80 #include "llvm/Transforms/Utils/SSAUpdater.h" 81 #include "llvm/Transforms/Utils/VNCoercion.h" 82 #include <algorithm> 83 #include <cassert> 84 #include <cstdint> 85 #include <utility> 86 #include <vector> 87 88 using namespace llvm; 89 using namespace llvm::gvn; 90 using namespace llvm::VNCoercion; 91 using namespace PatternMatch; 92 93 #define DEBUG_TYPE "gvn" 94 95 STATISTIC(NumGVNInstr, "Number of instructions deleted"); 96 STATISTIC(NumGVNLoad, "Number of loads deleted"); 97 STATISTIC(NumGVNPRE, "Number of instructions PRE'd"); 98 STATISTIC(NumGVNBlocks, "Number of blocks merged"); 99 STATISTIC(NumGVNSimpl, "Number of instructions simplified"); 100 STATISTIC(NumGVNEqProp, "Number of equalities propagated"); 101 STATISTIC(NumPRELoad, "Number of loads PRE'd"); 102 103 STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax, 104 "Number of blocks speculated as available in " 105 "IsValueFullyAvailableInBlock(), max"); 106 STATISTIC(MaxBBSpeculationCutoffReachedTimes, 107 "Number of times we we reached gvn-max-block-speculations cut-off " 108 "preventing further exploration"); 109 110 static cl::opt<bool> GVNEnablePRE("enable-pre", cl::init(true), cl::Hidden); 111 static cl::opt<bool> GVNEnableLoadPRE("enable-load-pre", cl::init(true)); 112 static cl::opt<bool> GVNEnableLoadInLoopPRE("enable-load-in-loop-pre", 113 cl::init(true)); 114 static cl::opt<bool> GVNEnableMemDep("enable-gvn-memdep", cl::init(true)); 115 116 static cl::opt<uint32_t> MaxNumDeps( 117 "gvn-max-num-deps", cl::Hidden, cl::init(100), cl::ZeroOrMore, 118 cl::desc("Max number of dependences to attempt Load PRE (default = 100)")); 119 120 // This is based on IsValueFullyAvailableInBlockNumSpeculationsMax stat. 121 static cl::opt<uint32_t> MaxBBSpeculations( 122 "gvn-max-block-speculations", cl::Hidden, cl::init(600), cl::ZeroOrMore, 123 cl::desc("Max number of blocks we're willing to speculate on (and recurse " 124 "into) when deducing if a value is fully available or not in GVN " 125 "(default = 600)")); 126 127 struct llvm::GVN::Expression { 128 uint32_t opcode; 129 bool commutative = false; 130 Type *type = nullptr; 131 SmallVector<uint32_t, 4> varargs; 132 133 Expression(uint32_t o = ~2U) : opcode(o) {} 134 135 bool operator==(const Expression &other) const { 136 if (opcode != other.opcode) 137 return false; 138 if (opcode == ~0U || opcode == ~1U) 139 return true; 140 if (type != other.type) 141 return false; 142 if (varargs != other.varargs) 143 return false; 144 return true; 145 } 146 147 friend hash_code hash_value(const Expression &Value) { 148 return hash_combine( 149 Value.opcode, Value.type, 150 hash_combine_range(Value.varargs.begin(), Value.varargs.end())); 151 } 152 }; 153 154 namespace llvm { 155 156 template <> struct DenseMapInfo<GVN::Expression> { 157 static inline GVN::Expression getEmptyKey() { return ~0U; } 158 static inline GVN::Expression getTombstoneKey() { return ~1U; } 159 160 static unsigned getHashValue(const GVN::Expression &e) { 161 using llvm::hash_value; 162 163 return static_cast<unsigned>(hash_value(e)); 164 } 165 166 static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS) { 167 return LHS == RHS; 168 } 169 }; 170 171 } // end namespace llvm 172 173 /// Represents a particular available value that we know how to materialize. 174 /// Materialization of an AvailableValue never fails. An AvailableValue is 175 /// implicitly associated with a rematerialization point which is the 176 /// location of the instruction from which it was formed. 177 struct llvm::gvn::AvailableValue { 178 enum ValType { 179 SimpleVal, // A simple offsetted value that is accessed. 180 LoadVal, // A value produced by a load. 181 MemIntrin, // A memory intrinsic which is loaded from. 182 UndefVal // A UndefValue representing a value from dead block (which 183 // is not yet physically removed from the CFG). 184 }; 185 186 /// V - The value that is live out of the block. 187 PointerIntPair<Value *, 2, ValType> Val; 188 189 /// Offset - The byte offset in Val that is interesting for the load query. 190 unsigned Offset = 0; 191 192 static AvailableValue get(Value *V, unsigned Offset = 0) { 193 AvailableValue Res; 194 Res.Val.setPointer(V); 195 Res.Val.setInt(SimpleVal); 196 Res.Offset = Offset; 197 return Res; 198 } 199 200 static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) { 201 AvailableValue Res; 202 Res.Val.setPointer(MI); 203 Res.Val.setInt(MemIntrin); 204 Res.Offset = Offset; 205 return Res; 206 } 207 208 static AvailableValue getLoad(LoadInst *LI, unsigned Offset = 0) { 209 AvailableValue Res; 210 Res.Val.setPointer(LI); 211 Res.Val.setInt(LoadVal); 212 Res.Offset = Offset; 213 return Res; 214 } 215 216 static AvailableValue getUndef() { 217 AvailableValue Res; 218 Res.Val.setPointer(nullptr); 219 Res.Val.setInt(UndefVal); 220 Res.Offset = 0; 221 return Res; 222 } 223 224 bool isSimpleValue() const { return Val.getInt() == SimpleVal; } 225 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; } 226 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; } 227 bool isUndefValue() const { return Val.getInt() == UndefVal; } 228 229 Value *getSimpleValue() const { 230 assert(isSimpleValue() && "Wrong accessor"); 231 return Val.getPointer(); 232 } 233 234 LoadInst *getCoercedLoadValue() const { 235 assert(isCoercedLoadValue() && "Wrong accessor"); 236 return cast<LoadInst>(Val.getPointer()); 237 } 238 239 MemIntrinsic *getMemIntrinValue() const { 240 assert(isMemIntrinValue() && "Wrong accessor"); 241 return cast<MemIntrinsic>(Val.getPointer()); 242 } 243 244 /// Emit code at the specified insertion point to adjust the value defined 245 /// here to the specified type. This handles various coercion cases. 246 Value *MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt, 247 GVN &gvn) const; 248 }; 249 250 /// Represents an AvailableValue which can be rematerialized at the end of 251 /// the associated BasicBlock. 252 struct llvm::gvn::AvailableValueInBlock { 253 /// BB - The basic block in question. 254 BasicBlock *BB = nullptr; 255 256 /// AV - The actual available value 257 AvailableValue AV; 258 259 static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) { 260 AvailableValueInBlock Res; 261 Res.BB = BB; 262 Res.AV = std::move(AV); 263 return Res; 264 } 265 266 static AvailableValueInBlock get(BasicBlock *BB, Value *V, 267 unsigned Offset = 0) { 268 return get(BB, AvailableValue::get(V, Offset)); 269 } 270 271 static AvailableValueInBlock getUndef(BasicBlock *BB) { 272 return get(BB, AvailableValue::getUndef()); 273 } 274 275 /// Emit code at the end of this block to adjust the value defined here to 276 /// the specified type. This handles various coercion cases. 277 Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const { 278 return AV.MaterializeAdjustedValue(LI, BB->getTerminator(), gvn); 279 } 280 }; 281 282 //===----------------------------------------------------------------------===// 283 // ValueTable Internal Functions 284 //===----------------------------------------------------------------------===// 285 286 GVN::Expression GVN::ValueTable::createExpr(Instruction *I) { 287 Expression e; 288 e.type = I->getType(); 289 e.opcode = I->getOpcode(); 290 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end(); 291 OI != OE; ++OI) 292 e.varargs.push_back(lookupOrAdd(*OI)); 293 if (I->isCommutative()) { 294 // Ensure that commutative instructions that only differ by a permutation 295 // of their operands get the same value number by sorting the operand value 296 // numbers. Since commutative operands are the 1st two operands it is more 297 // efficient to sort by hand rather than using, say, std::sort. 298 assert(I->getNumOperands() >= 2 && "Unsupported commutative instruction!"); 299 if (e.varargs[0] > e.varargs[1]) 300 std::swap(e.varargs[0], e.varargs[1]); 301 e.commutative = true; 302 } 303 304 if (auto *C = dyn_cast<CmpInst>(I)) { 305 // Sort the operand value numbers so x<y and y>x get the same value number. 306 CmpInst::Predicate Predicate = C->getPredicate(); 307 if (e.varargs[0] > e.varargs[1]) { 308 std::swap(e.varargs[0], e.varargs[1]); 309 Predicate = CmpInst::getSwappedPredicate(Predicate); 310 } 311 e.opcode = (C->getOpcode() << 8) | Predicate; 312 e.commutative = true; 313 } else if (auto *E = dyn_cast<InsertValueInst>(I)) { 314 e.varargs.append(E->idx_begin(), E->idx_end()); 315 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) { 316 ArrayRef<int> ShuffleMask = SVI->getShuffleMask(); 317 e.varargs.append(ShuffleMask.begin(), ShuffleMask.end()); 318 } 319 320 return e; 321 } 322 323 GVN::Expression GVN::ValueTable::createCmpExpr(unsigned Opcode, 324 CmpInst::Predicate Predicate, 325 Value *LHS, Value *RHS) { 326 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 327 "Not a comparison!"); 328 Expression e; 329 e.type = CmpInst::makeCmpResultType(LHS->getType()); 330 e.varargs.push_back(lookupOrAdd(LHS)); 331 e.varargs.push_back(lookupOrAdd(RHS)); 332 333 // Sort the operand value numbers so x<y and y>x get the same value number. 334 if (e.varargs[0] > e.varargs[1]) { 335 std::swap(e.varargs[0], e.varargs[1]); 336 Predicate = CmpInst::getSwappedPredicate(Predicate); 337 } 338 e.opcode = (Opcode << 8) | Predicate; 339 e.commutative = true; 340 return e; 341 } 342 343 GVN::Expression GVN::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) { 344 assert(EI && "Not an ExtractValueInst?"); 345 Expression e; 346 e.type = EI->getType(); 347 e.opcode = 0; 348 349 WithOverflowInst *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand()); 350 if (WO != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) { 351 // EI is an extract from one of our with.overflow intrinsics. Synthesize 352 // a semantically equivalent expression instead of an extract value 353 // expression. 354 e.opcode = WO->getBinaryOp(); 355 e.varargs.push_back(lookupOrAdd(WO->getLHS())); 356 e.varargs.push_back(lookupOrAdd(WO->getRHS())); 357 return e; 358 } 359 360 // Not a recognised intrinsic. Fall back to producing an extract value 361 // expression. 362 e.opcode = EI->getOpcode(); 363 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end(); 364 OI != OE; ++OI) 365 e.varargs.push_back(lookupOrAdd(*OI)); 366 367 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end(); 368 II != IE; ++II) 369 e.varargs.push_back(*II); 370 371 return e; 372 } 373 374 //===----------------------------------------------------------------------===// 375 // ValueTable External Functions 376 //===----------------------------------------------------------------------===// 377 378 GVN::ValueTable::ValueTable() = default; 379 GVN::ValueTable::ValueTable(const ValueTable &) = default; 380 GVN::ValueTable::ValueTable(ValueTable &&) = default; 381 GVN::ValueTable::~ValueTable() = default; 382 GVN::ValueTable &GVN::ValueTable::operator=(const GVN::ValueTable &Arg) = default; 383 384 /// add - Insert a value into the table with a specified value number. 385 void GVN::ValueTable::add(Value *V, uint32_t num) { 386 valueNumbering.insert(std::make_pair(V, num)); 387 if (PHINode *PN = dyn_cast<PHINode>(V)) 388 NumberingPhi[num] = PN; 389 } 390 391 uint32_t GVN::ValueTable::lookupOrAddCall(CallInst *C) { 392 if (AA->doesNotAccessMemory(C)) { 393 Expression exp = createExpr(C); 394 uint32_t e = assignExpNewValueNum(exp).first; 395 valueNumbering[C] = e; 396 return e; 397 } else if (MD && AA->onlyReadsMemory(C)) { 398 Expression exp = createExpr(C); 399 auto ValNum = assignExpNewValueNum(exp); 400 if (ValNum.second) { 401 valueNumbering[C] = ValNum.first; 402 return ValNum.first; 403 } 404 405 MemDepResult local_dep = MD->getDependency(C); 406 407 if (!local_dep.isDef() && !local_dep.isNonLocal()) { 408 valueNumbering[C] = nextValueNumber; 409 return nextValueNumber++; 410 } 411 412 if (local_dep.isDef()) { 413 CallInst* local_cdep = cast<CallInst>(local_dep.getInst()); 414 415 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) { 416 valueNumbering[C] = nextValueNumber; 417 return nextValueNumber++; 418 } 419 420 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) { 421 uint32_t c_vn = lookupOrAdd(C->getArgOperand(i)); 422 uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i)); 423 if (c_vn != cd_vn) { 424 valueNumbering[C] = nextValueNumber; 425 return nextValueNumber++; 426 } 427 } 428 429 uint32_t v = lookupOrAdd(local_cdep); 430 valueNumbering[C] = v; 431 return v; 432 } 433 434 // Non-local case. 435 const MemoryDependenceResults::NonLocalDepInfo &deps = 436 MD->getNonLocalCallDependency(C); 437 // FIXME: Move the checking logic to MemDep! 438 CallInst* cdep = nullptr; 439 440 // Check to see if we have a single dominating call instruction that is 441 // identical to C. 442 for (unsigned i = 0, e = deps.size(); i != e; ++i) { 443 const NonLocalDepEntry *I = &deps[i]; 444 if (I->getResult().isNonLocal()) 445 continue; 446 447 // We don't handle non-definitions. If we already have a call, reject 448 // instruction dependencies. 449 if (!I->getResult().isDef() || cdep != nullptr) { 450 cdep = nullptr; 451 break; 452 } 453 454 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst()); 455 // FIXME: All duplicated with non-local case. 456 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){ 457 cdep = NonLocalDepCall; 458 continue; 459 } 460 461 cdep = nullptr; 462 break; 463 } 464 465 if (!cdep) { 466 valueNumbering[C] = nextValueNumber; 467 return nextValueNumber++; 468 } 469 470 if (cdep->getNumArgOperands() != C->getNumArgOperands()) { 471 valueNumbering[C] = nextValueNumber; 472 return nextValueNumber++; 473 } 474 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) { 475 uint32_t c_vn = lookupOrAdd(C->getArgOperand(i)); 476 uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i)); 477 if (c_vn != cd_vn) { 478 valueNumbering[C] = nextValueNumber; 479 return nextValueNumber++; 480 } 481 } 482 483 uint32_t v = lookupOrAdd(cdep); 484 valueNumbering[C] = v; 485 return v; 486 } else { 487 valueNumbering[C] = nextValueNumber; 488 return nextValueNumber++; 489 } 490 } 491 492 /// Returns true if a value number exists for the specified value. 493 bool GVN::ValueTable::exists(Value *V) const { return valueNumbering.count(V) != 0; } 494 495 /// lookup_or_add - Returns the value number for the specified value, assigning 496 /// it a new number if it did not have one before. 497 uint32_t GVN::ValueTable::lookupOrAdd(Value *V) { 498 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V); 499 if (VI != valueNumbering.end()) 500 return VI->second; 501 502 if (!isa<Instruction>(V)) { 503 valueNumbering[V] = nextValueNumber; 504 return nextValueNumber++; 505 } 506 507 Instruction* I = cast<Instruction>(V); 508 Expression exp; 509 switch (I->getOpcode()) { 510 case Instruction::Call: 511 return lookupOrAddCall(cast<CallInst>(I)); 512 case Instruction::FNeg: 513 case Instruction::Add: 514 case Instruction::FAdd: 515 case Instruction::Sub: 516 case Instruction::FSub: 517 case Instruction::Mul: 518 case Instruction::FMul: 519 case Instruction::UDiv: 520 case Instruction::SDiv: 521 case Instruction::FDiv: 522 case Instruction::URem: 523 case Instruction::SRem: 524 case Instruction::FRem: 525 case Instruction::Shl: 526 case Instruction::LShr: 527 case Instruction::AShr: 528 case Instruction::And: 529 case Instruction::Or: 530 case Instruction::Xor: 531 case Instruction::ICmp: 532 case Instruction::FCmp: 533 case Instruction::Trunc: 534 case Instruction::ZExt: 535 case Instruction::SExt: 536 case Instruction::FPToUI: 537 case Instruction::FPToSI: 538 case Instruction::UIToFP: 539 case Instruction::SIToFP: 540 case Instruction::FPTrunc: 541 case Instruction::FPExt: 542 case Instruction::PtrToInt: 543 case Instruction::IntToPtr: 544 case Instruction::AddrSpaceCast: 545 case Instruction::BitCast: 546 case Instruction::Select: 547 case Instruction::Freeze: 548 case Instruction::ExtractElement: 549 case Instruction::InsertElement: 550 case Instruction::ShuffleVector: 551 case Instruction::InsertValue: 552 case Instruction::GetElementPtr: 553 exp = createExpr(I); 554 break; 555 case Instruction::ExtractValue: 556 exp = createExtractvalueExpr(cast<ExtractValueInst>(I)); 557 break; 558 case Instruction::PHI: 559 valueNumbering[V] = nextValueNumber; 560 NumberingPhi[nextValueNumber] = cast<PHINode>(V); 561 return nextValueNumber++; 562 default: 563 valueNumbering[V] = nextValueNumber; 564 return nextValueNumber++; 565 } 566 567 uint32_t e = assignExpNewValueNum(exp).first; 568 valueNumbering[V] = e; 569 return e; 570 } 571 572 /// Returns the value number of the specified value. Fails if 573 /// the value has not yet been numbered. 574 uint32_t GVN::ValueTable::lookup(Value *V, bool Verify) const { 575 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V); 576 if (Verify) { 577 assert(VI != valueNumbering.end() && "Value not numbered?"); 578 return VI->second; 579 } 580 return (VI != valueNumbering.end()) ? VI->second : 0; 581 } 582 583 /// Returns the value number of the given comparison, 584 /// assigning it a new number if it did not have one before. Useful when 585 /// we deduced the result of a comparison, but don't immediately have an 586 /// instruction realizing that comparison to hand. 587 uint32_t GVN::ValueTable::lookupOrAddCmp(unsigned Opcode, 588 CmpInst::Predicate Predicate, 589 Value *LHS, Value *RHS) { 590 Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS); 591 return assignExpNewValueNum(exp).first; 592 } 593 594 /// Remove all entries from the ValueTable. 595 void GVN::ValueTable::clear() { 596 valueNumbering.clear(); 597 expressionNumbering.clear(); 598 NumberingPhi.clear(); 599 PhiTranslateTable.clear(); 600 nextValueNumber = 1; 601 Expressions.clear(); 602 ExprIdx.clear(); 603 nextExprNumber = 0; 604 } 605 606 /// Remove a value from the value numbering. 607 void GVN::ValueTable::erase(Value *V) { 608 uint32_t Num = valueNumbering.lookup(V); 609 valueNumbering.erase(V); 610 // If V is PHINode, V <--> value number is an one-to-one mapping. 611 if (isa<PHINode>(V)) 612 NumberingPhi.erase(Num); 613 } 614 615 /// verifyRemoved - Verify that the value is removed from all internal data 616 /// structures. 617 void GVN::ValueTable::verifyRemoved(const Value *V) const { 618 for (DenseMap<Value*, uint32_t>::const_iterator 619 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) { 620 assert(I->first != V && "Inst still occurs in value numbering map!"); 621 } 622 } 623 624 //===----------------------------------------------------------------------===// 625 // GVN Pass 626 //===----------------------------------------------------------------------===// 627 628 bool GVN::isPREEnabled() const { 629 return Options.AllowPRE.getValueOr(GVNEnablePRE); 630 } 631 632 bool GVN::isLoadPREEnabled() const { 633 return Options.AllowLoadPRE.getValueOr(GVNEnableLoadPRE); 634 } 635 636 bool GVN::isLoadInLoopPREEnabled() const { 637 return Options.AllowLoadInLoopPRE.getValueOr(GVNEnableLoadInLoopPRE); 638 } 639 640 bool GVN::isMemDepEnabled() const { 641 return Options.AllowMemDep.getValueOr(GVNEnableMemDep); 642 } 643 644 PreservedAnalyses GVN::run(Function &F, FunctionAnalysisManager &AM) { 645 // FIXME: The order of evaluation of these 'getResult' calls is very 646 // significant! Re-ordering these variables will cause GVN when run alone to 647 // be less effective! We should fix memdep and basic-aa to not exhibit this 648 // behavior, but until then don't change the order here. 649 auto &AC = AM.getResult<AssumptionAnalysis>(F); 650 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 651 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 652 auto &AA = AM.getResult<AAManager>(F); 653 auto *MemDep = 654 isMemDepEnabled() ? &AM.getResult<MemoryDependenceAnalysis>(F) : nullptr; 655 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 656 auto *MSSA = AM.getCachedResult<MemorySSAAnalysis>(F); 657 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 658 bool Changed = runImpl(F, AC, DT, TLI, AA, MemDep, LI, &ORE, 659 MSSA ? &MSSA->getMSSA() : nullptr); 660 if (!Changed) 661 return PreservedAnalyses::all(); 662 PreservedAnalyses PA; 663 PA.preserve<DominatorTreeAnalysis>(); 664 PA.preserve<GlobalsAA>(); 665 PA.preserve<TargetLibraryAnalysis>(); 666 if (MSSA) 667 PA.preserve<MemorySSAAnalysis>(); 668 if (LI) 669 PA.preserve<LoopAnalysis>(); 670 return PA; 671 } 672 673 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 674 LLVM_DUMP_METHOD void GVN::dump(DenseMap<uint32_t, Value*>& d) const { 675 errs() << "{\n"; 676 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(), 677 E = d.end(); I != E; ++I) { 678 errs() << I->first << "\n"; 679 I->second->dump(); 680 } 681 errs() << "}\n"; 682 } 683 #endif 684 685 enum class AvailabilityState : char { 686 /// We know the block *is not* fully available. This is a fixpoint. 687 Unavailable = 0, 688 /// We know the block *is* fully available. This is a fixpoint. 689 Available = 1, 690 /// We do not know whether the block is fully available or not, 691 /// but we are currently speculating that it will be. 692 /// If it would have turned out that the block was, in fact, not fully 693 /// available, this would have been cleaned up into an Unavailable. 694 SpeculativelyAvailable = 2, 695 }; 696 697 /// Return true if we can prove that the value 698 /// we're analyzing is fully available in the specified block. As we go, keep 699 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This 700 /// map is actually a tri-state map with the following values: 701 /// 0) we know the block *is not* fully available. 702 /// 1) we know the block *is* fully available. 703 /// 2) we do not know whether the block is fully available or not, but we are 704 /// currently speculating that it will be. 705 static bool IsValueFullyAvailableInBlock( 706 BasicBlock *BB, 707 DenseMap<BasicBlock *, AvailabilityState> &FullyAvailableBlocks) { 708 SmallVector<BasicBlock *, 32> Worklist; 709 Optional<BasicBlock *> UnavailableBB; 710 711 // The number of times we didn't find an entry for a block in a map and 712 // optimistically inserted an entry marking block as speculatively available. 713 unsigned NumNewNewSpeculativelyAvailableBBs = 0; 714 715 #ifndef NDEBUG 716 SmallSet<BasicBlock *, 32> NewSpeculativelyAvailableBBs; 717 SmallVector<BasicBlock *, 32> AvailableBBs; 718 #endif 719 720 Worklist.emplace_back(BB); 721 while (!Worklist.empty()) { 722 BasicBlock *CurrBB = Worklist.pop_back_val(); // LIFO - depth-first! 723 // Optimistically assume that the block is Speculatively Available and check 724 // to see if we already know about this block in one lookup. 725 std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator, bool> IV = 726 FullyAvailableBlocks.try_emplace( 727 CurrBB, AvailabilityState::SpeculativelyAvailable); 728 AvailabilityState &State = IV.first->second; 729 730 // Did the entry already exist for this block? 731 if (!IV.second) { 732 if (State == AvailabilityState::Unavailable) { 733 UnavailableBB = CurrBB; 734 break; // Backpropagate unavailability info. 735 } 736 737 #ifndef NDEBUG 738 AvailableBBs.emplace_back(CurrBB); 739 #endif 740 continue; // Don't recurse further, but continue processing worklist. 741 } 742 743 // No entry found for block. 744 ++NumNewNewSpeculativelyAvailableBBs; 745 bool OutOfBudget = NumNewNewSpeculativelyAvailableBBs > MaxBBSpeculations; 746 747 // If we have exhausted our budget, mark this block as unavailable. 748 // Also, if this block has no predecessors, the value isn't live-in here. 749 if (OutOfBudget || pred_empty(CurrBB)) { 750 MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget; 751 State = AvailabilityState::Unavailable; 752 UnavailableBB = CurrBB; 753 break; // Backpropagate unavailability info. 754 } 755 756 // Tentatively consider this block as speculatively available. 757 #ifndef NDEBUG 758 NewSpeculativelyAvailableBBs.insert(CurrBB); 759 #endif 760 // And further recurse into block's predecessors, in depth-first order! 761 Worklist.append(pred_begin(CurrBB), pred_end(CurrBB)); 762 } 763 764 #if LLVM_ENABLE_STATS 765 IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax( 766 NumNewNewSpeculativelyAvailableBBs); 767 #endif 768 769 // If the block isn't marked as fixpoint yet 770 // (the Unavailable and Available states are fixpoints) 771 auto MarkAsFixpointAndEnqueueSuccessors = 772 [&](BasicBlock *BB, AvailabilityState FixpointState) { 773 auto It = FullyAvailableBlocks.find(BB); 774 if (It == FullyAvailableBlocks.end()) 775 return; // Never queried this block, leave as-is. 776 switch (AvailabilityState &State = It->second) { 777 case AvailabilityState::Unavailable: 778 case AvailabilityState::Available: 779 return; // Don't backpropagate further, continue processing worklist. 780 case AvailabilityState::SpeculativelyAvailable: // Fix it! 781 State = FixpointState; 782 #ifndef NDEBUG 783 assert(NewSpeculativelyAvailableBBs.erase(BB) && 784 "Found a speculatively available successor leftover?"); 785 #endif 786 // Queue successors for further processing. 787 Worklist.append(succ_begin(BB), succ_end(BB)); 788 return; 789 } 790 }; 791 792 if (UnavailableBB) { 793 // Okay, we have encountered an unavailable block. 794 // Mark speculatively available blocks reachable from UnavailableBB as 795 // unavailable as well. Paths are terminated when they reach blocks not in 796 // FullyAvailableBlocks or they are not marked as speculatively available. 797 Worklist.clear(); 798 Worklist.append(succ_begin(*UnavailableBB), succ_end(*UnavailableBB)); 799 while (!Worklist.empty()) 800 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(), 801 AvailabilityState::Unavailable); 802 } 803 804 #ifndef NDEBUG 805 Worklist.clear(); 806 for (BasicBlock *AvailableBB : AvailableBBs) 807 Worklist.append(succ_begin(AvailableBB), succ_end(AvailableBB)); 808 while (!Worklist.empty()) 809 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(), 810 AvailabilityState::Available); 811 812 assert(NewSpeculativelyAvailableBBs.empty() && 813 "Must have fixed all the new speculatively available blocks."); 814 #endif 815 816 return !UnavailableBB; 817 } 818 819 /// Given a set of loads specified by ValuesPerBlock, 820 /// construct SSA form, allowing us to eliminate LI. This returns the value 821 /// that should be used at LI's definition site. 822 static Value *ConstructSSAForLoadSet(LoadInst *LI, 823 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock, 824 GVN &gvn) { 825 // Check for the fully redundant, dominating load case. In this case, we can 826 // just use the dominating value directly. 827 if (ValuesPerBlock.size() == 1 && 828 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB, 829 LI->getParent())) { 830 assert(!ValuesPerBlock[0].AV.isUndefValue() && 831 "Dead BB dominate this block"); 832 return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn); 833 } 834 835 // Otherwise, we have to construct SSA form. 836 SmallVector<PHINode*, 8> NewPHIs; 837 SSAUpdater SSAUpdate(&NewPHIs); 838 SSAUpdate.Initialize(LI->getType(), LI->getName()); 839 840 for (const AvailableValueInBlock &AV : ValuesPerBlock) { 841 BasicBlock *BB = AV.BB; 842 843 if (SSAUpdate.HasValueForBlock(BB)) 844 continue; 845 846 // If the value is the load that we will be eliminating, and the block it's 847 // available in is the block that the load is in, then don't add it as 848 // SSAUpdater will resolve the value to the relevant phi which may let it 849 // avoid phi construction entirely if there's actually only one value. 850 if (BB == LI->getParent() && 851 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == LI) || 852 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == LI))) 853 continue; 854 855 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn)); 856 } 857 858 // Perform PHI construction. 859 return SSAUpdate.GetValueInMiddleOfBlock(LI->getParent()); 860 } 861 862 Value *AvailableValue::MaterializeAdjustedValue(LoadInst *LI, 863 Instruction *InsertPt, 864 GVN &gvn) const { 865 Value *Res; 866 Type *LoadTy = LI->getType(); 867 const DataLayout &DL = LI->getModule()->getDataLayout(); 868 if (isSimpleValue()) { 869 Res = getSimpleValue(); 870 if (Res->getType() != LoadTy) { 871 Res = getStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL); 872 873 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset 874 << " " << *getSimpleValue() << '\n' 875 << *Res << '\n' 876 << "\n\n\n"); 877 } 878 } else if (isCoercedLoadValue()) { 879 LoadInst *Load = getCoercedLoadValue(); 880 if (Load->getType() == LoadTy && Offset == 0) { 881 Res = Load; 882 } else { 883 Res = getLoadValueForLoad(Load, Offset, LoadTy, InsertPt, DL); 884 // We would like to use gvn.markInstructionForDeletion here, but we can't 885 // because the load is already memoized into the leader map table that GVN 886 // tracks. It is potentially possible to remove the load from the table, 887 // but then there all of the operations based on it would need to be 888 // rehashed. Just leave the dead load around. 889 gvn.getMemDep().removeInstruction(Load); 890 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset 891 << " " << *getCoercedLoadValue() << '\n' 892 << *Res << '\n' 893 << "\n\n\n"); 894 } 895 } else if (isMemIntrinValue()) { 896 Res = getMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy, 897 InsertPt, DL); 898 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset 899 << " " << *getMemIntrinValue() << '\n' 900 << *Res << '\n' 901 << "\n\n\n"); 902 } else { 903 assert(isUndefValue() && "Should be UndefVal"); 904 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";); 905 return UndefValue::get(LoadTy); 906 } 907 assert(Res && "failed to materialize?"); 908 return Res; 909 } 910 911 static bool isLifetimeStart(const Instruction *Inst) { 912 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst)) 913 return II->getIntrinsicID() == Intrinsic::lifetime_start; 914 return false; 915 } 916 917 /// Try to locate the three instruction involved in a missed 918 /// load-elimination case that is due to an intervening store. 919 static void reportMayClobberedLoad(LoadInst *LI, MemDepResult DepInfo, 920 DominatorTree *DT, 921 OptimizationRemarkEmitter *ORE) { 922 using namespace ore; 923 924 User *OtherAccess = nullptr; 925 926 OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", LI); 927 R << "load of type " << NV("Type", LI->getType()) << " not eliminated" 928 << setExtraArgs(); 929 930 for (auto *U : LI->getPointerOperand()->users()) 931 if (U != LI && (isa<LoadInst>(U) || isa<StoreInst>(U)) && 932 DT->dominates(cast<Instruction>(U), LI)) { 933 // FIXME: for now give up if there are multiple memory accesses that 934 // dominate the load. We need further analysis to decide which one is 935 // that we're forwarding from. 936 if (OtherAccess) 937 OtherAccess = nullptr; 938 else 939 OtherAccess = U; 940 } 941 942 if (OtherAccess) 943 R << " in favor of " << NV("OtherAccess", OtherAccess); 944 945 R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst()); 946 947 ORE->emit(R); 948 } 949 950 bool GVN::AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo, 951 Value *Address, AvailableValue &Res) { 952 assert((DepInfo.isDef() || DepInfo.isClobber()) && 953 "expected a local dependence"); 954 assert(LI->isUnordered() && "rules below are incorrect for ordered access"); 955 956 const DataLayout &DL = LI->getModule()->getDataLayout(); 957 958 Instruction *DepInst = DepInfo.getInst(); 959 if (DepInfo.isClobber()) { 960 // If the dependence is to a store that writes to a superset of the bits 961 // read by the load, we can extract the bits we need for the load from the 962 // stored value. 963 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) { 964 // Can't forward from non-atomic to atomic without violating memory model. 965 if (Address && LI->isAtomic() <= DepSI->isAtomic()) { 966 int Offset = 967 analyzeLoadFromClobberingStore(LI->getType(), Address, DepSI, DL); 968 if (Offset != -1) { 969 Res = AvailableValue::get(DepSI->getValueOperand(), Offset); 970 return true; 971 } 972 } 973 } 974 975 // Check to see if we have something like this: 976 // load i32* P 977 // load i8* (P+1) 978 // if we have this, replace the later with an extraction from the former. 979 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) { 980 // If this is a clobber and L is the first instruction in its block, then 981 // we have the first instruction in the entry block. 982 // Can't forward from non-atomic to atomic without violating memory model. 983 if (DepLI != LI && Address && LI->isAtomic() <= DepLI->isAtomic()) { 984 int Offset = 985 analyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL); 986 987 if (Offset != -1) { 988 Res = AvailableValue::getLoad(DepLI, Offset); 989 return true; 990 } 991 } 992 } 993 994 // If the clobbering value is a memset/memcpy/memmove, see if we can 995 // forward a value on from it. 996 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) { 997 if (Address && !LI->isAtomic()) { 998 int Offset = analyzeLoadFromClobberingMemInst(LI->getType(), Address, 999 DepMI, DL); 1000 if (Offset != -1) { 1001 Res = AvailableValue::getMI(DepMI, Offset); 1002 return true; 1003 } 1004 } 1005 } 1006 // Nothing known about this clobber, have to be conservative 1007 LLVM_DEBUG( 1008 // fast print dep, using operator<< on instruction is too slow. 1009 dbgs() << "GVN: load "; LI->printAsOperand(dbgs()); 1010 dbgs() << " is clobbered by " << *DepInst << '\n';); 1011 if (ORE->allowExtraAnalysis(DEBUG_TYPE)) 1012 reportMayClobberedLoad(LI, DepInfo, DT, ORE); 1013 1014 return false; 1015 } 1016 assert(DepInfo.isDef() && "follows from above"); 1017 1018 // Loading the allocation -> undef. 1019 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) || 1020 isAlignedAllocLikeFn(DepInst, TLI) || 1021 // Loading immediately after lifetime begin -> undef. 1022 isLifetimeStart(DepInst)) { 1023 Res = AvailableValue::get(UndefValue::get(LI->getType())); 1024 return true; 1025 } 1026 1027 // Loading from calloc (which zero initializes memory) -> zero 1028 if (isCallocLikeFn(DepInst, TLI)) { 1029 Res = AvailableValue::get(Constant::getNullValue(LI->getType())); 1030 return true; 1031 } 1032 1033 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) { 1034 // Reject loads and stores that are to the same address but are of 1035 // different types if we have to. If the stored value is larger or equal to 1036 // the loaded value, we can reuse it. 1037 if (!canCoerceMustAliasedValueToLoad(S->getValueOperand(), LI->getType(), 1038 DL)) 1039 return false; 1040 1041 // Can't forward from non-atomic to atomic without violating memory model. 1042 if (S->isAtomic() < LI->isAtomic()) 1043 return false; 1044 1045 Res = AvailableValue::get(S->getValueOperand()); 1046 return true; 1047 } 1048 1049 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) { 1050 // If the types mismatch and we can't handle it, reject reuse of the load. 1051 // If the stored value is larger or equal to the loaded value, we can reuse 1052 // it. 1053 if (!canCoerceMustAliasedValueToLoad(LD, LI->getType(), DL)) 1054 return false; 1055 1056 // Can't forward from non-atomic to atomic without violating memory model. 1057 if (LD->isAtomic() < LI->isAtomic()) 1058 return false; 1059 1060 Res = AvailableValue::getLoad(LD); 1061 return true; 1062 } 1063 1064 // Unknown def - must be conservative 1065 LLVM_DEBUG( 1066 // fast print dep, using operator<< on instruction is too slow. 1067 dbgs() << "GVN: load "; LI->printAsOperand(dbgs()); 1068 dbgs() << " has unknown def " << *DepInst << '\n';); 1069 return false; 1070 } 1071 1072 void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 1073 AvailValInBlkVect &ValuesPerBlock, 1074 UnavailBlkVect &UnavailableBlocks) { 1075 // Filter out useless results (non-locals, etc). Keep track of the blocks 1076 // where we have a value available in repl, also keep track of whether we see 1077 // dependencies that produce an unknown value for the load (such as a call 1078 // that could potentially clobber the load). 1079 unsigned NumDeps = Deps.size(); 1080 for (unsigned i = 0, e = NumDeps; i != e; ++i) { 1081 BasicBlock *DepBB = Deps[i].getBB(); 1082 MemDepResult DepInfo = Deps[i].getResult(); 1083 1084 if (DeadBlocks.count(DepBB)) { 1085 // Dead dependent mem-op disguise as a load evaluating the same value 1086 // as the load in question. 1087 ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB)); 1088 continue; 1089 } 1090 1091 if (!DepInfo.isDef() && !DepInfo.isClobber()) { 1092 UnavailableBlocks.push_back(DepBB); 1093 continue; 1094 } 1095 1096 // The address being loaded in this non-local block may not be the same as 1097 // the pointer operand of the load if PHI translation occurs. Make sure 1098 // to consider the right address. 1099 Value *Address = Deps[i].getAddress(); 1100 1101 AvailableValue AV; 1102 if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) { 1103 // subtlety: because we know this was a non-local dependency, we know 1104 // it's safe to materialize anywhere between the instruction within 1105 // DepInfo and the end of it's block. 1106 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, 1107 std::move(AV))); 1108 } else { 1109 UnavailableBlocks.push_back(DepBB); 1110 } 1111 } 1112 1113 assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() && 1114 "post condition violation"); 1115 } 1116 1117 bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 1118 UnavailBlkVect &UnavailableBlocks) { 1119 // Okay, we have *some* definitions of the value. This means that the value 1120 // is available in some of our (transitive) predecessors. Lets think about 1121 // doing PRE of this load. This will involve inserting a new load into the 1122 // predecessor when it's not available. We could do this in general, but 1123 // prefer to not increase code size. As such, we only do this when we know 1124 // that we only have to insert *one* load (which means we're basically moving 1125 // the load, not inserting a new one). 1126 1127 SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(), 1128 UnavailableBlocks.end()); 1129 1130 // Let's find the first basic block with more than one predecessor. Walk 1131 // backwards through predecessors if needed. 1132 BasicBlock *LoadBB = LI->getParent(); 1133 BasicBlock *TmpBB = LoadBB; 1134 bool IsSafeToSpeculativelyExecute = isSafeToSpeculativelyExecute(LI); 1135 1136 // Check that there is no implicit control flow instructions above our load in 1137 // its block. If there is an instruction that doesn't always pass the 1138 // execution to the following instruction, then moving through it may become 1139 // invalid. For example: 1140 // 1141 // int arr[LEN]; 1142 // int index = ???; 1143 // ... 1144 // guard(0 <= index && index < LEN); 1145 // use(arr[index]); 1146 // 1147 // It is illegal to move the array access to any point above the guard, 1148 // because if the index is out of bounds we should deoptimize rather than 1149 // access the array. 1150 // Check that there is no guard in this block above our instruction. 1151 if (!IsSafeToSpeculativelyExecute && ICF->isDominatedByICFIFromSameBlock(LI)) 1152 return false; 1153 while (TmpBB->getSinglePredecessor()) { 1154 TmpBB = TmpBB->getSinglePredecessor(); 1155 if (TmpBB == LoadBB) // Infinite (unreachable) loop. 1156 return false; 1157 if (Blockers.count(TmpBB)) 1158 return false; 1159 1160 // If any of these blocks has more than one successor (i.e. if the edge we 1161 // just traversed was critical), then there are other paths through this 1162 // block along which the load may not be anticipated. Hoisting the load 1163 // above this block would be adding the load to execution paths along 1164 // which it was not previously executed. 1165 if (TmpBB->getTerminator()->getNumSuccessors() != 1) 1166 return false; 1167 1168 // Check that there is no implicit control flow in a block above. 1169 if (!IsSafeToSpeculativelyExecute && ICF->hasICF(TmpBB)) 1170 return false; 1171 } 1172 1173 assert(TmpBB); 1174 LoadBB = TmpBB; 1175 1176 // Check to see how many predecessors have the loaded value fully 1177 // available. 1178 MapVector<BasicBlock *, Value *> PredLoads; 1179 DenseMap<BasicBlock *, AvailabilityState> FullyAvailableBlocks; 1180 for (const AvailableValueInBlock &AV : ValuesPerBlock) 1181 FullyAvailableBlocks[AV.BB] = AvailabilityState::Available; 1182 for (BasicBlock *UnavailableBB : UnavailableBlocks) 1183 FullyAvailableBlocks[UnavailableBB] = AvailabilityState::Unavailable; 1184 1185 SmallVector<BasicBlock *, 4> CriticalEdgePred; 1186 for (BasicBlock *Pred : predecessors(LoadBB)) { 1187 // If any predecessor block is an EH pad that does not allow non-PHI 1188 // instructions before the terminator, we can't PRE the load. 1189 if (Pred->getTerminator()->isEHPad()) { 1190 LLVM_DEBUG( 1191 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '" 1192 << Pred->getName() << "': " << *LI << '\n'); 1193 return false; 1194 } 1195 1196 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) { 1197 continue; 1198 } 1199 1200 if (Pred->getTerminator()->getNumSuccessors() != 1) { 1201 if (isa<IndirectBrInst>(Pred->getTerminator())) { 1202 LLVM_DEBUG( 1203 dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '" 1204 << Pred->getName() << "': " << *LI << '\n'); 1205 return false; 1206 } 1207 1208 // FIXME: Can we support the fallthrough edge? 1209 if (isa<CallBrInst>(Pred->getTerminator())) { 1210 LLVM_DEBUG( 1211 dbgs() << "COULD NOT PRE LOAD BECAUSE OF CALLBR CRITICAL EDGE '" 1212 << Pred->getName() << "': " << *LI << '\n'); 1213 return false; 1214 } 1215 1216 if (LoadBB->isEHPad()) { 1217 LLVM_DEBUG( 1218 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '" 1219 << Pred->getName() << "': " << *LI << '\n'); 1220 return false; 1221 } 1222 1223 CriticalEdgePred.push_back(Pred); 1224 } else { 1225 // Only add the predecessors that will not be split for now. 1226 PredLoads[Pred] = nullptr; 1227 } 1228 } 1229 1230 // Decide whether PRE is profitable for this load. 1231 unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size(); 1232 assert(NumUnavailablePreds != 0 && 1233 "Fully available value should already be eliminated!"); 1234 1235 // If this load is unavailable in multiple predecessors, reject it. 1236 // FIXME: If we could restructure the CFG, we could make a common pred with 1237 // all the preds that don't have an available LI and insert a new load into 1238 // that one block. 1239 if (NumUnavailablePreds != 1) 1240 return false; 1241 1242 // Split critical edges, and update the unavailable predecessors accordingly. 1243 for (BasicBlock *OrigPred : CriticalEdgePred) { 1244 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB); 1245 assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!"); 1246 PredLoads[NewPred] = nullptr; 1247 LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->" 1248 << LoadBB->getName() << '\n'); 1249 } 1250 1251 // Check if the load can safely be moved to all the unavailable predecessors. 1252 bool CanDoPRE = true; 1253 const DataLayout &DL = LI->getModule()->getDataLayout(); 1254 SmallVector<Instruction*, 8> NewInsts; 1255 for (auto &PredLoad : PredLoads) { 1256 BasicBlock *UnavailablePred = PredLoad.first; 1257 1258 // Do PHI translation to get its value in the predecessor if necessary. The 1259 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred. 1260 // We do the translation for each edge we skipped by going from LI's block 1261 // to LoadBB, otherwise we might miss pieces needing translation. 1262 1263 // If all preds have a single successor, then we know it is safe to insert 1264 // the load on the pred (?!?), so we can insert code to materialize the 1265 // pointer if it is not available. 1266 Value *LoadPtr = LI->getPointerOperand(); 1267 BasicBlock *Cur = LI->getParent(); 1268 while (Cur != LoadBB) { 1269 PHITransAddr Address(LoadPtr, DL, AC); 1270 LoadPtr = Address.PHITranslateWithInsertion( 1271 Cur, Cur->getSinglePredecessor(), *DT, NewInsts); 1272 if (!LoadPtr) { 1273 CanDoPRE = false; 1274 break; 1275 } 1276 Cur = Cur->getSinglePredecessor(); 1277 } 1278 1279 if (LoadPtr) { 1280 PHITransAddr Address(LoadPtr, DL, AC); 1281 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred, *DT, 1282 NewInsts); 1283 } 1284 // If we couldn't find or insert a computation of this phi translated value, 1285 // we fail PRE. 1286 if (!LoadPtr) { 1287 LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: " 1288 << *LI->getPointerOperand() << "\n"); 1289 CanDoPRE = false; 1290 break; 1291 } 1292 1293 PredLoad.second = LoadPtr; 1294 } 1295 1296 if (!CanDoPRE) { 1297 while (!NewInsts.empty()) { 1298 // Erase instructions generated by the failed PHI translation before 1299 // trying to number them. PHI translation might insert instructions 1300 // in basic blocks other than the current one, and we delete them 1301 // directly, as markInstructionForDeletion only allows removing from the 1302 // current basic block. 1303 NewInsts.pop_back_val()->eraseFromParent(); 1304 } 1305 // HINT: Don't revert the edge-splitting as following transformation may 1306 // also need to split these critical edges. 1307 return !CriticalEdgePred.empty(); 1308 } 1309 1310 // Okay, we can eliminate this load by inserting a reload in the predecessor 1311 // and using PHI construction to get the value in the other predecessors, do 1312 // it. 1313 LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n'); 1314 LLVM_DEBUG(if (!NewInsts.empty()) dbgs() 1315 << "INSERTED " << NewInsts.size() << " INSTS: " << *NewInsts.back() 1316 << '\n'); 1317 1318 // Assign value numbers to the new instructions. 1319 for (Instruction *I : NewInsts) { 1320 // Instructions that have been inserted in predecessor(s) to materialize 1321 // the load address do not retain their original debug locations. Doing 1322 // so could lead to confusing (but correct) source attributions. 1323 if (const DebugLoc &DL = I->getDebugLoc()) 1324 I->setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt())); 1325 1326 // FIXME: We really _ought_ to insert these value numbers into their 1327 // parent's availability map. However, in doing so, we risk getting into 1328 // ordering issues. If a block hasn't been processed yet, we would be 1329 // marking a value as AVAIL-IN, which isn't what we intend. 1330 VN.lookupOrAdd(I); 1331 } 1332 1333 for (const auto &PredLoad : PredLoads) { 1334 BasicBlock *UnavailablePred = PredLoad.first; 1335 Value *LoadPtr = PredLoad.second; 1336 1337 auto *NewLoad = new LoadInst( 1338 LI->getType(), LoadPtr, LI->getName() + ".pre", LI->isVolatile(), 1339 LI->getAlign(), LI->getOrdering(), LI->getSyncScopeID(), 1340 UnavailablePred->getTerminator()); 1341 NewLoad->setDebugLoc(LI->getDebugLoc()); 1342 if (MSSAU) { 1343 auto *MSSA = MSSAU->getMemorySSA(); 1344 // Get the defining access of the original load or use the load if it is a 1345 // MemoryDef (e.g. because it is volatile). The inserted loads are 1346 // guaranteed to load from the same definition. 1347 auto *LIAcc = MSSA->getMemoryAccess(LI); 1348 auto *DefiningAcc = 1349 isa<MemoryDef>(LIAcc) ? LIAcc : LIAcc->getDefiningAccess(); 1350 auto *NewAccess = MSSAU->createMemoryAccessInBB( 1351 NewLoad, DefiningAcc, NewLoad->getParent(), 1352 MemorySSA::BeforeTerminator); 1353 if (auto *NewDef = dyn_cast<MemoryDef>(NewAccess)) 1354 MSSAU->insertDef(NewDef, /*RenameUses=*/true); 1355 else 1356 MSSAU->insertUse(cast<MemoryUse>(NewAccess), /*RenameUses=*/true); 1357 } 1358 1359 // Transfer the old load's AA tags to the new load. 1360 AAMDNodes Tags; 1361 LI->getAAMetadata(Tags); 1362 if (Tags) 1363 NewLoad->setAAMetadata(Tags); 1364 1365 if (auto *MD = LI->getMetadata(LLVMContext::MD_invariant_load)) 1366 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD); 1367 if (auto *InvGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group)) 1368 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD); 1369 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) 1370 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD); 1371 1372 // We do not propagate the old load's debug location, because the new 1373 // load now lives in a different BB, and we want to avoid a jumpy line 1374 // table. 1375 // FIXME: How do we retain source locations without causing poor debugging 1376 // behavior? 1377 1378 // Add the newly created load. 1379 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred, 1380 NewLoad)); 1381 MD->invalidateCachedPointerInfo(LoadPtr); 1382 LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n'); 1383 } 1384 1385 // Perform PHI construction. 1386 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this); 1387 LI->replaceAllUsesWith(V); 1388 if (isa<PHINode>(V)) 1389 V->takeName(LI); 1390 if (Instruction *I = dyn_cast<Instruction>(V)) 1391 I->setDebugLoc(LI->getDebugLoc()); 1392 if (V->getType()->isPtrOrPtrVectorTy()) 1393 MD->invalidateCachedPointerInfo(V); 1394 markInstructionForDeletion(LI); 1395 ORE->emit([&]() { 1396 return OptimizationRemark(DEBUG_TYPE, "LoadPRE", LI) 1397 << "load eliminated by PRE"; 1398 }); 1399 ++NumPRELoad; 1400 return true; 1401 } 1402 1403 static void reportLoadElim(LoadInst *LI, Value *AvailableValue, 1404 OptimizationRemarkEmitter *ORE) { 1405 using namespace ore; 1406 1407 ORE->emit([&]() { 1408 return OptimizationRemark(DEBUG_TYPE, "LoadElim", LI) 1409 << "load of type " << NV("Type", LI->getType()) << " eliminated" 1410 << setExtraArgs() << " in favor of " 1411 << NV("InfavorOfValue", AvailableValue); 1412 }); 1413 } 1414 1415 /// Attempt to eliminate a load whose dependencies are 1416 /// non-local by performing PHI construction. 1417 bool GVN::processNonLocalLoad(LoadInst *LI) { 1418 // non-local speculations are not allowed under asan. 1419 if (LI->getParent()->getParent()->hasFnAttribute( 1420 Attribute::SanitizeAddress) || 1421 LI->getParent()->getParent()->hasFnAttribute( 1422 Attribute::SanitizeHWAddress)) 1423 return false; 1424 1425 // Step 1: Find the non-local dependencies of the load. 1426 LoadDepVect Deps; 1427 MD->getNonLocalPointerDependency(LI, Deps); 1428 1429 // If we had to process more than one hundred blocks to find the 1430 // dependencies, this load isn't worth worrying about. Optimizing 1431 // it will be too expensive. 1432 unsigned NumDeps = Deps.size(); 1433 if (NumDeps > MaxNumDeps) 1434 return false; 1435 1436 // If we had a phi translation failure, we'll have a single entry which is a 1437 // clobber in the current block. Reject this early. 1438 if (NumDeps == 1 && 1439 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) { 1440 LLVM_DEBUG(dbgs() << "GVN: non-local load "; LI->printAsOperand(dbgs()); 1441 dbgs() << " has unknown dependencies\n";); 1442 return false; 1443 } 1444 1445 // If this load follows a GEP, see if we can PRE the indices before analyzing. 1446 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) { 1447 for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(), 1448 OE = GEP->idx_end(); 1449 OI != OE; ++OI) 1450 if (Instruction *I = dyn_cast<Instruction>(OI->get())) 1451 performScalarPRE(I); 1452 } 1453 1454 // Step 2: Analyze the availability of the load 1455 AvailValInBlkVect ValuesPerBlock; 1456 UnavailBlkVect UnavailableBlocks; 1457 AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks); 1458 1459 // If we have no predecessors that produce a known value for this load, exit 1460 // early. 1461 if (ValuesPerBlock.empty()) 1462 return false; 1463 1464 // Step 3: Eliminate fully redundancy. 1465 // 1466 // If all of the instructions we depend on produce a known value for this 1467 // load, then it is fully redundant and we can use PHI insertion to compute 1468 // its value. Insert PHIs and remove the fully redundant value now. 1469 if (UnavailableBlocks.empty()) { 1470 LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n'); 1471 1472 // Perform PHI construction. 1473 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this); 1474 LI->replaceAllUsesWith(V); 1475 1476 if (isa<PHINode>(V)) 1477 V->takeName(LI); 1478 if (Instruction *I = dyn_cast<Instruction>(V)) 1479 // If instruction I has debug info, then we should not update it. 1480 // Also, if I has a null DebugLoc, then it is still potentially incorrect 1481 // to propagate LI's DebugLoc because LI may not post-dominate I. 1482 if (LI->getDebugLoc() && LI->getParent() == I->getParent()) 1483 I->setDebugLoc(LI->getDebugLoc()); 1484 if (V->getType()->isPtrOrPtrVectorTy()) 1485 MD->invalidateCachedPointerInfo(V); 1486 markInstructionForDeletion(LI); 1487 ++NumGVNLoad; 1488 reportLoadElim(LI, V, ORE); 1489 return true; 1490 } 1491 1492 // Step 4: Eliminate partial redundancy. 1493 if (!isPREEnabled() || !isLoadPREEnabled()) 1494 return false; 1495 if (!isLoadInLoopPREEnabled() && this->LI && 1496 this->LI->getLoopFor(LI->getParent())) 1497 return false; 1498 1499 return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks); 1500 } 1501 1502 static bool impliesEquivalanceIfTrue(CmpInst* Cmp) { 1503 if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_EQ) 1504 return true; 1505 1506 // Floating point comparisons can be equal, but not equivalent. Cases: 1507 // NaNs for unordered operators 1508 // +0.0 vs 0.0 for all operators 1509 if (Cmp->getPredicate() == CmpInst::Predicate::FCMP_OEQ || 1510 (Cmp->getPredicate() == CmpInst::Predicate::FCMP_UEQ && 1511 Cmp->getFastMathFlags().noNaNs())) { 1512 Value *LHS = Cmp->getOperand(0); 1513 Value *RHS = Cmp->getOperand(1); 1514 // If we can prove either side non-zero, then equality must imply 1515 // equivalence. 1516 // FIXME: We should do this optimization if 'no signed zeros' is 1517 // applicable via an instruction-level fast-math-flag or some other 1518 // indicator that relaxed FP semantics are being used. 1519 if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero()) 1520 return true; 1521 if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero()) 1522 return true;; 1523 // TODO: Handle vector floating point constants 1524 } 1525 return false; 1526 } 1527 1528 static bool impliesEquivalanceIfFalse(CmpInst* Cmp) { 1529 if (Cmp->getPredicate() == CmpInst::Predicate::ICMP_NE) 1530 return true; 1531 1532 // Floating point comparisons can be equal, but not equivelent. Cases: 1533 // NaNs for unordered operators 1534 // +0.0 vs 0.0 for all operators 1535 if ((Cmp->getPredicate() == CmpInst::Predicate::FCMP_ONE && 1536 Cmp->getFastMathFlags().noNaNs()) || 1537 Cmp->getPredicate() == CmpInst::Predicate::FCMP_UNE) { 1538 Value *LHS = Cmp->getOperand(0); 1539 Value *RHS = Cmp->getOperand(1); 1540 // If we can prove either side non-zero, then equality must imply 1541 // equivalence. 1542 // FIXME: We should do this optimization if 'no signed zeros' is 1543 // applicable via an instruction-level fast-math-flag or some other 1544 // indicator that relaxed FP semantics are being used. 1545 if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->isZero()) 1546 return true; 1547 if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->isZero()) 1548 return true;; 1549 // TODO: Handle vector floating point constants 1550 } 1551 return false; 1552 } 1553 1554 1555 static bool hasUsersIn(Value *V, BasicBlock *BB) { 1556 for (User *U : V->users()) 1557 if (isa<Instruction>(U) && 1558 cast<Instruction>(U)->getParent() == BB) 1559 return true; 1560 return false; 1561 } 1562 1563 bool GVN::processAssumeIntrinsic(IntrinsicInst *IntrinsicI) { 1564 assert(IntrinsicI->getIntrinsicID() == Intrinsic::assume && 1565 "This function can only be called with llvm.assume intrinsic"); 1566 Value *V = IntrinsicI->getArgOperand(0); 1567 1568 if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) { 1569 if (Cond->isZero()) { 1570 Type *Int8Ty = Type::getInt8Ty(V->getContext()); 1571 // Insert a new store to null instruction before the load to indicate that 1572 // this code is not reachable. FIXME: We could insert unreachable 1573 // instruction directly because we can modify the CFG. 1574 auto *NewS = new StoreInst(UndefValue::get(Int8Ty), 1575 Constant::getNullValue(Int8Ty->getPointerTo()), 1576 IntrinsicI); 1577 if (MSSAU) { 1578 // This added store is to null, so it will never executed and we can 1579 // just use the LiveOnEntry def as defining access. 1580 auto *NewDef = MSSAU->createMemoryAccessInBB( 1581 NewS, MSSAU->getMemorySSA()->getLiveOnEntryDef(), NewS->getParent(), 1582 MemorySSA::BeforeTerminator); 1583 MSSAU->insertDef(cast<MemoryDef>(NewDef), /*RenameUses=*/true); 1584 } 1585 } 1586 if (isAssumeWithEmptyBundle(*IntrinsicI)) 1587 markInstructionForDeletion(IntrinsicI); 1588 return false; 1589 } else if (isa<Constant>(V)) { 1590 // If it's not false, and constant, it must evaluate to true. This means our 1591 // assume is assume(true), and thus, pointless, and we don't want to do 1592 // anything more here. 1593 return false; 1594 } 1595 1596 Constant *True = ConstantInt::getTrue(V->getContext()); 1597 bool Changed = false; 1598 1599 for (BasicBlock *Successor : successors(IntrinsicI->getParent())) { 1600 BasicBlockEdge Edge(IntrinsicI->getParent(), Successor); 1601 1602 // This property is only true in dominated successors, propagateEquality 1603 // will check dominance for us. 1604 Changed |= propagateEquality(V, True, Edge, false); 1605 } 1606 1607 // We can replace assume value with true, which covers cases like this: 1608 // call void @llvm.assume(i1 %cmp) 1609 // br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true 1610 ReplaceOperandsWithMap[V] = True; 1611 1612 // If we find an equality fact, canonicalize all dominated uses in this block 1613 // to one of the two values. We heuristically choice the "oldest" of the 1614 // two where age is determined by value number. (Note that propagateEquality 1615 // above handles the cross block case.) 1616 // 1617 // Key case to cover are: 1618 // 1) 1619 // %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen 1620 // call void @llvm.assume(i1 %cmp) 1621 // ret float %0 ; will change it to ret float 3.000000e+00 1622 // 2) 1623 // %load = load float, float* %addr 1624 // %cmp = fcmp oeq float %load, %0 1625 // call void @llvm.assume(i1 %cmp) 1626 // ret float %load ; will change it to ret float %0 1627 if (auto *CmpI = dyn_cast<CmpInst>(V)) { 1628 if (impliesEquivalanceIfTrue(CmpI)) { 1629 Value *CmpLHS = CmpI->getOperand(0); 1630 Value *CmpRHS = CmpI->getOperand(1); 1631 // Heuristically pick the better replacement -- the choice of heuristic 1632 // isn't terribly important here, but the fact we canonicalize on some 1633 // replacement is for exposing other simplifications. 1634 // TODO: pull this out as a helper function and reuse w/existing 1635 // (slightly different) logic. 1636 if (isa<Constant>(CmpLHS) && !isa<Constant>(CmpRHS)) 1637 std::swap(CmpLHS, CmpRHS); 1638 if (!isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS)) 1639 std::swap(CmpLHS, CmpRHS); 1640 if ((isa<Argument>(CmpLHS) && isa<Argument>(CmpRHS)) || 1641 (isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))) { 1642 // Move the 'oldest' value to the right-hand side, using the value 1643 // number as a proxy for age. 1644 uint32_t LVN = VN.lookupOrAdd(CmpLHS); 1645 uint32_t RVN = VN.lookupOrAdd(CmpRHS); 1646 if (LVN < RVN) 1647 std::swap(CmpLHS, CmpRHS); 1648 } 1649 1650 // Handle degenerate case where we either haven't pruned a dead path or a 1651 // removed a trivial assume yet. 1652 if (isa<Constant>(CmpLHS) && isa<Constant>(CmpRHS)) 1653 return Changed; 1654 1655 LLVM_DEBUG(dbgs() << "Replacing dominated uses of " 1656 << *CmpLHS << " with " 1657 << *CmpRHS << " in block " 1658 << IntrinsicI->getParent()->getName() << "\n"); 1659 1660 1661 // Setup the replacement map - this handles uses within the same block 1662 if (hasUsersIn(CmpLHS, IntrinsicI->getParent())) 1663 ReplaceOperandsWithMap[CmpLHS] = CmpRHS; 1664 1665 // NOTE: The non-block local cases are handled by the call to 1666 // propagateEquality above; this block is just about handling the block 1667 // local cases. TODO: There's a bunch of logic in propagateEqualiy which 1668 // isn't duplicated for the block local case, can we share it somehow? 1669 } 1670 } 1671 return Changed; 1672 } 1673 1674 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) { 1675 patchReplacementInstruction(I, Repl); 1676 I->replaceAllUsesWith(Repl); 1677 } 1678 1679 /// Attempt to eliminate a load, first by eliminating it 1680 /// locally, and then attempting non-local elimination if that fails. 1681 bool GVN::processLoad(LoadInst *L) { 1682 if (!MD) 1683 return false; 1684 1685 // This code hasn't been audited for ordered or volatile memory access 1686 if (!L->isUnordered()) 1687 return false; 1688 1689 if (L->use_empty()) { 1690 markInstructionForDeletion(L); 1691 return true; 1692 } 1693 1694 // ... to a pointer that has been loaded from before... 1695 MemDepResult Dep = MD->getDependency(L); 1696 1697 // If it is defined in another block, try harder. 1698 if (Dep.isNonLocal()) 1699 return processNonLocalLoad(L); 1700 1701 // Only handle the local case below 1702 if (!Dep.isDef() && !Dep.isClobber()) { 1703 // This might be a NonFuncLocal or an Unknown 1704 LLVM_DEBUG( 1705 // fast print dep, using operator<< on instruction is too slow. 1706 dbgs() << "GVN: load "; L->printAsOperand(dbgs()); 1707 dbgs() << " has unknown dependence\n";); 1708 return false; 1709 } 1710 1711 AvailableValue AV; 1712 if (AnalyzeLoadAvailability(L, Dep, L->getPointerOperand(), AV)) { 1713 Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this); 1714 1715 // Replace the load! 1716 patchAndReplaceAllUsesWith(L, AvailableValue); 1717 markInstructionForDeletion(L); 1718 if (MSSAU) 1719 MSSAU->removeMemoryAccess(L); 1720 ++NumGVNLoad; 1721 reportLoadElim(L, AvailableValue, ORE); 1722 // Tell MDA to rexamine the reused pointer since we might have more 1723 // information after forwarding it. 1724 if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy()) 1725 MD->invalidateCachedPointerInfo(AvailableValue); 1726 return true; 1727 } 1728 1729 return false; 1730 } 1731 1732 /// Return a pair the first field showing the value number of \p Exp and the 1733 /// second field showing whether it is a value number newly created. 1734 std::pair<uint32_t, bool> 1735 GVN::ValueTable::assignExpNewValueNum(Expression &Exp) { 1736 uint32_t &e = expressionNumbering[Exp]; 1737 bool CreateNewValNum = !e; 1738 if (CreateNewValNum) { 1739 Expressions.push_back(Exp); 1740 if (ExprIdx.size() < nextValueNumber + 1) 1741 ExprIdx.resize(nextValueNumber * 2); 1742 e = nextValueNumber; 1743 ExprIdx[nextValueNumber++] = nextExprNumber++; 1744 } 1745 return {e, CreateNewValNum}; 1746 } 1747 1748 /// Return whether all the values related with the same \p num are 1749 /// defined in \p BB. 1750 bool GVN::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB, 1751 GVN &Gvn) { 1752 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num]; 1753 while (Vals && Vals->BB == BB) 1754 Vals = Vals->Next; 1755 return !Vals; 1756 } 1757 1758 /// Wrap phiTranslateImpl to provide caching functionality. 1759 uint32_t GVN::ValueTable::phiTranslate(const BasicBlock *Pred, 1760 const BasicBlock *PhiBlock, uint32_t Num, 1761 GVN &Gvn) { 1762 auto FindRes = PhiTranslateTable.find({Num, Pred}); 1763 if (FindRes != PhiTranslateTable.end()) 1764 return FindRes->second; 1765 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn); 1766 PhiTranslateTable.insert({{Num, Pred}, NewNum}); 1767 return NewNum; 1768 } 1769 1770 // Return true if the value number \p Num and NewNum have equal value. 1771 // Return false if the result is unknown. 1772 bool GVN::ValueTable::areCallValsEqual(uint32_t Num, uint32_t NewNum, 1773 const BasicBlock *Pred, 1774 const BasicBlock *PhiBlock, GVN &Gvn) { 1775 CallInst *Call = nullptr; 1776 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num]; 1777 while (Vals) { 1778 Call = dyn_cast<CallInst>(Vals->Val); 1779 if (Call && Call->getParent() == PhiBlock) 1780 break; 1781 Vals = Vals->Next; 1782 } 1783 1784 if (AA->doesNotAccessMemory(Call)) 1785 return true; 1786 1787 if (!MD || !AA->onlyReadsMemory(Call)) 1788 return false; 1789 1790 MemDepResult local_dep = MD->getDependency(Call); 1791 if (!local_dep.isNonLocal()) 1792 return false; 1793 1794 const MemoryDependenceResults::NonLocalDepInfo &deps = 1795 MD->getNonLocalCallDependency(Call); 1796 1797 // Check to see if the Call has no function local clobber. 1798 for (unsigned i = 0; i < deps.size(); i++) { 1799 if (deps[i].getResult().isNonFuncLocal()) 1800 return true; 1801 } 1802 return false; 1803 } 1804 1805 /// Translate value number \p Num using phis, so that it has the values of 1806 /// the phis in BB. 1807 uint32_t GVN::ValueTable::phiTranslateImpl(const BasicBlock *Pred, 1808 const BasicBlock *PhiBlock, 1809 uint32_t Num, GVN &Gvn) { 1810 if (PHINode *PN = NumberingPhi[Num]) { 1811 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { 1812 if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred) 1813 if (uint32_t TransVal = lookup(PN->getIncomingValue(i), false)) 1814 return TransVal; 1815 } 1816 return Num; 1817 } 1818 1819 // If there is any value related with Num is defined in a BB other than 1820 // PhiBlock, it cannot depend on a phi in PhiBlock without going through 1821 // a backedge. We can do an early exit in that case to save compile time. 1822 if (!areAllValsInBB(Num, PhiBlock, Gvn)) 1823 return Num; 1824 1825 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0) 1826 return Num; 1827 Expression Exp = Expressions[ExprIdx[Num]]; 1828 1829 for (unsigned i = 0; i < Exp.varargs.size(); i++) { 1830 // For InsertValue and ExtractValue, some varargs are index numbers 1831 // instead of value numbers. Those index numbers should not be 1832 // translated. 1833 if ((i > 1 && Exp.opcode == Instruction::InsertValue) || 1834 (i > 0 && Exp.opcode == Instruction::ExtractValue) || 1835 (i > 1 && Exp.opcode == Instruction::ShuffleVector)) 1836 continue; 1837 Exp.varargs[i] = phiTranslate(Pred, PhiBlock, Exp.varargs[i], Gvn); 1838 } 1839 1840 if (Exp.commutative) { 1841 assert(Exp.varargs.size() >= 2 && "Unsupported commutative instruction!"); 1842 if (Exp.varargs[0] > Exp.varargs[1]) { 1843 std::swap(Exp.varargs[0], Exp.varargs[1]); 1844 uint32_t Opcode = Exp.opcode >> 8; 1845 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) 1846 Exp.opcode = (Opcode << 8) | 1847 CmpInst::getSwappedPredicate( 1848 static_cast<CmpInst::Predicate>(Exp.opcode & 255)); 1849 } 1850 } 1851 1852 if (uint32_t NewNum = expressionNumbering[Exp]) { 1853 if (Exp.opcode == Instruction::Call && NewNum != Num) 1854 return areCallValsEqual(Num, NewNum, Pred, PhiBlock, Gvn) ? NewNum : Num; 1855 return NewNum; 1856 } 1857 return Num; 1858 } 1859 1860 /// Erase stale entry from phiTranslate cache so phiTranslate can be computed 1861 /// again. 1862 void GVN::ValueTable::eraseTranslateCacheEntry(uint32_t Num, 1863 const BasicBlock &CurrBlock) { 1864 for (const BasicBlock *Pred : predecessors(&CurrBlock)) { 1865 auto FindRes = PhiTranslateTable.find({Num, Pred}); 1866 if (FindRes != PhiTranslateTable.end()) 1867 PhiTranslateTable.erase(FindRes); 1868 } 1869 } 1870 1871 // In order to find a leader for a given value number at a 1872 // specific basic block, we first obtain the list of all Values for that number, 1873 // and then scan the list to find one whose block dominates the block in 1874 // question. This is fast because dominator tree queries consist of only 1875 // a few comparisons of DFS numbers. 1876 Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) { 1877 LeaderTableEntry Vals = LeaderTable[num]; 1878 if (!Vals.Val) return nullptr; 1879 1880 Value *Val = nullptr; 1881 if (DT->dominates(Vals.BB, BB)) { 1882 Val = Vals.Val; 1883 if (isa<Constant>(Val)) return Val; 1884 } 1885 1886 LeaderTableEntry* Next = Vals.Next; 1887 while (Next) { 1888 if (DT->dominates(Next->BB, BB)) { 1889 if (isa<Constant>(Next->Val)) return Next->Val; 1890 if (!Val) Val = Next->Val; 1891 } 1892 1893 Next = Next->Next; 1894 } 1895 1896 return Val; 1897 } 1898 1899 /// There is an edge from 'Src' to 'Dst'. Return 1900 /// true if every path from the entry block to 'Dst' passes via this edge. In 1901 /// particular 'Dst' must not be reachable via another edge from 'Src'. 1902 static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, 1903 DominatorTree *DT) { 1904 // While in theory it is interesting to consider the case in which Dst has 1905 // more than one predecessor, because Dst might be part of a loop which is 1906 // only reachable from Src, in practice it is pointless since at the time 1907 // GVN runs all such loops have preheaders, which means that Dst will have 1908 // been changed to have only one predecessor, namely Src. 1909 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor(); 1910 assert((!Pred || Pred == E.getStart()) && 1911 "No edge between these basic blocks!"); 1912 return Pred != nullptr; 1913 } 1914 1915 void GVN::assignBlockRPONumber(Function &F) { 1916 BlockRPONumber.clear(); 1917 uint32_t NextBlockNumber = 1; 1918 ReversePostOrderTraversal<Function *> RPOT(&F); 1919 for (BasicBlock *BB : RPOT) 1920 BlockRPONumber[BB] = NextBlockNumber++; 1921 InvalidBlockRPONumbers = false; 1922 } 1923 1924 bool GVN::replaceOperandsForInBlockEquality(Instruction *Instr) const { 1925 bool Changed = false; 1926 for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) { 1927 Value *Operand = Instr->getOperand(OpNum); 1928 auto it = ReplaceOperandsWithMap.find(Operand); 1929 if (it != ReplaceOperandsWithMap.end()) { 1930 LLVM_DEBUG(dbgs() << "GVN replacing: " << *Operand << " with " 1931 << *it->second << " in instruction " << *Instr << '\n'); 1932 Instr->setOperand(OpNum, it->second); 1933 Changed = true; 1934 } 1935 } 1936 return Changed; 1937 } 1938 1939 /// The given values are known to be equal in every block 1940 /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with 1941 /// 'RHS' everywhere in the scope. Returns whether a change was made. 1942 /// If DominatesByEdge is false, then it means that we will propagate the RHS 1943 /// value starting from the end of Root.Start. 1944 bool GVN::propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root, 1945 bool DominatesByEdge) { 1946 SmallVector<std::pair<Value*, Value*>, 4> Worklist; 1947 Worklist.push_back(std::make_pair(LHS, RHS)); 1948 bool Changed = false; 1949 // For speed, compute a conservative fast approximation to 1950 // DT->dominates(Root, Root.getEnd()); 1951 const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT); 1952 1953 while (!Worklist.empty()) { 1954 std::pair<Value*, Value*> Item = Worklist.pop_back_val(); 1955 LHS = Item.first; RHS = Item.second; 1956 1957 if (LHS == RHS) 1958 continue; 1959 assert(LHS->getType() == RHS->getType() && "Equality but unequal types!"); 1960 1961 // Don't try to propagate equalities between constants. 1962 if (isa<Constant>(LHS) && isa<Constant>(RHS)) 1963 continue; 1964 1965 // Prefer a constant on the right-hand side, or an Argument if no constants. 1966 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS))) 1967 std::swap(LHS, RHS); 1968 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!"); 1969 1970 // If there is no obvious reason to prefer the left-hand side over the 1971 // right-hand side, ensure the longest lived term is on the right-hand side, 1972 // so the shortest lived term will be replaced by the longest lived. 1973 // This tends to expose more simplifications. 1974 uint32_t LVN = VN.lookupOrAdd(LHS); 1975 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) || 1976 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) { 1977 // Move the 'oldest' value to the right-hand side, using the value number 1978 // as a proxy for age. 1979 uint32_t RVN = VN.lookupOrAdd(RHS); 1980 if (LVN < RVN) { 1981 std::swap(LHS, RHS); 1982 LVN = RVN; 1983 } 1984 } 1985 1986 // If value numbering later sees that an instruction in the scope is equal 1987 // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve 1988 // the invariant that instructions only occur in the leader table for their 1989 // own value number (this is used by removeFromLeaderTable), do not do this 1990 // if RHS is an instruction (if an instruction in the scope is morphed into 1991 // LHS then it will be turned into RHS by the next GVN iteration anyway, so 1992 // using the leader table is about compiling faster, not optimizing better). 1993 // The leader table only tracks basic blocks, not edges. Only add to if we 1994 // have the simple case where the edge dominates the end. 1995 if (RootDominatesEnd && !isa<Instruction>(RHS)) 1996 addToLeaderTable(LVN, RHS, Root.getEnd()); 1997 1998 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As 1999 // LHS always has at least one use that is not dominated by Root, this will 2000 // never do anything if LHS has only one use. 2001 if (!LHS->hasOneUse()) { 2002 unsigned NumReplacements = 2003 DominatesByEdge 2004 ? replaceDominatedUsesWith(LHS, RHS, *DT, Root) 2005 : replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart()); 2006 2007 Changed |= NumReplacements > 0; 2008 NumGVNEqProp += NumReplacements; 2009 // Cached information for anything that uses LHS will be invalid. 2010 if (MD) 2011 MD->invalidateCachedPointerInfo(LHS); 2012 } 2013 2014 // Now try to deduce additional equalities from this one. For example, if 2015 // the known equality was "(A != B)" == "false" then it follows that A and B 2016 // are equal in the scope. Only boolean equalities with an explicit true or 2017 // false RHS are currently supported. 2018 if (!RHS->getType()->isIntegerTy(1)) 2019 // Not a boolean equality - bail out. 2020 continue; 2021 ConstantInt *CI = dyn_cast<ConstantInt>(RHS); 2022 if (!CI) 2023 // RHS neither 'true' nor 'false' - bail out. 2024 continue; 2025 // Whether RHS equals 'true'. Otherwise it equals 'false'. 2026 bool isKnownTrue = CI->isMinusOne(); 2027 bool isKnownFalse = !isKnownTrue; 2028 2029 // If "A && B" is known true then both A and B are known true. If "A || B" 2030 // is known false then both A and B are known false. 2031 Value *A, *B; 2032 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) || 2033 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) { 2034 Worklist.push_back(std::make_pair(A, RHS)); 2035 Worklist.push_back(std::make_pair(B, RHS)); 2036 continue; 2037 } 2038 2039 // If we are propagating an equality like "(A == B)" == "true" then also 2040 // propagate the equality A == B. When propagating a comparison such as 2041 // "(A >= B)" == "true", replace all instances of "A < B" with "false". 2042 if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) { 2043 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1); 2044 2045 // If "A == B" is known true, or "A != B" is known false, then replace 2046 // A with B everywhere in the scope. For floating point operations, we 2047 // have to be careful since equality does not always imply equivalance. 2048 if ((isKnownTrue && impliesEquivalanceIfTrue(Cmp)) || 2049 (isKnownFalse && impliesEquivalanceIfFalse(Cmp))) 2050 Worklist.push_back(std::make_pair(Op0, Op1)); 2051 2052 // If "A >= B" is known true, replace "A < B" with false everywhere. 2053 CmpInst::Predicate NotPred = Cmp->getInversePredicate(); 2054 Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse); 2055 // Since we don't have the instruction "A < B" immediately to hand, work 2056 // out the value number that it would have and use that to find an 2057 // appropriate instruction (if any). 2058 uint32_t NextNum = VN.getNextUnusedValueNumber(); 2059 uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1); 2060 // If the number we were assigned was brand new then there is no point in 2061 // looking for an instruction realizing it: there cannot be one! 2062 if (Num < NextNum) { 2063 Value *NotCmp = findLeader(Root.getEnd(), Num); 2064 if (NotCmp && isa<Instruction>(NotCmp)) { 2065 unsigned NumReplacements = 2066 DominatesByEdge 2067 ? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root) 2068 : replaceDominatedUsesWith(NotCmp, NotVal, *DT, 2069 Root.getStart()); 2070 Changed |= NumReplacements > 0; 2071 NumGVNEqProp += NumReplacements; 2072 // Cached information for anything that uses NotCmp will be invalid. 2073 if (MD) 2074 MD->invalidateCachedPointerInfo(NotCmp); 2075 } 2076 } 2077 // Ensure that any instruction in scope that gets the "A < B" value number 2078 // is replaced with false. 2079 // The leader table only tracks basic blocks, not edges. Only add to if we 2080 // have the simple case where the edge dominates the end. 2081 if (RootDominatesEnd) 2082 addToLeaderTable(Num, NotVal, Root.getEnd()); 2083 2084 continue; 2085 } 2086 } 2087 2088 return Changed; 2089 } 2090 2091 /// When calculating availability, handle an instruction 2092 /// by inserting it into the appropriate sets 2093 bool GVN::processInstruction(Instruction *I) { 2094 // Ignore dbg info intrinsics. 2095 if (isa<DbgInfoIntrinsic>(I)) 2096 return false; 2097 2098 // If the instruction can be easily simplified then do so now in preference 2099 // to value numbering it. Value numbering often exposes redundancies, for 2100 // example if it determines that %y is equal to %x then the instruction 2101 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify. 2102 const DataLayout &DL = I->getModule()->getDataLayout(); 2103 if (Value *V = SimplifyInstruction(I, {DL, TLI, DT, AC})) { 2104 bool Changed = false; 2105 if (!I->use_empty()) { 2106 I->replaceAllUsesWith(V); 2107 Changed = true; 2108 } 2109 if (isInstructionTriviallyDead(I, TLI)) { 2110 markInstructionForDeletion(I); 2111 Changed = true; 2112 } 2113 if (Changed) { 2114 if (MD && V->getType()->isPtrOrPtrVectorTy()) 2115 MD->invalidateCachedPointerInfo(V); 2116 ++NumGVNSimpl; 2117 return true; 2118 } 2119 } 2120 2121 if (IntrinsicInst *IntrinsicI = dyn_cast<IntrinsicInst>(I)) 2122 if (IntrinsicI->getIntrinsicID() == Intrinsic::assume) 2123 return processAssumeIntrinsic(IntrinsicI); 2124 2125 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 2126 if (processLoad(LI)) 2127 return true; 2128 2129 unsigned Num = VN.lookupOrAdd(LI); 2130 addToLeaderTable(Num, LI, LI->getParent()); 2131 return false; 2132 } 2133 2134 // For conditional branches, we can perform simple conditional propagation on 2135 // the condition value itself. 2136 if (BranchInst *BI = dyn_cast<BranchInst>(I)) { 2137 if (!BI->isConditional()) 2138 return false; 2139 2140 if (isa<Constant>(BI->getCondition())) 2141 return processFoldableCondBr(BI); 2142 2143 Value *BranchCond = BI->getCondition(); 2144 BasicBlock *TrueSucc = BI->getSuccessor(0); 2145 BasicBlock *FalseSucc = BI->getSuccessor(1); 2146 // Avoid multiple edges early. 2147 if (TrueSucc == FalseSucc) 2148 return false; 2149 2150 BasicBlock *Parent = BI->getParent(); 2151 bool Changed = false; 2152 2153 Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext()); 2154 BasicBlockEdge TrueE(Parent, TrueSucc); 2155 Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true); 2156 2157 Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext()); 2158 BasicBlockEdge FalseE(Parent, FalseSucc); 2159 Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true); 2160 2161 return Changed; 2162 } 2163 2164 // For switches, propagate the case values into the case destinations. 2165 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 2166 Value *SwitchCond = SI->getCondition(); 2167 BasicBlock *Parent = SI->getParent(); 2168 bool Changed = false; 2169 2170 // Remember how many outgoing edges there are to every successor. 2171 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges; 2172 for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i) 2173 ++SwitchEdges[SI->getSuccessor(i)]; 2174 2175 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 2176 i != e; ++i) { 2177 BasicBlock *Dst = i->getCaseSuccessor(); 2178 // If there is only a single edge, propagate the case value into it. 2179 if (SwitchEdges.lookup(Dst) == 1) { 2180 BasicBlockEdge E(Parent, Dst); 2181 Changed |= propagateEquality(SwitchCond, i->getCaseValue(), E, true); 2182 } 2183 } 2184 return Changed; 2185 } 2186 2187 // Instructions with void type don't return a value, so there's 2188 // no point in trying to find redundancies in them. 2189 if (I->getType()->isVoidTy()) 2190 return false; 2191 2192 uint32_t NextNum = VN.getNextUnusedValueNumber(); 2193 unsigned Num = VN.lookupOrAdd(I); 2194 2195 // Allocations are always uniquely numbered, so we can save time and memory 2196 // by fast failing them. 2197 if (isa<AllocaInst>(I) || I->isTerminator() || isa<PHINode>(I)) { 2198 addToLeaderTable(Num, I, I->getParent()); 2199 return false; 2200 } 2201 2202 // If the number we were assigned was a brand new VN, then we don't 2203 // need to do a lookup to see if the number already exists 2204 // somewhere in the domtree: it can't! 2205 if (Num >= NextNum) { 2206 addToLeaderTable(Num, I, I->getParent()); 2207 return false; 2208 } 2209 2210 // Perform fast-path value-number based elimination of values inherited from 2211 // dominators. 2212 Value *Repl = findLeader(I->getParent(), Num); 2213 if (!Repl) { 2214 // Failure, just remember this instance for future use. 2215 addToLeaderTable(Num, I, I->getParent()); 2216 return false; 2217 } else if (Repl == I) { 2218 // If I was the result of a shortcut PRE, it might already be in the table 2219 // and the best replacement for itself. Nothing to do. 2220 return false; 2221 } 2222 2223 // Remove it! 2224 patchAndReplaceAllUsesWith(I, Repl); 2225 if (MD && Repl->getType()->isPtrOrPtrVectorTy()) 2226 MD->invalidateCachedPointerInfo(Repl); 2227 markInstructionForDeletion(I); 2228 return true; 2229 } 2230 2231 /// runOnFunction - This is the main transformation entry point for a function. 2232 bool GVN::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT, 2233 const TargetLibraryInfo &RunTLI, AAResults &RunAA, 2234 MemoryDependenceResults *RunMD, LoopInfo *LI, 2235 OptimizationRemarkEmitter *RunORE, MemorySSA *MSSA) { 2236 AC = &RunAC; 2237 DT = &RunDT; 2238 VN.setDomTree(DT); 2239 TLI = &RunTLI; 2240 VN.setAliasAnalysis(&RunAA); 2241 MD = RunMD; 2242 ImplicitControlFlowTracking ImplicitCFT; 2243 ICF = &ImplicitCFT; 2244 this->LI = LI; 2245 VN.setMemDep(MD); 2246 ORE = RunORE; 2247 InvalidBlockRPONumbers = true; 2248 MemorySSAUpdater Updater(MSSA); 2249 MSSAU = MSSA ? &Updater : nullptr; 2250 2251 bool Changed = false; 2252 bool ShouldContinue = true; 2253 2254 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 2255 // Merge unconditional branches, allowing PRE to catch more 2256 // optimization opportunities. 2257 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) { 2258 BasicBlock *BB = &*FI++; 2259 2260 bool removedBlock = MergeBlockIntoPredecessor(BB, &DTU, LI, MSSAU, MD); 2261 if (removedBlock) 2262 ++NumGVNBlocks; 2263 2264 Changed |= removedBlock; 2265 } 2266 2267 unsigned Iteration = 0; 2268 while (ShouldContinue) { 2269 LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n"); 2270 ShouldContinue = iterateOnFunction(F); 2271 Changed |= ShouldContinue; 2272 ++Iteration; 2273 } 2274 2275 if (isPREEnabled()) { 2276 // Fabricate val-num for dead-code in order to suppress assertion in 2277 // performPRE(). 2278 assignValNumForDeadCode(); 2279 bool PREChanged = true; 2280 while (PREChanged) { 2281 PREChanged = performPRE(F); 2282 Changed |= PREChanged; 2283 } 2284 } 2285 2286 // FIXME: Should perform GVN again after PRE does something. PRE can move 2287 // computations into blocks where they become fully redundant. Note that 2288 // we can't do this until PRE's critical edge splitting updates memdep. 2289 // Actually, when this happens, we should just fully integrate PRE into GVN. 2290 2291 cleanupGlobalSets(); 2292 // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each 2293 // iteration. 2294 DeadBlocks.clear(); 2295 2296 if (MSSA && VerifyMemorySSA) 2297 MSSA->verifyMemorySSA(); 2298 2299 return Changed; 2300 } 2301 2302 bool GVN::processBlock(BasicBlock *BB) { 2303 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function 2304 // (and incrementing BI before processing an instruction). 2305 assert(InstrsToErase.empty() && 2306 "We expect InstrsToErase to be empty across iterations"); 2307 if (DeadBlocks.count(BB)) 2308 return false; 2309 2310 // Clearing map before every BB because it can be used only for single BB. 2311 ReplaceOperandsWithMap.clear(); 2312 bool ChangedFunction = false; 2313 2314 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); 2315 BI != BE;) { 2316 if (!ReplaceOperandsWithMap.empty()) 2317 ChangedFunction |= replaceOperandsForInBlockEquality(&*BI); 2318 ChangedFunction |= processInstruction(&*BI); 2319 2320 if (InstrsToErase.empty()) { 2321 ++BI; 2322 continue; 2323 } 2324 2325 // If we need some instructions deleted, do it now. 2326 NumGVNInstr += InstrsToErase.size(); 2327 2328 // Avoid iterator invalidation. 2329 bool AtStart = BI == BB->begin(); 2330 if (!AtStart) 2331 --BI; 2332 2333 for (auto *I : InstrsToErase) { 2334 assert(I->getParent() == BB && "Removing instruction from wrong block?"); 2335 LLVM_DEBUG(dbgs() << "GVN removed: " << *I << '\n'); 2336 salvageKnowledge(I, AC); 2337 salvageDebugInfo(*I); 2338 if (MD) MD->removeInstruction(I); 2339 if (MSSAU) 2340 MSSAU->removeMemoryAccess(I); 2341 LLVM_DEBUG(verifyRemoved(I)); 2342 ICF->removeInstruction(I); 2343 I->eraseFromParent(); 2344 } 2345 InstrsToErase.clear(); 2346 2347 if (AtStart) 2348 BI = BB->begin(); 2349 else 2350 ++BI; 2351 } 2352 2353 return ChangedFunction; 2354 } 2355 2356 // Instantiate an expression in a predecessor that lacked it. 2357 bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred, 2358 BasicBlock *Curr, unsigned int ValNo) { 2359 // Because we are going top-down through the block, all value numbers 2360 // will be available in the predecessor by the time we need them. Any 2361 // that weren't originally present will have been instantiated earlier 2362 // in this loop. 2363 bool success = true; 2364 for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) { 2365 Value *Op = Instr->getOperand(i); 2366 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op)) 2367 continue; 2368 // This could be a newly inserted instruction, in which case, we won't 2369 // find a value number, and should give up before we hurt ourselves. 2370 // FIXME: Rewrite the infrastructure to let it easier to value number 2371 // and process newly inserted instructions. 2372 if (!VN.exists(Op)) { 2373 success = false; 2374 break; 2375 } 2376 uint32_t TValNo = 2377 VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this); 2378 if (Value *V = findLeader(Pred, TValNo)) { 2379 Instr->setOperand(i, V); 2380 } else { 2381 success = false; 2382 break; 2383 } 2384 } 2385 2386 // Fail out if we encounter an operand that is not available in 2387 // the PRE predecessor. This is typically because of loads which 2388 // are not value numbered precisely. 2389 if (!success) 2390 return false; 2391 2392 Instr->insertBefore(Pred->getTerminator()); 2393 Instr->setName(Instr->getName() + ".pre"); 2394 Instr->setDebugLoc(Instr->getDebugLoc()); 2395 2396 unsigned Num = VN.lookupOrAdd(Instr); 2397 VN.add(Instr, Num); 2398 2399 // Update the availability map to include the new instruction. 2400 addToLeaderTable(Num, Instr, Pred); 2401 return true; 2402 } 2403 2404 bool GVN::performScalarPRE(Instruction *CurInst) { 2405 if (isa<AllocaInst>(CurInst) || CurInst->isTerminator() || 2406 isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() || 2407 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() || 2408 isa<DbgInfoIntrinsic>(CurInst)) 2409 return false; 2410 2411 // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from 2412 // sinking the compare again, and it would force the code generator to 2413 // move the i1 from processor flags or predicate registers into a general 2414 // purpose register. 2415 if (isa<CmpInst>(CurInst)) 2416 return false; 2417 2418 // Don't do PRE on GEPs. The inserted PHI would prevent CodeGenPrepare from 2419 // sinking the addressing mode computation back to its uses. Extending the 2420 // GEP's live range increases the register pressure, and therefore it can 2421 // introduce unnecessary spills. 2422 // 2423 // This doesn't prevent Load PRE. PHI translation will make the GEP available 2424 // to the load by moving it to the predecessor block if necessary. 2425 if (isa<GetElementPtrInst>(CurInst)) 2426 return false; 2427 2428 // We don't currently value number ANY inline asm calls. 2429 if (auto *CallB = dyn_cast<CallBase>(CurInst)) 2430 if (CallB->isInlineAsm()) 2431 return false; 2432 2433 uint32_t ValNo = VN.lookup(CurInst); 2434 2435 // Look for the predecessors for PRE opportunities. We're 2436 // only trying to solve the basic diamond case, where 2437 // a value is computed in the successor and one predecessor, 2438 // but not the other. We also explicitly disallow cases 2439 // where the successor is its own predecessor, because they're 2440 // more complicated to get right. 2441 unsigned NumWith = 0; 2442 unsigned NumWithout = 0; 2443 BasicBlock *PREPred = nullptr; 2444 BasicBlock *CurrentBlock = CurInst->getParent(); 2445 2446 // Update the RPO numbers for this function. 2447 if (InvalidBlockRPONumbers) 2448 assignBlockRPONumber(*CurrentBlock->getParent()); 2449 2450 SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap; 2451 for (BasicBlock *P : predecessors(CurrentBlock)) { 2452 // We're not interested in PRE where blocks with predecessors that are 2453 // not reachable. 2454 if (!DT->isReachableFromEntry(P)) { 2455 NumWithout = 2; 2456 break; 2457 } 2458 // It is not safe to do PRE when P->CurrentBlock is a loop backedge, and 2459 // when CurInst has operand defined in CurrentBlock (so it may be defined 2460 // by phi in the loop header). 2461 assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) && 2462 "Invalid BlockRPONumber map."); 2463 if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] && 2464 llvm::any_of(CurInst->operands(), [&](const Use &U) { 2465 if (auto *Inst = dyn_cast<Instruction>(U.get())) 2466 return Inst->getParent() == CurrentBlock; 2467 return false; 2468 })) { 2469 NumWithout = 2; 2470 break; 2471 } 2472 2473 uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this); 2474 Value *predV = findLeader(P, TValNo); 2475 if (!predV) { 2476 predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P)); 2477 PREPred = P; 2478 ++NumWithout; 2479 } else if (predV == CurInst) { 2480 /* CurInst dominates this predecessor. */ 2481 NumWithout = 2; 2482 break; 2483 } else { 2484 predMap.push_back(std::make_pair(predV, P)); 2485 ++NumWith; 2486 } 2487 } 2488 2489 // Don't do PRE when it might increase code size, i.e. when 2490 // we would need to insert instructions in more than one pred. 2491 if (NumWithout > 1 || NumWith == 0) 2492 return false; 2493 2494 // We may have a case where all predecessors have the instruction, 2495 // and we just need to insert a phi node. Otherwise, perform 2496 // insertion. 2497 Instruction *PREInstr = nullptr; 2498 2499 if (NumWithout != 0) { 2500 if (!isSafeToSpeculativelyExecute(CurInst)) { 2501 // It is only valid to insert a new instruction if the current instruction 2502 // is always executed. An instruction with implicit control flow could 2503 // prevent us from doing it. If we cannot speculate the execution, then 2504 // PRE should be prohibited. 2505 if (ICF->isDominatedByICFIFromSameBlock(CurInst)) 2506 return false; 2507 } 2508 2509 // Don't do PRE across indirect branch. 2510 if (isa<IndirectBrInst>(PREPred->getTerminator())) 2511 return false; 2512 2513 // Don't do PRE across callbr. 2514 // FIXME: Can we do this across the fallthrough edge? 2515 if (isa<CallBrInst>(PREPred->getTerminator())) 2516 return false; 2517 2518 // We can't do PRE safely on a critical edge, so instead we schedule 2519 // the edge to be split and perform the PRE the next time we iterate 2520 // on the function. 2521 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock); 2522 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) { 2523 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum)); 2524 return false; 2525 } 2526 // We need to insert somewhere, so let's give it a shot 2527 PREInstr = CurInst->clone(); 2528 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) { 2529 // If we failed insertion, make sure we remove the instruction. 2530 LLVM_DEBUG(verifyRemoved(PREInstr)); 2531 PREInstr->deleteValue(); 2532 return false; 2533 } 2534 } 2535 2536 // Either we should have filled in the PRE instruction, or we should 2537 // not have needed insertions. 2538 assert(PREInstr != nullptr || NumWithout == 0); 2539 2540 ++NumGVNPRE; 2541 2542 // Create a PHI to make the value available in this block. 2543 PHINode *Phi = 2544 PHINode::Create(CurInst->getType(), predMap.size(), 2545 CurInst->getName() + ".pre-phi", &CurrentBlock->front()); 2546 for (unsigned i = 0, e = predMap.size(); i != e; ++i) { 2547 if (Value *V = predMap[i].first) { 2548 // If we use an existing value in this phi, we have to patch the original 2549 // value because the phi will be used to replace a later value. 2550 patchReplacementInstruction(CurInst, V); 2551 Phi->addIncoming(V, predMap[i].second); 2552 } else 2553 Phi->addIncoming(PREInstr, PREPred); 2554 } 2555 2556 VN.add(Phi, ValNo); 2557 // After creating a new PHI for ValNo, the phi translate result for ValNo will 2558 // be changed, so erase the related stale entries in phi translate cache. 2559 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock); 2560 addToLeaderTable(ValNo, Phi, CurrentBlock); 2561 Phi->setDebugLoc(CurInst->getDebugLoc()); 2562 CurInst->replaceAllUsesWith(Phi); 2563 if (MD && Phi->getType()->isPtrOrPtrVectorTy()) 2564 MD->invalidateCachedPointerInfo(Phi); 2565 VN.erase(CurInst); 2566 removeFromLeaderTable(ValNo, CurInst, CurrentBlock); 2567 2568 LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n'); 2569 if (MD) 2570 MD->removeInstruction(CurInst); 2571 if (MSSAU) 2572 MSSAU->removeMemoryAccess(CurInst); 2573 LLVM_DEBUG(verifyRemoved(CurInst)); 2574 // FIXME: Intended to be markInstructionForDeletion(CurInst), but it causes 2575 // some assertion failures. 2576 ICF->removeInstruction(CurInst); 2577 CurInst->eraseFromParent(); 2578 ++NumGVNInstr; 2579 2580 return true; 2581 } 2582 2583 /// Perform a purely local form of PRE that looks for diamond 2584 /// control flow patterns and attempts to perform simple PRE at the join point. 2585 bool GVN::performPRE(Function &F) { 2586 bool Changed = false; 2587 for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) { 2588 // Nothing to PRE in the entry block. 2589 if (CurrentBlock == &F.getEntryBlock()) 2590 continue; 2591 2592 // Don't perform PRE on an EH pad. 2593 if (CurrentBlock->isEHPad()) 2594 continue; 2595 2596 for (BasicBlock::iterator BI = CurrentBlock->begin(), 2597 BE = CurrentBlock->end(); 2598 BI != BE;) { 2599 Instruction *CurInst = &*BI++; 2600 Changed |= performScalarPRE(CurInst); 2601 } 2602 } 2603 2604 if (splitCriticalEdges()) 2605 Changed = true; 2606 2607 return Changed; 2608 } 2609 2610 /// Split the critical edge connecting the given two blocks, and return 2611 /// the block inserted to the critical edge. 2612 BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) { 2613 // GVN does not require loop-simplify, do not try to preserve it if it is not 2614 // possible. 2615 BasicBlock *BB = SplitCriticalEdge( 2616 Pred, Succ, 2617 CriticalEdgeSplittingOptions(DT, LI, MSSAU).unsetPreserveLoopSimplify()); 2618 if (MD) 2619 MD->invalidateCachedPredecessors(); 2620 InvalidBlockRPONumbers = true; 2621 return BB; 2622 } 2623 2624 /// Split critical edges found during the previous 2625 /// iteration that may enable further optimization. 2626 bool GVN::splitCriticalEdges() { 2627 if (toSplit.empty()) 2628 return false; 2629 do { 2630 std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val(); 2631 SplitCriticalEdge(Edge.first, Edge.second, 2632 CriticalEdgeSplittingOptions(DT, LI, MSSAU)); 2633 } while (!toSplit.empty()); 2634 if (MD) MD->invalidateCachedPredecessors(); 2635 InvalidBlockRPONumbers = true; 2636 return true; 2637 } 2638 2639 /// Executes one iteration of GVN 2640 bool GVN::iterateOnFunction(Function &F) { 2641 cleanupGlobalSets(); 2642 2643 // Top-down walk of the dominator tree 2644 bool Changed = false; 2645 // Needed for value numbering with phi construction to work. 2646 // RPOT walks the graph in its constructor and will not be invalidated during 2647 // processBlock. 2648 ReversePostOrderTraversal<Function *> RPOT(&F); 2649 2650 for (BasicBlock *BB : RPOT) 2651 Changed |= processBlock(BB); 2652 2653 return Changed; 2654 } 2655 2656 void GVN::cleanupGlobalSets() { 2657 VN.clear(); 2658 LeaderTable.clear(); 2659 BlockRPONumber.clear(); 2660 TableAllocator.Reset(); 2661 ICF->clear(); 2662 InvalidBlockRPONumbers = true; 2663 } 2664 2665 /// Verify that the specified instruction does not occur in our 2666 /// internal data structures. 2667 void GVN::verifyRemoved(const Instruction *Inst) const { 2668 VN.verifyRemoved(Inst); 2669 2670 // Walk through the value number scope to make sure the instruction isn't 2671 // ferreted away in it. 2672 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator 2673 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) { 2674 const LeaderTableEntry *Node = &I->second; 2675 assert(Node->Val != Inst && "Inst still in value numbering scope!"); 2676 2677 while (Node->Next) { 2678 Node = Node->Next; 2679 assert(Node->Val != Inst && "Inst still in value numbering scope!"); 2680 } 2681 } 2682 } 2683 2684 /// BB is declared dead, which implied other blocks become dead as well. This 2685 /// function is to add all these blocks to "DeadBlocks". For the dead blocks' 2686 /// live successors, update their phi nodes by replacing the operands 2687 /// corresponding to dead blocks with UndefVal. 2688 void GVN::addDeadBlock(BasicBlock *BB) { 2689 SmallVector<BasicBlock *, 4> NewDead; 2690 SmallSetVector<BasicBlock *, 4> DF; 2691 2692 NewDead.push_back(BB); 2693 while (!NewDead.empty()) { 2694 BasicBlock *D = NewDead.pop_back_val(); 2695 if (DeadBlocks.count(D)) 2696 continue; 2697 2698 // All blocks dominated by D are dead. 2699 SmallVector<BasicBlock *, 8> Dom; 2700 DT->getDescendants(D, Dom); 2701 DeadBlocks.insert(Dom.begin(), Dom.end()); 2702 2703 // Figure out the dominance-frontier(D). 2704 for (BasicBlock *B : Dom) { 2705 for (BasicBlock *S : successors(B)) { 2706 if (DeadBlocks.count(S)) 2707 continue; 2708 2709 bool AllPredDead = true; 2710 for (BasicBlock *P : predecessors(S)) 2711 if (!DeadBlocks.count(P)) { 2712 AllPredDead = false; 2713 break; 2714 } 2715 2716 if (!AllPredDead) { 2717 // S could be proved dead later on. That is why we don't update phi 2718 // operands at this moment. 2719 DF.insert(S); 2720 } else { 2721 // While S is not dominated by D, it is dead by now. This could take 2722 // place if S already have a dead predecessor before D is declared 2723 // dead. 2724 NewDead.push_back(S); 2725 } 2726 } 2727 } 2728 } 2729 2730 // For the dead blocks' live successors, update their phi nodes by replacing 2731 // the operands corresponding to dead blocks with UndefVal. 2732 for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end(); 2733 I != E; I++) { 2734 BasicBlock *B = *I; 2735 if (DeadBlocks.count(B)) 2736 continue; 2737 2738 // First, split the critical edges. This might also create additional blocks 2739 // to preserve LoopSimplify form and adjust edges accordingly. 2740 SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B)); 2741 for (BasicBlock *P : Preds) { 2742 if (!DeadBlocks.count(P)) 2743 continue; 2744 2745 if (llvm::any_of(successors(P), 2746 [B](BasicBlock *Succ) { return Succ == B; }) && 2747 isCriticalEdge(P->getTerminator(), B)) { 2748 if (BasicBlock *S = splitCriticalEdges(P, B)) 2749 DeadBlocks.insert(P = S); 2750 } 2751 } 2752 2753 // Now undef the incoming values from the dead predecessors. 2754 for (BasicBlock *P : predecessors(B)) { 2755 if (!DeadBlocks.count(P)) 2756 continue; 2757 for (PHINode &Phi : B->phis()) { 2758 Phi.setIncomingValueForBlock(P, UndefValue::get(Phi.getType())); 2759 if (MD) 2760 MD->invalidateCachedPointerInfo(&Phi); 2761 } 2762 } 2763 } 2764 } 2765 2766 // If the given branch is recognized as a foldable branch (i.e. conditional 2767 // branch with constant condition), it will perform following analyses and 2768 // transformation. 2769 // 1) If the dead out-coming edge is a critical-edge, split it. Let 2770 // R be the target of the dead out-coming edge. 2771 // 1) Identify the set of dead blocks implied by the branch's dead outcoming 2772 // edge. The result of this step will be {X| X is dominated by R} 2773 // 2) Identify those blocks which haves at least one dead predecessor. The 2774 // result of this step will be dominance-frontier(R). 2775 // 3) Update the PHIs in DF(R) by replacing the operands corresponding to 2776 // dead blocks with "UndefVal" in an hope these PHIs will optimized away. 2777 // 2778 // Return true iff *NEW* dead code are found. 2779 bool GVN::processFoldableCondBr(BranchInst *BI) { 2780 if (!BI || BI->isUnconditional()) 2781 return false; 2782 2783 // If a branch has two identical successors, we cannot declare either dead. 2784 if (BI->getSuccessor(0) == BI->getSuccessor(1)) 2785 return false; 2786 2787 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition()); 2788 if (!Cond) 2789 return false; 2790 2791 BasicBlock *DeadRoot = 2792 Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0); 2793 if (DeadBlocks.count(DeadRoot)) 2794 return false; 2795 2796 if (!DeadRoot->getSinglePredecessor()) 2797 DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot); 2798 2799 addDeadBlock(DeadRoot); 2800 return true; 2801 } 2802 2803 // performPRE() will trigger assert if it comes across an instruction without 2804 // associated val-num. As it normally has far more live instructions than dead 2805 // instructions, it makes more sense just to "fabricate" a val-number for the 2806 // dead code than checking if instruction involved is dead or not. 2807 void GVN::assignValNumForDeadCode() { 2808 for (BasicBlock *BB : DeadBlocks) { 2809 for (Instruction &Inst : *BB) { 2810 unsigned ValNum = VN.lookupOrAdd(&Inst); 2811 addToLeaderTable(ValNum, &Inst, BB); 2812 } 2813 } 2814 } 2815 2816 class llvm::gvn::GVNLegacyPass : public FunctionPass { 2817 public: 2818 static char ID; // Pass identification, replacement for typeid 2819 2820 explicit GVNLegacyPass(bool NoMemDepAnalysis = !GVNEnableMemDep) 2821 : FunctionPass(ID), Impl(GVNOptions().setMemDep(!NoMemDepAnalysis)) { 2822 initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry()); 2823 } 2824 2825 bool runOnFunction(Function &F) override { 2826 if (skipFunction(F)) 2827 return false; 2828 2829 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 2830 2831 auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 2832 return Impl.runImpl( 2833 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 2834 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 2835 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 2836 getAnalysis<AAResultsWrapperPass>().getAAResults(), 2837 Impl.isMemDepEnabled() 2838 ? &getAnalysis<MemoryDependenceWrapperPass>().getMemDep() 2839 : nullptr, 2840 LIWP ? &LIWP->getLoopInfo() : nullptr, 2841 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), 2842 MSSAWP ? &MSSAWP->getMSSA() : nullptr); 2843 } 2844 2845 void getAnalysisUsage(AnalysisUsage &AU) const override { 2846 AU.addRequired<AssumptionCacheTracker>(); 2847 AU.addRequired<DominatorTreeWrapperPass>(); 2848 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2849 AU.addRequired<LoopInfoWrapperPass>(); 2850 if (Impl.isMemDepEnabled()) 2851 AU.addRequired<MemoryDependenceWrapperPass>(); 2852 AU.addRequired<AAResultsWrapperPass>(); 2853 AU.addPreserved<DominatorTreeWrapperPass>(); 2854 AU.addPreserved<GlobalsAAWrapperPass>(); 2855 AU.addPreserved<TargetLibraryInfoWrapperPass>(); 2856 AU.addPreserved<LoopInfoWrapperPass>(); 2857 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 2858 AU.addPreserved<MemorySSAWrapperPass>(); 2859 } 2860 2861 private: 2862 GVN Impl; 2863 }; 2864 2865 char GVNLegacyPass::ID = 0; 2866 2867 INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false) 2868 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 2869 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 2870 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2871 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2872 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2873 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 2874 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 2875 INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false) 2876 2877 // The public interface to this file... 2878 FunctionPass *llvm::createGVNPass(bool NoMemDepAnalysis) { 2879 return new GVNLegacyPass(NoMemDepAnalysis); 2880 } 2881