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