LLVM 18.0.0git
Go to the documentation of this file.
1//===- Reg2Mem.cpp - Convert registers to allocas -------------------------===//
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
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.
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"
29#include "llvm/Pass.h"
34#include <list>
35using namespace llvm;
37#define DEBUG_TYPE "reg2mem"
39STATISTIC(NumRegsDemoted, "Number of registers demoted");
40STATISTIC(NumPhisDemoted, "Number of phi-nodes demoted");
42static bool valueEscapes(const Instruction &Inst) {
43 if (!Inst.getType()->isSized())
44 return false;
46 const BasicBlock *BB = Inst.getParent();
47 for (const User *U : Inst.users()) {
48 const Instruction *UI = cast<Instruction>(U);
49 if (UI->getParent() != BB || isa<PHINode>(UI))
50 return true;
51 }
52 return false;
55static bool runPass(Function &F) {
56 // Insert all new allocas into entry block.
57 BasicBlock *BBEntry = &F.getEntryBlock();
58 assert(pred_empty(BBEntry) &&
59 "Entry block to function must not have predecessors!");
61 // Find first non-alloca instruction and create insertion point. This is
62 // safe if block is well-formed: it always have terminator, otherwise
63 // we'll get and assertion.
64 BasicBlock::iterator I = BBEntry->begin();
65 while (isa<AllocaInst>(I)) ++I;
67 CastInst *AllocaInsertionPoint = new BitCastInst(
69 Type::getInt32Ty(F.getContext()), "reg2mem alloca point", &*I);
71 // Find the escaped instructions. But don't create stack slots for
72 // allocas in entry block.
73 std::list<Instruction*> WorkList;
74 for (Instruction &I : instructions(F))
75 if (!(isa<AllocaInst>(I) && I.getParent() == BBEntry) && valueEscapes(I))
76 WorkList.push_front(&I);
78 // Demote escaped instructions
79 NumRegsDemoted += WorkList.size();
80 for (Instruction *I : WorkList)
81 DemoteRegToStack(*I, false, AllocaInsertionPoint);
83 WorkList.clear();
85 // Find all phi's
86 for (BasicBlock &BB : F)
87 for (auto &Phi : BB.phis())
88 WorkList.push_front(&Phi);
90 // Demote phi nodes
91 NumPhisDemoted += WorkList.size();
92 for (Instruction *I : WorkList)
93 DemotePHIToStack(cast<PHINode>(I), AllocaInsertionPoint);
95 return true;
99 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
100 auto *LI = &AM.getResult<LoopAnalysis>(F);
102 bool Changed = runPass(F);
103 if (N == 0 && !Changed)
104 return PreservedAnalyses::all();
108 return PA;
111namespace {
112struct RegToMemLegacy : public FunctionPass {
113 static char ID; // Pass identification, replacement for typeid
114 RegToMemLegacy() : FunctionPass(ID) {
116 }
118 void getAnalysisUsage(AnalysisUsage &AU) const override {
121 }
123 bool runOnFunction(Function &F) override {
124 if (F.isDeclaration() || skipFunction(F))
125 return false;
126 return runPass(F);
127 }
129} // namespace
131char RegToMemLegacy::ID = 0;
132INITIALIZE_PASS_BEGIN(RegToMemLegacy, "reg2mem",
133 "Demote all values to stack slots", false, false)
135INITIALIZE_PASS_END(RegToMemLegacy, "reg2mem",
136 "Demote all values to stack slots", false, false)
138// createDemoteRegisterToMemory - Provide an entry point to create this pass.
139char &llvm::DemoteRegisterToMemoryID = RegToMemLegacy::ID;
141 return new RegToMemLegacy();
Mark the given Function as meaning that it cannot be changed in any way mark any values that are used as this function s parameters or by its return values(according to Uses) live as well. void DeadArgumentEliminationPass
static bool runOnFunction(Function &F, bool PostInlining)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Select target instructions out of generic instructions
#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"))
This header defines various interfaces for pass management in LLVM.
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
static bool valueEscapes(const Instruction &Inst)
Definition: Reg2Mem.cpp:42
static bool runPass(Function &F)
Definition: Reg2Mem.cpp:55
Definition: Reg2Mem.cpp:135
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Merge disjoint stack slots
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
Definition: Statistic.h:167
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
Represent the analysis usage information of a pass.
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:283
AnalysisUsage & addPreservedID(const void *ID)
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:335
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
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:428
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
const BasicBlock * getParent() const
Definition: Instruction.h:90
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:569
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:173
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: Reg2Mem.cpp:98
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
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
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void initializeRegToMemLegacyPass(PassRegistry &)
FunctionPass * createDemoteRegisterToMemoryPass()
Definition: Reg2Mem.cpp:140
char & DemoteRegisterToMemoryID
Definition: Reg2Mem.cpp:139
char & BreakCriticalEdgesID
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:118
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 ...
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...
#define N
Option class for critical edge splitting.