1 //===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===// 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 hoists expressions from branches to a common dominator. It uses 10 // GVN (global value numbering) to discover expressions computing the same 11 // values. The primary goals of code-hoisting are: 12 // 1. To reduce the code size. 13 // 2. In some cases reduce critical path (by exposing more ILP). 14 // 15 // The algorithm factors out the reachability of values such that multiple 16 // queries to find reachability of values are fast. This is based on finding the 17 // ANTIC points in the CFG which do not change during hoisting. The ANTIC points 18 // are basically the dominance-frontiers in the inverse graph. So we introduce a 19 // data structure (CHI nodes) to keep track of values flowing out of a basic 20 // block. We only do this for values with multiple occurrences in the function 21 // as they are the potential hoistable candidates. This approach allows us to 22 // hoist instructions to a basic block with more than two successors, as well as 23 // deal with infinite loops in a trivial way. 24 // 25 // Limitations: This pass does not hoist fully redundant expressions because 26 // they are already handled by GVN-PRE. It is advisable to run gvn-hoist before 27 // and after gvn-pre because gvn-pre creates opportunities for more instructions 28 // to be hoisted. 29 // 30 // Hoisting may affect the performance in some cases. To mitigate that, hoisting 31 // is disabled in the following cases. 32 // 1. Scalars across calls. 33 // 2. geps when corresponding load/store cannot be hoisted. 34 //===----------------------------------------------------------------------===// 35 36 #include "llvm/ADT/DenseMap.h" 37 #include "llvm/ADT/DenseSet.h" 38 #include "llvm/ADT/STLExtras.h" 39 #include "llvm/ADT/SmallPtrSet.h" 40 #include "llvm/ADT/SmallVector.h" 41 #include "llvm/ADT/Statistic.h" 42 #include "llvm/ADT/iterator_range.h" 43 #include "llvm/Analysis/AliasAnalysis.h" 44 #include "llvm/Analysis/GlobalsModRef.h" 45 #include "llvm/Analysis/IteratedDominanceFrontier.h" 46 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 47 #include "llvm/Analysis/MemorySSA.h" 48 #include "llvm/Analysis/MemorySSAUpdater.h" 49 #include "llvm/Analysis/PostDominators.h" 50 #include "llvm/Analysis/ValueTracking.h" 51 #include "llvm/IR/Argument.h" 52 #include "llvm/IR/BasicBlock.h" 53 #include "llvm/IR/CFG.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/Dominators.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/Instruction.h" 58 #include "llvm/IR/Instructions.h" 59 #include "llvm/IR/IntrinsicInst.h" 60 #include "llvm/IR/LLVMContext.h" 61 #include "llvm/IR/PassManager.h" 62 #include "llvm/IR/Use.h" 63 #include "llvm/IR/User.h" 64 #include "llvm/IR/Value.h" 65 #include "llvm/InitializePasses.h" 66 #include "llvm/Pass.h" 67 #include "llvm/Support/Casting.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Support/Debug.h" 70 #include "llvm/Support/raw_ostream.h" 71 #include "llvm/Transforms/Scalar.h" 72 #include "llvm/Transforms/Scalar/GVN.h" 73 #include "llvm/Transforms/Utils/Local.h" 74 #include <algorithm> 75 #include <cassert> 76 #include <iterator> 77 #include <memory> 78 #include <utility> 79 #include <vector> 80 81 using namespace llvm; 82 83 #define DEBUG_TYPE "gvn-hoist" 84 85 STATISTIC(NumHoisted, "Number of instructions hoisted"); 86 STATISTIC(NumRemoved, "Number of instructions removed"); 87 STATISTIC(NumLoadsHoisted, "Number of loads hoisted"); 88 STATISTIC(NumLoadsRemoved, "Number of loads removed"); 89 STATISTIC(NumStoresHoisted, "Number of stores hoisted"); 90 STATISTIC(NumStoresRemoved, "Number of stores removed"); 91 STATISTIC(NumCallsHoisted, "Number of calls hoisted"); 92 STATISTIC(NumCallsRemoved, "Number of calls removed"); 93 94 static cl::opt<int> 95 MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1), 96 cl::desc("Max number of instructions to hoist " 97 "(default unlimited = -1)")); 98 99 static cl::opt<int> MaxNumberOfBBSInPath( 100 "gvn-hoist-max-bbs", cl::Hidden, cl::init(4), 101 cl::desc("Max number of basic blocks on the path between " 102 "hoisting locations (default = 4, unlimited = -1)")); 103 104 static cl::opt<int> MaxDepthInBB( 105 "gvn-hoist-max-depth", cl::Hidden, cl::init(100), 106 cl::desc("Hoist instructions from the beginning of the BB up to the " 107 "maximum specified depth (default = 100, unlimited = -1)")); 108 109 static cl::opt<int> 110 MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10), 111 cl::desc("Maximum length of dependent chains to hoist " 112 "(default = 10, unlimited = -1)")); 113 114 namespace llvm { 115 116 using BBSideEffectsSet = DenseMap<const BasicBlock *, bool>; 117 using SmallVecInsn = SmallVector<Instruction *, 4>; 118 using SmallVecImplInsn = SmallVectorImpl<Instruction *>; 119 120 // Each element of a hoisting list contains the basic block where to hoist and 121 // a list of instructions to be hoisted. 122 using HoistingPointInfo = std::pair<BasicBlock *, SmallVecInsn>; 123 124 using HoistingPointList = SmallVector<HoistingPointInfo, 4>; 125 126 // A map from a pair of VNs to all the instructions with those VNs. 127 using VNType = std::pair<unsigned, unsigned>; 128 129 using VNtoInsns = DenseMap<VNType, SmallVector<Instruction *, 4>>; 130 131 // CHI keeps information about values flowing out of a basic block. It is 132 // similar to PHI but in the inverse graph, and used for outgoing values on each 133 // edge. For conciseness, it is computed only for instructions with multiple 134 // occurrences in the CFG because they are the only hoistable candidates. 135 // A (CHI[{V, B, I1}, {V, C, I2}] 136 // / \ 137 // / \ 138 // B(I1) C (I2) 139 // The Value number for both I1 and I2 is V, the CHI node will save the 140 // instruction as well as the edge where the value is flowing to. 141 struct CHIArg { 142 VNType VN; 143 144 // Edge destination (shows the direction of flow), may not be where the I is. 145 BasicBlock *Dest; 146 147 // The instruction (VN) which uses the values flowing out of CHI. 148 Instruction *I; 149 150 bool operator==(const CHIArg &A) const { return VN == A.VN; } 151 bool operator!=(const CHIArg &A) const { return !(*this == A); } 152 }; 153 154 using CHIIt = SmallVectorImpl<CHIArg>::iterator; 155 using CHIArgs = iterator_range<CHIIt>; 156 using OutValuesType = DenseMap<BasicBlock *, SmallVector<CHIArg, 2>>; 157 using InValuesType = 158 DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>; 159 160 // An invalid value number Used when inserting a single value number into 161 // VNtoInsns. 162 enum : unsigned { InvalidVN = ~2U }; 163 164 // Records all scalar instructions candidate for code hoisting. 165 class InsnInfo { 166 VNtoInsns VNtoScalars; 167 168 public: 169 // Inserts I and its value number in VNtoScalars. 170 void insert(Instruction *I, GVNPass::ValueTable &VN) { 171 // Scalar instruction. 172 unsigned V = VN.lookupOrAdd(I); 173 VNtoScalars[{V, InvalidVN}].push_back(I); 174 } 175 176 const VNtoInsns &getVNTable() const { return VNtoScalars; } 177 }; 178 179 // Records all load instructions candidate for code hoisting. 180 class LoadInfo { 181 VNtoInsns VNtoLoads; 182 183 public: 184 // Insert Load and the value number of its memory address in VNtoLoads. 185 void insert(LoadInst *Load, GVNPass::ValueTable &VN) { 186 if (Load->isSimple()) { 187 unsigned V = VN.lookupOrAdd(Load->getPointerOperand()); 188 VNtoLoads[{V, InvalidVN}].push_back(Load); 189 } 190 } 191 192 const VNtoInsns &getVNTable() const { return VNtoLoads; } 193 }; 194 195 // Records all store instructions candidate for code hoisting. 196 class StoreInfo { 197 VNtoInsns VNtoStores; 198 199 public: 200 // Insert the Store and a hash number of the store address and the stored 201 // value in VNtoStores. 202 void insert(StoreInst *Store, GVNPass::ValueTable &VN) { 203 if (!Store->isSimple()) 204 return; 205 // Hash the store address and the stored value. 206 Value *Ptr = Store->getPointerOperand(); 207 Value *Val = Store->getValueOperand(); 208 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store); 209 } 210 211 const VNtoInsns &getVNTable() const { return VNtoStores; } 212 }; 213 214 // Records all call instructions candidate for code hoisting. 215 class CallInfo { 216 VNtoInsns VNtoCallsScalars; 217 VNtoInsns VNtoCallsLoads; 218 VNtoInsns VNtoCallsStores; 219 220 public: 221 // Insert Call and its value numbering in one of the VNtoCalls* containers. 222 void insert(CallInst *Call, GVNPass::ValueTable &VN) { 223 // A call that doesNotAccessMemory is handled as a Scalar, 224 // onlyReadsMemory will be handled as a Load instruction, 225 // all other calls will be handled as stores. 226 unsigned V = VN.lookupOrAdd(Call); 227 auto Entry = std::make_pair(V, InvalidVN); 228 229 if (Call->doesNotAccessMemory()) 230 VNtoCallsScalars[Entry].push_back(Call); 231 else if (Call->onlyReadsMemory()) 232 VNtoCallsLoads[Entry].push_back(Call); 233 else 234 VNtoCallsStores[Entry].push_back(Call); 235 } 236 237 const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; } 238 const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; } 239 const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; } 240 }; 241 242 static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) { 243 static const unsigned KnownIDs[] = {LLVMContext::MD_tbaa, 244 LLVMContext::MD_alias_scope, 245 LLVMContext::MD_noalias, 246 LLVMContext::MD_range, 247 LLVMContext::MD_fpmath, 248 LLVMContext::MD_invariant_load, 249 LLVMContext::MD_invariant_group, 250 LLVMContext::MD_access_group}; 251 combineMetadata(ReplInst, I, KnownIDs, true); 252 } 253 254 // This pass hoists common computations across branches sharing common 255 // dominator. The primary goal is to reduce the code size, and in some 256 // cases reduce critical path (by exposing more ILP). 257 class GVNHoist { 258 public: 259 GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA, 260 MemoryDependenceResults *MD, MemorySSA *MSSA) 261 : DT(DT), PDT(PDT), AA(AA), MD(MD), MSSA(MSSA), 262 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {} 263 264 bool run(Function &F); 265 266 // Copied from NewGVN.cpp 267 // This function provides global ranking of operations so that we can place 268 // them in a canonical order. Note that rank alone is not necessarily enough 269 // for a complete ordering, as constants all have the same rank. However, 270 // generally, we will simplify an operation with all constants so that it 271 // doesn't matter what order they appear in. 272 unsigned int rank(const Value *V) const; 273 274 private: 275 GVNPass::ValueTable VN; 276 DominatorTree *DT; 277 PostDominatorTree *PDT; 278 AliasAnalysis *AA; 279 MemoryDependenceResults *MD; 280 MemorySSA *MSSA; 281 std::unique_ptr<MemorySSAUpdater> MSSAUpdater; 282 DenseMap<const Value *, unsigned> DFSNumber; 283 BBSideEffectsSet BBSideEffects; 284 DenseSet<const BasicBlock *> HoistBarrier; 285 SmallVector<BasicBlock *, 32> IDFBlocks; 286 unsigned NumFuncArgs; 287 const bool HoistingGeps = false; 288 289 enum InsKind { Unknown, Scalar, Load, Store }; 290 291 // Return true when there are exception handling in BB. 292 bool hasEH(const BasicBlock *BB); 293 294 // Return true when I1 appears before I2 in the instructions of BB. 295 bool firstInBB(const Instruction *I1, const Instruction *I2) { 296 assert(I1->getParent() == I2->getParent()); 297 unsigned I1DFS = DFSNumber.lookup(I1); 298 unsigned I2DFS = DFSNumber.lookup(I2); 299 assert(I1DFS && I2DFS); 300 return I1DFS < I2DFS; 301 } 302 303 // Return true when there are memory uses of Def in BB. 304 bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def, 305 const BasicBlock *BB); 306 307 bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB, 308 int &NBBsOnAllPaths); 309 310 // Return true when there are exception handling or loads of memory Def 311 // between Def and NewPt. This function is only called for stores: Def is 312 // the MemoryDef of the store to be hoisted. 313 314 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 315 // return true when the counter NBBsOnAllPaths reaces 0, except when it is 316 // initialized to -1 which is unlimited. 317 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def, 318 int &NBBsOnAllPaths); 319 320 // Return true when there are exception handling between HoistPt and BB. 321 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and 322 // return true when the counter NBBsOnAllPaths reaches 0, except when it is 323 // initialized to -1 which is unlimited. 324 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB, 325 int &NBBsOnAllPaths); 326 327 // Return true when it is safe to hoist a memory load or store U from OldPt 328 // to NewPt. 329 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt, 330 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths); 331 332 // Return true when it is safe to hoist scalar instructions from all blocks in 333 // WL to HoistBB. 334 bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB, 335 int &NBBsOnAllPaths) { 336 return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths); 337 } 338 339 // In the inverse CFG, the dominance frontier of basic block (BB) is the 340 // point where ANTIC needs to be computed for instructions which are going 341 // to be hoisted. Since this point does not change during gvn-hoist, 342 // we compute it only once (on demand). 343 // The ides is inspired from: 344 // "Partial Redundancy Elimination in SSA Form" 345 // ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW 346 // They use similar idea in the forward graph to find fully redundant and 347 // partially redundant expressions, here it is used in the inverse graph to 348 // find fully anticipable instructions at merge point (post-dominator in 349 // the inverse CFG). 350 // Returns the edge via which an instruction in BB will get the values from. 351 352 // Returns true when the values are flowing out to each edge. 353 bool valueAnticipable(CHIArgs C, Instruction *TI) const; 354 355 // Check if it is safe to hoist values tracked by CHI in the range 356 // [Begin, End) and accumulate them in Safe. 357 void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K, 358 SmallVectorImpl<CHIArg> &Safe); 359 360 using RenameStackType = DenseMap<VNType, SmallVector<Instruction *, 2>>; 361 362 // Push all the VNs corresponding to BB into RenameStack. 363 void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs, 364 RenameStackType &RenameStack); 365 366 void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs, 367 RenameStackType &RenameStack); 368 369 // Walk the post-dominator tree top-down and use a stack for each value to 370 // store the last value you see. When you hit a CHI from a given edge, the 371 // value to use as the argument is at the top of the stack, add the value to 372 // CHI and pop. 373 void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) { 374 auto Root = PDT->getNode(nullptr); 375 if (!Root) 376 return; 377 // Depth first walk on PDom tree to fill the CHIargs at each PDF. 378 for (auto Node : depth_first(Root)) { 379 BasicBlock *BB = Node->getBlock(); 380 if (!BB) 381 continue; 382 383 RenameStackType RenameStack; 384 // Collect all values in BB and push to stack. 385 fillRenameStack(BB, ValueBBs, RenameStack); 386 387 // Fill outgoing values in each CHI corresponding to BB. 388 fillChiArgs(BB, CHIBBs, RenameStack); 389 } 390 } 391 392 // Walk all the CHI-nodes to find ones which have a empty-entry and remove 393 // them Then collect all the instructions which are safe to hoist and see if 394 // they form a list of anticipable values. OutValues contains CHIs 395 // corresponding to each basic block. 396 void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K, 397 HoistingPointList &HPL); 398 399 // Compute insertion points for each values which can be fully anticipated at 400 // a dominator. HPL contains all such values. 401 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL, 402 InsKind K) { 403 // Sort VNs based on their rankings 404 std::vector<VNType> Ranks; 405 for (const auto &Entry : Map) { 406 Ranks.push_back(Entry.first); 407 } 408 409 // TODO: Remove fully-redundant expressions. 410 // Get instruction from the Map, assume that all the Instructions 411 // with same VNs have same rank (this is an approximation). 412 llvm::sort(Ranks, [this, &Map](const VNType &r1, const VNType &r2) { 413 return (rank(*Map.lookup(r1).begin()) < rank(*Map.lookup(r2).begin())); 414 }); 415 416 // - Sort VNs according to their rank, and start with lowest ranked VN 417 // - Take a VN and for each instruction with same VN 418 // - Find the dominance frontier in the inverse graph (PDF) 419 // - Insert the chi-node at PDF 420 // - Remove the chi-nodes with missing entries 421 // - Remove values from CHI-nodes which do not truly flow out, e.g., 422 // modified along the path. 423 // - Collect the remaining values that are still anticipable 424 SmallVector<BasicBlock *, 2> IDFBlocks; 425 ReverseIDFCalculator IDFs(*PDT); 426 OutValuesType OutValue; 427 InValuesType InValue; 428 for (const auto &R : Ranks) { 429 const SmallVecInsn &V = Map.lookup(R); 430 if (V.size() < 2) 431 continue; 432 const VNType &VN = R; 433 SmallPtrSet<BasicBlock *, 2> VNBlocks; 434 for (auto &I : V) { 435 BasicBlock *BBI = I->getParent(); 436 if (!hasEH(BBI)) 437 VNBlocks.insert(BBI); 438 } 439 // Compute the Post Dominance Frontiers of each basic block 440 // The dominance frontier of a live block X in the reverse 441 // control graph is the set of blocks upon which X is control 442 // dependent. The following sequence computes the set of blocks 443 // which currently have dead terminators that are control 444 // dependence sources of a block which is in NewLiveBlocks. 445 IDFs.setDefiningBlocks(VNBlocks); 446 IDFBlocks.clear(); 447 IDFs.calculate(IDFBlocks); 448 449 // Make a map of BB vs instructions to be hoisted. 450 for (unsigned i = 0; i < V.size(); ++i) { 451 InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i])); 452 } 453 // Insert empty CHI node for this VN. This is used to factor out 454 // basic blocks where the ANTIC can potentially change. 455 CHIArg EmptyChi = {VN, nullptr, nullptr}; 456 for (auto *IDFBB : IDFBlocks) { 457 for (unsigned i = 0; i < V.size(); ++i) { 458 // Ignore spurious PDFs. 459 if (DT->properlyDominates(IDFBB, V[i]->getParent())) { 460 OutValue[IDFBB].push_back(EmptyChi); 461 LLVM_DEBUG(dbgs() << "\nInserting a CHI for BB: " 462 << IDFBB->getName() << ", for Insn: " << *V[i]); 463 } 464 } 465 } 466 } 467 468 // Insert CHI args at each PDF to iterate on factored graph of 469 // control dependence. 470 insertCHI(InValue, OutValue); 471 // Using the CHI args inserted at each PDF, find fully anticipable values. 472 findHoistableCandidates(OutValue, K, HPL); 473 } 474 475 // Return true when all operands of Instr are available at insertion point 476 // HoistPt. When limiting the number of hoisted expressions, one could hoist 477 // a load without hoisting its access function. So before hoisting any 478 // expression, make sure that all its operands are available at insert point. 479 bool allOperandsAvailable(const Instruction *I, 480 const BasicBlock *HoistPt) const; 481 482 // Same as allOperandsAvailable with recursive check for GEP operands. 483 bool allGepOperandsAvailable(const Instruction *I, 484 const BasicBlock *HoistPt) const; 485 486 // Make all operands of the GEP available. 487 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt, 488 const SmallVecInsn &InstructionsToHoist, 489 Instruction *Gep) const; 490 491 void updateAlignment(Instruction *I, Instruction *Repl); 492 493 // Remove all the instructions in Candidates and replace their usage with 494 // Repl. Returns the number of instructions removed. 495 unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl, 496 MemoryUseOrDef *NewMemAcc); 497 498 // Replace all Memory PHI usage with NewMemAcc. 499 void raMPHIuw(MemoryUseOrDef *NewMemAcc); 500 501 // Remove all other instructions and replace them with Repl. 502 unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl, 503 BasicBlock *DestBB, bool MoveAccess); 504 505 // In the case Repl is a load or a store, we make all their GEPs 506 // available: GEPs are not hoisted by default to avoid the address 507 // computations to be hoisted without the associated load or store. 508 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt, 509 const SmallVecInsn &InstructionsToHoist) const; 510 511 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL); 512 513 // Hoist all expressions. Returns Number of scalars hoisted 514 // and number of non-scalars hoisted. 515 std::pair<unsigned, unsigned> hoistExpressions(Function &F); 516 }; 517 518 class GVNHoistLegacyPass : public FunctionPass { 519 public: 520 static char ID; 521 522 GVNHoistLegacyPass() : FunctionPass(ID) { 523 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry()); 524 } 525 526 bool runOnFunction(Function &F) override { 527 if (skipFunction(F)) 528 return false; 529 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 530 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 531 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 532 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); 533 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 534 535 GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA); 536 return G.run(F); 537 } 538 539 void getAnalysisUsage(AnalysisUsage &AU) const override { 540 AU.addRequired<DominatorTreeWrapperPass>(); 541 AU.addRequired<PostDominatorTreeWrapperPass>(); 542 AU.addRequired<AAResultsWrapperPass>(); 543 AU.addRequired<MemoryDependenceWrapperPass>(); 544 AU.addRequired<MemorySSAWrapperPass>(); 545 AU.addPreserved<DominatorTreeWrapperPass>(); 546 AU.addPreserved<MemorySSAWrapperPass>(); 547 AU.addPreserved<GlobalsAAWrapperPass>(); 548 } 549 }; 550 551 bool GVNHoist::run(Function &F) { 552 NumFuncArgs = F.arg_size(); 553 VN.setDomTree(DT); 554 VN.setAliasAnalysis(AA); 555 VN.setMemDep(MD); 556 bool Res = false; 557 // Perform DFS Numbering of instructions. 558 unsigned BBI = 0; 559 for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) { 560 DFSNumber[BB] = ++BBI; 561 unsigned I = 0; 562 for (auto &Inst : *BB) 563 DFSNumber[&Inst] = ++I; 564 } 565 566 int ChainLength = 0; 567 568 // FIXME: use lazy evaluation of VN to avoid the fix-point computation. 569 while (true) { 570 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength) 571 return Res; 572 573 auto HoistStat = hoistExpressions(F); 574 if (HoistStat.first + HoistStat.second == 0) 575 return Res; 576 577 if (HoistStat.second > 0) 578 // To address a limitation of the current GVN, we need to rerun the 579 // hoisting after we hoisted loads or stores in order to be able to 580 // hoist all scalars dependent on the hoisted ld/st. 581 VN.clear(); 582 583 Res = true; 584 } 585 586 return Res; 587 } 588 589 unsigned int GVNHoist::rank(const Value *V) const { 590 // Prefer constants to undef to anything else 591 // Undef is a constant, have to check it first. 592 // Prefer smaller constants to constantexprs 593 if (isa<ConstantExpr>(V)) 594 return 2; 595 if (isa<UndefValue>(V)) 596 return 1; 597 if (isa<Constant>(V)) 598 return 0; 599 else if (auto *A = dyn_cast<Argument>(V)) 600 return 3 + A->getArgNo(); 601 602 // Need to shift the instruction DFS by number of arguments + 3 to account 603 // for the constant and argument ranking above. 604 auto Result = DFSNumber.lookup(V); 605 if (Result > 0) 606 return 4 + NumFuncArgs + Result; 607 // Unreachable or something else, just return a really large number. 608 return ~0; 609 } 610 611 bool GVNHoist::hasEH(const BasicBlock *BB) { 612 auto It = BBSideEffects.find(BB); 613 if (It != BBSideEffects.end()) 614 return It->second; 615 616 if (BB->isEHPad() || BB->hasAddressTaken()) { 617 BBSideEffects[BB] = true; 618 return true; 619 } 620 621 if (BB->getTerminator()->mayThrow()) { 622 BBSideEffects[BB] = true; 623 return true; 624 } 625 626 BBSideEffects[BB] = false; 627 return false; 628 } 629 630 bool GVNHoist::hasMemoryUse(const Instruction *NewPt, MemoryDef *Def, 631 const BasicBlock *BB) { 632 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB); 633 if (!Acc) 634 return false; 635 636 Instruction *OldPt = Def->getMemoryInst(); 637 const BasicBlock *OldBB = OldPt->getParent(); 638 const BasicBlock *NewBB = NewPt->getParent(); 639 bool ReachedNewPt = false; 640 641 for (const MemoryAccess &MA : *Acc) 642 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) { 643 Instruction *Insn = MU->getMemoryInst(); 644 645 // Do not check whether MU aliases Def when MU occurs after OldPt. 646 if (BB == OldBB && firstInBB(OldPt, Insn)) 647 break; 648 649 // Do not check whether MU aliases Def when MU occurs before NewPt. 650 if (BB == NewBB) { 651 if (!ReachedNewPt) { 652 if (firstInBB(Insn, NewPt)) 653 continue; 654 ReachedNewPt = true; 655 } 656 } 657 if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA)) 658 return true; 659 } 660 661 return false; 662 } 663 664 bool GVNHoist::hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB, 665 int &NBBsOnAllPaths) { 666 // Stop walk once the limit is reached. 667 if (NBBsOnAllPaths == 0) 668 return true; 669 670 // Impossible to hoist with exceptions on the path. 671 if (hasEH(BB)) 672 return true; 673 674 // No such instruction after HoistBarrier in a basic block was 675 // selected for hoisting so instructions selected within basic block with 676 // a hoist barrier can be hoisted. 677 if ((BB != SrcBB) && HoistBarrier.count(BB)) 678 return true; 679 680 return false; 681 } 682 683 bool GVNHoist::hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def, 684 int &NBBsOnAllPaths) { 685 const BasicBlock *NewBB = NewPt->getParent(); 686 const BasicBlock *OldBB = Def->getBlock(); 687 assert(DT->dominates(NewBB, OldBB) && "invalid path"); 688 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) && 689 "def does not dominate new hoisting point"); 690 691 // Walk all basic blocks reachable in depth-first iteration on the inverse 692 // CFG from OldBB to NewBB. These blocks are all the blocks that may be 693 // executed between the execution of NewBB and OldBB. Hoisting an expression 694 // from OldBB into NewBB has to be safe on all execution paths. 695 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) { 696 const BasicBlock *BB = *I; 697 if (BB == NewBB) { 698 // Stop traversal when reaching HoistPt. 699 I.skipChildren(); 700 continue; 701 } 702 703 if (hasEHhelper(BB, OldBB, NBBsOnAllPaths)) 704 return true; 705 706 // Check that we do not move a store past loads. 707 if (hasMemoryUse(NewPt, Def, BB)) 708 return true; 709 710 // -1 is unlimited number of blocks on all paths. 711 if (NBBsOnAllPaths != -1) 712 --NBBsOnAllPaths; 713 714 ++I; 715 } 716 717 return false; 718 } 719 720 bool GVNHoist::hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB, 721 int &NBBsOnAllPaths) { 722 assert(DT->dominates(HoistPt, SrcBB) && "Invalid path"); 723 724 // Walk all basic blocks reachable in depth-first iteration on 725 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the 726 // blocks that may be executed between the execution of NewHoistPt and 727 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe 728 // on all execution paths. 729 for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) { 730 const BasicBlock *BB = *I; 731 if (BB == HoistPt) { 732 // Stop traversal when reaching NewHoistPt. 733 I.skipChildren(); 734 continue; 735 } 736 737 if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths)) 738 return true; 739 740 // -1 is unlimited number of blocks on all paths. 741 if (NBBsOnAllPaths != -1) 742 --NBBsOnAllPaths; 743 744 ++I; 745 } 746 747 return false; 748 } 749 750 bool GVNHoist::safeToHoistLdSt(const Instruction *NewPt, 751 const Instruction *OldPt, MemoryUseOrDef *U, 752 GVNHoist::InsKind K, int &NBBsOnAllPaths) { 753 // In place hoisting is safe. 754 if (NewPt == OldPt) 755 return true; 756 757 const BasicBlock *NewBB = NewPt->getParent(); 758 const BasicBlock *OldBB = OldPt->getParent(); 759 const BasicBlock *UBB = U->getBlock(); 760 761 // Check for dependences on the Memory SSA. 762 MemoryAccess *D = U->getDefiningAccess(); 763 BasicBlock *DBB = D->getBlock(); 764 if (DT->properlyDominates(NewBB, DBB)) 765 // Cannot move the load or store to NewBB above its definition in DBB. 766 return false; 767 768 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D)) 769 if (auto *UD = dyn_cast<MemoryUseOrDef>(D)) 770 if (!firstInBB(UD->getMemoryInst(), NewPt)) 771 // Cannot move the load or store to NewPt above its definition in D. 772 return false; 773 774 // Check for unsafe hoistings due to side effects. 775 if (K == InsKind::Store) { 776 if (hasEHOrLoadsOnPath(NewPt, cast<MemoryDef>(U), NBBsOnAllPaths)) 777 return false; 778 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths)) 779 return false; 780 781 if (UBB == NewBB) { 782 if (DT->properlyDominates(DBB, NewBB)) 783 return true; 784 assert(UBB == DBB); 785 assert(MSSA->locallyDominates(D, U)); 786 } 787 788 // No side effects: it is safe to hoist. 789 return true; 790 } 791 792 bool GVNHoist::valueAnticipable(CHIArgs C, Instruction *TI) const { 793 if (TI->getNumSuccessors() > (unsigned)size(C)) 794 return false; // Not enough args in this CHI. 795 796 for (auto CHI : C) { 797 // Find if all the edges have values flowing out of BB. 798 if (!llvm::is_contained(successors(TI), CHI.Dest)) 799 return false; 800 } 801 return true; 802 } 803 804 void GVNHoist::checkSafety(CHIArgs C, BasicBlock *BB, GVNHoist::InsKind K, 805 SmallVectorImpl<CHIArg> &Safe) { 806 int NumBBsOnAllPaths = MaxNumberOfBBSInPath; 807 for (auto CHI : C) { 808 Instruction *Insn = CHI.I; 809 if (!Insn) // No instruction was inserted in this CHI. 810 continue; 811 if (K == InsKind::Scalar) { 812 if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths)) 813 Safe.push_back(CHI); 814 } else { 815 auto *T = BB->getTerminator(); 816 if (MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn)) 817 if (safeToHoistLdSt(T, Insn, UD, K, NumBBsOnAllPaths)) 818 Safe.push_back(CHI); 819 } 820 } 821 } 822 823 void GVNHoist::fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs, 824 GVNHoist::RenameStackType &RenameStack) { 825 auto it1 = ValueBBs.find(BB); 826 if (it1 != ValueBBs.end()) { 827 // Iterate in reverse order to keep lower ranked values on the top. 828 LLVM_DEBUG(dbgs() << "\nVisiting: " << BB->getName() 829 << " for pushing instructions on stack";); 830 for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) { 831 // Get the value of instruction I 832 LLVM_DEBUG(dbgs() << "\nPushing on stack: " << *VI.second); 833 RenameStack[VI.first].push_back(VI.second); 834 } 835 } 836 } 837 838 void GVNHoist::fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs, 839 GVNHoist::RenameStackType &RenameStack) { 840 // For each *predecessor* (because Post-DOM) of BB check if it has a CHI 841 for (auto Pred : predecessors(BB)) { 842 auto P = CHIBBs.find(Pred); 843 if (P == CHIBBs.end()) { 844 continue; 845 } 846 LLVM_DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName();); 847 // A CHI is found (BB -> Pred is an edge in the CFG) 848 // Pop the stack until Top(V) = Ve. 849 auto &VCHI = P->second; 850 for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) { 851 CHIArg &C = *It; 852 if (!C.Dest) { 853 auto si = RenameStack.find(C.VN); 854 // The Basic Block where CHI is must dominate the value we want to 855 // track in a CHI. In the PDom walk, there can be values in the 856 // stack which are not control dependent e.g., nested loop. 857 if (si != RenameStack.end() && si->second.size() && 858 DT->properlyDominates(Pred, si->second.back()->getParent())) { 859 C.Dest = BB; // Assign the edge 860 C.I = si->second.pop_back_val(); // Assign the argument 861 LLVM_DEBUG(dbgs() 862 << "\nCHI Inserted in BB: " << C.Dest->getName() << *C.I 863 << ", VN: " << C.VN.first << ", " << C.VN.second); 864 } 865 // Move to next CHI of a different value 866 It = std::find_if(It, VCHI.end(), [It](CHIArg &A) { return A != *It; }); 867 } else 868 ++It; 869 } 870 } 871 } 872 873 void GVNHoist::findHoistableCandidates(OutValuesType &CHIBBs, 874 GVNHoist::InsKind K, 875 HoistingPointList &HPL) { 876 auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; }; 877 878 // CHIArgs now have the outgoing values, so check for anticipability and 879 // accumulate hoistable candidates in HPL. 880 for (std::pair<BasicBlock *, SmallVector<CHIArg, 2>> &A : CHIBBs) { 881 BasicBlock *BB = A.first; 882 SmallVectorImpl<CHIArg> &CHIs = A.second; 883 // Vector of PHIs contains PHIs for different instructions. 884 // Sort the args according to their VNs, such that identical 885 // instructions are together. 886 llvm::stable_sort(CHIs, cmpVN); 887 auto TI = BB->getTerminator(); 888 auto B = CHIs.begin(); 889 // [PreIt, PHIIt) form a range of CHIs which have identical VNs. 890 auto PHIIt = llvm::find_if(CHIs, [B](CHIArg &A) { return A != *B; }); 891 auto PrevIt = CHIs.begin(); 892 while (PrevIt != PHIIt) { 893 // Collect values which satisfy safety checks. 894 SmallVector<CHIArg, 2> Safe; 895 // We check for safety first because there might be multiple values in 896 // the same path, some of which are not safe to be hoisted, but overall 897 // each edge has at least one value which can be hoisted, making the 898 // value anticipable along that path. 899 checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe); 900 901 // List of safe values should be anticipable at TI. 902 if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) { 903 HPL.push_back({BB, SmallVecInsn()}); 904 SmallVecInsn &V = HPL.back().second; 905 for (auto B : Safe) 906 V.push_back(B.I); 907 } 908 909 // Check other VNs 910 PrevIt = PHIIt; 911 PHIIt = std::find_if(PrevIt, CHIs.end(), 912 [PrevIt](CHIArg &A) { return A != *PrevIt; }); 913 } 914 } 915 } 916 917 bool GVNHoist::allOperandsAvailable(const Instruction *I, 918 const BasicBlock *HoistPt) const { 919 for (const Use &Op : I->operands()) 920 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 921 if (!DT->dominates(Inst->getParent(), HoistPt)) 922 return false; 923 924 return true; 925 } 926 927 bool GVNHoist::allGepOperandsAvailable(const Instruction *I, 928 const BasicBlock *HoistPt) const { 929 for (const Use &Op : I->operands()) 930 if (const auto *Inst = dyn_cast<Instruction>(&Op)) 931 if (!DT->dominates(Inst->getParent(), HoistPt)) { 932 if (const GetElementPtrInst *GepOp = 933 dyn_cast<GetElementPtrInst>(Inst)) { 934 if (!allGepOperandsAvailable(GepOp, HoistPt)) 935 return false; 936 // Gep is available if all operands of GepOp are available. 937 } else { 938 // Gep is not available if it has operands other than GEPs that are 939 // defined in blocks not dominating HoistPt. 940 return false; 941 } 942 } 943 return true; 944 } 945 946 void GVNHoist::makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt, 947 const SmallVecInsn &InstructionsToHoist, 948 Instruction *Gep) const { 949 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available"); 950 951 Instruction *ClonedGep = Gep->clone(); 952 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i) 953 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) { 954 // Check whether the operand is already available. 955 if (DT->dominates(Op->getParent(), HoistPt)) 956 continue; 957 958 // As a GEP can refer to other GEPs, recursively make all the operands 959 // of this GEP available at HoistPt. 960 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op)) 961 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp); 962 } 963 964 // Copy Gep and replace its uses in Repl with ClonedGep. 965 ClonedGep->insertBefore(HoistPt->getTerminator()); 966 967 // Conservatively discard any optimization hints, they may differ on the 968 // other paths. 969 ClonedGep->dropUnknownNonDebugMetadata(); 970 971 // If we have optimization hints which agree with each other along different 972 // paths, preserve them. 973 for (const Instruction *OtherInst : InstructionsToHoist) { 974 const GetElementPtrInst *OtherGep; 975 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst)) 976 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand()); 977 else 978 OtherGep = cast<GetElementPtrInst>( 979 cast<StoreInst>(OtherInst)->getPointerOperand()); 980 ClonedGep->andIRFlags(OtherGep); 981 } 982 983 // Replace uses of Gep with ClonedGep in Repl. 984 Repl->replaceUsesOfWith(Gep, ClonedGep); 985 } 986 987 void GVNHoist::updateAlignment(Instruction *I, Instruction *Repl) { 988 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) { 989 ReplacementLoad->setAlignment( 990 std::min(ReplacementLoad->getAlign(), cast<LoadInst>(I)->getAlign())); 991 ++NumLoadsRemoved; 992 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) { 993 ReplacementStore->setAlignment( 994 std::min(ReplacementStore->getAlign(), cast<StoreInst>(I)->getAlign())); 995 ++NumStoresRemoved; 996 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) { 997 ReplacementAlloca->setAlignment(std::max(ReplacementAlloca->getAlign(), 998 cast<AllocaInst>(I)->getAlign())); 999 } else if (isa<CallInst>(Repl)) { 1000 ++NumCallsRemoved; 1001 } 1002 } 1003 1004 unsigned GVNHoist::rauw(const SmallVecInsn &Candidates, Instruction *Repl, 1005 MemoryUseOrDef *NewMemAcc) { 1006 unsigned NR = 0; 1007 for (Instruction *I : Candidates) { 1008 if (I != Repl) { 1009 ++NR; 1010 updateAlignment(I, Repl); 1011 if (NewMemAcc) { 1012 // Update the uses of the old MSSA access with NewMemAcc. 1013 MemoryAccess *OldMA = MSSA->getMemoryAccess(I); 1014 OldMA->replaceAllUsesWith(NewMemAcc); 1015 MSSAUpdater->removeMemoryAccess(OldMA); 1016 } 1017 1018 Repl->andIRFlags(I); 1019 combineKnownMetadata(Repl, I); 1020 I->replaceAllUsesWith(Repl); 1021 // Also invalidate the Alias Analysis cache. 1022 MD->removeInstruction(I); 1023 I->eraseFromParent(); 1024 } 1025 } 1026 return NR; 1027 } 1028 1029 void GVNHoist::raMPHIuw(MemoryUseOrDef *NewMemAcc) { 1030 SmallPtrSet<MemoryPhi *, 4> UsePhis; 1031 for (User *U : NewMemAcc->users()) 1032 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U)) 1033 UsePhis.insert(Phi); 1034 1035 for (MemoryPhi *Phi : UsePhis) { 1036 auto In = Phi->incoming_values(); 1037 if (llvm::all_of(In, [&](Use &U) { return U == NewMemAcc; })) { 1038 Phi->replaceAllUsesWith(NewMemAcc); 1039 MSSAUpdater->removeMemoryAccess(Phi); 1040 } 1041 } 1042 } 1043 1044 unsigned GVNHoist::removeAndReplace(const SmallVecInsn &Candidates, 1045 Instruction *Repl, BasicBlock *DestBB, 1046 bool MoveAccess) { 1047 MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl); 1048 if (MoveAccess && NewMemAcc) { 1049 // The definition of this ld/st will not change: ld/st hoisting is 1050 // legal when the ld/st is not moved past its current definition. 1051 MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::BeforeTerminator); 1052 } 1053 1054 // Replace all other instructions with Repl with memory access NewMemAcc. 1055 unsigned NR = rauw(Candidates, Repl, NewMemAcc); 1056 1057 // Remove MemorySSA phi nodes with the same arguments. 1058 if (NewMemAcc) 1059 raMPHIuw(NewMemAcc); 1060 return NR; 1061 } 1062 1063 bool GVNHoist::makeGepOperandsAvailable( 1064 Instruction *Repl, BasicBlock *HoistPt, 1065 const SmallVecInsn &InstructionsToHoist) const { 1066 // Check whether the GEP of a ld/st can be synthesized at HoistPt. 1067 GetElementPtrInst *Gep = nullptr; 1068 Instruction *Val = nullptr; 1069 if (auto *Ld = dyn_cast<LoadInst>(Repl)) { 1070 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand()); 1071 } else if (auto *St = dyn_cast<StoreInst>(Repl)) { 1072 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand()); 1073 Val = dyn_cast<Instruction>(St->getValueOperand()); 1074 // Check that the stored value is available. 1075 if (Val) { 1076 if (isa<GetElementPtrInst>(Val)) { 1077 // Check whether we can compute the GEP at HoistPt. 1078 if (!allGepOperandsAvailable(Val, HoistPt)) 1079 return false; 1080 } else if (!DT->dominates(Val->getParent(), HoistPt)) 1081 return false; 1082 } 1083 } 1084 1085 // Check whether we can compute the Gep at HoistPt. 1086 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt)) 1087 return false; 1088 1089 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep); 1090 1091 if (Val && isa<GetElementPtrInst>(Val)) 1092 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val); 1093 1094 return true; 1095 } 1096 1097 std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) { 1098 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0; 1099 for (const HoistingPointInfo &HP : HPL) { 1100 // Find out whether we already have one of the instructions in HoistPt, 1101 // in which case we do not have to move it. 1102 BasicBlock *DestBB = HP.first; 1103 const SmallVecInsn &InstructionsToHoist = HP.second; 1104 Instruction *Repl = nullptr; 1105 for (Instruction *I : InstructionsToHoist) 1106 if (I->getParent() == DestBB) 1107 // If there are two instructions in HoistPt to be hoisted in place: 1108 // update Repl to be the first one, such that we can rename the uses 1109 // of the second based on the first. 1110 if (!Repl || firstInBB(I, Repl)) 1111 Repl = I; 1112 1113 // Keep track of whether we moved the instruction so we know whether we 1114 // should move the MemoryAccess. 1115 bool MoveAccess = true; 1116 if (Repl) { 1117 // Repl is already in HoistPt: it remains in place. 1118 assert(allOperandsAvailable(Repl, DestBB) && 1119 "instruction depends on operands that are not available"); 1120 MoveAccess = false; 1121 } else { 1122 // When we do not find Repl in HoistPt, select the first in the list 1123 // and move it to HoistPt. 1124 Repl = InstructionsToHoist.front(); 1125 1126 // We can move Repl in HoistPt only when all operands are available. 1127 // The order in which hoistings are done may influence the availability 1128 // of operands. 1129 if (!allOperandsAvailable(Repl, DestBB)) { 1130 // When HoistingGeps there is nothing more we can do to make the 1131 // operands available: just continue. 1132 if (HoistingGeps) 1133 continue; 1134 1135 // When not HoistingGeps we need to copy the GEPs. 1136 if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist)) 1137 continue; 1138 } 1139 1140 // Move the instruction at the end of HoistPt. 1141 Instruction *Last = DestBB->getTerminator(); 1142 MD->removeInstruction(Repl); 1143 Repl->moveBefore(Last); 1144 1145 DFSNumber[Repl] = DFSNumber[Last]++; 1146 } 1147 1148 NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess); 1149 1150 if (isa<LoadInst>(Repl)) 1151 ++NL; 1152 else if (isa<StoreInst>(Repl)) 1153 ++NS; 1154 else if (isa<CallInst>(Repl)) 1155 ++NC; 1156 else // Scalar 1157 ++NI; 1158 } 1159 1160 if (MSSA && VerifyMemorySSA) 1161 MSSA->verifyMemorySSA(); 1162 1163 NumHoisted += NL + NS + NC + NI; 1164 NumRemoved += NR; 1165 NumLoadsHoisted += NL; 1166 NumStoresHoisted += NS; 1167 NumCallsHoisted += NC; 1168 return {NI, NL + NC + NS}; 1169 } 1170 1171 std::pair<unsigned, unsigned> GVNHoist::hoistExpressions(Function &F) { 1172 InsnInfo II; 1173 LoadInfo LI; 1174 StoreInfo SI; 1175 CallInfo CI; 1176 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) { 1177 int InstructionNb = 0; 1178 for (Instruction &I1 : *BB) { 1179 // If I1 cannot guarantee progress, subsequent instructions 1180 // in BB cannot be hoisted anyways. 1181 if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) { 1182 HoistBarrier.insert(BB); 1183 break; 1184 } 1185 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting 1186 // deeper may increase the register pressure and compilation time. 1187 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB) 1188 break; 1189 1190 // Do not value number terminator instructions. 1191 if (I1.isTerminator()) 1192 break; 1193 1194 if (auto *Load = dyn_cast<LoadInst>(&I1)) 1195 LI.insert(Load, VN); 1196 else if (auto *Store = dyn_cast<StoreInst>(&I1)) 1197 SI.insert(Store, VN); 1198 else if (auto *Call = dyn_cast<CallInst>(&I1)) { 1199 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) { 1200 if (isa<DbgInfoIntrinsic>(Intr) || 1201 Intr->getIntrinsicID() == Intrinsic::assume || 1202 Intr->getIntrinsicID() == Intrinsic::sideeffect) 1203 continue; 1204 } 1205 if (Call->mayHaveSideEffects()) 1206 break; 1207 1208 if (Call->isConvergent()) 1209 break; 1210 1211 CI.insert(Call, VN); 1212 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1)) 1213 // Do not hoist scalars past calls that may write to memory because 1214 // that could result in spills later. geps are handled separately. 1215 // TODO: We can relax this for targets like AArch64 as they have more 1216 // registers than X86. 1217 II.insert(&I1, VN); 1218 } 1219 } 1220 1221 HoistingPointList HPL; 1222 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar); 1223 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load); 1224 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store); 1225 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar); 1226 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load); 1227 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store); 1228 return hoist(HPL); 1229 } 1230 1231 } // end namespace llvm 1232 1233 PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) { 1234 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F); 1235 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 1236 AliasAnalysis &AA = AM.getResult<AAManager>(F); 1237 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F); 1238 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); 1239 GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA); 1240 if (!G.run(F)) 1241 return PreservedAnalyses::all(); 1242 1243 PreservedAnalyses PA; 1244 PA.preserve<DominatorTreeAnalysis>(); 1245 PA.preserve<MemorySSAAnalysis>(); 1246 return PA; 1247 } 1248 1249 char GVNHoistLegacyPass::ID = 0; 1250 1251 INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist", 1252 "Early GVN Hoisting of Expressions", false, false) 1253 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) 1254 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1255 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1256 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 1257 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1258 INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist", 1259 "Early GVN Hoisting of Expressions", false, false) 1260 1261 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); } 1262