1 //===- GVNSink.cpp - sink expressions into successors ---------------------===// 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 /// \file GVNSink.cpp 10 /// This pass attempts to sink instructions into successors, reducing static 11 /// instruction count and enabling if-conversion. 12 /// 13 /// We use a variant of global value numbering to decide what can be sunk. 14 /// Consider: 15 /// 16 /// [ %a1 = add i32 %b, 1 ] [ %c1 = add i32 %d, 1 ] 17 /// [ %a2 = xor i32 %a1, 1 ] [ %c2 = xor i32 %c1, 1 ] 18 /// \ / 19 /// [ %e = phi i32 %a2, %c2 ] 20 /// [ add i32 %e, 4 ] 21 /// 22 /// 23 /// GVN would number %a1 and %c1 differently because they compute different 24 /// results - the VN of an instruction is a function of its opcode and the 25 /// transitive closure of its operands. This is the key property for hoisting 26 /// and CSE. 27 /// 28 /// What we want when sinking however is for a numbering that is a function of 29 /// the *uses* of an instruction, which allows us to answer the question "if I 30 /// replace %a1 with %c1, will it contribute in an equivalent way to all 31 /// successive instructions?". The PostValueTable class in GVN provides this 32 /// mapping. 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "llvm/ADT/ArrayRef.h" 37 #include "llvm/ADT/DenseMap.h" 38 #include "llvm/ADT/DenseSet.h" 39 #include "llvm/ADT/Hashing.h" 40 #include "llvm/ADT/None.h" 41 #include "llvm/ADT/Optional.h" 42 #include "llvm/ADT/PostOrderIterator.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/SmallPtrSet.h" 45 #include "llvm/ADT/SmallVector.h" 46 #include "llvm/ADT/Statistic.h" 47 #include "llvm/Analysis/GlobalsModRef.h" 48 #include "llvm/IR/BasicBlock.h" 49 #include "llvm/IR/CFG.h" 50 #include "llvm/IR/Constants.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/IR/InstrTypes.h" 53 #include "llvm/IR/Instruction.h" 54 #include "llvm/IR/Instructions.h" 55 #include "llvm/IR/PassManager.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/Use.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/InitializePasses.h" 60 #include "llvm/Pass.h" 61 #include "llvm/Support/Allocator.h" 62 #include "llvm/Support/ArrayRecycler.h" 63 #include "llvm/Support/AtomicOrdering.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/Compiler.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Transforms/Scalar.h" 69 #include "llvm/Transforms/Scalar/GVN.h" 70 #include "llvm/Transforms/Scalar/GVNExpression.h" 71 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 72 #include "llvm/Transforms/Utils/Local.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstddef> 76 #include <cstdint> 77 #include <iterator> 78 #include <utility> 79 80 using namespace llvm; 81 82 #define DEBUG_TYPE "gvn-sink" 83 84 STATISTIC(NumRemoved, "Number of instructions removed"); 85 86 namespace llvm { 87 namespace GVNExpression { 88 89 LLVM_DUMP_METHOD void Expression::dump() const { 90 print(dbgs()); 91 dbgs() << "\n"; 92 } 93 94 } // end namespace GVNExpression 95 } // end namespace llvm 96 97 namespace { 98 99 static bool isMemoryInst(const Instruction *I) { 100 return isa<LoadInst>(I) || isa<StoreInst>(I) || 101 (isa<InvokeInst>(I) && !cast<InvokeInst>(I)->doesNotAccessMemory()) || 102 (isa<CallInst>(I) && !cast<CallInst>(I)->doesNotAccessMemory()); 103 } 104 105 /// Iterates through instructions in a set of blocks in reverse order from the 106 /// first non-terminator. For example (assume all blocks have size n): 107 /// LockstepReverseIterator I([B1, B2, B3]); 108 /// *I-- = [B1[n], B2[n], B3[n]]; 109 /// *I-- = [B1[n-1], B2[n-1], B3[n-1]]; 110 /// *I-- = [B1[n-2], B2[n-2], B3[n-2]]; 111 /// ... 112 /// 113 /// It continues until all blocks have been exhausted. Use \c getActiveBlocks() 114 /// to 115 /// determine which blocks are still going and the order they appear in the 116 /// list returned by operator*. 117 class LockstepReverseIterator { 118 ArrayRef<BasicBlock *> Blocks; 119 SmallSetVector<BasicBlock *, 4> ActiveBlocks; 120 SmallVector<Instruction *, 4> Insts; 121 bool Fail; 122 123 public: 124 LockstepReverseIterator(ArrayRef<BasicBlock *> Blocks) : Blocks(Blocks) { 125 reset(); 126 } 127 128 void reset() { 129 Fail = false; 130 ActiveBlocks.clear(); 131 for (BasicBlock *BB : Blocks) 132 ActiveBlocks.insert(BB); 133 Insts.clear(); 134 for (BasicBlock *BB : Blocks) { 135 if (BB->size() <= 1) { 136 // Block wasn't big enough - only contained a terminator. 137 ActiveBlocks.remove(BB); 138 continue; 139 } 140 Insts.push_back(BB->getTerminator()->getPrevNode()); 141 } 142 if (Insts.empty()) 143 Fail = true; 144 } 145 146 bool isValid() const { return !Fail; } 147 ArrayRef<Instruction *> operator*() const { return Insts; } 148 149 // Note: This needs to return a SmallSetVector as the elements of 150 // ActiveBlocks will be later copied to Blocks using std::copy. The 151 // resultant order of elements in Blocks needs to be deterministic. 152 // Using SmallPtrSet instead causes non-deterministic order while 153 // copying. And we cannot simply sort Blocks as they need to match the 154 // corresponding Values. 155 SmallSetVector<BasicBlock *, 4> &getActiveBlocks() { return ActiveBlocks; } 156 157 void restrictToBlocks(SmallSetVector<BasicBlock *, 4> &Blocks) { 158 for (auto II = Insts.begin(); II != Insts.end();) { 159 if (!llvm::is_contained(Blocks, (*II)->getParent())) { 160 ActiveBlocks.remove((*II)->getParent()); 161 II = Insts.erase(II); 162 } else { 163 ++II; 164 } 165 } 166 } 167 168 void operator--() { 169 if (Fail) 170 return; 171 SmallVector<Instruction *, 4> NewInsts; 172 for (auto *Inst : Insts) { 173 if (Inst == &Inst->getParent()->front()) 174 ActiveBlocks.remove(Inst->getParent()); 175 else 176 NewInsts.push_back(Inst->getPrevNode()); 177 } 178 if (NewInsts.empty()) { 179 Fail = true; 180 return; 181 } 182 Insts = NewInsts; 183 } 184 }; 185 186 //===----------------------------------------------------------------------===// 187 188 /// Candidate solution for sinking. There may be different ways to 189 /// sink instructions, differing in the number of instructions sunk, 190 /// the number of predecessors sunk from and the number of PHIs 191 /// required. 192 struct SinkingInstructionCandidate { 193 unsigned NumBlocks; 194 unsigned NumInstructions; 195 unsigned NumPHIs; 196 unsigned NumMemoryInsts; 197 int Cost = -1; 198 SmallVector<BasicBlock *, 4> Blocks; 199 200 void calculateCost(unsigned NumOrigPHIs, unsigned NumOrigBlocks) { 201 unsigned NumExtraPHIs = NumPHIs - NumOrigPHIs; 202 unsigned SplitEdgeCost = (NumOrigBlocks > NumBlocks) ? 2 : 0; 203 Cost = (NumInstructions * (NumBlocks - 1)) - 204 (NumExtraPHIs * 205 NumExtraPHIs) // PHIs are expensive, so make sure they're worth it. 206 - SplitEdgeCost; 207 } 208 209 bool operator>(const SinkingInstructionCandidate &Other) const { 210 return Cost > Other.Cost; 211 } 212 }; 213 214 #ifndef NDEBUG 215 raw_ostream &operator<<(raw_ostream &OS, const SinkingInstructionCandidate &C) { 216 OS << "<Candidate Cost=" << C.Cost << " #Blocks=" << C.NumBlocks 217 << " #Insts=" << C.NumInstructions << " #PHIs=" << C.NumPHIs << ">"; 218 return OS; 219 } 220 #endif 221 222 //===----------------------------------------------------------------------===// 223 224 /// Describes a PHI node that may or may not exist. These track the PHIs 225 /// that must be created if we sunk a sequence of instructions. It provides 226 /// a hash function for efficient equality comparisons. 227 class ModelledPHI { 228 SmallVector<Value *, 4> Values; 229 SmallVector<BasicBlock *, 4> Blocks; 230 231 public: 232 ModelledPHI() = default; 233 234 ModelledPHI(const PHINode *PN) { 235 // BasicBlock comes first so we sort by basic block pointer order, then by value pointer order. 236 SmallVector<std::pair<BasicBlock *, Value *>, 4> Ops; 237 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) 238 Ops.push_back({PN->getIncomingBlock(I), PN->getIncomingValue(I)}); 239 llvm::sort(Ops); 240 for (auto &P : Ops) { 241 Blocks.push_back(P.first); 242 Values.push_back(P.second); 243 } 244 } 245 246 /// Create a dummy ModelledPHI that will compare unequal to any other ModelledPHI 247 /// without the same ID. 248 /// \note This is specifically for DenseMapInfo - do not use this! 249 static ModelledPHI createDummy(size_t ID) { 250 ModelledPHI M; 251 M.Values.push_back(reinterpret_cast<Value*>(ID)); 252 return M; 253 } 254 255 /// Create a PHI from an array of incoming values and incoming blocks. 256 template <typename VArray, typename BArray> 257 ModelledPHI(const VArray &V, const BArray &B) { 258 llvm::copy(V, std::back_inserter(Values)); 259 llvm::copy(B, std::back_inserter(Blocks)); 260 } 261 262 /// Create a PHI from [I[OpNum] for I in Insts]. 263 template <typename BArray> 264 ModelledPHI(ArrayRef<Instruction *> Insts, unsigned OpNum, const BArray &B) { 265 llvm::copy(B, std::back_inserter(Blocks)); 266 for (auto *I : Insts) 267 Values.push_back(I->getOperand(OpNum)); 268 } 269 270 /// Restrict the PHI's contents down to only \c NewBlocks. 271 /// \c NewBlocks must be a subset of \c this->Blocks. 272 void restrictToBlocks(const SmallSetVector<BasicBlock *, 4> &NewBlocks) { 273 auto BI = Blocks.begin(); 274 auto VI = Values.begin(); 275 while (BI != Blocks.end()) { 276 assert(VI != Values.end()); 277 if (!llvm::is_contained(NewBlocks, *BI)) { 278 BI = Blocks.erase(BI); 279 VI = Values.erase(VI); 280 } else { 281 ++BI; 282 ++VI; 283 } 284 } 285 assert(Blocks.size() == NewBlocks.size()); 286 } 287 288 ArrayRef<Value *> getValues() const { return Values; } 289 290 bool areAllIncomingValuesSame() const { 291 return llvm::all_of(Values, [&](Value *V) { return V == Values[0]; }); 292 } 293 294 bool areAllIncomingValuesSameType() const { 295 return llvm::all_of( 296 Values, [&](Value *V) { return V->getType() == Values[0]->getType(); }); 297 } 298 299 bool areAnyIncomingValuesConstant() const { 300 return llvm::any_of(Values, [&](Value *V) { return isa<Constant>(V); }); 301 } 302 303 // Hash functor 304 unsigned hash() const { 305 return (unsigned)hash_combine_range(Values.begin(), Values.end()); 306 } 307 308 bool operator==(const ModelledPHI &Other) const { 309 return Values == Other.Values && Blocks == Other.Blocks; 310 } 311 }; 312 313 template <typename ModelledPHI> struct DenseMapInfo { 314 static inline ModelledPHI &getEmptyKey() { 315 static ModelledPHI Dummy = ModelledPHI::createDummy(0); 316 return Dummy; 317 } 318 319 static inline ModelledPHI &getTombstoneKey() { 320 static ModelledPHI Dummy = ModelledPHI::createDummy(1); 321 return Dummy; 322 } 323 324 static unsigned getHashValue(const ModelledPHI &V) { return V.hash(); } 325 326 static bool isEqual(const ModelledPHI &LHS, const ModelledPHI &RHS) { 327 return LHS == RHS; 328 } 329 }; 330 331 using ModelledPHISet = DenseSet<ModelledPHI, DenseMapInfo<ModelledPHI>>; 332 333 //===----------------------------------------------------------------------===// 334 // ValueTable 335 //===----------------------------------------------------------------------===// 336 // This is a value number table where the value number is a function of the 337 // *uses* of a value, rather than its operands. Thus, if VN(A) == VN(B) we know 338 // that the program would be equivalent if we replaced A with PHI(A, B). 339 //===----------------------------------------------------------------------===// 340 341 /// A GVN expression describing how an instruction is used. The operands 342 /// field of BasicExpression is used to store uses, not operands. 343 /// 344 /// This class also contains fields for discriminators used when determining 345 /// equivalence of instructions with sideeffects. 346 class InstructionUseExpr : public GVNExpression::BasicExpression { 347 unsigned MemoryUseOrder = -1; 348 bool Volatile = false; 349 ArrayRef<int> ShuffleMask; 350 351 public: 352 InstructionUseExpr(Instruction *I, ArrayRecycler<Value *> &R, 353 BumpPtrAllocator &A) 354 : GVNExpression::BasicExpression(I->getNumUses()) { 355 allocateOperands(R, A); 356 setOpcode(I->getOpcode()); 357 setType(I->getType()); 358 359 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) 360 ShuffleMask = SVI->getShuffleMask().copy(A); 361 362 for (auto &U : I->uses()) 363 op_push_back(U.getUser()); 364 llvm::sort(op_begin(), op_end()); 365 } 366 367 void setMemoryUseOrder(unsigned MUO) { MemoryUseOrder = MUO; } 368 void setVolatile(bool V) { Volatile = V; } 369 370 hash_code getHashValue() const override { 371 return hash_combine(GVNExpression::BasicExpression::getHashValue(), 372 MemoryUseOrder, Volatile, ShuffleMask); 373 } 374 375 template <typename Function> hash_code getHashValue(Function MapFn) { 376 hash_code H = hash_combine(getOpcode(), getType(), MemoryUseOrder, Volatile, 377 ShuffleMask); 378 for (auto *V : operands()) 379 H = hash_combine(H, MapFn(V)); 380 return H; 381 } 382 }; 383 384 class ValueTable { 385 DenseMap<Value *, uint32_t> ValueNumbering; 386 DenseMap<GVNExpression::Expression *, uint32_t> ExpressionNumbering; 387 DenseMap<size_t, uint32_t> HashNumbering; 388 BumpPtrAllocator Allocator; 389 ArrayRecycler<Value *> Recycler; 390 uint32_t nextValueNumber = 1; 391 392 /// Create an expression for I based on its opcode and its uses. If I 393 /// touches or reads memory, the expression is also based upon its memory 394 /// order - see \c getMemoryUseOrder(). 395 InstructionUseExpr *createExpr(Instruction *I) { 396 InstructionUseExpr *E = 397 new (Allocator) InstructionUseExpr(I, Recycler, Allocator); 398 if (isMemoryInst(I)) 399 E->setMemoryUseOrder(getMemoryUseOrder(I)); 400 401 if (CmpInst *C = dyn_cast<CmpInst>(I)) { 402 CmpInst::Predicate Predicate = C->getPredicate(); 403 E->setOpcode((C->getOpcode() << 8) | Predicate); 404 } 405 return E; 406 } 407 408 /// Helper to compute the value number for a memory instruction 409 /// (LoadInst/StoreInst), including checking the memory ordering and 410 /// volatility. 411 template <class Inst> InstructionUseExpr *createMemoryExpr(Inst *I) { 412 if (isStrongerThanUnordered(I->getOrdering()) || I->isAtomic()) 413 return nullptr; 414 InstructionUseExpr *E = createExpr(I); 415 E->setVolatile(I->isVolatile()); 416 return E; 417 } 418 419 public: 420 ValueTable() = default; 421 422 /// Returns the value number for the specified value, assigning 423 /// it a new number if it did not have one before. 424 uint32_t lookupOrAdd(Value *V) { 425 auto VI = ValueNumbering.find(V); 426 if (VI != ValueNumbering.end()) 427 return VI->second; 428 429 if (!isa<Instruction>(V)) { 430 ValueNumbering[V] = nextValueNumber; 431 return nextValueNumber++; 432 } 433 434 Instruction *I = cast<Instruction>(V); 435 InstructionUseExpr *exp = nullptr; 436 switch (I->getOpcode()) { 437 case Instruction::Load: 438 exp = createMemoryExpr(cast<LoadInst>(I)); 439 break; 440 case Instruction::Store: 441 exp = createMemoryExpr(cast<StoreInst>(I)); 442 break; 443 case Instruction::Call: 444 case Instruction::Invoke: 445 case Instruction::FNeg: 446 case Instruction::Add: 447 case Instruction::FAdd: 448 case Instruction::Sub: 449 case Instruction::FSub: 450 case Instruction::Mul: 451 case Instruction::FMul: 452 case Instruction::UDiv: 453 case Instruction::SDiv: 454 case Instruction::FDiv: 455 case Instruction::URem: 456 case Instruction::SRem: 457 case Instruction::FRem: 458 case Instruction::Shl: 459 case Instruction::LShr: 460 case Instruction::AShr: 461 case Instruction::And: 462 case Instruction::Or: 463 case Instruction::Xor: 464 case Instruction::ICmp: 465 case Instruction::FCmp: 466 case Instruction::Trunc: 467 case Instruction::ZExt: 468 case Instruction::SExt: 469 case Instruction::FPToUI: 470 case Instruction::FPToSI: 471 case Instruction::UIToFP: 472 case Instruction::SIToFP: 473 case Instruction::FPTrunc: 474 case Instruction::FPExt: 475 case Instruction::PtrToInt: 476 case Instruction::IntToPtr: 477 case Instruction::BitCast: 478 case Instruction::AddrSpaceCast: 479 case Instruction::Select: 480 case Instruction::ExtractElement: 481 case Instruction::InsertElement: 482 case Instruction::ShuffleVector: 483 case Instruction::InsertValue: 484 case Instruction::GetElementPtr: 485 exp = createExpr(I); 486 break; 487 default: 488 break; 489 } 490 491 if (!exp) { 492 ValueNumbering[V] = nextValueNumber; 493 return nextValueNumber++; 494 } 495 496 uint32_t e = ExpressionNumbering[exp]; 497 if (!e) { 498 hash_code H = exp->getHashValue([=](Value *V) { return lookupOrAdd(V); }); 499 auto I = HashNumbering.find(H); 500 if (I != HashNumbering.end()) { 501 e = I->second; 502 } else { 503 e = nextValueNumber++; 504 HashNumbering[H] = e; 505 ExpressionNumbering[exp] = e; 506 } 507 } 508 ValueNumbering[V] = e; 509 return e; 510 } 511 512 /// Returns the value number of the specified value. Fails if the value has 513 /// not yet been numbered. 514 uint32_t lookup(Value *V) const { 515 auto VI = ValueNumbering.find(V); 516 assert(VI != ValueNumbering.end() && "Value not numbered?"); 517 return VI->second; 518 } 519 520 /// Removes all value numberings and resets the value table. 521 void clear() { 522 ValueNumbering.clear(); 523 ExpressionNumbering.clear(); 524 HashNumbering.clear(); 525 Recycler.clear(Allocator); 526 nextValueNumber = 1; 527 } 528 529 /// \c Inst uses or touches memory. Return an ID describing the memory state 530 /// at \c Inst such that if getMemoryUseOrder(I1) == getMemoryUseOrder(I2), 531 /// the exact same memory operations happen after I1 and I2. 532 /// 533 /// This is a very hard problem in general, so we use domain-specific 534 /// knowledge that we only ever check for equivalence between blocks sharing a 535 /// single immediate successor that is common, and when determining if I1 == 536 /// I2 we will have already determined that next(I1) == next(I2). This 537 /// inductive property allows us to simply return the value number of the next 538 /// instruction that defines memory. 539 uint32_t getMemoryUseOrder(Instruction *Inst) { 540 auto *BB = Inst->getParent(); 541 for (auto I = std::next(Inst->getIterator()), E = BB->end(); 542 I != E && !I->isTerminator(); ++I) { 543 if (!isMemoryInst(&*I)) 544 continue; 545 if (isa<LoadInst>(&*I)) 546 continue; 547 CallInst *CI = dyn_cast<CallInst>(&*I); 548 if (CI && CI->onlyReadsMemory()) 549 continue; 550 InvokeInst *II = dyn_cast<InvokeInst>(&*I); 551 if (II && II->onlyReadsMemory()) 552 continue; 553 return lookupOrAdd(&*I); 554 } 555 return 0; 556 } 557 }; 558 559 //===----------------------------------------------------------------------===// 560 561 class GVNSink { 562 public: 563 GVNSink() = default; 564 565 bool run(Function &F) { 566 LLVM_DEBUG(dbgs() << "GVNSink: running on function @" << F.getName() 567 << "\n"); 568 569 unsigned NumSunk = 0; 570 ReversePostOrderTraversal<Function*> RPOT(&F); 571 for (auto *N : RPOT) 572 NumSunk += sinkBB(N); 573 574 return NumSunk > 0; 575 } 576 577 private: 578 ValueTable VN; 579 580 bool shouldAvoidSinkingInstruction(Instruction *I) { 581 // These instructions may change or break semantics if moved. 582 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) || 583 I->getType()->isTokenTy()) 584 return true; 585 return false; 586 } 587 588 /// The main heuristic function. Analyze the set of instructions pointed to by 589 /// LRI and return a candidate solution if these instructions can be sunk, or 590 /// None otherwise. 591 Optional<SinkingInstructionCandidate> analyzeInstructionForSinking( 592 LockstepReverseIterator &LRI, unsigned &InstNum, unsigned &MemoryInstNum, 593 ModelledPHISet &NeededPHIs, SmallPtrSetImpl<Value *> &PHIContents); 594 595 /// Create a ModelledPHI for each PHI in BB, adding to PHIs. 596 void analyzeInitialPHIs(BasicBlock *BB, ModelledPHISet &PHIs, 597 SmallPtrSetImpl<Value *> &PHIContents) { 598 for (PHINode &PN : BB->phis()) { 599 auto MPHI = ModelledPHI(&PN); 600 PHIs.insert(MPHI); 601 for (auto *V : MPHI.getValues()) 602 PHIContents.insert(V); 603 } 604 } 605 606 /// The main instruction sinking driver. Set up state and try and sink 607 /// instructions into BBEnd from its predecessors. 608 unsigned sinkBB(BasicBlock *BBEnd); 609 610 /// Perform the actual mechanics of sinking an instruction from Blocks into 611 /// BBEnd, which is their only successor. 612 void sinkLastInstruction(ArrayRef<BasicBlock *> Blocks, BasicBlock *BBEnd); 613 614 /// Remove PHIs that all have the same incoming value. 615 void foldPointlessPHINodes(BasicBlock *BB) { 616 auto I = BB->begin(); 617 while (PHINode *PN = dyn_cast<PHINode>(I++)) { 618 if (!llvm::all_of(PN->incoming_values(), [&](const Value *V) { 619 return V == PN->getIncomingValue(0); 620 })) 621 continue; 622 if (PN->getIncomingValue(0) != PN) 623 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 624 else 625 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 626 PN->eraseFromParent(); 627 } 628 } 629 }; 630 631 Optional<SinkingInstructionCandidate> GVNSink::analyzeInstructionForSinking( 632 LockstepReverseIterator &LRI, unsigned &InstNum, unsigned &MemoryInstNum, 633 ModelledPHISet &NeededPHIs, SmallPtrSetImpl<Value *> &PHIContents) { 634 auto Insts = *LRI; 635 LLVM_DEBUG(dbgs() << " -- Analyzing instruction set: [\n"; for (auto *I 636 : Insts) { 637 I->dump(); 638 } dbgs() << " ]\n";); 639 640 DenseMap<uint32_t, unsigned> VNums; 641 for (auto *I : Insts) { 642 uint32_t N = VN.lookupOrAdd(I); 643 LLVM_DEBUG(dbgs() << " VN=" << Twine::utohexstr(N) << " for" << *I << "\n"); 644 if (N == ~0U) 645 return None; 646 VNums[N]++; 647 } 648 unsigned VNumToSink = 649 std::max_element(VNums.begin(), VNums.end(), 650 [](const std::pair<uint32_t, unsigned> &I, 651 const std::pair<uint32_t, unsigned> &J) { 652 return I.second < J.second; 653 }) 654 ->first; 655 656 if (VNums[VNumToSink] == 1) 657 // Can't sink anything! 658 return None; 659 660 // Now restrict the number of incoming blocks down to only those with 661 // VNumToSink. 662 auto &ActivePreds = LRI.getActiveBlocks(); 663 unsigned InitialActivePredSize = ActivePreds.size(); 664 SmallVector<Instruction *, 4> NewInsts; 665 for (auto *I : Insts) { 666 if (VN.lookup(I) != VNumToSink) 667 ActivePreds.remove(I->getParent()); 668 else 669 NewInsts.push_back(I); 670 } 671 for (auto *I : NewInsts) 672 if (shouldAvoidSinkingInstruction(I)) 673 return None; 674 675 // If we've restricted the incoming blocks, restrict all needed PHIs also 676 // to that set. 677 bool RecomputePHIContents = false; 678 if (ActivePreds.size() != InitialActivePredSize) { 679 ModelledPHISet NewNeededPHIs; 680 for (auto P : NeededPHIs) { 681 P.restrictToBlocks(ActivePreds); 682 NewNeededPHIs.insert(P); 683 } 684 NeededPHIs = NewNeededPHIs; 685 LRI.restrictToBlocks(ActivePreds); 686 RecomputePHIContents = true; 687 } 688 689 // The sunk instruction's results. 690 ModelledPHI NewPHI(NewInsts, ActivePreds); 691 692 // Does sinking this instruction render previous PHIs redundant? 693 if (NeededPHIs.erase(NewPHI)) 694 RecomputePHIContents = true; 695 696 if (RecomputePHIContents) { 697 // The needed PHIs have changed, so recompute the set of all needed 698 // values. 699 PHIContents.clear(); 700 for (auto &PHI : NeededPHIs) 701 PHIContents.insert(PHI.getValues().begin(), PHI.getValues().end()); 702 } 703 704 // Is this instruction required by a later PHI that doesn't match this PHI? 705 // if so, we can't sink this instruction. 706 for (auto *V : NewPHI.getValues()) 707 if (PHIContents.count(V)) 708 // V exists in this PHI, but the whole PHI is different to NewPHI 709 // (else it would have been removed earlier). We cannot continue 710 // because this isn't representable. 711 return None; 712 713 // Which operands need PHIs? 714 // FIXME: If any of these fail, we should partition up the candidates to 715 // try and continue making progress. 716 Instruction *I0 = NewInsts[0]; 717 718 // If all instructions that are going to participate don't have the same 719 // number of operands, we can't do any useful PHI analysis for all operands. 720 auto hasDifferentNumOperands = [&I0](Instruction *I) { 721 return I->getNumOperands() != I0->getNumOperands(); 722 }; 723 if (any_of(NewInsts, hasDifferentNumOperands)) 724 return None; 725 726 for (unsigned OpNum = 0, E = I0->getNumOperands(); OpNum != E; ++OpNum) { 727 ModelledPHI PHI(NewInsts, OpNum, ActivePreds); 728 if (PHI.areAllIncomingValuesSame()) 729 continue; 730 if (!canReplaceOperandWithVariable(I0, OpNum)) 731 // We can 't create a PHI from this instruction! 732 return None; 733 if (NeededPHIs.count(PHI)) 734 continue; 735 if (!PHI.areAllIncomingValuesSameType()) 736 return None; 737 // Don't create indirect calls! The called value is the final operand. 738 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OpNum == E - 1 && 739 PHI.areAnyIncomingValuesConstant()) 740 return None; 741 742 NeededPHIs.reserve(NeededPHIs.size()); 743 NeededPHIs.insert(PHI); 744 PHIContents.insert(PHI.getValues().begin(), PHI.getValues().end()); 745 } 746 747 if (isMemoryInst(NewInsts[0])) 748 ++MemoryInstNum; 749 750 SinkingInstructionCandidate Cand; 751 Cand.NumInstructions = ++InstNum; 752 Cand.NumMemoryInsts = MemoryInstNum; 753 Cand.NumBlocks = ActivePreds.size(); 754 Cand.NumPHIs = NeededPHIs.size(); 755 append_range(Cand.Blocks, ActivePreds); 756 757 return Cand; 758 } 759 760 unsigned GVNSink::sinkBB(BasicBlock *BBEnd) { 761 LLVM_DEBUG(dbgs() << "GVNSink: running on basic block "; 762 BBEnd->printAsOperand(dbgs()); dbgs() << "\n"); 763 SmallVector<BasicBlock *, 4> Preds; 764 for (auto *B : predecessors(BBEnd)) { 765 auto *T = B->getTerminator(); 766 if (isa<BranchInst>(T) || isa<SwitchInst>(T)) 767 Preds.push_back(B); 768 else 769 return 0; 770 } 771 if (Preds.size() < 2) 772 return 0; 773 llvm::sort(Preds); 774 775 unsigned NumOrigPreds = Preds.size(); 776 // We can only sink instructions through unconditional branches. 777 llvm::erase_if(Preds, [](BasicBlock *BB) { 778 return BB->getTerminator()->getNumSuccessors() != 1; 779 }); 780 781 LockstepReverseIterator LRI(Preds); 782 SmallVector<SinkingInstructionCandidate, 4> Candidates; 783 unsigned InstNum = 0, MemoryInstNum = 0; 784 ModelledPHISet NeededPHIs; 785 SmallPtrSet<Value *, 4> PHIContents; 786 analyzeInitialPHIs(BBEnd, NeededPHIs, PHIContents); 787 unsigned NumOrigPHIs = NeededPHIs.size(); 788 789 while (LRI.isValid()) { 790 auto Cand = analyzeInstructionForSinking(LRI, InstNum, MemoryInstNum, 791 NeededPHIs, PHIContents); 792 if (!Cand) 793 break; 794 Cand->calculateCost(NumOrigPHIs, Preds.size()); 795 Candidates.emplace_back(*Cand); 796 --LRI; 797 } 798 799 llvm::stable_sort(Candidates, std::greater<SinkingInstructionCandidate>()); 800 LLVM_DEBUG(dbgs() << " -- Sinking candidates:\n"; for (auto &C 801 : Candidates) dbgs() 802 << " " << C << "\n";); 803 804 // Pick the top candidate, as long it is positive! 805 if (Candidates.empty() || Candidates.front().Cost <= 0) 806 return 0; 807 auto C = Candidates.front(); 808 809 LLVM_DEBUG(dbgs() << " -- Sinking: " << C << "\n"); 810 BasicBlock *InsertBB = BBEnd; 811 if (C.Blocks.size() < NumOrigPreds) { 812 LLVM_DEBUG(dbgs() << " -- Splitting edge to "; 813 BBEnd->printAsOperand(dbgs()); dbgs() << "\n"); 814 InsertBB = SplitBlockPredecessors(BBEnd, C.Blocks, ".gvnsink.split"); 815 if (!InsertBB) { 816 LLVM_DEBUG(dbgs() << " -- FAILED to split edge!\n"); 817 // Edge couldn't be split. 818 return 0; 819 } 820 } 821 822 for (unsigned I = 0; I < C.NumInstructions; ++I) 823 sinkLastInstruction(C.Blocks, InsertBB); 824 825 return C.NumInstructions; 826 } 827 828 void GVNSink::sinkLastInstruction(ArrayRef<BasicBlock *> Blocks, 829 BasicBlock *BBEnd) { 830 SmallVector<Instruction *, 4> Insts; 831 for (BasicBlock *BB : Blocks) 832 Insts.push_back(BB->getTerminator()->getPrevNode()); 833 Instruction *I0 = Insts.front(); 834 835 SmallVector<Value *, 4> NewOperands; 836 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) { 837 bool NeedPHI = llvm::any_of(Insts, [&I0, O](const Instruction *I) { 838 return I->getOperand(O) != I0->getOperand(O); 839 }); 840 if (!NeedPHI) { 841 NewOperands.push_back(I0->getOperand(O)); 842 continue; 843 } 844 845 // Create a new PHI in the successor block and populate it. 846 auto *Op = I0->getOperand(O); 847 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!"); 848 auto *PN = PHINode::Create(Op->getType(), Insts.size(), 849 Op->getName() + ".sink", &BBEnd->front()); 850 for (auto *I : Insts) 851 PN->addIncoming(I->getOperand(O), I->getParent()); 852 NewOperands.push_back(PN); 853 } 854 855 // Arbitrarily use I0 as the new "common" instruction; remap its operands 856 // and move it to the start of the successor block. 857 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) 858 I0->getOperandUse(O).set(NewOperands[O]); 859 I0->moveBefore(&*BBEnd->getFirstInsertionPt()); 860 861 // Update metadata and IR flags. 862 for (auto *I : Insts) 863 if (I != I0) { 864 combineMetadataForCSE(I0, I, true); 865 I0->andIRFlags(I); 866 } 867 868 for (auto *I : Insts) 869 if (I != I0) 870 I->replaceAllUsesWith(I0); 871 foldPointlessPHINodes(BBEnd); 872 873 // Finally nuke all instructions apart from the common instruction. 874 for (auto *I : Insts) 875 if (I != I0) 876 I->eraseFromParent(); 877 878 NumRemoved += Insts.size() - 1; 879 } 880 881 //////////////////////////////////////////////////////////////////////////////// 882 // Pass machinery / boilerplate 883 884 class GVNSinkLegacyPass : public FunctionPass { 885 public: 886 static char ID; 887 888 GVNSinkLegacyPass() : FunctionPass(ID) { 889 initializeGVNSinkLegacyPassPass(*PassRegistry::getPassRegistry()); 890 } 891 892 bool runOnFunction(Function &F) override { 893 if (skipFunction(F)) 894 return false; 895 GVNSink G; 896 return G.run(F); 897 } 898 899 void getAnalysisUsage(AnalysisUsage &AU) const override { 900 AU.addPreserved<GlobalsAAWrapperPass>(); 901 } 902 }; 903 904 } // end anonymous namespace 905 906 PreservedAnalyses GVNSinkPass::run(Function &F, FunctionAnalysisManager &AM) { 907 GVNSink G; 908 if (!G.run(F)) 909 return PreservedAnalyses::all(); 910 return PreservedAnalyses::none(); 911 } 912 913 char GVNSinkLegacyPass::ID = 0; 914 915 INITIALIZE_PASS_BEGIN(GVNSinkLegacyPass, "gvn-sink", 916 "Early GVN sinking of Expressions", false, false) 917 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 918 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 919 INITIALIZE_PASS_END(GVNSinkLegacyPass, "gvn-sink", 920 "Early GVN sinking of Expressions", false, false) 921 922 FunctionPass *llvm::createGVNSinkPass() { return new GVNSinkLegacyPass(); } 923