1009b1c42SEd Schouten //===- DemoteRegToStack.cpp - Move a virtual register to the stack --------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten
963faed5bSDimitry Andric #include "llvm/ADT/DenseMap.h"
10f8af5cf6SDimitry Andric #include "llvm/Analysis/CFG.h"
11ac9a064cSDimitry Andric #include "llvm/IR/DataLayout.h"
124a16efa3SDimitry Andric #include "llvm/IR/Function.h"
134a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
147ab83427SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
15145449b1SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
16009b1c42SEd Schouten using namespace llvm;
17009b1c42SEd Schouten
18009b1c42SEd Schouten /// DemoteRegToStack - This function takes a virtual register computed by an
19009b1c42SEd Schouten /// Instruction and replaces it with a slot in the stack frame, allocated via
20009b1c42SEd Schouten /// alloca. This allows the CFG to be changed around without fear of
21009b1c42SEd Schouten /// invalidating the SSA information for the value. It returns the pointer to
22009b1c42SEd Schouten /// the alloca inserted to create a stack slot for I.
DemoteRegToStack(Instruction & I,bool VolatileLoads,std::optional<BasicBlock::iterator> AllocaPoint)23009b1c42SEd Schouten AllocaInst *llvm::DemoteRegToStack(Instruction &I, bool VolatileLoads,
24ac9a064cSDimitry Andric std::optional<BasicBlock::iterator> AllocaPoint) {
25009b1c42SEd Schouten if (I.use_empty()) {
26009b1c42SEd Schouten I.eraseFromParent();
275ca98fd9SDimitry Andric return nullptr;
28009b1c42SEd Schouten }
29009b1c42SEd Schouten
3071d5a254SDimitry Andric Function *F = I.getParent()->getParent();
31ac9a064cSDimitry Andric const DataLayout &DL = F->getDataLayout();
3271d5a254SDimitry Andric
33009b1c42SEd Schouten // Create a stack slot to hold the value.
34009b1c42SEd Schouten AllocaInst *Slot;
35009b1c42SEd Schouten if (AllocaPoint) {
3671d5a254SDimitry Andric Slot = new AllocaInst(I.getType(), DL.getAllocaAddrSpace(), nullptr,
37ac9a064cSDimitry Andric I.getName()+".reg2mem", *AllocaPoint);
38009b1c42SEd Schouten } else {
3971d5a254SDimitry Andric Slot = new AllocaInst(I.getType(), DL.getAllocaAddrSpace(), nullptr,
40ac9a064cSDimitry Andric I.getName() + ".reg2mem", F->getEntryBlock().begin());
41009b1c42SEd Schouten }
42009b1c42SEd Schouten
435a5ac124SDimitry Andric // We cannot demote invoke instructions to the stack if their normal edge
445a5ac124SDimitry Andric // is critical. Therefore, split the critical edge and create a basic block
455a5ac124SDimitry Andric // into which the store can be inserted.
465a5ac124SDimitry Andric if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
475a5ac124SDimitry Andric if (!II->getNormalDest()->getSinglePredecessor()) {
485a5ac124SDimitry Andric unsigned SuccNum = GetSuccessorNumber(II->getParent(), II->getNormalDest());
495a5ac124SDimitry Andric assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
505a5ac124SDimitry Andric BasicBlock *BB = SplitCriticalEdge(II, SuccNum);
515a5ac124SDimitry Andric assert(BB && "Unable to split critical edge.");
525a5ac124SDimitry Andric (void)BB;
535a5ac124SDimitry Andric }
54ac9a064cSDimitry Andric } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
55ac9a064cSDimitry Andric for (unsigned i = 0; i < CBI->getNumSuccessors(); i++) {
56ac9a064cSDimitry Andric auto *Succ = CBI->getSuccessor(i);
57ac9a064cSDimitry Andric if (!Succ->getSinglePredecessor()) {
58ac9a064cSDimitry Andric assert(isCriticalEdge(II, i) && "Expected a critical edge!");
59ac9a064cSDimitry Andric [[maybe_unused]] BasicBlock *BB = SplitCriticalEdge(II, i);
60ac9a064cSDimitry Andric assert(BB && "Unable to split critical edge.");
61ac9a064cSDimitry Andric }
62ac9a064cSDimitry Andric }
635a5ac124SDimitry Andric }
645a5ac124SDimitry Andric
6563faed5bSDimitry Andric // Change all of the users of the instruction to read from the stack slot.
66009b1c42SEd Schouten while (!I.use_empty()) {
675ca98fd9SDimitry Andric Instruction *U = cast<Instruction>(I.user_back());
68009b1c42SEd Schouten if (PHINode *PN = dyn_cast<PHINode>(U)) {
69009b1c42SEd Schouten // If this is a PHI node, we can't insert a load of the value before the
7063faed5bSDimitry Andric // use. Instead insert the load in the predecessor block corresponding
71009b1c42SEd Schouten // to the incoming value.
72009b1c42SEd Schouten //
73009b1c42SEd Schouten // Note that if there are multiple edges from a basic block to this PHI
7463faed5bSDimitry Andric // node that we cannot have multiple loads. The problem is that the
7563faed5bSDimitry Andric // resulting PHI node will have multiple values (from each load) coming in
7663faed5bSDimitry Andric // from the same block, which is illegal SSA form. For this reason, we
7763faed5bSDimitry Andric // keep track of and reuse loads we insert.
7863faed5bSDimitry Andric DenseMap<BasicBlock*, Value*> Loads;
79009b1c42SEd Schouten for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
80009b1c42SEd Schouten if (PN->getIncomingValue(i) == &I) {
81009b1c42SEd Schouten Value *&V = Loads[PN->getIncomingBlock(i)];
825ca98fd9SDimitry Andric if (!V) {
83009b1c42SEd Schouten // Insert the load into the predecessor block
84e6d15924SDimitry Andric V = new LoadInst(I.getType(), Slot, I.getName() + ".reload",
85e6d15924SDimitry Andric VolatileLoads,
86ac9a064cSDimitry Andric PN->getIncomingBlock(i)->getTerminator()->getIterator());
877fa27ce4SDimitry Andric Loads[PN->getIncomingBlock(i)] = V;
88009b1c42SEd Schouten }
89009b1c42SEd Schouten PN->setIncomingValue(i, V);
90009b1c42SEd Schouten }
91009b1c42SEd Schouten
92009b1c42SEd Schouten } else {
93009b1c42SEd Schouten // If this is a normal instruction, just insert a load.
94e6d15924SDimitry Andric Value *V = new LoadInst(I.getType(), Slot, I.getName() + ".reload",
95ac9a064cSDimitry Andric VolatileLoads, U->getIterator());
96009b1c42SEd Schouten U->replaceUsesOfWith(&I, V);
97009b1c42SEd Schouten }
98009b1c42SEd Schouten }
99009b1c42SEd Schouten
100009b1c42SEd Schouten // Insert stores of the computed value into the stack slot. We have to be
10163faed5bSDimitry Andric // careful if I is an invoke instruction, because we can't insert the store
10263faed5bSDimitry Andric // AFTER the terminator instruction.
103009b1c42SEd Schouten BasicBlock::iterator InsertPt;
104d8e91e46SDimitry Andric if (!I.isTerminator()) {
105dd58ef01SDimitry Andric InsertPt = ++I.getIterator();
106e3b55780SDimitry Andric // Don't insert before PHI nodes or landingpad instrs.
107dd58ef01SDimitry Andric for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
108e3b55780SDimitry Andric if (isa<CatchSwitchInst>(InsertPt))
109e3b55780SDimitry Andric break;
110e3b55780SDimitry Andric if (isa<CatchSwitchInst>(InsertPt)) {
111e3b55780SDimitry Andric for (BasicBlock *Handler : successors(&*InsertPt))
112ac9a064cSDimitry Andric new StoreInst(&I, Slot, Handler->getFirstInsertionPt());
113e3b55780SDimitry Andric return Slot;
114e3b55780SDimitry Andric }
115ac9a064cSDimitry Andric } else if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
116ac9a064cSDimitry Andric InsertPt = II->getNormalDest()->getFirstInsertionPt();
117ac9a064cSDimitry Andric } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
118ac9a064cSDimitry Andric for (BasicBlock *Succ : successors(CBI))
119ac9a064cSDimitry Andric new StoreInst(CBI, Slot, Succ->getFirstInsertionPt());
120ac9a064cSDimitry Andric return Slot;
1215a5ac124SDimitry Andric } else {
122ac9a064cSDimitry Andric llvm_unreachable("Unsupported terminator for Reg2Mem");
1235a5ac124SDimitry Andric }
124009b1c42SEd Schouten
125ac9a064cSDimitry Andric new StoreInst(&I, Slot, InsertPt);
126009b1c42SEd Schouten return Slot;
127009b1c42SEd Schouten }
128009b1c42SEd Schouten
12963faed5bSDimitry Andric /// DemotePHIToStack - This function takes a virtual register computed by a PHI
13063faed5bSDimitry Andric /// node and replaces it with a slot in the stack frame allocated via alloca.
13163faed5bSDimitry Andric /// The PHI node is deleted. It returns the pointer to the alloca inserted.
DemotePHIToStack(PHINode * P,std::optional<BasicBlock::iterator> AllocaPoint)132ac9a064cSDimitry Andric AllocaInst *llvm::DemotePHIToStack(PHINode *P, std::optional<BasicBlock::iterator> AllocaPoint) {
133009b1c42SEd Schouten if (P->use_empty()) {
134009b1c42SEd Schouten P->eraseFromParent();
1355ca98fd9SDimitry Andric return nullptr;
136009b1c42SEd Schouten }
137009b1c42SEd Schouten
138ac9a064cSDimitry Andric const DataLayout &DL = P->getDataLayout();
13971d5a254SDimitry Andric
140009b1c42SEd Schouten // Create a stack slot to hold the value.
141009b1c42SEd Schouten AllocaInst *Slot;
142009b1c42SEd Schouten if (AllocaPoint) {
14371d5a254SDimitry Andric Slot = new AllocaInst(P->getType(), DL.getAllocaAddrSpace(), nullptr,
144ac9a064cSDimitry Andric P->getName()+".reg2mem", *AllocaPoint);
145009b1c42SEd Schouten } else {
146009b1c42SEd Schouten Function *F = P->getParent()->getParent();
14771d5a254SDimitry Andric Slot = new AllocaInst(P->getType(), DL.getAllocaAddrSpace(), nullptr,
14871d5a254SDimitry Andric P->getName() + ".reg2mem",
149ac9a064cSDimitry Andric F->getEntryBlock().begin());
150009b1c42SEd Schouten }
151009b1c42SEd Schouten
15263faed5bSDimitry Andric // Iterate over each operand inserting a store in each predecessor.
153009b1c42SEd Schouten for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
154009b1c42SEd Schouten if (InvokeInst *II = dyn_cast<InvokeInst>(P->getIncomingValue(i))) {
155009b1c42SEd Schouten assert(II->getParent() != P->getIncomingBlock(i) &&
156cf099d11SDimitry Andric "Invoke edge not supported yet"); (void)II;
157009b1c42SEd Schouten }
158009b1c42SEd Schouten new StoreInst(P->getIncomingValue(i), Slot,
159ac9a064cSDimitry Andric P->getIncomingBlock(i)->getTerminator()->getIterator());
160009b1c42SEd Schouten }
161009b1c42SEd Schouten
16263faed5bSDimitry Andric // Insert a load in place of the PHI and replace all uses.
163dd58ef01SDimitry Andric BasicBlock::iterator InsertPt = P->getIterator();
164e3b55780SDimitry Andric // Don't insert before PHI nodes or landingpad instrs.
165dd58ef01SDimitry Andric for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
166e3b55780SDimitry Andric if (isa<CatchSwitchInst>(InsertPt))
167e3b55780SDimitry Andric break;
168e3b55780SDimitry Andric if (isa<CatchSwitchInst>(InsertPt)) {
169e3b55780SDimitry Andric // We need a separate load before each actual use of the PHI
170e3b55780SDimitry Andric SmallVector<Instruction *, 4> Users;
171e3b55780SDimitry Andric for (User *U : P->users()) {
172e3b55780SDimitry Andric Instruction *User = cast<Instruction>(U);
173e3b55780SDimitry Andric Users.push_back(User);
174e3b55780SDimitry Andric }
175e3b55780SDimitry Andric for (Instruction *User : Users) {
176e3b55780SDimitry Andric Value *V =
177ac9a064cSDimitry Andric new LoadInst(P->getType(), Slot, P->getName() + ".reload", User->getIterator());
178e3b55780SDimitry Andric User->replaceUsesOfWith(P, V);
179e3b55780SDimitry Andric }
180e3b55780SDimitry Andric } else {
181e6d15924SDimitry Andric Value *V =
182ac9a064cSDimitry Andric new LoadInst(P->getType(), Slot, P->getName() + ".reload", InsertPt);
183009b1c42SEd Schouten P->replaceAllUsesWith(V);
184e3b55780SDimitry Andric }
18563faed5bSDimitry Andric // Delete PHI.
186009b1c42SEd Schouten P->eraseFromParent();
187009b1c42SEd Schouten return Slot;
188009b1c42SEd Schouten }
189