1//===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===// 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 7//===----------------------------------------------------------------------===// 9// This file implements the SSAUpdater class. 11//===----------------------------------------------------------------------===// 37#define DEBUG_TYPE "ssaupdater" 46 : InsertedPHIs(NewPHI) {}
58 ProtoName = std::string(
Name);
70assert(ProtoType &&
"Need to initialize SSAUpdater");
71assert(ProtoType == V->getType() &&
72"All rewritten values must have the same type");
78unsigned PHINumValues =
PHI->getNumIncomingValues();
79if (PHINumValues != ValueMapping.
size())
82// Scan the phi to see if it matches. 83for (
unsigned i = 0, e = PHINumValues; i != e; ++i)
84if (ValueMapping[
PHI->getIncomingBlock(i)] !=
85PHI->getIncomingValue(i)) {
93Value *Res = GetValueAtEndOfBlockInternal(BB);
98// If there is no definition of the renamed variable in this block, just use 99// GetValueAtEndOfBlock to do our work. 103// Otherwise, we have the hard case. Get the live-in values for each 106Value *SingularValue =
nullptr;
108// We can get our predecessor info by walking the pred_iterator list, but it 109// is relatively slow. If we already have PHI nodes in this block, walk one 110// of them to get the predecessor list instead. 112for (
unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
113BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
115 PredValues.
push_back(std::make_pair(PredBB, PredVal));
117// Compute SingularValue. 119 SingularValue = PredVal;
120elseif (PredVal != SingularValue)
121 SingularValue =
nullptr;
124bool isFirstPred =
true;
127 PredValues.
push_back(std::make_pair(PredBB, PredVal));
129// Compute SingularValue. 131 SingularValue = PredVal;
133 }
elseif (PredVal != SingularValue)
134 SingularValue =
nullptr;
138// If there are no predecessors, just return poison. 139if (PredValues.
empty())
142// Otherwise, if all the merged values are the same, just use it. 146// Otherwise, we do need a PHI: check to see if we already have one available 147// in this block that produces the right value. 148if (isa<PHINode>(BB->
begin())) {
157// Ok, we have no way out, insert a new one now. 162// Fill in all the predecessors of the PHI. 163for (
constauto &PredValue : PredValues)
164 InsertedPHI->
addIncoming(PredValue.second, PredValue.first);
166// See if the PHI node can be merged to a single value. This can happen in 167// loop cases when we get a PHI of itself and one other value. 174// Set the DebugLoc of the inserted PHI, if available. 177DL = It->getDebugLoc();
180// If the client wants to know about all new instructions, tell it. 181if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
204if (
DbgValue->getParent() ==
I->getParent())
208for (
auto &DVR : DbgVariableRecords) {
209if (DVR->getParent() ==
I->getParent())
211 UpdateDebugValue(
I, DVR);
224for (
auto &DVR : DbgVariableRecords) {
225 UpdateDebugValue(
I, DVR);
233DbgValue->replaceVariableLocationOp(
I, NewVal);
281 :
PHI(
P), idx(
PHI->getNumIncomingValues()) {}
284booloperator==(
const PHI_iterator& x)
const{
return idx == x.idx; }
293return PHI_iterator(
PHI,
true);
296 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds 297 /// vector, set Info->NumPreds, and allocate space in Info->Preds. 300// We can get our predecessor info by walking the pred_iterator list, 301// but it is relatively slow. If we already have PHI nodes in this 302// block, walk one of them to get the predecessor list instead. 309 /// GetPoisonVal - Get a poison value of the same type as the value 315 /// CreateEmptyPHI - Create a new PHI instruction in the specified block. 316 /// Reserve space for the operands but do not fill them in yet. 325 /// AddPHIOperand - Add the specified value as an operand of the PHI for 326 /// the specified predecessor block. 328PHI->addIncoming(Val, Pred);
331 /// ValueIsPHI - Check if a value is a PHI. 333return dyn_cast<PHINode>(Val);
336 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 337 /// operands, i.e., it was just added. 340if (
PHI &&
PHI->getNumIncomingValues() == 0)
345 /// GetPHIValue - For the specified PHI instruction, return the value 352}
// end namespace llvm 354/// Check to see if AvailableVals has an entry for the specified BB and if so, 355/// return it. If not, construct SSA form by first calculating the required 356/// placement of PHIs and then inserting new PHIs where needed. 359if (
Value *V = AvailableVals[BB])
363return Impl.GetValue(BB);
366//===----------------------------------------------------------------------===// 367// LoadAndStorePromoter Implementation 368//===----------------------------------------------------------------------===// 373if (Insts.
empty())
return;
376if (
constLoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
379 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
387// First step: bucket up uses of the alloca by the block they occur in. 388// This is important because we have to handle multiple defs/uses in a block 389// ourselves: SSAUpdater is purely for cross-block references. 393 UsesByBlock[
User->getParent()].push_back(
User);
395// Okay, now we can iterate over all the blocks in the function with uses, 396// processing them. Keep track of which loads are loading a live-in value. 397// Walk the uses in the use-list order to be determinstic. 405// If this block has already been processed, ignore this repeat use. 406if (BlockUses.
empty())
continue;
408// Okay, this is the first use in the block. If this block just has a 409// single user in it, we can rewrite it trivially. 410if (BlockUses.
size() == 1) {
411// If it is a store, it is a trivial def of the value in the block. 415 }
elseif (
auto *AI = dyn_cast<AllocaInst>(
User)) {
416// We treat AllocaInst as a store of an getValueToUseForAlloca value. 419// Otherwise it is a load, queue it to rewrite as a live-in load. 426// Otherwise, check to see if this block is all loads. 429if (isa<StoreInst>(
I) || isa<AllocaInst>(
I)) {
435// If so, we can queue them all as live in loads. 443// Sort all of the interesting instructions in the block so that we don't 444// have to scan a large block just to find a few instructions. 449// Otherwise, we have mixed loads and stores (or just a bunch of stores). 450// Since SSAUpdater is purely for cross-block values, we need to determine 451// the order of these instructions in the block. If the first use in the 452// block is a load, then it uses the live in value. The last store defines 453// the live out value. 454Value *StoredValue =
nullptr;
456if (
LoadInst *L = dyn_cast<LoadInst>(
I)) {
457// If we haven't seen a store yet, this is a live in use, otherwise 458// use the stored value. 461 L->replaceAllUsesWith(StoredValue);
462 ReplacedLoads[L] = StoredValue;
472// Remember that this is the active value in the block. 473 StoredValue = SI->getOperand(0);
474 }
elseif (
auto *AI = dyn_cast<AllocaInst>(
I)) {
475// Check if this an alloca, in which case we treat it as a store of 476// getValueToUseForAlloca. 481// The last stored value that happened is the live-out for the block. 482assert(StoredValue &&
"Already checked that there is a store in block");
487// Okay, now we rewrite all loads that use live-in values in the loop, 488// inserting PHI nodes as necessary. 489for (
LoadInst *ALoad : LiveInLoads) {
493// Avoid assertions in unreachable code. 495 ALoad->replaceAllUsesWith(NewVal);
496 ReplacedLoads[ALoad] = NewVal;
499// Allow the client to do stuff before we start nuking things. 502// Now that everything is rewritten, delete the old instructions from the 503// function. They should all be dead now. 508// If this is a load that still has uses, then the load must have been added 509// as a live value in the SSAUpdate data structure for a block (e.g. because 510// the loaded value was stored later). In this case, we need to recursively 511// propagate the updates until we get to the real value. 514assert(NewVal &&
"not a replaced load?");
516// Propagate down to the ultimate replacee. The intermediately loads 517// could theoretically already have been deleted, so we don't want to 518// dereference the Value*'s. 520while (RLI != ReplacedLoads.
end()) {
521 NewVal = RLI->second;
522 RLI = ReplacedLoads.
find(NewVal);
530User->eraseFromParent();
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
static AvailableValsTy & getAvailableVals(void *AV)
DenseMap< MachineBasicBlock *, Register > AvailableValsTy
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static AvailableValsTy & getAvailableVals(void *AV)
static bool IsEquivalentPHI(PHINode *PHI, SmallDenseMap< BasicBlock *, Value *, 8 > &ValueMapping)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
Class recording the (high level) value of a variable.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
InstListType::const_iterator getFirstNonPHIIt() const
Iterator returning form of getFirstNonPHI.
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
const BasicBlock * getParent() const
This represents the llvm.dbg.value instruction.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
virtual Value * getValueToUseForAlloca(Instruction *AI) const
Return the value to use for the point in the code that the alloca is positioned.
virtual void instructionDeleted(Instruction *I) const
Called before each instruction is deleted.
virtual void doExtraRewritesBeforeFinalDeletion()
This hook is invoked after all the stores are found and inserted as available values.
LoadAndStorePromoter(ArrayRef< const Instruction * > Insts, SSAUpdater &S, StringRef Name=StringRef())
virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const
Clients can choose to implement this to get notified right before a load is RAUW'd another value.
void run(const SmallVectorImpl< Instruction * > &Insts)
This does the promotion.
virtual void updateDebugInfo(Instruction *I) const
Called to update debug info associated with the instruction.
virtual bool shouldDelete(Instruction *I) const
Return false if a sub-class wants to keep one of the loads/stores after the SSA construction.
An instruction for reading from memory.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getIncomingValue()
BasicBlock * getIncomingBlock()
PHI_iterator(PHINode *P, bool)
PHI_iterator & operator++()
bool operator!=(const PHI_iterator &x) const
bool operator==(const PHI_iterator &x) const
static BlkSucc_iterator BlkSucc_end(BlkT *BB)
static BlkSucc_iterator BlkSucc_begin(BlkT *BB)
static void FindPredecessorBlocks(BasicBlock *BB, SmallVectorImpl< BasicBlock * > *Preds)
FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds vector, set Info->NumPreds,...
static Value * CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds, SSAUpdater *Updater)
CreateEmptyPHI - Create a new PHI instruction in the specified block.
static PHINode * ValueIsNewPHI(Value *Val, SSAUpdater *Updater)
ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source operands, i....
static PHI_iterator PHI_begin(PhiT *PHI)
static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred)
AddPHIOperand - Add the specified value as an operand of the PHI for the specified predecessor block.
static Value * GetPHIValue(PHINode *PHI)
GetPHIValue - For the specified PHI instruction, return the value that it defines.
static Value * GetPoisonVal(BasicBlock *BB, SSAUpdater *Updater)
GetPoisonVal - Get a poison value of the same type as the value being handled.
static PHI_iterator PHI_end(PhiT *PHI)
static PHINode * ValueIsPHI(Value *Val, SSAUpdater *Updater)
ValueIsPHI - Check if a value is a PHI.
Helper class for SSA formation on a set of values defined in multiple blocks.
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
void RewriteUseAfterInsertions(Use &U)
Rewrite a use like RewriteUse but handling in-block definitions.
Value * FindValueForBlock(BasicBlock *BB) const
Return the value for the specified block if the SSAUpdater has one, otherwise return nullptr.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block.
SSAUpdater(SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
If InsertedPHIs is specified, it will be filled in with all PHI Nodes created by rewriting.
void UpdateDebugValues(Instruction *I)
Rewrite debug value intrinsics to conform to a new SSA form.
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
Value * GetValueAtEndOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live at the end of the specified block.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
The instances of the Type class are immutable: once they are created, they are never changed.
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
StringRef getName() const
Return a constant reference to the value's name.
This is an optimization pass for GlobalISel generic memory operations.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
void findDbgValues(SmallVectorImpl< DbgValueInst * > &DbgValues, Value *V, SmallVectorImpl< DbgVariableRecord * > *DbgVariableRecords=nullptr)
Finds the llvm.dbg.value intrinsics describing a value.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
void sort(IteratorTy Start, IteratorTy End)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
SuccIterator< Instruction, BasicBlock > succ_iterator
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
auto predecessors(const MachineBasicBlock *BB)