1 //===- DemoteRegToStack.cpp - Move a virtual reg. to stack ------*- C++ -*-===//
3 // This file provide the function DemoteRegToStack().
4 // This function takes a virtual register computed by an
5 // Instruction& X and replaces it with a slot in the stack frame,
6 // allocated via alloca. It returns the pointer to the AllocaInst inserted.
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/Utils/DemoteRegToStack.h"
10 #include "llvm/Function.h"
11 #include "llvm/BasicBlock.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iPHINode.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/Type.h"
16 #include "Support/hash_set"
20 //----------------------------------------------------------------------------
21 // function DemoteRegToStack()
23 //----------------------------------------------------------------------------
25 typedef hash_set<PHINode*> PhiSet;
26 typedef hash_set<PHINode*>::iterator PhiSetIterator;
28 // Helper function to push a phi *and* all its operands to the worklist!
29 // Do not push an instruction if it is already in the result set of Phis to go.
30 inline void PushOperandsOnWorkList(std::stack<Instruction*>& workList,
31 PhiSet& phisToGo, PHINode* phiN)
33 for (User::op_iterator OI=phiN->op_begin(), OE=phiN->op_end();
35 if (Instruction* opI = dyn_cast<Instruction>(OI->get()))
36 if (!isa<PHINode>(opI) ||
37 phisToGo.find(cast<PHINode>(opI)) == phisToGo.end())
41 void FindPhis(Instruction& X, PhiSet& phisToGo)
43 std::stack<Instruction*> workList;
46 // Handle the case that X itself is a Phi!
47 if (PHINode* phiX = dyn_cast<PHINode>(&X))
49 phisToGo.insert(phiX);
50 PushOperandsOnWorkList(workList, phisToGo, phiX);
53 // Now use a worklist to find all phis reachable from X, and
54 // (recursively) all phis reachable from operands of such phis.
55 for (Instruction* workI; !workList.empty(); workList.pop())
57 workI = workList.top();
58 for (Value::use_iterator UI=workI->use_begin(), UE=workI->use_end();
60 if (PHINode* phiN = dyn_cast<PHINode>(*UI))
61 if (phisToGo.find(phiN) == phisToGo.end())
62 { // Seeing this phi for the first time: it must go!
63 phisToGo.insert(phiN);
65 PushOperandsOnWorkList(workList, phisToGo, phiN);
71 // Create the Alloca for X
72 AllocaInst* CreateAllocaForX(Instruction& X)
74 Function* parentFunc = X.getParent()->getParent();
75 Instruction* entryInst = parentFunc->getEntryNode().begin();
76 return new AllocaInst(X.getType(), /*arraySize*/ NULL,
77 X.hasName()? X.getName()+std::string("OnStack")
82 // Insert loads before all uses of I, except uses in Phis
83 // since all such Phis *must* be deleted.
84 void LoadBeforeUses(Instruction* def, AllocaInst* XSlot)
86 for (unsigned nPhis = 0; def->use_size() - nPhis > 0; )
88 Instruction* useI = cast<Instruction>(def->use_back());
89 if (!isa<PHINode>(useI))
92 new LoadInst(XSlot, std::string("Load")+XSlot->getName(), useI);
93 useI->replaceUsesOfWith(def, loadI);
100 void AddLoadsAndStores(AllocaInst* XSlot, Instruction& X, PhiSet& phisToGo)
102 for (PhiSetIterator PI=phisToGo.begin(), PE=phisToGo.end(); PI != PE; ++PI)
106 // First, insert loads before all uses except uses in Phis.
107 // Do this first because new stores will appear as uses also!
108 LoadBeforeUses(pn, XSlot);
110 // For every incoming operand of the Phi, insert a store either
111 // just after the instruction defining the value or just before the
112 // predecessor of the Phi if the value is a formal, not an instruction.
114 for (unsigned i=0, N=pn->getNumIncomingValues(); i < N; ++i)
116 Value* phiOp = pn->getIncomingValue(i);
118 (!isa<PHINode>(phiOp) ||
119 phisToGo.find(cast<PHINode>(phiOp)) == phisToGo.end()))
120 { // This operand is not a phi that will be deleted: need to store.
121 assert(!isa<TerminatorInst>(phiOp));
123 Instruction* storeBefore;
124 if (Instruction* I = dyn_cast<Instruction>(phiOp))
125 { // phiOp is an instruction, store its result right after it.
126 assert(I->getNext() && "Non-terminator without successor?");
127 storeBefore = I->getNext();
130 { // If not, it must be a formal: store it at the end of the
131 // predecessor block of the Phi (*not* at function entry!).
132 storeBefore = pn->getIncomingBlock(i)->getTerminator();
135 // Create instr. to store the value of phiOp before `insertBefore'
136 StoreInst* storeI = new StoreInst(phiOp, XSlot, storeBefore);
142 void DeletePhis(PhiSet& phisToGo)
144 for (PhiSetIterator PI=phisToGo.begin(), PE=phisToGo.end(); PI != PE; ++PI)
146 assert((*PI)->use_size() == 0 && "This PHI should be DEAD!");
147 (*PI)->getParent()->getInstList().remove(*PI);
153 //----------------------------------------------------------------------------
154 // function DemoteRegToStack()
156 // This function takes a virtual register computed by an
157 // Instruction& X and replaces it with a slot in the stack frame,
158 // allocated via alloca. It has to:
159 // (1) Identify all Phi operations that have X as an operand and
160 // transitively other Phis that use such Phis;
161 // (2) Store all values merged with X via Phi operations to the stack slot;
162 // (3) Load the value from the stack slot just before any use of X or any
163 // of the Phis that were eliminated; and
164 // (4) Delete all the Phis, which should all now be dead.
166 // Returns the pointer to the alloca inserted to create a stack slot for X.
167 //----------------------------------------------------------------------------
169 AllocaInst* DemoteRegToStack(Instruction& X)
171 if (X.getType() == Type::VoidTy)
172 return NULL; // nothing to do!
174 // Find all Phis involving X or recursively using such Phis or Phis
175 // involving operands of such Phis (essentially all Phis in the "web" of X)
177 FindPhis(X, phisToGo);
179 // Create a stack slot to hold X
180 AllocaInst* XSlot = CreateAllocaForX(X);
182 // Insert loads before all uses of X and (*only then*) insert store after X
183 assert(X.getNext() && "Non-terminator (since non-void) with no successor?");
184 LoadBeforeUses(&X, XSlot);
185 StoreInst* storeI = new StoreInst(&X, XSlot, X.getNext());
187 // Do the same for all the phis that will be deleted
188 AddLoadsAndStores(XSlot, X, phisToGo);
190 // Delete the phis and return the alloca instruction
191 DeletePhis(phisToGo);