42 #define DEBUG_TYPE "loop-utils" 47 if (!Set.
count(dyn_cast<Instruction>(*
Use)))
61 case RK_IntegerMinMax:
68 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
94 const APInt *M =
nullptr;
100 int32_t
Bits = (*M + 1).exactLogBase2();
117 bool IsSigned =
false;
128 MaxBitWidth =
Mask.getBitWidth() -
Mask.countLeadingZeros();
137 MaxBitWidth = NumTypeBits - NumSignBits;
163 Type *RecurrenceType,
170 while (!Worklist.
empty()) {
173 if (
auto *Cast = dyn_cast<CastInst>(Val))
174 if (Cast->getSrcTy() == RecurrenceType) {
184 for (
Value *
O : cast<User>(Val)->operands())
185 if (
auto *
I = dyn_cast<Instruction>(
O))
192 Loop *TheLoop,
bool HasFunNoNaNAttr,
214 bool FoundReduxOp =
false;
220 bool FoundStartPHI =
false;
225 unsigned NumCmpSelectPatternInst = 0;
232 bool IsSigned =
false;
243 if (!isFloatingPointRecurrenceKind(Kind))
246 if (!isIntegerRecurrenceKind(Kind))
248 if (isArithmeticRecurrenceKind(Kind))
249 Start =
lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
253 VisitedInsts.
insert(Start);
270 while (!Worklist.
empty()) {
280 bool IsAPhi = isa<PHINode>(Cur);
288 if (!Cur->
isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
289 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
297 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
303 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
304 hasMultipleUsesOf(Cur, VisitedInsts))
308 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
311 if (Kind == RK_IntegerMinMax &&
312 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
313 ++NumCmpSelectPatternInst;
314 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
315 ++NumCmpSelectPatternInst;
318 FoundReduxOp |= !IsAPhi && Cur != Start;
333 if (ExitInstruction == Cur)
340 if (ExitInstruction !=
nullptr || Cur == Phi)
349 ExitInstruction = Cur;
356 InstDesc IgnoredVal(
false,
nullptr);
357 if (VisitedInsts.
insert(UI).second) {
358 if (isa<PHINode>(UI))
362 }
else if (!isa<PHINode>(UI) &&
363 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
364 !isa<SelectInst>(UI)) ||
365 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
370 FoundStartPHI =
true;
378 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
379 NumCmpSelectPatternInst != 2)
382 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
411 std::tie(ComputedType, IsSigned) =
413 if (ComputedType != RecurrenceType)
448 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
449 "Expect a select instruction");
455 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
462 if (!(Select = dyn_cast<SelectInst>(I)))
464 if (!(Cmp = dyn_cast<ICmpInst>(I->
getOperand(0))) &&
475 return InstDesc(Select, MRK_UIntMin);
477 return InstDesc(Select, MRK_UIntMax);
479 return InstDesc(Select, MRK_SIntMax);
481 return InstDesc(Select, MRK_SIntMin);
483 return InstDesc(Select, MRK_FloatMin);
485 return InstDesc(Select, MRK_FloatMax);
487 return InstDesc(Select, MRK_FloatMin);
489 return InstDesc(Select, MRK_FloatMax);
496 InstDesc &Prev,
bool HasFunNoNaNAttr) {
499 if (!UAI && FP && !I->
isFast())
505 case Instruction::PHI:
507 case Instruction::Sub:
509 return InstDesc(Kind == RK_IntegerAdd, I);
510 case Instruction::Mul:
511 return InstDesc(Kind == RK_IntegerMult, I);
512 case Instruction::And:
513 return InstDesc(Kind == RK_IntegerAnd, I);
514 case Instruction::Or:
515 return InstDesc(Kind == RK_IntegerOr, I);
516 case Instruction::Xor:
517 return InstDesc(Kind == RK_IntegerXor, I);
518 case Instruction::FMul:
519 return InstDesc(Kind == RK_FloatMult, I, UAI);
520 case Instruction::FSub:
521 case Instruction::FAdd:
522 return InstDesc(Kind == RK_FloatAdd, I, UAI);
523 case Instruction::FCmp:
524 case Instruction::ICmp:
526 if (Kind != RK_IntegerMinMax &&
527 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
529 return isMinMaxSelectCmpPattern(I, Prev);
535 unsigned NumUses = 0;
538 if (Insts.
count(dyn_cast<Instruction>(*
Use)))
553 bool HasFunNoNaNAttr =
556 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
558 LLVM_DEBUG(
dbgs() <<
"Found an ADD reduction PHI." << *Phi <<
"\n");
561 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
563 LLVM_DEBUG(
dbgs() <<
"Found a MUL reduction PHI." << *Phi <<
"\n");
566 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB,
568 LLVM_DEBUG(
dbgs() <<
"Found an OR reduction PHI." << *Phi <<
"\n");
571 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
573 LLVM_DEBUG(
dbgs() <<
"Found an AND reduction PHI." << *Phi <<
"\n");
576 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
578 LLVM_DEBUG(
dbgs() <<
"Found a XOR reduction PHI." << *Phi <<
"\n");
581 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes,
583 LLVM_DEBUG(
dbgs() <<
"Found a MINMAX reduction PHI." << *Phi <<
"\n");
586 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
588 LLVM_DEBUG(
dbgs() <<
"Found an FMult reduction PHI." << *Phi <<
"\n");
591 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
593 LLVM_DEBUG(
dbgs() <<
"Found an FAdd reduction PHI." << *Phi <<
"\n");
596 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB,
598 LLVM_DEBUG(
dbgs() <<
"Found an float MINMAX reduction PHI." << *Phi
619 if (!Preheader || !Latch)
630 if (!Previous || !TheLoop->
contains(Previous) || isa<PHINode>(Previous) ||
631 SinkAfter.
count(Previous))
641 if (
I->isCast() && (
I->getParent() == Phi->
getParent()) &&
I->hasOneUse() &&
644 SinkAfter[
I] = Previous;
650 if (
auto *
I = dyn_cast<Instruction>(U)) {
691 return Instruction::Mul;
693 return Instruction::Or;
695 return Instruction::And;
697 return Instruction::Xor;
699 return Instruction::FMul;
701 return Instruction::FAdd;
702 case RK_IntegerMinMax:
703 return Instruction::ICmp;
705 return Instruction::FCmp;
746 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
747 Cmp = Builder.
CreateFCmp(P, Left, Right,
"rdx.minmax.cmp");
749 Cmp = Builder.
CreateICmp(P, Left, Right,
"rdx.minmax.cmp");
758 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
759 assert(IK != IK_NoInduction &&
"Not an induction");
763 assert(StartValue &&
"StartValue is null");
764 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
765 "StartValue is not a pointer for pointer induction");
766 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
767 "StartValue is not an integer for integer induction");
770 assert((!getConstIntStepValue() || !getConstIntStepValue()->
isZero()) &&
771 "Step value is zero");
773 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
774 "Step value should be constant for pointer induction");
776 "StepValue is not an integer");
779 "StepValue is not FP for FpInduction");
780 assert((IK != IK_FpInduction || (InductionBinOp &&
781 (InductionBinOp->getOpcode() == Instruction::FAdd ||
782 InductionBinOp->getOpcode() == Instruction::FSub))) &&
783 "Binary opcode should be specified for FP induction");
786 for (
auto &Inst : *Casts) {
787 RedundantCasts.push_back(Inst);
800 if (isa<SCEVConstant>(Step))
811 "Index type does not match StepValue type");
813 case IK_IntInduction: {
815 "Index type does not match StartValue type");
825 if (getConstIntStepValue() &&
826 getConstIntStepValue()->isMinusOne())
828 if (getConstIntStepValue() &&
829 getConstIntStepValue()->isOne())
835 case IK_PtrInduction: {
836 assert(isa<SCEVConstant>(Step) &&
837 "Expected constant step for pointer induction");
840 return B.
CreateGEP(
nullptr, StartValue, Index);
842 case IK_FpInduction: {
845 (InductionBinOp->getOpcode() == Instruction::FAdd ||
846 InductionBinOp->getOpcode() == Instruction::FSub) &&
847 "Original bin op should be defined for FP induction");
849 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
856 if (isa<Instruction>(MulExp))
858 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
861 MulExp,
"induction");
862 if (isa<Instruction>(BOp))
863 cast<Instruction>(BOp)->setFastMathFlags(Flags);
887 Value *BEValue =
nullptr, *StartValue =
nullptr;
893 "Unexpected Phi node in the loop");
902 Value *Addend =
nullptr;
903 if (BOp->
getOpcode() == Instruction::FAdd) {
908 }
else if (BOp->
getOpcode() == Instruction::FSub)
916 if (
auto *
I = dyn_cast<Instruction>(Addend))
963 assert(CastInsts.
empty() &&
"CastInsts is expected to be empty.");
964 auto *PN = cast<PHINode>(PhiScev->
getValue());
965 assert(PSE.
getSCEV(PN) == AR &&
"Unexpected phi node SCEV expression");
983 if (L->isLoopInvariant(Op0))
985 else if (L->isLoopInvariant(Op1))
995 Value *Val = PN->getIncomingValueForBlock(Latch);
1003 bool InCastSequence =
false;
1008 if (!Inst || !L->contains(Inst)) {
1013 InCastSequence =
true;
1014 if (InCastSequence) {
1017 if (!CastInsts.
empty())
1018 if (!Inst->hasOneUse())
1028 return InCastSequence;
1046 return isFPInductionPHI(Phi, TheLoop, PSE.
getSE(),
D);
1067 if (PhiScev != AR && SymbolicPhi) {
1070 return isInductionPHI(Phi, TheLoop, PSE.
getSE(),
D, AR, &Casts);
1073 return isInductionPHI(Phi, TheLoop, PSE.
getSE(),
D, AR);
1086 const SCEV *PhiScev = Expr ? Expr : SE->
getSCEV(Phi);
1094 if (AR->
getLoop() != TheLoop) {
1098 dbgs() <<
"LV: PHI is a recurrence with respect to an outer loop.\n");
1126 if (!PointerElementType->
isSized())
1144 bool PreserveLCSSA) {
1145 bool Changed =
false;
1152 "Must start with an empty predecessors list!");
1157 bool IsDedicatedExit =
true;
1160 if (isa<IndirectBrInst>(PredBB->getTerminator()))
1166 IsDedicatedExit =
false;
1169 assert(!InLoopPredecessors.
empty() &&
"Must have *some* loop predecessor!");
1172 if (IsDedicatedExit)
1176 BB, InLoopPredecessors,
".loopexit", DT, LI, PreserveLCSSA);
1180 dbgs() <<
"WARNING: Can't create a dedicated exit block for loop: " 1183 LLVM_DEBUG(
dbgs() <<
"LoopSimplify: Creating dedicated exit block " 1184 << NewExitBB->getName() <<
"\n");
1191 for (
auto *BB : L->
blocks())
1198 if (!Visited.
insert(SuccBB).second)
1201 Changed |= RewriteExit(SuccBB);
1214 for (
auto &Inst : *Block) {
1215 auto Users = Inst.users();
1217 auto *
Use = cast<Instruction>(U);
1327 auto AddRegionToWorklist = [&](
DomTreeNode *DTN) {
1334 AddRegionToWorklist(N);
1336 for (
size_t I = 0;
I < Worklist.
size();
I++)
1338 AddRegionToWorklist(Child);
1348 assert(Preheader &&
"Preheader should exist!");
1363 assert(ExitBlock &&
"Should have a unique exit block!");
1367 assert(OldBr &&
"Preheader must end with a branch");
1368 assert(OldBr->isUnconditional() &&
"Preheader must have a single successor");
1395 Builder.CreateCondBr(Builder.getFalse(), L->
getHeader(), ExitBlock);
1397 OldBr->eraseFromParent();
1401 for (
PHINode &
P : ExitBlock->phis()) {
1406 P.setIncomingBlock(PredIndex, Preheader);
1414 for (
unsigned i = 0, e =
P.getNumIncomingValues() - 1; i != e; ++i)
1415 P.removeIncomingValue(e - i,
false);
1417 assert((
P.getNumIncomingValues() == 1 &&
1418 P.getIncomingBlock(PredIndex) == Preheader) &&
1419 "Should have exactly one value and that's from the preheader!");
1423 Builder.SetInsertPoint(Preheader->getTerminator());
1424 Builder.CreateBr(ExitBlock);
1426 Preheader->getTerminator()->eraseFromParent();
1431 DT->insertEdge(Preheader, ExitBlock);
1433 DT->deleteEdge(Preheader, L->
getHeader());
1444 for (
auto *Block : L->
blocks())
1450 if (
auto *Usr = dyn_cast<Instruction>(U.
getUser()))
1456 assert(!DT->isReachableFromEntry(U) &&
1457 "Unexpected user in reachable block");
1464 for (
auto *Block : L->
blocks())
1465 Block->dropAllReferences();
1474 (*LpI)->eraseFromParent();
1482 LI->removeBlock(BB);
1502 "At least one edge out of the latch must go to the header");
1507 uint64_t TrueVal, FalseVal;
1511 if (!TrueVal || !FalseVal)
1517 return (TrueVal + (FalseVal / 2)) / FalseVal;
1519 return (FalseVal + (TrueVal / 2)) / TrueVal;
1524 if (isa<FPMathOperator>(V)) {
1527 cast<Instruction>(V)->setFastMathFlags(Flags);
1543 for (
unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
1547 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1557 if (!RedOps.
empty())
1574 "Reduction emission only supported for pow2 vectors!");
1575 Value *TmpVec = Src;
1577 for (
unsigned i = VF; i != 1; i >>= 1) {
1579 for (
unsigned j = 0; j != i / 2; ++j)
1580 ShuffleMask[j] = Builder.
getInt32(i / 2 + j);
1583 std::fill(&ShuffleMask[i / 2], ShuffleMask.
end(),
1590 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1593 TmpVec, Shuf,
"bin.rdx"));
1600 if (!RedOps.
empty())
1613 assert(isa<VectorType>(Src->
getType()) &&
"Type must be a vector");
1616 std::function<Value*()> BuildFunc;
1618 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1627 case Instruction::Mul:
1630 case Instruction::And:
1633 case Instruction::Or:
1636 case Instruction::Xor:
1639 case Instruction::FAdd:
1642 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1646 case Instruction::FMul:
1649 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1653 case Instruction::ICmp:
1655 MinMaxKind = Flags.
IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1660 MinMaxKind = Flags.
IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1666 case Instruction::FCmp:
1668 MinMaxKind = RD::MRK_FloatMax;
1671 MinMaxKind = RD::MRK_FloatMin;
1693 Flags.
NoNaN = NoNaN;
1695 case RD::RK_FloatAdd:
1697 case RD::RK_FloatMult:
1699 case RD::RK_IntegerAdd:
1701 case RD::RK_IntegerMult:
1703 case RD::RK_IntegerAnd:
1705 case RD::RK_IntegerOr:
1707 case RD::RK_IntegerXor:
1709 case RD::RK_IntegerMinMax: {
1711 Flags.
IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
1712 Flags.
IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
1715 case RD::RK_FloatMinMax: {
1728 auto *Intersection = (OpValue ==
nullptr) ? dyn_cast<Instruction>(VL[0])
1732 const unsigned Opcode = Intersection->
getOpcode();
1733 VecOp->copyIRFlags(Intersection);
1734 for (
auto *V : VL) {
1738 if (OpValue ==
nullptr || Opcode == Instr->getOpcode())
Legacy wrapper pass to provide the GlobalsAAResult object.
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
Type * getVectorElementType() const
static bool isArithmeticRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is an arithmetic kind.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
static bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D)
Returns true if Phi is a floating point induction in the loop L.
void setFast(bool B=true)
InductionDescriptor()=default
Default constructor - creates an invalid induction.
const SCEV * getConstant(ConstantInt *V)
static Instruction * lookThroughAnd(PHINode *Phi, Type *&RT, SmallPtrSetImpl< Instruction *> &Visited, SmallPtrSetImpl< Instruction *> &CI)
Determines if Phi may have been type-promoted.
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
This is the interface for a simple mod/ref and alias analysis over globals.
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction *> *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
int getConsecutiveDirection() const
Get the consecutive direction.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
ConstantInt * getConstIntStepValue() const
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
static bool AddReductionVar(PHINode *Phi, RecurrenceKind Kind, Loop *TheLoop, bool HasFunNoNaNAttr, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction of type Kind and adds it to the RecurrenceDescriptor.
The main scalar evolution driver.
A global registry used in conjunction with static constructors to make pluggable components (like tar...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
A cache of @llvm.assume calls within a function.
0 1 0 0 True if ordered and less than
Value * createSimpleTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, unsigned Opcode, Value *Src, TargetTransformInfo::ReductionFlags Flags=TargetTransformInfo::ReductionFlags(), ArrayRef< Value *> RedOps=None)
Create a target reduction of the given vector.
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
LLVMContext & getContext() const
All values hold a context through their type.
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
BasicBlock * getSuccessor(unsigned i) const
MinMaxRecurrenceKind getMinMaxRecurrenceKind()
const MDOperand & getOperand(unsigned I) const
Value * getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind=RecurrenceDescriptor::MRK_Invalid, ArrayRef< Value *> RedOps=None)
Generates a vector reduction using shufflevectors to reduce the value.
MaxMin_match< FCmpInst, LHS, RHS, ufmax_pred_ty > m_UnordFMax(const LHS &L, const RHS &R)
Match an 'unordered' floating point maximum function.
iv Induction Variable Users
static InstDesc isRecurrenceInstr(Instruction *I, RecurrenceKind Kind, InstDesc &Prev, bool HasFunNoNaNAttr)
Returns a struct describing if the instruction 'I' can be a recurrence variable of type 'Kind'...
static bool hasMultipleUsesOf(Instruction *I, SmallPtrSetImpl< Instruction *> &Insts)
Returns true if instruction I has multiple uses in Insts.
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
This is the interface for a SCEV-based alias analysis.
void initializeLoopPassPass(PassRegistry &)
Manually defined generic "LoopPass" dependency initialization.
This class represents the LLVM 'select' instruction.
Type * getPointerElementType() const
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
unsigned getNumSuccessors() const
CallInst * CreateFAddReduce(Value *Acc, Value *Src)
Create a vector fadd reduction intrinsic of the source vector.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl< Instruction *> &Set)
Returns true if all uses of the instruction I is within the Set.
static InstDesc isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev)
Returns a struct describing if the instruction if the instruction is a Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y) or max(X, Y).
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
MaxMin_match< FCmpInst, LHS, RHS, ufmin_pred_ty > m_UnordFMin(const LHS &L, const RHS &R)
Match an 'unordered' floating point minimum function.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
SmallVector< Instruction *, 8 > findDefsUsedOutsideOfLoop(Loop *L)
Returns the instructions that use values defined in the loop.
BlockT * getHeader() const
CallInst * CreateFPMinReduce(Value *Src, bool NoNaN=false)
Create a vector float min reduction intrinsic of the source vector.
void deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, LoopInfo *LI)
This function deletes dead loops.
Value * getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src, unsigned Op, RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind=RecurrenceDescriptor::MRK_Invalid, ArrayRef< Value *> RedOps=None)
Generates an ordered vector reduction using extracts to reduce the value.
ConstantInt * getValue() const
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Type * getType() const
All values are typed, get the type of this value.
This node represents a polynomial recurrence on the trip count of the specified loop.
This instruction compares its operands according to the predicate given to the constructor.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
MaxMin_match< FCmpInst, LHS, RHS, ofmin_pred_ty > m_OrdFMin(const LHS &L, const RHS &R)
Match an 'ordered' floating point minimum function.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
const SCEVAddRecExpr * getAsAddRec(Value *V)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
AnalysisUsage & addPreservedID(const void *ID)
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
This POD struct holds information about a potential recurrence operation.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
use_iterator_impl< Use > use_iterator
static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit, Type *RecurrenceType, SmallPtrSetImpl< Instruction *> &Casts)
Collect cast instructions that can be ignored in the vectorizer's cost model, given a reduction exit ...
CallInst * CreateXorReduce(Value *Src)
Create a vector int XOR reduction intrinsic of the source vector.
bool isNegative() const
Returns true if this value is known to be negative.
StringRef getString() const
static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE, const SCEVUnknown *PhiScev, const SCEVAddRecExpr *AR, SmallVectorImpl< Instruction *> &CastInsts)
This function is called when we suspect that the update-chain of a phi node (whose symbolic SCEV expr...
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
bool isPointerTy() const
True if this is an instance of PointerType.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
Represent the analysis usage information of a pass.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
bool isFast() const
Determine whether all fast-math-flags are set.
Instruction * getUnsafeAlgebraInst()
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
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...
bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Returns true if Phi is a reduction in TheLoop.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
RecurrenceKind getRecurrenceKind()
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Optional< const MDOperand * > findStringMetadataForLoop(Loop *TheLoop, StringRef Name)
Find string metadata for loop.
static unsigned getRecurrenceBinOp(RecurrenceKind Kind)
Returns the opcode of binary operation corresponding to the RecurrenceKind.
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void propagateIRFlags(Value *I, ArrayRef< Value *> VL, Value *OpValue=nullptr)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
static bool isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, DenseMap< Instruction *, Instruction *> &SinkAfter, DominatorTree *DT)
Returns true if Phi is a first-order recurrence.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
0 0 1 0 True if ordered and greater than
Value * transform(IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL) const
Compute the transformed value of Index at offset StartValue using step StepValue. ...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
MinMaxRecurrenceKind getMinMaxKind()
CallInst * CreateAddReduce(Value *Src)
Create a vector int add reduction intrinsic of the source vector.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Legacy wrapper pass to provide the SCEVAAResult object.
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
A struct for saving information about induction variables.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return the number of times the sign bit of the register is replicated into the other bits...
CallInst * CreateIntMaxReduce(Value *Src, bool IsSigned=false)
Create a vector integer max reduction intrinsic of the source vector.
AnalysisUsage & addRequiredID(const void *ID)
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.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
static bool isFloatingPointRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is a floating point kind.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
pred_range predecessors(BasicBlock *BB)
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
CallInst * CreateFMulReduce(Value *Acc, Value *Src)
Create a vector fmul reduction intrinsic of the source vector.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
APInt getDemandedBits(Instruction *I)
Return the bits demanded from instruction I.
bool isCommutative() const
Return true if the instruction is commutative:
Value * createTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, RecurrenceDescriptor &Desc, Value *Src, bool NoNaN=false)
Create a generic target reduction using a recurrence descriptor Desc The target is queried to determi...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned getVectorNumElements() const
static Constant * getRecurrenceIdentity(RecurrenceKind K, Type *Tp)
Returns identity corresponding to the RecurrenceKind.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
iterator_range< user_iterator > users()
static Value * createMinMaxOp(IRBuilder<> &Builder, MinMaxRecurrenceKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
This class uses information about analyze scalars to rewrite expressions in canonical form...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
CallInst * CreateAndReduce(Value *Src)
Create a vector int AND reduction intrinsic of the source vector.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
static MachineInstr * getDef(unsigned Reg, const MachineRegisterInfo *MRI)
CallInst * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
CallInst * CreateIntMinReduce(Value *Src, bool IsSigned=false)
Create a vector integer min reduction intrinsic of the source vector.
This class represents an analyzed expression in the program.
static bool isIntegerRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is an integer kind.
LLVM_NODISCARD bool empty() const
StringRef getValueAsString() const
Return the attribute's value as a string.
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
CallInst * CreateMulReduce(Value *Src)
Create a vector int mul reduction intrinsic of the source vector.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
block_iterator block_end() const
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
SmallVector< DomTreeNode *, 16 > collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
static std::pair< Type *, bool > computeRecurrenceType(Instruction *Exit, DemandedBits *DB, AssumptionCache *AC, DominatorTree *DT)
Compute the minimal bit width needed to represent a reduction whose exit instruction is given by Exit...
MaxMin_match< FCmpInst, LHS, RHS, ofmax_pred_ty > m_OrdFMax(const LHS &L, const RHS &R)
Match an 'ordered' floating point maximum function.
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
BasicBlock::iterator GetInsertPoint() const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
const SCEV * getUnknown(Value *V)
The legacy pass manager's analysis pass to compute loop information.
bool hasOneUse() const
Return true if there is exactly one user of this value.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
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...
CallInst * CreateFPMaxReduce(Value *Src, bool NoNaN=false)
Create a vector float max reduction intrinsic of the source vector.
unsigned getNumOperands() const
Return number of MDNode operands.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
iterator_range< block_iterator > blocks() const
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
static Value * addFastMathFlag(Value *V)
Adds a 'fast' flag to floating point operations.
block_iterator block_begin() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static Constant * get(ArrayRef< Constant *> V)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
bool empty() const
empty - Check if the array is empty.
RecurrenceKind
This enum represents the kinds of recurrences that we support.
const BasicBlock * getParent() const
This class represents a constant integer value.
Legacy wrapper pass to provide the BasicAAResult object.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.