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