60 #include <unordered_set>
63 #define DEBUG_TYPE "gvn-sink"
65 STATISTIC(NumRemoved,
"Number of instructions removed");
68 namespace GVNExpression {
81 return isa<LoadInst>(
I) || isa<StoreInst>(I) ||
82 (isa<InvokeInst>(
I) && !cast<InvokeInst>(I)->doesNotAccessMemory()) ||
83 (isa<CallInst>(I) && !cast<CallInst>(
I)->doesNotAccessMemory());
98 class LockstepReverseIterator {
111 ActiveBlocks.clear();
113 ActiveBlocks.insert(BB);
116 if (BB->size() <= 1) {
118 ActiveBlocks.erase(BB);
121 Insts.push_back(BB->getTerminator()->getPrevNode());
132 for (
auto II = Insts.begin(); II != Insts.end();) {
135 ActiveBlocks.
erase((*II)->getParent());
136 II = Insts.erase(II);
147 for (
auto *Inst : Insts) {
148 if (Inst == &Inst->getParent()->front())
149 ActiveBlocks.
erase(Inst->getParent());
153 if (NewInsts.
empty()) {
167 struct SinkingInstructionCandidate {
169 unsigned NumInstructions;
171 unsigned NumMemoryInsts;
175 void calculateCost(
unsigned NumOrigPHIs,
unsigned NumOrigBlocks) {
176 unsigned NumExtraPHIs = NumPHIs - NumOrigPHIs;
177 unsigned SplitEdgeCost = (NumOrigBlocks > NumBlocks) ? 2 : 0;
178 Cost = (NumInstructions * (NumBlocks - 1)) -
184 return Cost > Other.Cost;
190 const SinkingInstructionCandidate &
C) {
191 OS <<
"<Candidate Cost=" << C.Cost <<
" #Blocks=" << C.NumBlocks
192 <<
" #Insts=" << C.NumInstructions <<
" #PHIs=" << C.NumPHIs <<
">";
208 ModelledPHI(
const PHINode *PN) {
215 for (
auto *
B : Blocks)
221 static ModelledPHI createDummy(
size_t ID) {
223 M.Values.push_back(reinterpret_cast<Value*>(ID));
228 template <
typename VArray,
typename BArray>
229 ModelledPHI(
const VArray &V,
const BArray &
B) {
230 std::copy(V.begin(), V.end(), std::back_inserter(Values));
231 std::copy(B.begin(), B.end(), std::back_inserter(Blocks));
235 template <
typename BArray>
237 std::copy(B.begin(), B.end(), std::back_inserter(Blocks));
238 for (
auto *I : Insts)
245 auto BI = Blocks.begin();
246 auto VI = Values.begin();
247 while (BI != Blocks.end()) {
251 BI = Blocks.erase(BI);
252 VI = Values.erase(
VI);
263 bool areAllIncomingValuesSame()
const {
264 return all_of(Values, [&](
Value *V) {
return V == Values[0]; });
266 bool areAllIncomingValuesSameType()
const {
268 Values, [&](
Value *V) {
return V->
getType() == Values[0]->getType(); });
270 bool areAnyIncomingValuesConstant()
const {
271 return any_of(Values, [&](
Value *V) {
return isa<Constant>(V); });
274 unsigned hash()
const {
278 return Values == Other.Values && Blocks == Other.Blocks;
283 static inline ModelledPHI &getEmptyKey() {
284 static ModelledPHI
Dummy = ModelledPHI::createDummy(0);
287 static inline ModelledPHI &getTombstoneKey() {
288 static ModelledPHI
Dummy = ModelledPHI::createDummy(1);
291 static unsigned getHashValue(
const ModelledPHI &V) {
return V.hash(); }
292 static bool isEqual(
const ModelledPHI &LHS,
const ModelledPHI &RHS) {
313 unsigned MemoryUseOrder = -1;
319 : GVNExpression::BasicExpression(I->getNumUses()) {
324 for (
auto &U : I->
uses())
328 void setMemoryUseOrder(
unsigned MUO) { MemoryUseOrder = MUO; }
329 void setVolatile(
bool V) {
Volatile = V; }
332 return hash_combine(GVNExpression::BasicExpression::getHashValue(),
333 MemoryUseOrder, Volatile);
357 InstructionUseExpr *
E =
360 E->setMemoryUseOrder(getMemoryUseOrder(I));
362 if (
CmpInst *
C = dyn_cast<CmpInst>(I)) {
364 E->setOpcode((
C->getOpcode() << 8) | Predicate);
372 template <
class Inst> InstructionUseExpr *createMemoryExpr(Inst *I) {
375 InstructionUseExpr *E = createExpr(I);
376 E->setVolatile(I->isVolatile());
384 auto VI = ValueNumbering.find(V);
385 if (
VI != ValueNumbering.end())
388 if (!isa<Instruction>(V)) {
389 ValueNumbering[V] = nextValueNumber;
390 return nextValueNumber++;
394 InstructionUseExpr *exp =
nullptr;
397 exp = createMemoryExpr(cast<LoadInst>(I));
400 exp = createMemoryExpr(cast<StoreInst>(I));
403 case Instruction::Invoke:
405 case Instruction::FAdd:
406 case Instruction::Sub:
407 case Instruction::FSub:
408 case Instruction::Mul:
409 case Instruction::FMul:
410 case Instruction::UDiv:
411 case Instruction::SDiv:
412 case Instruction::FDiv:
413 case Instruction::URem:
414 case Instruction::SRem:
415 case Instruction::FRem:
416 case Instruction::Shl:
417 case Instruction::LShr:
418 case Instruction::AShr:
419 case Instruction::And:
420 case Instruction::Or:
421 case Instruction::Xor:
422 case Instruction::ICmp:
423 case Instruction::FCmp:
424 case Instruction::Trunc:
425 case Instruction::ZExt:
426 case Instruction::SExt:
427 case Instruction::FPToUI:
428 case Instruction::FPToSI:
429 case Instruction::UIToFP:
430 case Instruction::SIToFP:
431 case Instruction::FPTrunc:
432 case Instruction::FPExt:
433 case Instruction::PtrToInt:
434 case Instruction::IntToPtr:
435 case Instruction::BitCast:
437 case Instruction::ExtractElement:
438 case Instruction::InsertElement:
439 case Instruction::ShuffleVector:
440 case Instruction::InsertValue:
441 case Instruction::GetElementPtr:
449 ValueNumbering[V] = nextValueNumber;
450 return nextValueNumber++;
453 uint32_t e = ExpressionNumbering[exp];
455 hash_code H = exp->getHashValue([=](
Value *V) {
return lookupOrAdd(V); });
456 auto I = HashNumbering.find(H);
457 if (I != HashNumbering.end()) {
460 e = nextValueNumber++;
461 HashNumbering[
H] = e;
462 ExpressionNumbering[exp] = e;
465 ValueNumbering[V] = e;
472 auto VI = ValueNumbering.find(V);
473 assert(
VI != ValueNumbering.end() &&
"Value not numbered?");
479 ValueNumbering.clear();
480 ExpressionNumbering.clear();
481 HashNumbering.clear();
486 ValueTable() : nextValueNumber(1) {}
500 for (
auto I = std::next(Inst->
getIterator()), E = BB->end();
502 if (!isMemoryInst(&*I))
504 if (isa<LoadInst>(&*I))
512 return lookupOrAdd(&*I);
526 unsigned NumSunk = 0;
529 NumSunk += sinkBB(
N);
539 if (isa<PHINode>(I) || I->
isEHPad() || isa<AllocaInst>(
I) ||
549 LockstepReverseIterator &LRI,
unsigned &InstNum,
unsigned &MemoryInstNum,
553 void analyzeInitialPHIs(
BasicBlock *BB, ModelledPHISet &PHIs,
555 for (
auto &I : *BB) {
560 auto MPHI = ModelledPHI(PN);
562 for (
auto *V : MPHI.getValues())
577 auto I = BB->
begin();
578 while (
PHINode *PN = dyn_cast<PHINode>(I++)) {
592 LockstepReverseIterator &LRI,
unsigned &InstNum,
unsigned &MemoryInstNum,
595 DEBUG(
dbgs() <<
" -- Analyzing instruction set: [\n";
for (
auto *I
598 }
dbgs() <<
" ]\n";);
601 for (
auto *I : Insts) {
608 unsigned VNumToSink =
609 std::max_element(VNums.begin(), VNums.end(),
610 [](
const std::pair<uint32_t, unsigned> &
I,
611 const std::pair<uint32_t, unsigned> &J) {
612 return I.second < J.second;
616 if (VNums[VNumToSink] == 1)
622 auto &ActivePreds = LRI.getActiveBlocks();
623 unsigned InitialActivePredSize = ActivePreds.size();
625 for (
auto *I : Insts) {
626 if (VN.lookup(I) != VNumToSink)
627 ActivePreds.
erase(I->getParent());
631 for (
auto *I : NewInsts)
632 if (isInstructionBlacklisted(I))
637 bool RecomputePHIContents =
false;
638 if (ActivePreds.size() != InitialActivePredSize) {
639 ModelledPHISet NewNeededPHIs;
640 for (
auto P : NeededPHIs) {
641 P.restrictToBlocks(ActivePreds);
642 NewNeededPHIs.insert(
P);
644 NeededPHIs = NewNeededPHIs;
645 LRI.restrictToBlocks(ActivePreds);
646 RecomputePHIContents =
true;
650 ModelledPHI NewPHI(NewInsts, ActivePreds);
653 if (NeededPHIs.find(NewPHI) != NeededPHIs.end()) {
654 NeededPHIs.erase(NewPHI);
655 RecomputePHIContents =
true;
658 if (RecomputePHIContents) {
662 for (
auto &PHI : NeededPHIs)
663 PHIContents.
insert(PHI.getValues().begin(), PHI.getValues().end());
668 for (
auto *V : NewPHI.getValues())
669 if (PHIContents.
count(V))
679 for (
unsigned OpNum = 0, E = I0->
getNumOperands(); OpNum !=
E; ++OpNum) {
680 ModelledPHI PHI(NewInsts, OpNum, ActivePreds);
681 if (PHI.areAllIncomingValuesSame())
686 if (NeededPHIs.count(PHI))
688 if (!PHI.areAllIncomingValuesSameType())
691 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OpNum == E - 1 &&
692 PHI.areAnyIncomingValuesConstant())
695 NeededPHIs.reserve(NeededPHIs.size());
696 NeededPHIs.insert(PHI);
697 PHIContents.
insert(PHI.getValues().begin(), PHI.getValues().end());
700 if (isMemoryInst(NewInsts[0]))
703 SinkingInstructionCandidate Cand;
704 Cand.NumInstructions = ++InstNum;
705 Cand.NumMemoryInsts = MemoryInstNum;
706 Cand.NumBlocks = ActivePreds.size();
707 Cand.NumPHIs = NeededPHIs.size();
708 for (
auto *
C : ActivePreds)
709 Cand.Blocks.push_back(
C);
715 DEBUG(
dbgs() <<
"GVNSink: running on basic block ";
719 auto *
T = B->getTerminator();
720 if (isa<BranchInst>(
T) || isa<SwitchInst>(
T))
725 if (Preds.size() < 2)
729 unsigned NumOrigPreds = Preds.size();
731 for (
auto I = Preds.begin(); I != Preds.end();) {
732 if ((*I)->getTerminator()->getNumSuccessors() != 1)
738 LockstepReverseIterator LRI(Preds);
740 unsigned InstNum = 0, MemoryInstNum = 0;
741 ModelledPHISet NeededPHIs;
743 analyzeInitialPHIs(BBEnd, NeededPHIs, PHIContents);
744 unsigned NumOrigPHIs = NeededPHIs.size();
746 while (LRI.isValid()) {
747 auto Cand = analyzeInstructionForSinking(LRI, InstNum, MemoryInstNum,
748 NeededPHIs, PHIContents);
751 Cand->calculateCost(NumOrigPHIs, Preds.size());
757 Candidates.
begin(), Candidates.
end(),
758 [](
const SinkingInstructionCandidate &
A,
759 const SinkingInstructionCandidate &
B) {
return A >
B; });
760 DEBUG(
dbgs() <<
" -- Sinking candidates:\n";
for (
auto &
C
762 <<
" " <<
C <<
"\n";);
765 if (Candidates.empty() || Candidates.front().Cost <= 0)
767 auto C = Candidates.front();
769 DEBUG(
dbgs() <<
" -- Sinking: " <<
C <<
"\n");
771 if (
C.Blocks.size() < NumOrigPreds) {
776 DEBUG(
dbgs() <<
" -- FAILED to split edge!\n");
782 for (
unsigned I = 0; I <
C.NumInstructions; ++
I)
785 return C.NumInstructions;
807 assert(!
Op->getType()->isTokenTy() &&
"Can't PHI tokens!");
808 auto *PN = PHINode::Create(
Op->getType(), Insts.
size(),
809 Op->getName() +
".sink", &BBEnd->
front());
810 for (
auto *I : Insts)
822 for (
auto *I : Insts)
828 for (
auto *I : Insts)
831 foldPointlessPHINodes(BBEnd);
834 for (
auto *I : Insts)
838 NumRemoved += Insts.size() - 1;
877 "Early GVN sinking of Expressions",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
const Use & getOperandUse(unsigned i) const
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This class is the base class for the comparison instructions.
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
STATISTIC(NumFunctions,"Total number of functions")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
This is the interface for a simple mod/ref and alias analysis over globals.
Implements a dense probed hash-table based set.
unsigned getNumOperands() const
bool operator>(int64_t V1, const APSInt &V2)
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
This class represents a function call, abstracting a target machine's calling convention.
INITIALIZE_PASS_BEGIN(GVNSinkLegacyPass,"gvn-sink","Early GVN sinking of Expressions", false, false) INITIALIZE_PASS_END(GVNSinkLegacyPass
Recycle small arrays allocated from a BumpPtrAllocator.
bool isTokenTy() const
Return true if this is 'token'.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
const Instruction & front() const
LLVM_DUMP_METHOD void dump() const
unsigned getOpcode() const
StringRef getName() const
Return a constant reference to the value's name.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
gvn Early GVN sinking of false
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
static const uint16_t * lookup(unsigned opcode, unsigned domain, ArrayRef< uint16_t[3]> Table)
APInt operator*(APInt a, uint64_t RHS)
LLVM_NODISCARD bool empty() const
static bool isEqual(const Function &Caller, const Function &Callee)
The core GVN pass object.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void print(raw_ostream &OS) const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
LLVM Basic Block Representation.
Allocate memory in an ever growing pool, as if by bump-pointer.
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
self_iterator getIterator()
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static bool sinkLastInstruction(ArrayRef< BasicBlock * > Blocks)
void dump() const
Support for debugging, callable in GDB: V->dump()
bool isTerminator() const
hash_code getHashValue() const override
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void setOpcode(unsigned opcode)
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Recycler - This class manages a linked-list of deallocated nodes and facilitates reusing deallocated ...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
gvn Early GVN sinking of Expressions
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
pred_range predecessors(BasicBlock *BB)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
An opaque object representing a hash code.
static void clear(coro::Shape &Shape)
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
static bool isStrongerThanUnordered(AtomicOrdering ao)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void emplace_back(ArgTypes &&...Args)
FunctionPass * createGVNSinkPass()
void initializeGVNSinkLegacyPassPass(PassRegistry &)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
INITIALIZE_PASS(HexagonGenMux,"hexagon-gen-mux","Hexagon generate mux instructions", false, false) void HexagonGenMux I isValid()
void combineMetadataForCSE(Instruction *K, const Instruction *J)
Combine the metadata of two instructions so that K can replace J.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
static std::string utohexstr(uint64_t X, bool LowerCase=false)
iterator_range< op_iterator > operands()
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
void clear(AllocatorType &Allocator)
clear - Release all the tracked allocations to the allocator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
The header file for the GVN pass that contains expression handling classes.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
This class implements an extremely fast bulk output stream that can only output to a stream...
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
bool operator==(uint64_t V1, const APInt &V2)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
op_range incoming_values()
void op_push_back(Value *Arg)
const BasicBlock * getParent() const
void allocateOperands(RecyclerType &Recycler, BumpPtrAllocator &Allocator)