1 //===- Reg2Mem.cpp - Convert registers to allocas -------------------------===//
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 // This file demotes all registers to memory references.  It is intended to be
10 // the inverse of PromoteMemoryToRegister.  By converting to loads, the only
11 // values live across basic blocks are allocas and loads before phi nodes.
12 // It is intended that this should make CFG hacking much easier.
13 // To make later hacking easier, the entry block is split into two, such that
14 // all introduced allocas and nothing else are in the entry block.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Transforms/Scalar/Reg2Mem.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/InstIterator.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/PassManager.h"
28 #include "llvm/InitializePasses.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Transforms/Utils.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include <list>
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "reg2mem"
38 
39 STATISTIC(NumRegsDemoted, "Number of registers demoted");
40 STATISTIC(NumPhisDemoted, "Number of phi-nodes demoted");
41 
42 static bool valueEscapes(const Instruction &Inst) {
43   const BasicBlock *BB = Inst.getParent();
44   for (const User *U : Inst.users()) {
45     const Instruction *UI = cast<Instruction>(U);
46     if (UI->getParent() != BB || isa<PHINode>(UI))
47       return true;
48   }
49   return false;
50 }
51 
52 static bool runPass(Function &F) {
53   // Insert all new allocas into entry block.
54   BasicBlock *BBEntry = &F.getEntryBlock();
55   assert(pred_empty(BBEntry) &&
56          "Entry block to function must not have predecessors!");
57 
58   // Find first non-alloca instruction and create insertion point. This is
59   // safe if block is well-formed: it always have terminator, otherwise
60   // we'll get and assertion.
61   BasicBlock::iterator I = BBEntry->begin();
62   while (isa<AllocaInst>(I)) ++I;
63 
64   CastInst *AllocaInsertionPoint = new BitCastInst(
65       Constant::getNullValue(Type::getInt32Ty(F.getContext())),
66       Type::getInt32Ty(F.getContext()), "reg2mem alloca point", &*I);
67 
68   // Find the escaped instructions. But don't create stack slots for
69   // allocas in entry block.
70   std::list<Instruction*> WorkList;
71   for (Instruction &I : instructions(F))
72     if (!(isa<AllocaInst>(I) && I.getParent() == BBEntry) && valueEscapes(I))
73       WorkList.push_front(&I);
74 
75   // Demote escaped instructions
76   NumRegsDemoted += WorkList.size();
77   for (Instruction *I : WorkList)
78     DemoteRegToStack(*I, false, AllocaInsertionPoint);
79 
80   WorkList.clear();
81 
82   // Find all phi's
83   for (BasicBlock &BB : F)
84     for (auto &Phi : BB.phis())
85       WorkList.push_front(&Phi);
86 
87   // Demote phi nodes
88   NumPhisDemoted += WorkList.size();
89   for (Instruction *I : WorkList)
90     DemotePHIToStack(cast<PHINode>(I), AllocaInsertionPoint);
91 
92   return true;
93 }
94 
95 PreservedAnalyses RegToMemPass::run(Function &F, FunctionAnalysisManager &AM) {
96   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
97   auto *LI = &AM.getResult<LoopAnalysis>(F);
98   unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
99   bool Changed = runPass(F);
100   if (N == 0 && !Changed)
101     return PreservedAnalyses::all();
102   PreservedAnalyses PA;
103   PA.preserve<DominatorTreeAnalysis>();
104   PA.preserve<LoopAnalysis>();
105   return PA;
106 }
107 
108 namespace {
109 struct RegToMemLegacy : public FunctionPass {
110   static char ID; // Pass identification, replacement for typeid
111   RegToMemLegacy() : FunctionPass(ID) {
112     initializeRegToMemLegacyPass(*PassRegistry::getPassRegistry());
113   }
114 
115   void getAnalysisUsage(AnalysisUsage &AU) const override {
116     AU.addRequiredID(BreakCriticalEdgesID);
117     AU.addPreservedID(BreakCriticalEdgesID);
118   }
119 
120   bool runOnFunction(Function &F) override {
121     if (F.isDeclaration() || skipFunction(F))
122       return false;
123     return runPass(F);
124   }
125 };
126 } // namespace
127 
128 char RegToMemLegacy::ID = 0;
129 INITIALIZE_PASS_BEGIN(RegToMemLegacy, "reg2mem",
130                       "Demote all values to stack slots", false, false)
131 INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
132 INITIALIZE_PASS_END(RegToMemLegacy, "reg2mem",
133                     "Demote all values to stack slots", false, false)
134 
135 // createDemoteRegisterToMemory - Provide an entry point to create this pass.
136 char &llvm::DemoteRegisterToMemoryID = RegToMemLegacy::ID;
137 FunctionPass *llvm::createDemoteRegisterToMemoryPass() {
138   return new RegToMemLegacy();
139 }
140