xref: /llvm-project/llvm/lib/Transforms/Utils/DemoteRegToStack.cpp (revision 5dd566b7c7b78bd385418c72d63c79895be9ae97)
1 //===- DemoteRegToStack.cpp - Move a virtual register to the stack --------===//
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 #include "llvm/ADT/DenseMap.h"
10 #include "llvm/Analysis/CFG.h"
11 #include "llvm/IR/Function.h"
12 #include "llvm/IR/Instructions.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/IR/Type.h"
15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16 #include "llvm/Transforms/Utils/Local.h"
17 
18 using namespace llvm;
19 
20 /// DemoteRegToStack - This function takes a virtual register computed by an
21 /// Instruction and replaces it with a slot in the stack frame, allocated via
22 /// alloca.  This allows the CFG to be changed around without fear of
23 /// invalidating the SSA information for the value.  It returns the pointer to
24 /// the alloca inserted to create a stack slot for I.
25 AllocaInst *llvm::DemoteRegToStack(Instruction &I, bool VolatileLoads,
26                                    Instruction *AllocaPoint) {
27   if (I.use_empty()) {
28     I.eraseFromParent();
29     return nullptr;
30   }
31 
32   Function *F = I.getParent()->getParent();
33   const DataLayout &DL = F->getParent()->getDataLayout();
34 
35   // Create a stack slot to hold the value.
36   AllocaInst *Slot;
37   if (AllocaPoint) {
38     Slot = new AllocaInst(I.getType(), DL.getAllocaAddrSpace(), nullptr,
39                           I.getName()+".reg2mem", AllocaPoint);
40   } else {
41     Slot = new AllocaInst(I.getType(), DL.getAllocaAddrSpace(), nullptr,
42                           I.getName() + ".reg2mem", &F->getEntryBlock().front());
43   }
44 
45   // We cannot demote invoke instructions to the stack if their normal edge
46   // is critical. Therefore, split the critical edge and create a basic block
47   // into which the store can be inserted.
48   if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
49     if (!II->getNormalDest()->getSinglePredecessor()) {
50       unsigned SuccNum = GetSuccessorNumber(II->getParent(), II->getNormalDest());
51       assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
52       BasicBlock *BB = SplitCriticalEdge(II, SuccNum);
53       assert(BB && "Unable to split critical edge.");
54       (void)BB;
55     }
56   }
57 
58   // Change all of the users of the instruction to read from the stack slot.
59   while (!I.use_empty()) {
60     Instruction *U = cast<Instruction>(I.user_back());
61     if (PHINode *PN = dyn_cast<PHINode>(U)) {
62       // If this is a PHI node, we can't insert a load of the value before the
63       // use.  Instead insert the load in the predecessor block corresponding
64       // to the incoming value.
65       //
66       // Note that if there are multiple edges from a basic block to this PHI
67       // node that we cannot have multiple loads. The problem is that the
68       // resulting PHI node will have multiple values (from each load) coming in
69       // from the same block, which is illegal SSA form. For this reason, we
70       // keep track of and reuse loads we insert.
71       DenseMap<BasicBlock*, Value*> Loads;
72       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
73         if (PN->getIncomingValue(i) == &I) {
74           Value *&V = Loads[PN->getIncomingBlock(i)];
75           if (!V) {
76             // Insert the load into the predecessor block
77             V = new LoadInst(I.getType(), Slot, I.getName() + ".reload",
78                              VolatileLoads,
79                              PN->getIncomingBlock(i)->getTerminator());
80           }
81           PN->setIncomingValue(i, V);
82         }
83 
84     } else {
85       // If this is a normal instruction, just insert a load.
86       Value *V = new LoadInst(I.getType(), Slot, I.getName() + ".reload",
87                               VolatileLoads, U);
88       U->replaceUsesOfWith(&I, V);
89     }
90   }
91 
92   // Insert stores of the computed value into the stack slot. We have to be
93   // careful if I is an invoke instruction, because we can't insert the store
94   // AFTER the terminator instruction.
95   BasicBlock::iterator InsertPt;
96   if (!I.isTerminator()) {
97     InsertPt = ++I.getIterator();
98     for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
99       /* empty */;   // Don't insert before PHI nodes or landingpad instrs.
100   } else {
101     InvokeInst &II = cast<InvokeInst>(I);
102     InsertPt = II.getNormalDest()->getFirstInsertionPt();
103   }
104 
105   new StoreInst(&I, Slot, &*InsertPt);
106   return Slot;
107 }
108 
109 /// DemotePHIToStack - This function takes a virtual register computed by a PHI
110 /// node and replaces it with a slot in the stack frame allocated via alloca.
111 /// The PHI node is deleted. It returns the pointer to the alloca inserted.
112 AllocaInst *llvm::DemotePHIToStack(PHINode *P, Instruction *AllocaPoint) {
113   if (P->use_empty()) {
114     P->eraseFromParent();
115     return nullptr;
116   }
117 
118   const DataLayout &DL = P->getModule()->getDataLayout();
119 
120   // Create a stack slot to hold the value.
121   AllocaInst *Slot;
122   if (AllocaPoint) {
123     Slot = new AllocaInst(P->getType(), DL.getAllocaAddrSpace(), nullptr,
124                           P->getName()+".reg2mem", AllocaPoint);
125   } else {
126     Function *F = P->getParent()->getParent();
127     Slot = new AllocaInst(P->getType(), DL.getAllocaAddrSpace(), nullptr,
128                           P->getName() + ".reg2mem",
129                           &F->getEntryBlock().front());
130   }
131 
132   // Iterate over each operand inserting a store in each predecessor.
133   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
134     if (InvokeInst *II = dyn_cast<InvokeInst>(P->getIncomingValue(i))) {
135       assert(II->getParent() != P->getIncomingBlock(i) &&
136              "Invoke edge not supported yet"); (void)II;
137     }
138     new StoreInst(P->getIncomingValue(i), Slot,
139                   P->getIncomingBlock(i)->getTerminator());
140   }
141 
142   // Insert a load in place of the PHI and replace all uses.
143   BasicBlock::iterator InsertPt = P->getIterator();
144 
145   for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
146     /* empty */;   // Don't insert before PHI nodes or landingpad instrs.
147 
148   Value *V =
149       new LoadInst(P->getType(), Slot, P->getName() + ".reload", &*InsertPt);
150   P->replaceAllUsesWith(V);
151 
152   // Delete PHI.
153   P->eraseFromParent();
154   return Slot;
155 }
156