[SimplifyLibCalls] Use hasFloatVersion(). NFCI.
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file promotes memory references to be register references.  It promotes
11 // alloca instructions which only have loads and stores as uses.  An alloca is
12 // transformed by using iterated dominator frontiers to place PHI nodes, then
13 // traversing the function in depth-first order to rewrite loads and stores as
14 // appropriate.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasSetTracker.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/IteratedDominanceFrontier.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/CFG.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 #include <algorithm>
42 using namespace llvm;
43
44 #define DEBUG_TYPE "mem2reg"
45
46 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
47 STATISTIC(NumSingleStore,   "Number of alloca's promoted with a single store");
48 STATISTIC(NumDeadAlloca,    "Number of dead alloca's removed");
49 STATISTIC(NumPHIInsert,     "Number of PHI nodes inserted");
50
51 bool llvm::isAllocaPromotable(const AllocaInst *AI) {
52   // FIXME: If the memory unit is of pointer or integer type, we can permit
53   // assignments to subsections of the memory unit.
54   unsigned AS = AI->getType()->getAddressSpace();
55
56   // Only allow direct and non-volatile loads and stores...
57   for (const User *U : AI->users()) {
58     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
59       // Note that atomic loads can be transformed; atomic semantics do
60       // not have any meaning for a local alloca.
61       if (LI->isVolatile())
62         return false;
63     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
64       if (SI->getOperand(0) == AI)
65         return false; // Don't allow a store OF the AI, only INTO the AI.
66       // Note that atomic stores can be transformed; atomic semantics do
67       // not have any meaning for a local alloca.
68       if (SI->isVolatile())
69         return false;
70     } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
71       if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
72           II->getIntrinsicID() != Intrinsic::lifetime_end)
73         return false;
74     } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
75       if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
76         return false;
77       if (!onlyUsedByLifetimeMarkers(BCI))
78         return false;
79     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
80       if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS))
81         return false;
82       if (!GEPI->hasAllZeroIndices())
83         return false;
84       if (!onlyUsedByLifetimeMarkers(GEPI))
85         return false;
86     } else {
87       return false;
88     }
89   }
90
91   return true;
92 }
93
94 namespace {
95
96 struct AllocaInfo {
97   SmallVector<BasicBlock *, 32> DefiningBlocks;
98   SmallVector<BasicBlock *, 32> UsingBlocks;
99
100   StoreInst *OnlyStore;
101   BasicBlock *OnlyBlock;
102   bool OnlyUsedInOneBlock;
103
104   Value *AllocaPointerVal;
105   DbgDeclareInst *DbgDeclare;
106
107   void clear() {
108     DefiningBlocks.clear();
109     UsingBlocks.clear();
110     OnlyStore = nullptr;
111     OnlyBlock = nullptr;
112     OnlyUsedInOneBlock = true;
113     AllocaPointerVal = nullptr;
114     DbgDeclare = nullptr;
115   }
116
117   /// Scan the uses of the specified alloca, filling in the AllocaInfo used
118   /// by the rest of the pass to reason about the uses of this alloca.
119   void AnalyzeAlloca(AllocaInst *AI) {
120     clear();
121
122     // As we scan the uses of the alloca instruction, keep track of stores,
123     // and decide whether all of the loads and stores to the alloca are within
124     // the same basic block.
125     for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
126       Instruction *User = cast<Instruction>(*UI++);
127
128       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
129         // Remember the basic blocks which define new values for the alloca
130         DefiningBlocks.push_back(SI->getParent());
131         AllocaPointerVal = SI->getOperand(0);
132         OnlyStore = SI;
133       } else {
134         LoadInst *LI = cast<LoadInst>(User);
135         // Otherwise it must be a load instruction, keep track of variable
136         // reads.
137         UsingBlocks.push_back(LI->getParent());
138         AllocaPointerVal = LI;
139       }
140
141       if (OnlyUsedInOneBlock) {
142         if (!OnlyBlock)
143           OnlyBlock = User->getParent();
144         else if (OnlyBlock != User->getParent())
145           OnlyUsedInOneBlock = false;
146       }
147     }
148
149     DbgDeclare = FindAllocaDbgDeclare(AI);
150   }
151 };
152
153 // Data package used by RenamePass()
154 class RenamePassData {
155 public:
156   typedef std::vector<Value *> ValVector;
157
158   RenamePassData() : BB(nullptr), Pred(nullptr), Values() {}
159   RenamePassData(BasicBlock *B, BasicBlock *P, const ValVector &V)
160       : BB(B), Pred(P), Values(V) {}
161   BasicBlock *BB;
162   BasicBlock *Pred;
163   ValVector Values;
164
165   void swap(RenamePassData &RHS) {
166     std::swap(BB, RHS.BB);
167     std::swap(Pred, RHS.Pred);
168     Values.swap(RHS.Values);
169   }
170 };
171
172 /// \brief This assigns and keeps a per-bb relative ordering of load/store
173 /// instructions in the block that directly load or store an alloca.
174 ///
175 /// This functionality is important because it avoids scanning large basic
176 /// blocks multiple times when promoting many allocas in the same block.
177 class LargeBlockInfo {
178   /// \brief For each instruction that we track, keep the index of the
179   /// instruction.
180   ///
181   /// The index starts out as the number of the instruction from the start of
182   /// the block.
183   DenseMap<const Instruction *, unsigned> InstNumbers;
184
185 public:
186
187   /// This code only looks at accesses to allocas.
188   static bool isInterestingInstruction(const Instruction *I) {
189     return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
190            (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
191   }
192
193   /// Get or calculate the index of the specified instruction.
194   unsigned getInstructionIndex(const Instruction *I) {
195     assert(isInterestingInstruction(I) &&
196            "Not a load/store to/from an alloca?");
197
198     // If we already have this instruction number, return it.
199     DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
200     if (It != InstNumbers.end())
201       return It->second;
202
203     // Scan the whole block to get the instruction.  This accumulates
204     // information for every interesting instruction in the block, in order to
205     // avoid gratuitus rescans.
206     const BasicBlock *BB = I->getParent();
207     unsigned InstNo = 0;
208     for (const Instruction &BBI : *BB)
209       if (isInterestingInstruction(&BBI))
210         InstNumbers[&BBI] = InstNo++;
211     It = InstNumbers.find(I);
212
213     assert(It != InstNumbers.end() && "Didn't insert instruction?");
214     return It->second;
215   }
216
217   void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
218
219   void clear() { InstNumbers.clear(); }
220 };
221
222 struct PromoteMem2Reg {
223   /// The alloca instructions being promoted.
224   std::vector<AllocaInst *> Allocas;
225   DominatorTree &DT;
226   DIBuilder DIB;
227
228   /// An AliasSetTracker object to update.  If null, don't update it.
229   AliasSetTracker *AST;
230
231   /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
232   AssumptionCache *AC;
233
234   /// Reverse mapping of Allocas.
235   DenseMap<AllocaInst *, unsigned> AllocaLookup;
236
237   /// \brief The PhiNodes we're adding.
238   ///
239   /// That map is used to simplify some Phi nodes as we iterate over it, so
240   /// it should have deterministic iterators.  We could use a MapVector, but
241   /// since we already maintain a map from BasicBlock* to a stable numbering
242   /// (BBNumbers), the DenseMap is more efficient (also supports removal).
243   DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
244
245   /// For each PHI node, keep track of which entry in Allocas it corresponds
246   /// to.
247   DenseMap<PHINode *, unsigned> PhiToAllocaMap;
248
249   /// If we are updating an AliasSetTracker, then for each alloca that is of
250   /// pointer type, we keep track of what to copyValue to the inserted PHI
251   /// nodes here.
252   std::vector<Value *> PointerAllocaValues;
253
254   /// For each alloca, we keep track of the dbg.declare intrinsic that
255   /// describes it, if any, so that we can convert it to a dbg.value
256   /// intrinsic if the alloca gets promoted.
257   SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares;
258
259   /// The set of basic blocks the renamer has already visited.
260   ///
261   SmallPtrSet<BasicBlock *, 16> Visited;
262
263   /// Contains a stable numbering of basic blocks to avoid non-determinstic
264   /// behavior.
265   DenseMap<BasicBlock *, unsigned> BBNumbers;
266
267   /// Lazily compute the number of predecessors a block has.
268   DenseMap<const BasicBlock *, unsigned> BBNumPreds;
269
270 public:
271   PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
272                  AliasSetTracker *AST, AssumptionCache *AC)
273       : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
274         DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
275         AST(AST), AC(AC) {}
276
277   void run();
278
279 private:
280   void RemoveFromAllocasList(unsigned &AllocaIdx) {
281     Allocas[AllocaIdx] = Allocas.back();
282     Allocas.pop_back();
283     --AllocaIdx;
284   }
285
286   unsigned getNumPreds(const BasicBlock *BB) {
287     unsigned &NP = BBNumPreds[BB];
288     if (NP == 0)
289       NP = std::distance(pred_begin(BB), pred_end(BB)) + 1;
290     return NP - 1;
291   }
292
293   void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
294                            const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
295                            SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
296   void RenamePass(BasicBlock *BB, BasicBlock *Pred,
297                   RenamePassData::ValVector &IncVals,
298                   std::vector<RenamePassData> &Worklist);
299   bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
300 };
301
302 } // end of anonymous namespace
303
304 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) {
305   // Knowing that this alloca is promotable, we know that it's safe to kill all
306   // instructions except for load and store.
307
308   for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) {
309     Instruction *I = cast<Instruction>(*UI);
310     ++UI;
311     if (isa<LoadInst>(I) || isa<StoreInst>(I))
312       continue;
313
314     if (!I->getType()->isVoidTy()) {
315       // The only users of this bitcast/GEP instruction are lifetime intrinsics.
316       // Follow the use/def chain to erase them now instead of leaving it for
317       // dead code elimination later.
318       for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) {
319         Instruction *Inst = cast<Instruction>(*UUI);
320         ++UUI;
321         Inst->eraseFromParent();
322       }
323     }
324     I->eraseFromParent();
325   }
326 }
327
328 /// \brief Rewrite as many loads as possible given a single store.
329 ///
330 /// When there is only a single store, we can use the domtree to trivially
331 /// replace all of the dominated loads with the stored value. Do so, and return
332 /// true if this has successfully promoted the alloca entirely. If this returns
333 /// false there were some loads which were not dominated by the single store
334 /// and thus must be phi-ed with undef. We fall back to the standard alloca
335 /// promotion algorithm in that case.
336 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
337                                      LargeBlockInfo &LBI,
338                                      DominatorTree &DT,
339                                      AliasSetTracker *AST) {
340   StoreInst *OnlyStore = Info.OnlyStore;
341   bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
342   BasicBlock *StoreBB = OnlyStore->getParent();
343   int StoreIndex = -1;
344
345   // Clear out UsingBlocks.  We will reconstruct it here if needed.
346   Info.UsingBlocks.clear();
347
348   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
349     Instruction *UserInst = cast<Instruction>(*UI++);
350     if (!isa<LoadInst>(UserInst)) {
351       assert(UserInst == OnlyStore && "Should only have load/stores");
352       continue;
353     }
354     LoadInst *LI = cast<LoadInst>(UserInst);
355
356     // Okay, if we have a load from the alloca, we want to replace it with the
357     // only value stored to the alloca.  We can do this if the value is
358     // dominated by the store.  If not, we use the rest of the mem2reg machinery
359     // to insert the phi nodes as needed.
360     if (!StoringGlobalVal) { // Non-instructions are always dominated.
361       if (LI->getParent() == StoreBB) {
362         // If we have a use that is in the same block as the store, compare the
363         // indices of the two instructions to see which one came first.  If the
364         // load came before the store, we can't handle it.
365         if (StoreIndex == -1)
366           StoreIndex = LBI.getInstructionIndex(OnlyStore);
367
368         if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
369           // Can't handle this load, bail out.
370           Info.UsingBlocks.push_back(StoreBB);
371           continue;
372         }
373
374       } else if (LI->getParent() != StoreBB &&
375                  !DT.dominates(StoreBB, LI->getParent())) {
376         // If the load and store are in different blocks, use BB dominance to
377         // check their relationships.  If the store doesn't dom the use, bail
378         // out.
379         Info.UsingBlocks.push_back(LI->getParent());
380         continue;
381       }
382     }
383
384     // Otherwise, we *can* safely rewrite this load.
385     Value *ReplVal = OnlyStore->getOperand(0);
386     // If the replacement value is the load, this must occur in unreachable
387     // code.
388     if (ReplVal == LI)
389       ReplVal = UndefValue::get(LI->getType());
390     LI->replaceAllUsesWith(ReplVal);
391     if (AST && LI->getType()->isPointerTy())
392       AST->deleteValue(LI);
393     LI->eraseFromParent();
394     LBI.deleteValue(LI);
395   }
396
397   // Finally, after the scan, check to see if the store is all that is left.
398   if (!Info.UsingBlocks.empty())
399     return false; // If not, we'll have to fall back for the remainder.
400
401   // Record debuginfo for the store and remove the declaration's
402   // debuginfo.
403   if (DbgDeclareInst *DDI = Info.DbgDeclare) {
404     DIBuilder DIB(*AI->getParent()->getParent()->getParent(),
405                   /*AllowUnresolved*/ false);
406     ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB);
407     DDI->eraseFromParent();
408     LBI.deleteValue(DDI);
409   }
410   // Remove the (now dead) store and alloca.
411   Info.OnlyStore->eraseFromParent();
412   LBI.deleteValue(Info.OnlyStore);
413
414   if (AST)
415     AST->deleteValue(AI);
416   AI->eraseFromParent();
417   LBI.deleteValue(AI);
418   return true;
419 }
420
421 /// Many allocas are only used within a single basic block.  If this is the
422 /// case, avoid traversing the CFG and inserting a lot of potentially useless
423 /// PHI nodes by just performing a single linear pass over the basic block
424 /// using the Alloca.
425 ///
426 /// If we cannot promote this alloca (because it is read before it is written),
427 /// return false.  This is necessary in cases where, due to control flow, the
428 /// alloca is undefined only on some control flow paths.  e.g. code like
429 /// this is correct in LLVM IR:
430 ///  // A is an alloca with no stores so far
431 ///  for (...) {
432 ///    int t = *A;
433 ///    if (!first_iteration)
434 ///      use(t);
435 ///    *A = 42;
436 ///  }
437 static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
438                                      LargeBlockInfo &LBI,
439                                      AliasSetTracker *AST) {
440   // The trickiest case to handle is when we have large blocks. Because of this,
441   // this code is optimized assuming that large blocks happen.  This does not
442   // significantly pessimize the small block case.  This uses LargeBlockInfo to
443   // make it efficient to get the index of various operations in the block.
444
445   // Walk the use-def list of the alloca, getting the locations of all stores.
446   typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
447   StoresByIndexTy StoresByIndex;
448
449   for (User *U : AI->users())
450     if (StoreInst *SI = dyn_cast<StoreInst>(U))
451       StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
452
453   // Sort the stores by their index, making it efficient to do a lookup with a
454   // binary search.
455   std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
456
457   // Walk all of the loads from this alloca, replacing them with the nearest
458   // store above them, if any.
459   for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
460     LoadInst *LI = dyn_cast<LoadInst>(*UI++);
461     if (!LI)
462       continue;
463
464     unsigned LoadIdx = LBI.getInstructionIndex(LI);
465
466     // Find the nearest store that has a lower index than this load.
467     StoresByIndexTy::iterator I =
468         std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
469                          std::make_pair(LoadIdx,
470                                         static_cast<StoreInst *>(nullptr)),
471                          less_first());
472     if (I == StoresByIndex.begin()) {
473       if (StoresByIndex.empty())
474         // If there are no stores, the load takes the undef value.
475         LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
476       else
477         // There is no store before this load, bail out (load may be affected
478         // by the following stores - see main comment).
479         return false;
480     }
481     else
482       // Otherwise, there was a store before this load, the load takes its value.
483       LI->replaceAllUsesWith(std::prev(I)->second->getOperand(0));
484
485     if (AST && LI->getType()->isPointerTy())
486       AST->deleteValue(LI);
487     LI->eraseFromParent();
488     LBI.deleteValue(LI);
489   }
490
491   // Remove the (now dead) stores and alloca.
492   while (!AI->use_empty()) {
493     StoreInst *SI = cast<StoreInst>(AI->user_back());
494     // Record debuginfo for the store before removing it.
495     if (DbgDeclareInst *DDI = Info.DbgDeclare) {
496       DIBuilder DIB(*AI->getParent()->getParent()->getParent(),
497                     /*AllowUnresolved*/ false);
498       ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
499     }
500     SI->eraseFromParent();
501     LBI.deleteValue(SI);
502   }
503
504   if (AST)
505     AST->deleteValue(AI);
506   AI->eraseFromParent();
507   LBI.deleteValue(AI);
508
509   // The alloca's debuginfo can be removed as well.
510   if (DbgDeclareInst *DDI = Info.DbgDeclare) {
511     DDI->eraseFromParent();
512     LBI.deleteValue(DDI);
513   }
514
515   ++NumLocalPromoted;
516   return true;
517 }
518
519 void PromoteMem2Reg::run() {
520   Function &F = *DT.getRoot()->getParent();
521
522   if (AST)
523     PointerAllocaValues.resize(Allocas.size());
524   AllocaDbgDeclares.resize(Allocas.size());
525
526   AllocaInfo Info;
527   LargeBlockInfo LBI;
528   IDFCalculator IDF(DT);
529
530   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
531     AllocaInst *AI = Allocas[AllocaNum];
532
533     assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
534     assert(AI->getParent()->getParent() == &F &&
535            "All allocas should be in the same function, which is same as DF!");
536
537     removeLifetimeIntrinsicUsers(AI);
538
539     if (AI->use_empty()) {
540       // If there are no uses of the alloca, just delete it now.
541       if (AST)
542         AST->deleteValue(AI);
543       AI->eraseFromParent();
544
545       // Remove the alloca from the Allocas list, since it has been processed
546       RemoveFromAllocasList(AllocaNum);
547       ++NumDeadAlloca;
548       continue;
549     }
550
551     // Calculate the set of read and write-locations for each alloca.  This is
552     // analogous to finding the 'uses' and 'definitions' of each variable.
553     Info.AnalyzeAlloca(AI);
554
555     // If there is only a single store to this value, replace any loads of
556     // it that are directly dominated by the definition with the value stored.
557     if (Info.DefiningBlocks.size() == 1) {
558       if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
559         // The alloca has been processed, move on.
560         RemoveFromAllocasList(AllocaNum);
561         ++NumSingleStore;
562         continue;
563       }
564     }
565
566     // If the alloca is only read and written in one basic block, just perform a
567     // linear sweep over the block to eliminate it.
568     if (Info.OnlyUsedInOneBlock &&
569         promoteSingleBlockAlloca(AI, Info, LBI, AST)) {
570       // The alloca has been processed, move on.
571       RemoveFromAllocasList(AllocaNum);
572       continue;
573     }
574
575     // If we haven't computed a numbering for the BB's in the function, do so
576     // now.
577     if (BBNumbers.empty()) {
578       unsigned ID = 0;
579       for (auto &BB : F)
580         BBNumbers[&BB] = ID++;
581     }
582
583     // If we have an AST to keep updated, remember some pointer value that is
584     // stored into the alloca.
585     if (AST)
586       PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
587
588     // Remember the dbg.declare intrinsic describing this alloca, if any.
589     if (Info.DbgDeclare)
590       AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
591
592     // Keep the reverse mapping of the 'Allocas' array for the rename pass.
593     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
594
595     // At this point, we're committed to promoting the alloca using IDF's, and
596     // the standard SSA construction algorithm.  Determine which blocks need PHI
597     // nodes and see if we can optimize out some work by avoiding insertion of
598     // dead phi nodes.
599
600
601     // Unique the set of defining blocks for efficient lookup.
602     SmallPtrSet<BasicBlock *, 32> DefBlocks;
603     DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
604
605     // Determine which blocks the value is live in.  These are blocks which lead
606     // to uses.
607     SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
608     ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
609
610     // At this point, we're committed to promoting the alloca using IDF's, and
611     // the standard SSA construction algorithm.  Determine which blocks need phi
612     // nodes and see if we can optimize out some work by avoiding insertion of
613     // dead phi nodes.
614     IDF.setLiveInBlocks(LiveInBlocks);
615     IDF.setDefiningBlocks(DefBlocks);
616     SmallVector<BasicBlock *, 32> PHIBlocks;
617     IDF.calculate(PHIBlocks);
618     if (PHIBlocks.size() > 1)
619       std::sort(PHIBlocks.begin(), PHIBlocks.end(),
620                 [this](BasicBlock *A, BasicBlock *B) {
621                   return BBNumbers.lookup(A) < BBNumbers.lookup(B);
622                 });
623
624     unsigned CurrentVersion = 0;
625     for (unsigned i = 0, e = PHIBlocks.size(); i != e; ++i)
626       QueuePhiNode(PHIBlocks[i], AllocaNum, CurrentVersion);
627   }
628
629   if (Allocas.empty())
630     return; // All of the allocas must have been trivial!
631
632   LBI.clear();
633
634   // Set the incoming values for the basic block to be null values for all of
635   // the alloca's.  We do this in case there is a load of a value that has not
636   // been stored yet.  In this case, it will get this null value.
637   //
638   RenamePassData::ValVector Values(Allocas.size());
639   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
640     Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
641
642   // Walks all basic blocks in the function performing the SSA rename algorithm
643   // and inserting the phi nodes we marked as necessary
644   //
645   std::vector<RenamePassData> RenamePassWorkList;
646   RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values));
647   do {
648     RenamePassData RPD;
649     RPD.swap(RenamePassWorkList.back());
650     RenamePassWorkList.pop_back();
651     // RenamePass may add new worklist entries.
652     RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
653   } while (!RenamePassWorkList.empty());
654
655   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
656   Visited.clear();
657
658   // Remove the allocas themselves from the function.
659   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
660     Instruction *A = Allocas[i];
661
662     // If there are any uses of the alloca instructions left, they must be in
663     // unreachable basic blocks that were not processed by walking the dominator
664     // tree. Just delete the users now.
665     if (!A->use_empty())
666       A->replaceAllUsesWith(UndefValue::get(A->getType()));
667     if (AST)
668       AST->deleteValue(A);
669     A->eraseFromParent();
670   }
671
672   const DataLayout &DL = F.getParent()->getDataLayout();
673
674   // Remove alloca's dbg.declare instrinsics from the function.
675   for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
676     if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
677       DDI->eraseFromParent();
678
679   // Loop over all of the PHI nodes and see if there are any that we can get
680   // rid of because they merge all of the same incoming values.  This can
681   // happen due to undef values coming into the PHI nodes.  This process is
682   // iterative, because eliminating one PHI node can cause others to be removed.
683   bool EliminatedAPHI = true;
684   while (EliminatedAPHI) {
685     EliminatedAPHI = false;
686
687     // Iterating over NewPhiNodes is deterministic, so it is safe to try to
688     // simplify and RAUW them as we go.  If it was not, we could add uses to
689     // the values we replace with in a non-deterministic order, thus creating
690     // non-deterministic def->use chains.
691     for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
692              I = NewPhiNodes.begin(),
693              E = NewPhiNodes.end();
694          I != E;) {
695       PHINode *PN = I->second;
696
697       // If this PHI node merges one value and/or undefs, get the value.
698       if (Value *V = SimplifyInstruction(PN, DL, nullptr, &DT, AC)) {
699         if (AST && PN->getType()->isPointerTy())
700           AST->deleteValue(PN);
701         PN->replaceAllUsesWith(V);
702         PN->eraseFromParent();
703         NewPhiNodes.erase(I++);
704         EliminatedAPHI = true;
705         continue;
706       }
707       ++I;
708     }
709   }
710
711   // At this point, the renamer has added entries to PHI nodes for all reachable
712   // code.  Unfortunately, there may be unreachable blocks which the renamer
713   // hasn't traversed.  If this is the case, the PHI nodes may not
714   // have incoming values for all predecessors.  Loop over all PHI nodes we have
715   // created, inserting undef values if they are missing any incoming values.
716   //
717   for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
718            I = NewPhiNodes.begin(),
719            E = NewPhiNodes.end();
720        I != E; ++I) {
721     // We want to do this once per basic block.  As such, only process a block
722     // when we find the PHI that is the first entry in the block.
723     PHINode *SomePHI = I->second;
724     BasicBlock *BB = SomePHI->getParent();
725     if (&BB->front() != SomePHI)
726       continue;
727
728     // Only do work here if there the PHI nodes are missing incoming values.  We
729     // know that all PHI nodes that were inserted in a block will have the same
730     // number of incoming values, so we can just check any of them.
731     if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
732       continue;
733
734     // Get the preds for BB.
735     SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
736
737     // Ok, now we know that all of the PHI nodes are missing entries for some
738     // basic blocks.  Start by sorting the incoming predecessors for efficient
739     // access.
740     std::sort(Preds.begin(), Preds.end());
741
742     // Now we loop through all BB's which have entries in SomePHI and remove
743     // them from the Preds list.
744     for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
745       // Do a log(n) search of the Preds list for the entry we want.
746       SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
747           Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
748       assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
749              "PHI node has entry for a block which is not a predecessor!");
750
751       // Remove the entry
752       Preds.erase(EntIt);
753     }
754
755     // At this point, the blocks left in the preds list must have dummy
756     // entries inserted into every PHI nodes for the block.  Update all the phi
757     // nodes in this block that we are inserting (there could be phis before
758     // mem2reg runs).
759     unsigned NumBadPreds = SomePHI->getNumIncomingValues();
760     BasicBlock::iterator BBI = BB->begin();
761     while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
762            SomePHI->getNumIncomingValues() == NumBadPreds) {
763       Value *UndefVal = UndefValue::get(SomePHI->getType());
764       for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
765         SomePHI->addIncoming(UndefVal, Preds[pred]);
766     }
767   }
768
769   NewPhiNodes.clear();
770 }
771
772 /// \brief Determine which blocks the value is live in.
773 ///
774 /// These are blocks which lead to uses.  Knowing this allows us to avoid
775 /// inserting PHI nodes into blocks which don't lead to uses (thus, the
776 /// inserted phi nodes would be dead).
777 void PromoteMem2Reg::ComputeLiveInBlocks(
778     AllocaInst *AI, AllocaInfo &Info,
779     const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
780     SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
781
782   // To determine liveness, we must iterate through the predecessors of blocks
783   // where the def is live.  Blocks are added to the worklist if we need to
784   // check their predecessors.  Start with all the using blocks.
785   SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
786                                                     Info.UsingBlocks.end());
787
788   // If any of the using blocks is also a definition block, check to see if the
789   // definition occurs before or after the use.  If it happens before the use,
790   // the value isn't really live-in.
791   for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
792     BasicBlock *BB = LiveInBlockWorklist[i];
793     if (!DefBlocks.count(BB))
794       continue;
795
796     // Okay, this is a block that both uses and defines the value.  If the first
797     // reference to the alloca is a def (store), then we know it isn't live-in.
798     for (BasicBlock::iterator I = BB->begin();; ++I) {
799       if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
800         if (SI->getOperand(1) != AI)
801           continue;
802
803         // We found a store to the alloca before a load.  The alloca is not
804         // actually live-in here.
805         LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
806         LiveInBlockWorklist.pop_back();
807         --i, --e;
808         break;
809       }
810
811       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
812         if (LI->getOperand(0) != AI)
813           continue;
814
815         // Okay, we found a load before a store to the alloca.  It is actually
816         // live into this block.
817         break;
818       }
819     }
820   }
821
822   // Now that we have a set of blocks where the phi is live-in, recursively add
823   // their predecessors until we find the full region the value is live.
824   while (!LiveInBlockWorklist.empty()) {
825     BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
826
827     // The block really is live in here, insert it into the set.  If already in
828     // the set, then it has already been processed.
829     if (!LiveInBlocks.insert(BB).second)
830       continue;
831
832     // Since the value is live into BB, it is either defined in a predecessor or
833     // live into it to.  Add the preds to the worklist unless they are a
834     // defining block.
835     for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
836       BasicBlock *P = *PI;
837
838       // The value is not live into a predecessor if it defines the value.
839       if (DefBlocks.count(P))
840         continue;
841
842       // Otherwise it is, add to the worklist.
843       LiveInBlockWorklist.push_back(P);
844     }
845   }
846 }
847
848 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
849 ///
850 /// Returns true if there wasn't already a phi-node for that variable
851 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
852                                   unsigned &Version) {
853   // Look up the basic-block in question.
854   PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
855
856   // If the BB already has a phi node added for the i'th alloca then we're done!
857   if (PN)
858     return false;
859
860   // Create a PhiNode using the dereferenced type... and add the phi-node to the
861   // BasicBlock.
862   PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
863                        Allocas[AllocaNo]->getName() + "." + Twine(Version++),
864                        &BB->front());
865   ++NumPHIInsert;
866   PhiToAllocaMap[PN] = AllocaNo;
867
868   if (AST && PN->getType()->isPointerTy())
869     AST->copyValue(PointerAllocaValues[AllocaNo], PN);
870
871   return true;
872 }
873
874 /// \brief Recursively traverse the CFG of the function, renaming loads and
875 /// stores to the allocas which we are promoting.
876 ///
877 /// IncomingVals indicates what value each Alloca contains on exit from the
878 /// predecessor block Pred.
879 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
880                                 RenamePassData::ValVector &IncomingVals,
881                                 std::vector<RenamePassData> &Worklist) {
882 NextIteration:
883   // If we are inserting any phi nodes into this BB, they will already be in the
884   // block.
885   if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
886     // If we have PHI nodes to update, compute the number of edges from Pred to
887     // BB.
888     if (PhiToAllocaMap.count(APN)) {
889       // We want to be able to distinguish between PHI nodes being inserted by
890       // this invocation of mem2reg from those phi nodes that already existed in
891       // the IR before mem2reg was run.  We determine that APN is being inserted
892       // because it is missing incoming edges.  All other PHI nodes being
893       // inserted by this pass of mem2reg will have the same number of incoming
894       // operands so far.  Remember this count.
895       unsigned NewPHINumOperands = APN->getNumOperands();
896
897       unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
898       assert(NumEdges && "Must be at least one edge from Pred to BB!");
899
900       // Add entries for all the phis.
901       BasicBlock::iterator PNI = BB->begin();
902       do {
903         unsigned AllocaNo = PhiToAllocaMap[APN];
904
905         // Add N incoming values to the PHI node.
906         for (unsigned i = 0; i != NumEdges; ++i)
907           APN->addIncoming(IncomingVals[AllocaNo], Pred);
908
909         // The currently active variable for this block is now the PHI.
910         IncomingVals[AllocaNo] = APN;
911
912         // Get the next phi node.
913         ++PNI;
914         APN = dyn_cast<PHINode>(PNI);
915         if (!APN)
916           break;
917
918         // Verify that it is missing entries.  If not, it is not being inserted
919         // by this mem2reg invocation so we want to ignore it.
920       } while (APN->getNumOperands() == NewPHINumOperands);
921     }
922   }
923
924   // Don't revisit blocks.
925   if (!Visited.insert(BB).second)
926     return;
927
928   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
929     Instruction *I = &*II++; // get the instruction, increment iterator
930
931     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
932       AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
933       if (!Src)
934         continue;
935
936       DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
937       if (AI == AllocaLookup.end())
938         continue;
939
940       Value *V = IncomingVals[AI->second];
941
942       // Anything using the load now uses the current value.
943       LI->replaceAllUsesWith(V);
944       if (AST && LI->getType()->isPointerTy())
945         AST->deleteValue(LI);
946       BB->getInstList().erase(LI);
947     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
948       // Delete this instruction and mark the name as the current holder of the
949       // value
950       AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
951       if (!Dest)
952         continue;
953
954       DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
955       if (ai == AllocaLookup.end())
956         continue;
957
958       // what value were we writing?
959       IncomingVals[ai->second] = SI->getOperand(0);
960       // Record debuginfo for the store before removing it.
961       if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
962         ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
963       BB->getInstList().erase(SI);
964     }
965   }
966
967   // 'Recurse' to our successors.
968   succ_iterator I = succ_begin(BB), E = succ_end(BB);
969   if (I == E)
970     return;
971
972   // Keep track of the successors so we don't visit the same successor twice
973   SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
974
975   // Handle the first successor without using the worklist.
976   VisitedSuccs.insert(*I);
977   Pred = BB;
978   BB = *I;
979   ++I;
980
981   for (; I != E; ++I)
982     if (VisitedSuccs.insert(*I).second)
983       Worklist.emplace_back(*I, Pred, IncomingVals);
984
985   goto NextIteration;
986 }
987
988 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
989                            AliasSetTracker *AST, AssumptionCache *AC) {
990   // If there is nothing to do, bail out...
991   if (Allocas.empty())
992     return;
993
994   PromoteMem2Reg(Allocas, DT, AST, AC).run();
995 }