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