LLVM 20.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"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/CFG.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/Function.h"
27#include "llvm/IR/PassManager.h"
33#include <list>
34using namespace llvm;
35
36#define DEBUG_TYPE "reg2mem"
37
38STATISTIC(NumRegsDemoted, "Number of registers demoted");
39STATISTIC(NumPhisDemoted, "Number of phi-nodes demoted");
40
41static bool valueEscapes(const Instruction &Inst) {
42 if (!Inst.getType()->isSized())
43 return false;
44
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
54static 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->getIterator());
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->getIterator());
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();
107 return PA;
108}
109
110namespace llvm {
111
113
115public:
116 static char ID;
117
119
120 void getAnalysisUsage(AnalysisUsage &AU) const override {
121 AU.setPreservesAll();
122
125
128 }
129
130 bool runOnFunction(Function &F) override {
131 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
132 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
133
135 bool Changed = runPass(F);
136 return N != 0 || Changed;
137 }
138};
139} // namespace llvm
140
141INITIALIZE_PASS_BEGIN(RegToMemWrapperPass, "reg2mem", "", true, true)
145
146char RegToMemWrapperPass::ID = 0;
147
149 return new RegToMemWrapperPass();
150}
Expand Atomic instructions
basic Basic Alias true
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
static bool valueEscapes(const Instruction &Inst)
Definition: Reg2Mem.cpp:41
static bool runPass(Function &F)
Definition: Reg2Mem.cpp:54
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
This class represents a no-op cast from one type to another.
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:444
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:317
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:593
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:37
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: Reg2Mem.cpp:97
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Reg2Mem.cpp:120
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Definition: Reg2Mem.cpp:130
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:310
static IntegerType * getInt32Ty(LLVMContext &C)
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
iterator_range< user_iterator > users()
Definition: Value.h:421
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FunctionPass * createRegToMemWrapperPass()
Definition: Reg2Mem.cpp:148
AllocaInst * DemoteRegToStack(Instruction &X, bool VolatileLoads=false, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by an Instruction and replaces it with a slot in the ...
AllocaInst * DemotePHIToStack(PHINode *P, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by a phi node and replaces it with a slot in the stac...
void initializeRegToMemWrapperPassPass(PassRegistry &)
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:118
#define N
Option class for critical edge splitting.