1 //===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===// 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 file implements the SSAUpdater class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Utils/SSAUpdater.h" 14 #include "llvm/ADT/DenseMap.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/TinyPtrVector.h" 18 #include "llvm/Analysis/InstructionSimplify.h" 19 #include "llvm/IR/BasicBlock.h" 20 #include "llvm/IR/CFG.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DebugLoc.h" 23 #include "llvm/IR/Instruction.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/Module.h" 26 #include "llvm/IR/Use.h" 27 #include "llvm/IR/Value.h" 28 #include "llvm/Support/Casting.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 32 #include <cassert> 33 #include <utility> 34 35 using namespace llvm; 36 37 #define DEBUG_TYPE "ssaupdater" 38 39 using AvailableValsTy = DenseMap<BasicBlock *, Value *>; 40 41 static AvailableValsTy &getAvailableVals(void *AV) { 42 return *static_cast<AvailableValsTy*>(AV); 43 } 44 45 SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode *> *NewPHI) 46 : InsertedPHIs(NewPHI) {} 47 48 SSAUpdater::~SSAUpdater() { 49 delete static_cast<AvailableValsTy*>(AV); 50 } 51 52 void SSAUpdater::Initialize(Type *Ty, StringRef Name) { 53 if (!AV) 54 AV = new AvailableValsTy(); 55 else 56 getAvailableVals(AV).clear(); 57 ProtoType = Ty; 58 ProtoName = std::string(Name); 59 } 60 61 bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const { 62 return getAvailableVals(AV).count(BB); 63 } 64 65 Value *SSAUpdater::FindValueForBlock(BasicBlock *BB) const { 66 return getAvailableVals(AV).lookup(BB); 67 } 68 69 void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) { 70 assert(ProtoType && "Need to initialize SSAUpdater"); 71 assert(ProtoType == V->getType() && 72 "All rewritten values must have the same type"); 73 getAvailableVals(AV)[BB] = V; 74 } 75 76 static bool IsEquivalentPHI(PHINode *PHI, 77 SmallDenseMap<BasicBlock *, Value *, 8> &ValueMapping) { 78 unsigned PHINumValues = PHI->getNumIncomingValues(); 79 if (PHINumValues != ValueMapping.size()) 80 return false; 81 82 // Scan the phi to see if it matches. 83 for (unsigned i = 0, e = PHINumValues; i != e; ++i) 84 if (ValueMapping[PHI->getIncomingBlock(i)] != 85 PHI->getIncomingValue(i)) { 86 return false; 87 } 88 89 return true; 90 } 91 92 Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) { 93 Value *Res = GetValueAtEndOfBlockInternal(BB); 94 return Res; 95 } 96 97 Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) { 98 // If there is no definition of the renamed variable in this block, just use 99 // GetValueAtEndOfBlock to do our work. 100 if (!HasValueForBlock(BB)) 101 return GetValueAtEndOfBlock(BB); 102 103 // Ok, we have already got a value for this block. If it is out of our block 104 // or it is a phi - we can re-use it as it will be defined in the middle of 105 // block as well. 106 Value *defV = FindValueForBlock(BB); 107 if (auto I = dyn_cast<Instruction>(defV)) 108 if (isa<PHINode>(I) || I->getParent() != BB) 109 return defV; 110 111 // Otherwise, we have the hard case. Get the live-in values for each 112 // predecessor. 113 SmallVector<std::pair<BasicBlock *, Value *>, 8> PredValues; 114 Value *SingularValue = nullptr; 115 116 // We can get our predecessor info by walking the pred_iterator list, but it 117 // is relatively slow. If we already have PHI nodes in this block, walk one 118 // of them to get the predecessor list instead. 119 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) { 120 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) { 121 BasicBlock *PredBB = SomePhi->getIncomingBlock(i); 122 Value *PredVal = GetValueAtEndOfBlock(PredBB); 123 PredValues.push_back(std::make_pair(PredBB, PredVal)); 124 125 // Compute SingularValue. 126 if (i == 0) 127 SingularValue = PredVal; 128 else if (PredVal != SingularValue) 129 SingularValue = nullptr; 130 } 131 } else { 132 bool isFirstPred = true; 133 for (BasicBlock *PredBB : predecessors(BB)) { 134 Value *PredVal = GetValueAtEndOfBlock(PredBB); 135 PredValues.push_back(std::make_pair(PredBB, PredVal)); 136 137 // Compute SingularValue. 138 if (isFirstPred) { 139 SingularValue = PredVal; 140 isFirstPred = false; 141 } else if (PredVal != SingularValue) 142 SingularValue = nullptr; 143 } 144 } 145 146 // If there are no predecessors, just return undef. 147 if (PredValues.empty()) 148 return UndefValue::get(ProtoType); 149 150 // Otherwise, if all the merged values are the same, just use it. 151 if (SingularValue) 152 return SingularValue; 153 154 // Otherwise, we do need a PHI: check to see if we already have one available 155 // in this block that produces the right value. 156 if (isa<PHINode>(BB->begin())) { 157 SmallDenseMap<BasicBlock *, Value *, 8> ValueMapping(PredValues.begin(), 158 PredValues.end()); 159 for (PHINode &SomePHI : BB->phis()) { 160 if (IsEquivalentPHI(&SomePHI, ValueMapping)) 161 return &SomePHI; 162 } 163 } 164 165 // Ok, we have no way out, insert a new one now. 166 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(), 167 ProtoName, &BB->front()); 168 169 // Fill in all the predecessors of the PHI. 170 for (const auto &PredValue : PredValues) 171 InsertedPHI->addIncoming(PredValue.second, PredValue.first); 172 173 // See if the PHI node can be merged to a single value. This can happen in 174 // loop cases when we get a PHI of itself and one other value. 175 if (Value *V = 176 simplifyInstruction(InsertedPHI, BB->getModule()->getDataLayout())) { 177 InsertedPHI->eraseFromParent(); 178 return V; 179 } 180 181 // Set the DebugLoc of the inserted PHI, if available. 182 DebugLoc DL; 183 if (const Instruction *I = BB->getFirstNonPHI()) 184 DL = I->getDebugLoc(); 185 InsertedPHI->setDebugLoc(DL); 186 187 // If the client wants to know about all new instructions, tell it. 188 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI); 189 190 LLVM_DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n"); 191 return InsertedPHI; 192 } 193 194 void SSAUpdater::RewriteUse(Use &U) { 195 Instruction *User = cast<Instruction>(U.getUser()); 196 197 Value *V; 198 if (PHINode *UserPN = dyn_cast<PHINode>(User)) 199 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); 200 else 201 V = GetValueInMiddleOfBlock(User->getParent()); 202 203 U.set(V); 204 } 205 206 void SSAUpdater::RewriteUseAfterInsertions(Use &U) { 207 Instruction *User = cast<Instruction>(U.getUser()); 208 209 Value *V; 210 if (PHINode *UserPN = dyn_cast<PHINode>(User)) 211 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U)); 212 else 213 V = GetValueAtEndOfBlock(User->getParent()); 214 215 U.set(V); 216 } 217 218 namespace llvm { 219 220 template<> 221 class SSAUpdaterTraits<SSAUpdater> { 222 public: 223 using BlkT = BasicBlock; 224 using ValT = Value *; 225 using PhiT = PHINode; 226 using BlkSucc_iterator = succ_iterator; 227 228 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); } 229 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); } 230 231 class PHI_iterator { 232 private: 233 PHINode *PHI; 234 unsigned idx; 235 236 public: 237 explicit PHI_iterator(PHINode *P) // begin iterator 238 : PHI(P), idx(0) {} 239 PHI_iterator(PHINode *P, bool) // end iterator 240 : PHI(P), idx(PHI->getNumIncomingValues()) {} 241 242 PHI_iterator &operator++() { ++idx; return *this; } 243 bool operator==(const PHI_iterator& x) const { return idx == x.idx; } 244 bool operator!=(const PHI_iterator& x) const { return !operator==(x); } 245 246 Value *getIncomingValue() { return PHI->getIncomingValue(idx); } 247 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); } 248 }; 249 250 static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 251 static PHI_iterator PHI_end(PhiT *PHI) { 252 return PHI_iterator(PHI, true); 253 } 254 255 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds 256 /// vector, set Info->NumPreds, and allocate space in Info->Preds. 257 static void FindPredecessorBlocks(BasicBlock *BB, 258 SmallVectorImpl<BasicBlock *> *Preds) { 259 // We can get our predecessor info by walking the pred_iterator list, 260 // but it is relatively slow. If we already have PHI nodes in this 261 // block, walk one of them to get the predecessor list instead. 262 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) 263 append_range(*Preds, SomePhi->blocks()); 264 else 265 append_range(*Preds, predecessors(BB)); 266 } 267 268 /// GetUndefVal - Get an undefined value of the same type as the value 269 /// being handled. 270 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) { 271 return UndefValue::get(Updater->ProtoType); 272 } 273 274 /// CreateEmptyPHI - Create a new PHI instruction in the specified block. 275 /// Reserve space for the operands but do not fill them in yet. 276 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds, 277 SSAUpdater *Updater) { 278 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds, 279 Updater->ProtoName, &BB->front()); 280 return PHI; 281 } 282 283 /// AddPHIOperand - Add the specified value as an operand of the PHI for 284 /// the specified predecessor block. 285 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) { 286 PHI->addIncoming(Val, Pred); 287 } 288 289 /// ValueIsPHI - Check if a value is a PHI. 290 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) { 291 return dyn_cast<PHINode>(Val); 292 } 293 294 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 295 /// operands, i.e., it was just added. 296 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) { 297 PHINode *PHI = ValueIsPHI(Val, Updater); 298 if (PHI && PHI->getNumIncomingValues() == 0) 299 return PHI; 300 return nullptr; 301 } 302 303 /// GetPHIValue - For the specified PHI instruction, return the value 304 /// that it defines. 305 static Value *GetPHIValue(PHINode *PHI) { 306 return PHI; 307 } 308 }; 309 310 } // end namespace llvm 311 312 /// Check to see if AvailableVals has an entry for the specified BB and if so, 313 /// return it. If not, construct SSA form by first calculating the required 314 /// placement of PHIs and then inserting new PHIs where needed. 315 Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) { 316 AvailableValsTy &AvailableVals = getAvailableVals(AV); 317 if (Value *V = AvailableVals[BB]) 318 return V; 319 320 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs); 321 return Impl.GetValue(BB); 322 } 323 324 //===----------------------------------------------------------------------===// 325 // LoadAndStorePromoter Implementation 326 //===----------------------------------------------------------------------===// 327 328 LoadAndStorePromoter:: 329 LoadAndStorePromoter(ArrayRef<const Instruction *> Insts, 330 SSAUpdater &S, StringRef BaseName) : SSA(S) { 331 if (Insts.empty()) return; 332 333 const Value *SomeVal; 334 if (const LoadInst *LI = dyn_cast<LoadInst>(Insts[0])) 335 SomeVal = LI; 336 else 337 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0); 338 339 if (BaseName.empty()) 340 BaseName = SomeVal->getName(); 341 SSA.Initialize(SomeVal->getType(), BaseName); 342 } 343 344 void LoadAndStorePromoter::run(const SmallVectorImpl<Instruction *> &Insts) { 345 // First step: bucket up uses of the alloca by the block they occur in. 346 // This is important because we have to handle multiple defs/uses in a block 347 // ourselves: SSAUpdater is purely for cross-block references. 348 DenseMap<BasicBlock *, TinyPtrVector<Instruction *>> UsesByBlock; 349 350 for (Instruction *User : Insts) 351 UsesByBlock[User->getParent()].push_back(User); 352 353 // Okay, now we can iterate over all the blocks in the function with uses, 354 // processing them. Keep track of which loads are loading a live-in value. 355 // Walk the uses in the use-list order to be determinstic. 356 SmallVector<LoadInst *, 32> LiveInLoads; 357 DenseMap<Value *, Value *> ReplacedLoads; 358 359 for (Instruction *User : Insts) { 360 BasicBlock *BB = User->getParent(); 361 TinyPtrVector<Instruction *> &BlockUses = UsesByBlock[BB]; 362 363 // If this block has already been processed, ignore this repeat use. 364 if (BlockUses.empty()) continue; 365 366 // Okay, this is the first use in the block. If this block just has a 367 // single user in it, we can rewrite it trivially. 368 if (BlockUses.size() == 1) { 369 // If it is a store, it is a trivial def of the value in the block. 370 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 371 updateDebugInfo(SI); 372 SSA.AddAvailableValue(BB, SI->getOperand(0)); 373 } else 374 // Otherwise it is a load, queue it to rewrite as a live-in load. 375 LiveInLoads.push_back(cast<LoadInst>(User)); 376 BlockUses.clear(); 377 continue; 378 } 379 380 // Otherwise, check to see if this block is all loads. 381 bool HasStore = false; 382 for (Instruction *I : BlockUses) { 383 if (isa<StoreInst>(I)) { 384 HasStore = true; 385 break; 386 } 387 } 388 389 // If so, we can queue them all as live in loads. We don't have an 390 // efficient way to tell which on is first in the block and don't want to 391 // scan large blocks, so just add all loads as live ins. 392 if (!HasStore) { 393 for (Instruction *I : BlockUses) 394 LiveInLoads.push_back(cast<LoadInst>(I)); 395 BlockUses.clear(); 396 continue; 397 } 398 399 // Otherwise, we have mixed loads and stores (or just a bunch of stores). 400 // Since SSAUpdater is purely for cross-block values, we need to determine 401 // the order of these instructions in the block. If the first use in the 402 // block is a load, then it uses the live in value. The last store defines 403 // the live out value. We handle this by doing a linear scan of the block. 404 Value *StoredValue = nullptr; 405 for (Instruction &I : *BB) { 406 if (LoadInst *L = dyn_cast<LoadInst>(&I)) { 407 // If this is a load from an unrelated pointer, ignore it. 408 if (!isInstInList(L, Insts)) continue; 409 410 // If we haven't seen a store yet, this is a live in use, otherwise 411 // use the stored value. 412 if (StoredValue) { 413 replaceLoadWithValue(L, StoredValue); 414 L->replaceAllUsesWith(StoredValue); 415 ReplacedLoads[L] = StoredValue; 416 } else { 417 LiveInLoads.push_back(L); 418 } 419 continue; 420 } 421 422 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) { 423 // If this is a store to an unrelated pointer, ignore it. 424 if (!isInstInList(SI, Insts)) continue; 425 updateDebugInfo(SI); 426 427 // Remember that this is the active value in the block. 428 StoredValue = SI->getOperand(0); 429 } 430 } 431 432 // The last stored value that happened is the live-out for the block. 433 assert(StoredValue && "Already checked that there is a store in block"); 434 SSA.AddAvailableValue(BB, StoredValue); 435 BlockUses.clear(); 436 } 437 438 // Okay, now we rewrite all loads that use live-in values in the loop, 439 // inserting PHI nodes as necessary. 440 for (LoadInst *ALoad : LiveInLoads) { 441 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent()); 442 replaceLoadWithValue(ALoad, NewVal); 443 444 // Avoid assertions in unreachable code. 445 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType()); 446 ALoad->replaceAllUsesWith(NewVal); 447 ReplacedLoads[ALoad] = NewVal; 448 } 449 450 // Allow the client to do stuff before we start nuking things. 451 doExtraRewritesBeforeFinalDeletion(); 452 453 // Now that everything is rewritten, delete the old instructions from the 454 // function. They should all be dead now. 455 for (Instruction *User : Insts) { 456 if (!shouldDelete(User)) 457 continue; 458 459 // If this is a load that still has uses, then the load must have been added 460 // as a live value in the SSAUpdate data structure for a block (e.g. because 461 // the loaded value was stored later). In this case, we need to recursively 462 // propagate the updates until we get to the real value. 463 if (!User->use_empty()) { 464 Value *NewVal = ReplacedLoads[User]; 465 assert(NewVal && "not a replaced load?"); 466 467 // Propagate down to the ultimate replacee. The intermediately loads 468 // could theoretically already have been deleted, so we don't want to 469 // dereference the Value*'s. 470 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal); 471 while (RLI != ReplacedLoads.end()) { 472 NewVal = RLI->second; 473 RLI = ReplacedLoads.find(NewVal); 474 } 475 476 replaceLoadWithValue(cast<LoadInst>(User), NewVal); 477 User->replaceAllUsesWith(NewVal); 478 } 479 480 instructionDeleted(User); 481 User->eraseFromParent(); 482 } 483 } 484 485 bool 486 LoadAndStorePromoter::isInstInList(Instruction *I, 487 const SmallVectorImpl<Instruction *> &Insts) 488 const { 489 return is_contained(Insts, I); 490 } 491