LLVM  12.0.0git
Reg2Mem.cpp
Go to the documentation of this file.
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 
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/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/PassManager.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "llvm/Transforms/Utils.h"
36 #include <list>
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "reg2mem"
40 
41 STATISTIC(NumRegsDemoted, "Number of registers demoted");
42 STATISTIC(NumPhisDemoted, "Number of phi-nodes demoted");
43 
44 static bool valueEscapes(const Instruction &Inst) {
45  const BasicBlock *BB = Inst.getParent();
46  for (const User *U : Inst.users()) {
47  const Instruction *UI = cast<Instruction>(U);
48  if (UI->getParent() != BB || isa<PHINode>(UI))
49  return true;
50  }
51  return false;
52 }
53 
54 static bool runPass(Function &F) {
55  // Insert all new allocas into entry block.
56  BasicBlock *BBEntry = &F.getEntryBlock();
57  assert(pred_empty(BBEntry) &&
58  "Entry block to function must not have predecessors!");
59 
60  // Find first non-alloca instruction and create insertion point. This is
61  // safe if block is well-formed: it always have terminator, otherwise
62  // we'll get and assertion.
63  BasicBlock::iterator I = BBEntry->begin();
64  while (isa<AllocaInst>(I)) ++I;
65 
66  CastInst *AllocaInsertionPoint = new BitCastInst(
68  Type::getInt32Ty(F.getContext()), "reg2mem alloca point", &*I);
69 
70  // Find the escaped instructions. But don't create stack slots for
71  // allocas in entry block.
72  std::list<Instruction*> WorkList;
73  for (Instruction &I : instructions(F))
74  if (!(isa<AllocaInst>(I) && I.getParent() == BBEntry) && valueEscapes(I))
75  WorkList.push_front(&I);
76 
77  // Demote escaped instructions
78  NumRegsDemoted += WorkList.size();
79  for (Instruction *I : WorkList)
80  DemoteRegToStack(*I, false, AllocaInsertionPoint);
81 
82  WorkList.clear();
83 
84  // Find all phi's
85  for (BasicBlock &BB : F)
86  for (auto &Phi : BB.phis())
87  WorkList.push_front(&Phi);
88 
89  // Demote phi nodes
90  NumPhisDemoted += WorkList.size();
91  for (Instruction *I : WorkList)
92  DemotePHIToStack(cast<PHINode>(I), AllocaInsertionPoint);
93 
94  return true;
95 }
96 
98  auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
99  auto *LI = &AM.getResult<LoopAnalysis>(F);
101  bool Changed = runPass(F);
102  if (N == 0 && !Changed)
103  return PreservedAnalyses::all();
106  PA.preserve<LoopAnalysis>();
107  return PA;
108 }
109 
110 namespace {
111 struct RegToMemLegacy : public FunctionPass {
112  static char ID; // Pass identification, replacement for typeid
113  RegToMemLegacy() : FunctionPass(ID) {
115  }
116 
117  void getAnalysisUsage(AnalysisUsage &AU) const override {
120  }
121 
122  bool runOnFunction(Function &F) override {
123  if (F.isDeclaration() || skipFunction(F))
124  return false;
125  return runPass(F);
126  }
127 };
128 } // namespace
129 
130 char RegToMemLegacy::ID = 0;
131 INITIALIZE_PASS_BEGIN(RegToMemLegacy, "reg2mem",
132  "Demote all values to stack slots", false, false)
133 INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges)
134 INITIALIZE_PASS_END(RegToMemLegacy, "reg2mem",
135  "Demote all values to stack slots", false, false)
136 
137 // createDemoteRegisterToMemory - Provide an entry point to create this pass.
138 char &llvm::DemoteRegisterToMemoryID = RegToMemLegacy::ID;
140  return new RegToMemLegacy();
141 }
AllocaInst * DemoteRegToStack(Instruction &X, bool VolatileLoads=false, Instruction *AllocaPoint=nullptr)
This function takes a virtual register computed by an Instruction and replaces it with a slot in the ...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: Reg2Mem.cpp:97
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:785
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void initializeRegToMemLegacyPass(PassRegistry &)
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:249
F(f)
FunctionPass * createDemoteRegisterToMemoryPass()
Definition: Reg2Mem.cpp:139
unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:347
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:296
Option class for critical edge splitting.
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:432
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:1224
Predicate all(Predicate P0, Predicate P1)
True iff P0 and P1 are true.
This class represents a no-op cast from one type to another.
AnalysisUsage & addPreservedID(const void *ID)
static bool runOnFunction(Function &F, bool PostInlining)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
char & BreakCriticalEdgesID
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:683
Demote all values to stack slots
Definition: Reg2Mem.cpp:134
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:117
char & DemoteRegisterToMemoryID
Definition: Reg2Mem.cpp:138
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:161
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
static bool valueEscapes(const Instruction &Inst)
Definition: Reg2Mem.cpp:44
Iterator for intrusive lists based on ilist_node.
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:266
Module.h This file contains the declarations for the Module class.
static bool runPass(Function &F)
Definition: Reg2Mem.cpp:54
INITIALIZE_PASS_BEGIN(RegToMemLegacy, "reg2mem", "Demote all values to stack slots", false, false) INITIALIZE_PASS_END(RegToMemLegacy
iterator_range< user_iterator > users()
Definition: Value.h:424
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:197
reg2mem
Definition: Reg2Mem.cpp:134
#define I(x, y, z)
Definition: MD5.cpp:59
#define N
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:176
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
AllocaInst * DemotePHIToStack(PHINode *P, Instruction *AllocaPoint=nullptr)
This function takes a virtual register computed by a phi node and replaces it with a slot in the stac...
inst_range instructions(Function *F)
Definition: InstIterator.h:133
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
const BasicBlock * getParent() const
Definition: Instruction.h:94
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)