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