25 #define DEBUG_TYPE "spec-phis" 27 STATISTIC(NumPHIsSpeculated,
"Number of PHI nodes we speculated around");
29 "Number of critical edges which were split for speculation");
31 "Number of instructions we speculated around the PHI nodes");
33 "Number of new, redundant instructions inserted");
58 auto *UI = cast<Instruction>(U.getUser());
65 if (UI->getParent() != PhiBB) {
66 LLVM_DEBUG(
dbgs() <<
" Unsafe: use in a different BB: " << *UI <<
"\n");
71 if (CS.isConvergent() || CS.cannotDuplicate()) {
73 "callsite cannot de duplicated: " << *UI <<
'\n');
85 LLVM_DEBUG(
dbgs() <<
" Unsafe: can't speculate use: " << *UI <<
"\n");
93 DFSStack.
push_back({UI, UI->value_op_begin()});
98 while (OpIt != UI->value_op_end()) {
117 if (ParentBB == PhiBB) {
118 if (isa<PHINode>(OpI)) {
122 }
else if (DT.
dominates(ParentBB, PhiBB)) {
129 if (PotentialSpecSet.
count(OpI))
134 if (UnsafeSet.
count(OpI) || ParentBB != PhiBB ||
141 for (
auto &StackPair : DFSStack) {
149 if (!Visited.
insert(OpI).second)
156 OpIt = OpI->value_op_begin();
161 PotentialSpecSet.
insert(UI);
164 }
while (!DFSStack.
empty());
170 for (
auto *
I : Visited)
172 "Failed to mark a visited instruction as safe!");
210 bool NonFreeMat =
false;
211 struct CostsAndCount {
227 auto InsertResult = CostsAndCounts.
insert({IncomingC, {}});
229 ++InsertResult.first->second.Count;
231 if (!InsertResult.second)
234 int &MatCost = InsertResult.first->second.MatCost;
235 MatCost = TTI.
getIntImmCost(IncomingC->getValue(), IncomingC->getType());
236 NonFreeMat |= MatCost != TTI.
TCC_Free;
254 auto *UserI = cast<Instruction>(U.getUser());
257 unsigned Idx = U.getOperandNo();
272 if (UserI->isBinaryOp() && UserI->isCommutative() && Idx != 1)
278 if (
auto *UserII = dyn_cast<IntrinsicInst>(UserI))
279 IID = UserII->getIntrinsicID();
281 for (
auto &IncomingConstantAndCostsAndCount : CostsAndCounts) {
282 ConstantInt *IncomingC = IncomingConstantAndCostsAndCount.first;
283 int MatCost = IncomingConstantAndCostsAndCount.second.MatCost;
284 int &FoldedCost = IncomingConstantAndCostsAndCount.second.FoldedCost;
297 if (FoldedCost > MatCost) {
298 LLVM_DEBUG(
dbgs() <<
" Not profitable to fold imm: " << *IncomingC
300 " Materializing cost: " 303 " Accumulated folded cost: " 304 << FoldedCost <<
"\n");
312 for (
auto IncomingConstantAndCostsAndCount : CostsAndCounts) {
313 int MatCost = IncomingConstantAndCostsAndCount.second.MatCost;
314 int FoldedCost = IncomingConstantAndCostsAndCount.second.FoldedCost;
315 int Count = IncomingConstantAndCostsAndCount.second.Count;
317 TotalMatCost += MatCost * Count;
318 TotalFoldedCost += FoldedCost * Count;
320 assert(TotalFoldedCost <= TotalMatCost &&
"If each constant's folded cost is " 321 "less that its materialized cost, " 322 "the sum must be as well.");
324 LLVM_DEBUG(
dbgs() <<
" Cost savings " << (TotalMatCost - TotalFoldedCost)
325 <<
": " << PN <<
"\n");
326 CostSavingsMap[&PN] = TotalMatCost - TotalFoldedCost;
342 template <
typename IsVisitedT,
typename VisitT>
344 IsVisitedT IsVisited,
349 auto *UI = cast<Instruction>(U.getUser());
356 DFSStack.
push_back({UI, UI->value_op_begin()});
360 while (OpIt != UI->value_op_end()) {
368 if (!OpI || IsVisited(OpI))
375 OpIt = OpI->value_op_begin();
379 assert(!IsVisited(UI) &&
"Should not have already visited a node!");
381 }
while (!DFSStack.
empty());
433 for (
auto *PN : PNs) {
434 assert(UserSet.
empty() &&
"Must start with an empty user set!");
436 UserSet.
insert(cast<Instruction>(U.getUser()));
437 PNUserCountMap[PN] = UserSet.
size();
438 for (
auto *UI : UserSet)
439 UserToPNMap.
insert({UI, {}}).
first->second.push_back(PN);
455 return !PotentialSpecSet.
count(I) || SpecCostMap.
count(I);
463 if (
auto *OpI = dyn_cast<Instruction>(OpV)) {
464 auto CostMapIt = SpecCostMap.
find(OpI);
465 if (CostMapIt != SpecCostMap.
end())
466 Cost += CostMapIt->second;
471 assert(Inserted &&
"Must not re-insert a cost during the DFS!");
475 auto UserPNsIt = UserToPNMap.
find(I);
476 if (UserPNsIt == UserToPNMap.
end())
478 auto &UserPNs = UserPNsIt->second;
479 auto UserPNsSplitIt = std::stable_partition(
480 UserPNs.begin(), UserPNs.end(), [&](
PHINode *UserPN) {
481 int &PNUserCount = PNUserCountMap.
find(UserPN)->second;
484 "Should never re-visit a PN after its user count hits zero!");
486 return PNUserCount != 0;
496 SpecCostMap.
find(cast<Instruction>(U.getUser()))->second;
497 SpecCost *= (NumPreds - 1);
501 int CostSavings = CostSavingsMap.
find(PN)->second;
502 if (SpecCost > CostSavings) {
508 " Speculation cost: " 509 << SpecCost <<
"\n");
517 auto *UI = cast<Instruction>(U.getUser());
518 auto CostMapIt = SpecCostMap.
find(UI);
519 if (CostMapIt->second == 0)
522 CostMapIt->second = 0;
523 SpecWorklist.push_back(UI);
529 while (!SpecWorklist.empty()) {
531 assert(SpecCostMap.
find(SpecI)->second == 0 &&
532 "Didn't zero out a cost!");
539 auto CostMapIt = SpecCostMap.
find(OpI);
540 if (CostMapIt == SpecCostMap.
end() || CostMapIt->second == 0)
542 CostMapIt->second = 0;
543 SpecWorklist.push_back(OpI);
564 NumPHIsSpeculated += SpecPNs.
size();
567 auto *ParentBB = SpecPNs[0]->getParent();
570 for (
auto *PredBB : PredSet) {
576 LLVM_DEBUG(
dbgs() <<
" Split critical edge from: " << PredBB->getName()
580 assert(PredBB->getSingleSuccessor() == ParentBB &&
581 "We need a non-critical predecessor to speculate into.");
582 assert(!isa<InvokeInst>(PredBB->getTerminator()) &&
583 "Cannot have a non-critical invoke!");
598 return !PotentialSpecSet.
count(I) ||
609 int NumSpecInsts = SpecList.
size() * SpecPreds.
size();
610 int NumRedundantInsts = NumSpecInsts - SpecList.
size();
612 <<
" speculated instructions, " << NumRedundantInsts
613 <<
" redundancies\n");
614 NumSpeculatedInstructions += NumSpecInsts;
615 NumNewRedundantInstructions += NumRedundantInsts;
626 for (
auto *OrigI : SpecList)
627 for (
auto *OpV : OrigI->operand_values()) {
629 if (!OpPN || OpPN->getParent() != ParentBB)
632 auto InsertResult = SpeculatedValueMap.
insert({OpPN, {}});
633 if (!InsertResult.second)
636 auto &SpeculatedVals = InsertResult.first->second;
644 for (
int i : llvm::seq<int>(0, OpPN->getNumIncomingValues()))
645 IncomingValueMap[OpPN->getIncomingBlock(i)] = OpPN->getIncomingValue(i);
647 for (
auto *PredBB : SpecPreds)
648 SpeculatedVals.push_back(IncomingValueMap.
find(PredBB)->second);
652 for (
int PredIdx : llvm::seq<int>(0, SpecPreds.
size())) {
653 auto *PredBB = SpecPreds[PredIdx];
654 assert(PredBB->getSingleSuccessor() == ParentBB &&
655 "We need a non-critical predecessor to speculate into.");
657 for (
auto *OrigI : SpecList) {
658 auto *NewI = OrigI->clone();
659 NewI->setName(
Twine(OrigI->getName()) +
"." +
Twine(PredIdx));
660 NewI->insertBefore(PredBB->getTerminator());
665 for (
Use &U : NewI->operands()) {
669 auto MapIt = SpeculatedValueMap.
find(OpI);
670 if (MapIt == SpeculatedValueMap.
end())
672 const auto &SpeculatedVals = MapIt->second;
673 assert(SpeculatedVals[PredIdx] &&
674 "Must have a speculated value for this predecessor!");
675 assert(SpeculatedVals[PredIdx]->
getType() == OpI->getType() &&
676 "Speculated value has the wrong type!");
679 U.set(SpeculatedVals[PredIdx]);
684 if (NewI->isBinaryOp() && NewI->isCommutative() &&
685 isa<Constant>(NewI->getOperand(0)) &&
686 !isa<Constant>(NewI->getOperand(1)))
687 NewI->getOperandUse(0).swap(NewI->getOperandUse(1));
689 SpeculatedValueMap[OrigI].push_back(NewI);
690 assert(SpeculatedValueMap[OrigI][PredIdx] == NewI &&
691 "Mismatched speculated instruction index!");
703 if (!OrigI->use_empty()) {
704 auto *SpecIPN = IRB.
CreatePHI(OrigI->getType(), SpecPreds.
size(),
705 Twine(OrigI->getName()) +
".phi");
707 auto &SpeculatedVals = SpeculatedValueMap.
find(OrigI)->second;
708 for (
int PredIdx : llvm::seq<int>(0, SpecPreds.
size()))
709 SpecIPN->addIncoming(SpeculatedVals[PredIdx], SpecPreds[PredIdx]);
712 OrigI->replaceAllUsesWith(SpecIPN);
717 OrigI->eraseFromParent();
722 for (
auto *SpecPN : SpecPNs) {
723 assert(SpecPN->use_empty() &&
"All users should have been speculated!");
724 SpecPN->eraseFromParent();
758 *PN, CostSavingsMap, PotentialSpecSet,
771 for (
auto *PredBB : PNs[0]->blocks()) {
772 if (!PredSet.
insert(PredBB))
780 const auto *TermInst = PredBB->getTerminator();
781 if (isa<IndirectBrInst>(TermInst) ||
782 isa<InvokeInst>(TermInst) ||
783 isa<CallBrInst>(TermInst)) {
785 << PredBB->getName() <<
"\n");
789 if (PredSet.
size() < 2) {
790 LLVM_DEBUG(
dbgs() <<
" Unimportant: phi with only one predecessor\n");
795 PNs, CostSavingsMap, PotentialSpecSet, PredSet.
size(), DT, TTI);
809 bool Changed =
false;
812 auto BBI = BB->
begin();
813 while (
auto *PN = dyn_cast<PHINode>(&*BBI)) {
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
This routine provides some synthesis utilities to produce sequences of values.
iterator_range< use_iterator > uses()
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
size_type size() const
Determine the number of elements in the SetVector.
void push_back(const T &Elt)
Analysis pass providing the TargetTransformInfo.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
void reserve(size_type N)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Option class for critical edge splitting.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A Use represents the edge between a Value definition and its users.
static bool isSafeToSpeculatePHIUsers(PHINode &PN, DominatorTree &DT, SmallPtrSetImpl< Instruction *> &PotentialSpecSet, SmallPtrSetImpl< Instruction *> &UnsafeSet)
Check whether speculating the users of a PHI node around the PHI will be safe.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool insert(const value_type &X)
Insert a new element into the SetVector.
DenseMap< BasicBlock *, Value * > IncomingValueMap
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const APInt & getValue() const
Return the constant as an APInt value reference.
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
iterator find(const_arg_type_t< KeyT > Val)
A set of analyses that are preserved following a run of a transformation pass.
size_t size() const
size - Get the array size.
static SmallVector< PHINode *, 16 > findProfitablePHIs(ArrayRef< PHINode *> PNs, const SmallDenseMap< PHINode *, int, 16 > &CostSavingsMap, const SmallPtrSetImpl< Instruction *> &PotentialSpecSet, int NumPreds, DominatorTree &DT, TargetTransformInfo &TTI)
Find profitable PHIs to speculate.
LLVM_NODISCARD bool empty() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static bool tryToSpeculatePHIs(SmallVectorImpl< PHINode *> &PNs, DominatorTree &DT, TargetTransformInfo &TTI)
Try to speculate around a series of PHIs from a single basic block.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
static void visitPHIUsersAndDepsInPostOrder(ArrayRef< PHINode *> PNs, IsVisitedT IsVisited, VisitT Visit)
Simple helper to walk all the users of a list of phis depth first, and call a visit function on each ...
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Iterator for directly iterating over the operand Values.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
A SetVector that performs no allocations if smaller than a certain size.
This is the shared class of boolean and integer constants.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
LLVM_NODISCARD T pop_back_val()
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool mayBeMemoryDependent(const Instruction &I)
Returns true if the result or effects of the given instructions I depend on or influence global memor...
LLVM_NODISCARD bool empty() const
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
iterator_range< value_op_iterator > operand_values()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static bool isSafeAndProfitableToSpeculateAroundPHI(PHINode &PN, SmallDenseMap< PHINode *, int, 16 > &CostSavingsMap, SmallPtrSetImpl< Instruction *> &PotentialSpecSet, SmallPtrSetImpl< Instruction *> &UnsafeSet, DominatorTree &DT, TargetTransformInfo &TTI)
Check whether, in isolation, a given PHI node is both safe and profitable to speculate users around...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
static void speculatePHIs(ArrayRef< PHINode *> SpecPNs, SmallPtrSetImpl< Instruction *> &PotentialSpecSet, SmallSetVector< BasicBlock *, 16 > &PredSet, DominatorTree &DT)
Speculate users around a set of PHI nodes.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
A container for analyses that lazily runs them and caches their results.
const BasicBlock * getParent() const