45 #define DEBUG_TYPE "instcombine" 54 if (
auto *
C = dyn_cast<Constant>(V))
55 return IsConstantExtractIndex ||
C->getSplatValue();
61 return IsConstantExtractIndex;
91 for (
auto U : PN->
users()) {
97 }
else if (!PHIUser) {
98 PHIUser = cast<Instruction>(U);
116 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
124 if (PHIInVal == PHIUser) {
129 unsigned opId = (B0->
getOperand(0) == PN) ? 1 : 0;
134 Value *newPHIUser = InsertNewInstWith(
136 scalarPHI,
Op, B0), *B0);
144 if (pos && !isa<PHINode>(pos)) {
150 InsertNewInstWith(newEI, *InsertPos);
156 for (
auto E : Extracts)
157 replaceInstUsesWith(*
E, scalarPHI);
179 if (NumSrcElts == NumElts)
185 if (NumSrcElts < NumElts) {
196 unsigned NarrowingRatio = NumElts / NumSrcElts;
197 if (ExtIndexC / NarrowingRatio != InsIndexC)
211 unsigned Chunk = ExtIndexC % NarrowingRatio;
213 Chunk = NarrowingRatio - 1 - Chunk;
220 if (NeedSrcBitcast && NeedDestBitcast)
225 unsigned ShAmt = Chunk * DestWidth;
231 if (NeedSrcBitcast || NeedDestBitcast)
234 if (NeedSrcBitcast) {
246 if (NeedDestBitcast) {
264 case Instruction::ExtractElement: {
268 if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
273 case Instruction::ShuffleVector: {
277 UsedElts =
APInt(VWidth, 0);
278 for (
unsigned i = 0; i < MaskNumElts; i++) {
280 if (MaskVal == -1u || MaskVal >= 2 * VWidth)
282 if (Shuffle->
getOperand(0) == V && (MaskVal < VWidth))
285 ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
286 UsedElts.
setBit(MaskVal - VWidth);
303 APInt UnionUsedElts(VWidth, 0);
304 for (
const Use &U : V->
uses()) {
305 if (
Instruction *
I = dyn_cast<Instruction>(U.getUser())) {
316 return UnionUsedElts;
323 SQ.getWithInstruction(&EI)))
324 return replaceInstUsesWith(EI, V);
333 if (!IndexC->getValue().ule(NumElts))
341 APInt UndefElts(NumElts, 0);
342 APInt DemandedElts(NumElts, 0);
343 DemandedElts.
setBit(IndexC->getZExtValue());
345 SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts)) {
354 APInt UndefElts(NumElts, 0);
355 if (
Value *V = SimplifyDemandedVectorElts(
356 SrcVec, DemandedElts, UndefElts, 0 ,
371 if (
auto *Phi = dyn_cast<PHINode>(SrcVec))
372 if (
Instruction *ScalarPHI = scalarizePHI(EI, Phi))
380 Value *E0 = Builder.CreateExtractElement(X, Index);
381 Value *E1 = Builder.CreateExtractElement(
Y, Index);
390 Value *E0 = Builder.CreateExtractElement(X, Index);
391 Value *E1 = Builder.CreateExtractElement(Y, Index);
395 if (
auto *
I = dyn_cast<Instruction>(SrcVec)) {
396 if (
auto *
IE = dyn_cast<InsertElementInst>(
I)) {
398 if (
IE->getOperand(2) ==
Index)
399 return replaceInstUsesWith(EI,
IE->getOperand(1));
402 if (isa<Constant>(
IE->getOperand(2)) && IndexC) {
403 Worklist.AddValue(SrcVec);
407 }
else if (
auto *SVI = dyn_cast<ShuffleVectorInst>(
I)) {
410 if (
auto *Elt = dyn_cast<ConstantInt>(Index)) {
411 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
418 if (SrcIdx < (
int)LHSWidth)
419 Src = SVI->getOperand(0);
422 Src = SVI->getOperand(1);
429 }
else if (
auto *CI = dyn_cast<CastInst>(
I)) {
433 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
434 Value *EE = Builder.CreateExtractElement(CI->getOperand(0),
Index);
435 Worklist.AddValue(EE);
448 "Invalid CollectSingleShuffleElements");
451 if (isa<UndefValue>(V)) {
457 for (
unsigned i = 0; i != NumElts; ++i)
463 for (
unsigned i = 0; i != NumElts; ++i)
471 Value *VecOp = IEI->getOperand(0);
472 Value *ScalarOp = IEI->getOperand(1);
473 Value *IdxOp = IEI->getOperand(2);
475 if (!isa<ConstantInt>(IdxOp))
477 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
479 if (isa<UndefValue>(ScalarOp)) {
489 unsigned ExtractedIdx =
490 cast<ConstantInt>(EI->
getOperand(1))->getZExtValue();
500 Mask[InsertedIdx % NumElts] =
505 Mask[InsertedIdx % NumElts] =
507 ExtractedIdx + NumLHSElts);
532 NumExtElts >= NumInsElts)
541 for (
unsigned i = 0; i < NumExtElts; ++i)
543 for (
unsigned i = NumExtElts; i < NumInsElts; ++i)
548 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
561 if (InsertionBlock != InsElt->
getParent())
579 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
580 WideVec->insertAfter(ExtVecOpInst);
613 if (isa<UndefValue>(V)) {
615 return std::make_pair(
619 if (isa<ConstantAggregateZero>(V)) {
621 return std::make_pair(V,
nullptr);
626 Value *VecOp = IEI->getOperand(0);
627 Value *ScalarOp = IEI->getOperand(1);
628 Value *IdxOp = IEI->getOperand(2);
631 if (isa<ConstantInt>(EI->
getOperand(1)) && isa<ConstantInt>(IdxOp)) {
632 unsigned ExtractedIdx =
633 cast<ConstantInt>(EI->
getOperand(1))->getZExtValue();
634 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
638 if (EI->
getOperand(0) == PermittedRHS || PermittedRHS ==
nullptr) {
641 assert(LR.second ==
nullptr || LR.second == RHS);
643 if (LR.first->getType() != RHS->
getType()) {
650 for (
unsigned i = 0; i < NumElts; ++i)
652 return std::make_pair(V,
nullptr);
656 Mask[InsertedIdx % NumElts] =
658 NumLHSElts+ExtractedIdx);
659 return std::make_pair(LR.first, RHS);
662 if (VecOp == PermittedRHS) {
665 unsigned NumLHSElts =
667 for (
unsigned i = 0; i != NumElts; ++i)
670 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
671 return std::make_pair(EI->
getOperand(0), PermittedRHS);
679 return std::make_pair(EI->
getOperand(0), PermittedRHS);
685 for (
unsigned i = 0; i != NumElts; ++i)
687 return std::make_pair(V,
nullptr);
698 bool IsRedundant =
false;
712 if (UserInsInst->getIndices() == FirstIndices) {
721 return replaceInstUsesWith(I, I.
getOperand(0));
730 if (MaskSize != VecSize)
735 for (
int i = 0; i != MaskSize; ++i) {
737 if (Elt != -1 && Elt != i && Elt != i + VecSize)
753 auto *VecTy = cast<VectorType>(InsElt.
getType());
754 unsigned NumElements = VecTy->getNumElements();
758 if (NumElements == 1)
770 if (!Idx || CurrIE->
getOperand(1) != SplatVal)
777 if (CurrIE != &InsElt &&
778 (!CurrIE->
hasOneUse() && (NextIE !=
nullptr || !Idx->isZero())))
781 ElementPresent[Idx->getZExtValue()] =
true;
787 if (FirstIE == &InsElt)
795 if (
any_of(ElementPresent, [](
bool Present) {
return !Present; }))
807 for (
unsigned i = 0; i != NumElements; ++i)
808 if (!ElementPresent[i])
819 if (!Shuf || !Shuf->isZeroEltSplat())
829 Value *Op0 = Shuf->getOperand(0);
841 for (
unsigned i = 0; i != NumMaskElts; ++i)
842 NewMaskVec[i] = i == IdxC ? Zero : Shuf->getMask()->getAggregateElement(i);
853 if (!Shuf || !isa<UndefValue>(Shuf->getOperand(1)) ||
854 !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
865 Value *
X = Shuf->getOperand(0);
873 unsigned NumMaskElts = Shuf->getType()->getVectorNumElements();
877 Constant *OldMask = Shuf->getMask();
878 for (
unsigned i = 0; i != NumMaskElts; ++i) {
888 "Unexpected shuffle mask element for identity shuffle");
889 NewMaskVec[i] = NewMaskEltC;
909 if (!InsElt1 || !InsElt1->hasOneUse())
916 match(InsElt1->getOperand(1),
m_Value(Y)) && !isa<Constant>(Y) &&
933 if (!Inst || !Inst->hasOneUse())
935 if (
auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.
getOperand(0))) {
938 Constant *ShufConstVec, *InsEltScalar;
939 uint64_t InsEltIndex;
965 for (
unsigned I = 0;
I != NumElts; ++
I) {
966 if (
I == InsEltIndex) {
967 NewShufElts[
I] = InsEltScalar;
982 }
else if (
auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
987 uint64_t InsertIdx[2];
1000 for (uint64_t
I : InsertIdx) {
1010 for (
unsigned I = 0;
I < NumElts; ++
I) {
1032 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
1033 return replaceInstUsesWith(IE, V);
1037 Value *VecSrc, *ScalarSrc;
1045 Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1051 uint64_t InsertedIdx, ExtractedIdx;
1072 if (!Insert.hasOneUse())
1081 if (isShuffleRootCandidate(IE)) {
1087 if (LR.first != &IE && LR.second != &IE) {
1089 if (LR.second ==
nullptr)
1098 APInt UndefElts(VWidth, 0);
1100 if (
Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
1102 return replaceInstUsesWith(IE, V);
1119 return IdentityShuf;
1127 unsigned Depth = 5) {
1129 if (isa<Constant>(V))
1134 if (!I)
return false;
1140 if (
Depth == 0)
return false;
1143 case Instruction::UDiv:
1144 case Instruction::SDiv:
1145 case Instruction::URem:
1146 case Instruction::SRem:
1154 case Instruction::FAdd:
1155 case Instruction::Sub:
1156 case Instruction::FSub:
1157 case Instruction::Mul:
1158 case Instruction::FMul:
1159 case Instruction::FDiv:
1160 case Instruction::FRem:
1161 case Instruction::Shl:
1162 case Instruction::LShr:
1163 case Instruction::AShr:
1164 case Instruction::And:
1165 case Instruction::Or:
1166 case Instruction::Xor:
1167 case Instruction::ICmp:
1168 case Instruction::FCmp:
1169 case Instruction::Trunc:
1170 case Instruction::ZExt:
1171 case Instruction::SExt:
1172 case Instruction::FPToUI:
1173 case Instruction::FPToSI:
1174 case Instruction::UIToFP:
1175 case Instruction::SIToFP:
1176 case Instruction::FPTrunc:
1177 case Instruction::FPExt:
1178 case Instruction::GetElementPtr: {
1190 case Instruction::InsertElement: {
1192 if (!CI)
return false;
1197 bool SeenOnce =
false;
1198 for (
int i = 0,
e = Mask.
size(); i !=
e; ++i) {
1199 if (Mask[i] == ElementNumber) {
1218 case Instruction::FAdd:
1219 case Instruction::Sub:
1220 case Instruction::FSub:
1221 case Instruction::Mul:
1222 case Instruction::FMul:
1223 case Instruction::UDiv:
1224 case Instruction::SDiv:
1225 case Instruction::FDiv:
1226 case Instruction::URem:
1227 case Instruction::SRem:
1228 case Instruction::FRem:
1229 case Instruction::Shl:
1230 case Instruction::LShr:
1231 case Instruction::AShr:
1232 case Instruction::And:
1233 case Instruction::Or:
1234 case Instruction::Xor: {
1236 assert(NewOps.
size() == 2 &&
"binary operator with #ops != 2");
1239 NewOps[0], NewOps[1],
"", BO);
1240 if (isa<OverflowingBinaryOperator>(BO)) {
1244 if (isa<PossiblyExactOperator>(BO)) {
1245 New->setIsExact(BO->
isExact());
1247 if (isa<FPMathOperator>(BO))
1248 New->copyFastMathFlags(I);
1251 case Instruction::ICmp:
1252 assert(NewOps.
size() == 2 &&
"icmp with #ops != 2");
1254 NewOps[0], NewOps[1]);
1255 case Instruction::FCmp:
1256 assert(NewOps.
size() == 2 &&
"fcmp with #ops != 2");
1258 NewOps[0], NewOps[1]);
1259 case Instruction::Trunc:
1260 case Instruction::ZExt:
1261 case Instruction::SExt:
1262 case Instruction::FPToUI:
1263 case Instruction::FPToSI:
1264 case Instruction::UIToFP:
1265 case Instruction::SIToFP:
1266 case Instruction::FPTrunc:
1267 case Instruction::FPExt: {
1272 NewOps[0]->getType()->getVectorNumElements());
1273 assert(NewOps.
size() == 1 &&
"cast with #ops != 1");
1277 case Instruction::GetElementPtr: {
1278 Value *Ptr = NewOps[0];
1281 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx,
"", I);
1282 GEP->
setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1295 if (isa<UndefValue>(V))
1298 if (isa<ConstantAggregateZero>(V))
1301 if (
Constant *
C = dyn_cast<Constant>(V)) {
1303 for (
int i = 0,
e = Mask.
size(); i !=
e; ++i) {
1314 switch (I->getOpcode()) {
1316 case Instruction::FAdd:
1317 case Instruction::Sub:
1318 case Instruction::FSub:
1319 case Instruction::Mul:
1320 case Instruction::FMul:
1321 case Instruction::UDiv:
1322 case Instruction::SDiv:
1323 case Instruction::FDiv:
1324 case Instruction::URem:
1325 case Instruction::SRem:
1326 case Instruction::FRem:
1327 case Instruction::Shl:
1328 case Instruction::LShr:
1329 case Instruction::AShr:
1330 case Instruction::And:
1331 case Instruction::Or:
1332 case Instruction::Xor:
1333 case Instruction::ICmp:
1334 case Instruction::FCmp:
1335 case Instruction::Trunc:
1336 case Instruction::ZExt:
1337 case Instruction::SExt:
1338 case Instruction::FPToUI:
1339 case Instruction::FPToSI:
1340 case Instruction::UIToFP:
1341 case Instruction::SIToFP:
1342 case Instruction::FPTrunc:
1343 case Instruction::FPExt:
1345 case Instruction::GetElementPtr: {
1347 bool NeedsRebuild = (Mask.
size() != I->getType()->getVectorNumElements());
1348 for (
int i = 0,
e = I->getNumOperands(); i !=
e; ++i) {
1353 if (I->getOperand(i)->getType()->isVectorTy())
1356 V = I->getOperand(i);
1358 NeedsRebuild |= (V != I->getOperand(i));
1365 case Instruction::InsertElement: {
1366 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
1374 if (Mask[Index] == Element) {
1402 unsigned MaskElems = Mask.
size();
1403 unsigned BegIdx = Mask.
front();
1404 unsigned EndIdx = Mask.
back();
1405 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1407 for (
unsigned I = 0;
I != MaskElems; ++
I)
1408 if (static_cast<unsigned>(Mask[
I]) != BegIdx + I)
1421 Opcode(Opc), Op0(V0), Op1(V1) {}
1422 operator bool()
const {
return Opcode != 0; }
1433 case Instruction::Shl: {
1438 return { Instruction::Mul, BO0, ShlOne };
1442 case Instruction::Or: {
1456 assert(Shuf.
isSelect() &&
"Must have select-equivalent shuffle");
1473 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
1487 bool MightCreatePoisonOrUB =
1490 if (MightCreatePoisonOrUB)
1495 Value *
X = Op0IsBinop ? Op1 : Op0;
1535 for (
unsigned i = 0; i != NumMaskElts; ++i)
1570 bool ConstantsAreOp1;
1573 ConstantsAreOp1 =
true;
1576 ConstantsAreOp1 =
false;
1583 bool DropNSW =
false;
1584 if (ConstantsAreOp1 && Opc0 != Opc1) {
1588 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
1591 assert(isa<Constant>(AltB0.Op1) &&
"Expecting constant with alt binop");
1592 Opc0 = AltB0.Opcode;
1593 C0 = cast<Constant>(AltB0.Op1);
1595 assert(isa<Constant>(AltB1.Op1) &&
"Expecting constant with alt binop");
1596 Opc1 = AltB1.Opcode;
1597 C1 = cast<Constant>(AltB1.Op1);
1614 bool MightCreatePoisonOrUB =
1617 if (MightCreatePoisonOrUB)
1639 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
1693 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
1734 "Identity with extract must have less elements than its inputs");
1736 for (
unsigned i = 0; i != NumElts; ++i) {
1739 NewMask[i] = isa<UndefValue>(ExtractMaskElt) ? ExtractMaskElt : MaskElt;
1753 int NumElts = Mask.
size();
1766 if (
none_of(Mask, [IdxC](
int MaskElt) {
return MaskElt == (int)IdxC; })) {
1776 if (
none_of(Mask, [IdxC](
int MaskElt) {
return MaskElt == (int)IdxC; })) {
1791 int NewInsIndex = -1;
1792 for (
int i = 0; i != NumElts; ++i) {
1798 if (Mask[i] == NumElts + i)
1802 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
1809 assert(NewInsIndex != -1 &&
"Did not fold shuffle with unused operand?");
1821 if (isShufflingScalarIntoOp1(Scalar, IndexC))
1829 if (isShufflingScalarIntoOp1(Scalar, IndexC))
1841 if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
1842 !Shuffle1 || !Shuffle1->isIdentityWithPadding())
1850 Value *
X = Shuffle0->getOperand(0);
1851 Value *
Y = Shuffle1->getOperand(0);
1854 !
isPowerOf2_32(Shuffle0->getType()->getVectorNumElements()) ||
1856 isa<UndefValue>(X) || isa<UndefValue>(
Y))
1858 assert(isa<UndefValue>(Shuffle0->getOperand(1)) &&
1859 isa<UndefValue>(Shuffle1->getOperand(1)) &&
1860 "Unexpected operand for identity shuffle");
1867 int WideElts = Shuffle0->getType()->getVectorNumElements();
1868 assert(WideElts > NarrowElts &&
"Unexpected types for identity with padding");
1873 for (
int i = 0,
e = Mask.size(); i !=
e; ++i) {
1879 if (Mask[i] < WideElts) {
1880 if (Shuffle0->getMaskValue(Mask[i]) == -1)
1883 if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
1890 if (Mask[i] < WideElts) {
1891 assert(Mask[i] < NarrowElts &&
"Unexpected shuffle mask");
1894 assert(Mask[i] < (WideElts + NarrowElts) &&
"Unexpected shuffle mask");
1905 LHS, RHS, SVI.
getMask(), SVI.
getType(), SQ.getWithInstruction(&SVI)))
1906 return replaceInstUsesWith(SVI, V);
1914 assert(!isa<UndefValue>(RHS) &&
"Shuffle with 2 undef ops not simplified?");
1917 for (
unsigned i = 0; i != VWidth; ++i) {
1931 if (isa<UndefValue>(LHS)) {
1945 APInt UndefElts(VWidth, 0);
1947 if (
Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
1949 return replaceInstUsesWith(SVI, V);
1965 return replaceInstUsesWith(SVI, V);
1997 bool MadeChange =
false;
2000 unsigned MaskElems = Mask.
size();
2003 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->
getElementType());
2004 assert(SrcElemBitWidth &&
"vector elements must have a bitwidth");
2010 if (!BC->use_empty())
2014 unsigned BegIdx = Mask.
front();
2015 Type *TgtTy = BC->getDestTy();
2016 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
2017 if (!TgtElemBitWidth)
2019 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
2020 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
2021 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
2022 if (!VecBitWidthsEqual)
2027 if (!BegIsAligned) {
2032 for (
unsigned I = 0,
E = MaskElems, Idx = BegIdx;
I !=
E; ++Idx, ++
I)
2039 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
2040 assert(SrcElemsPerTgtElem);
2041 BegIdx /= SrcElemsPerTgtElem;
2042 bool BCAlreadyExists = NewBCs.
find(CastSrcTy) != NewBCs.
end();
2046 : Builder.CreateBitCast(V, CastSrcTy, SVI.
getName() +
".bc");
2047 if (!BCAlreadyExists)
2048 NewBCs[CastSrcTy] = NewBC;
2049 auto *
Ext = Builder.CreateExtractElement(
2053 replaceInstUsesWith(*BC,
Ext);
2104 if (!isa<UndefValue>(LHSShuffle->
getOperand(1)) && !isa<UndefValue>(RHS))
2105 LHSShuffle =
nullptr;
2107 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
2108 RHSShuffle =
nullptr;
2109 if (!LHSShuffle && !RHSShuffle)
2110 return MadeChange ? &SVI :
nullptr;
2112 Value* LHSOp0 =
nullptr;
2113 Value* LHSOp1 =
nullptr;
2114 Value* RHSOp0 =
nullptr;
2115 unsigned LHSOp0Width = 0;
2116 unsigned RHSOp0Width = 0;
2123 RHSOp0 = RHSShuffle->getOperand(0);
2126 Value* newLHS = LHS;
2127 Value* newRHS = RHS;
2130 if (isa<UndefValue>(RHS)) {
2135 else if (LHSOp0Width == LHSWidth) {
2140 if (RHSShuffle && RHSOp0Width == LHSWidth) {
2144 if (LHSOp0 == RHSOp0) {
2149 if (newLHS == LHS && newRHS == RHS)
2150 return MadeChange ? &SVI :
nullptr;
2156 if (RHSShuffle && newRHS != RHS)
2157 RHSMask = RHSShuffle->getShuffleMask();
2159 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
2165 for (
unsigned i = 0; i < VWidth; ++i) {
2170 }
else if (Mask[i] < (
int)LHSWidth) {
2175 if (newLHS != LHS) {
2176 eltMask = LHSMask[Mask[i]];
2179 if (eltMask >= (
int)LHSOp0Width && isa<UndefValue>(LHSOp1))
2188 if (isa<UndefValue>(RHS))
2192 else if (newRHS != RHS) {
2193 eltMask = RHSMask[Mask[i]-LHSWidth];
2196 if (eltMask >= (
int)RHSOp0Width) {
2197 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
2198 &&
"should have been check above");
2202 eltMask = Mask[i]-LHSWidth;
2210 if (eltMask >= 0 && newRHS !=
nullptr && newLHS != newRHS)
2211 eltMask += newLHSWidth;
2216 if (SplatElt >= 0 && SplatElt != eltMask)
2226 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
2228 for (
unsigned i = 0,
e = newMask.
size(); i !=
e; ++i) {
2229 if (newMask[i] < 0) {
2240 return MadeChange ? &SVI :
nullptr;
static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf)
std::pair< Value *, Value * > ShuffleOps
We are building a shuffle to create V, which is a sequence of insertelement, extractelement pairs...
Instruction * visitInsertValueInst(InsertValueInst &IV)
Try to find redundant insertvalue instructions, like the following ones: %0 = insertvalue { i8...
Type * getVectorElementType() const
bool isIdentityWithExtract() const
Return true if this shuffle extracts the first N elements of exactly one source vector.
Instruction * InsertNewInstWith(Instruction *New, Instruction &Old)
Same as InsertNewInstBefore, but also sets the debug loc.
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.
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
iterator_range< use_iterator > uses()
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
static Value * evaluateInDifferentElementOrder(Value *V, ArrayRef< int > Mask)
static Instruction * foldSelectShuffle(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
Try to fold shuffles that are the equivalent of a vector select.
Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register...
This class represents lattice values for constants.
BinaryOps getOpcode() const
static Instruction * foldConstantInsEltIntoShuffle(InsertElementInst &InsElt)
insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex –> shufflevector X...
static Instruction * foldInsEltIntoSplat(InsertElementInst &InsElt)
Try to fold an insert element into an existing splat shuffle by changing the shuffle's mask to includ...
void push_back(const T &Elt)
static bool cheapToScalarize(Value *V, bool IsConstantExtractIndex)
Return true if the value is cheaper to scalarize than it is to leave as a vector operation.
static ConstantAggregateZero * get(Type *Ty)
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static Instruction * foldIdentityExtractShuffle(ShuffleVectorInst &Shuf)
Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElement(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
ThreeOps_match< V1_t, V2_t, Mask_t, Instruction::ShuffleVector > m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m)
Matches ShuffleVectorInst.
static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, SmallVector< int, 16 > &Mask)
bool isVectorTy() const
True if this is an instance of VectorType.
static Instruction * hoistInsEltConst(InsertElementInst &InsElt2, InstCombiner::BuilderTy &Builder)
If we have an insertelement instruction feeding into another insertelement and the 2nd is inserting a...
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL)
Binops may be transformed into binops with different opcodes and operands.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
Constant * getMask() const
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
unsigned getBitWidth() const
Return the minimum number of bits in the Vector type.
void setBit(unsigned BitPosition)
Set a given bit to 1.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElement(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
'undef' values are things that do not have specified contents.
A Use represents the edge between a Value definition and its users.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
The core instruction combiner logic.
void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if 'V & Mask' is known to be zero.
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Instruction *CopyO, const Twine &Name="")
static APInt findDemandedEltsByAllUsers(Value *V)
Find union of elements of V demanded by all its users.
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
BinopElts(BinaryOperator::BinaryOps Opc=(BinaryOperator::BinaryOps) 0, Value *V0=nullptr, Value *V1=nullptr)
This file implements a class to represent arbitrary precision integral constant values and operations...
void assign(size_type NumElts, const T &Elt)
static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr)
Find elements of V demanded by UserInstr.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
static Instruction * canonicalizeInsertSplat(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
If we have an insert of a scalar to a non-zero element of an undefined vector and then shuffle that v...
static Instruction * foldShuffleWithInsert(ShuffleVectorInst &Shuf)
Try to replace a shuffle with an insertelement or try to replace a shuffle operand with the operand o...
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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...
This class represents a no-op cast from one type to another.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Instruction * visitExtractElementInst(ExtractElementInst &EI)
These are the ingredients in an alternate form binary operator as described below.
static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, SmallVectorImpl< Constant *> &Mask)
If V is a shuffle of values that ONLY returns elements from either LHS or RHS, return the shuffle mas...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isSelect() const
Return true if this shuffle chooses elements from its source vectors without lane crossings and all o...
VectorType * getType() const
Overload to return most specific vector type.
This class represents a truncation of integer types.
Value * getOperand(unsigned i) const
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
Instruction * visitInsertElementInst(InsertElementInst &IE)
Value * SimplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx, const SimplifyQuery &Q)
Given operands for an InsertElement, fold the result or return null.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
OneUse_match< T > m_OneUse(const T &SubPattern)
This instruction inserts a single (scalar) element into a VectorType value.
bool isAllOnesValue() const
Determine if all bits are set.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
The instances of the Type class are immutable: once they are created, they are never changed...
size_t size() const
size - Get the array size.
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
specific_intval m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
static Instruction * foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Class to represent integer types.
static void replaceExtractElements(InsertElementInst *InsElt, ExtractElementInst *ExtElt, InstCombiner &IC)
If we have insertion into a vector that is wider than the vector that we are extracting from...
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
static Instruction * foldInsSequenceIntoSplat(InsertElementInst &InsElt)
Turn a chain of inserts that splats a value into an insert + shuffle: insertelt(insertelt(insertelt(i...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool isExact() const
Determine whether the exact flag is set.
static int getMaskValue(const Constant *Mask, unsigned Elt)
Return the shuffle mask value for the specified element of the mask.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Value * SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask, Type *RetTy, const SimplifyQuery &Q)
Given operands for a ShuffleVectorInst, fold the result or return null.
void commute()
Swap the first 2 operands and adjust the mask to preserve the semantics of the instruction.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Iterator for intrusive lists based on ilist_node.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
This is the shared class of boolean and integer constants.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
BinaryOperator::BinaryOps Opcode
bool containsUndefElement() const
Return true if this is a vector constant that includes any undefined elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
static void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
static Instruction * foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf)
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 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.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void setOperand(unsigned i, Value *Val)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getVectorNumElements() const
Class to represent vector types.
Class for arbitrary precision integers.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
static IntegerType * getInt32Ty(LLVMContext &C)
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
Instruction * visitShuffleVectorInst(ShuffleVectorInst &SVI)
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 Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static bool canEvaluateShuffled(Value *V, ArrayRef< int > Mask, unsigned Depth=5)
Return true if we can evaluate the specified expression tree if the vector elements were shuffled in ...
static Instruction * foldBitcastExtElt(ExtractElementInst &Ext, InstCombiner::BuilderTy &Builder, bool IsBigEndian)
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static Instruction * narrowVectorSelect(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
Match a shuffle-select-shuffle pattern where the shuffles are widening and narrowing (concatenating w...
ArrayRef< unsigned > getIndices() const
LLVM Value Representation.
This file provides internal interfaces used to implement the InstCombine.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Value * SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &Q)
Given operands for an ExtractElementInst, fold the result or return null.
static Value * buildNew(Instruction *I, ArrayRef< Value *> NewOps)
Rebuild a new instruction just like 'I' but with the new operands given.
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.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Type * getElementType() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
static bool isSplat(ArrayRef< Value *> VL)
static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl< Constant *> &Mask, Value *PermittedRHS, InstCombiner &IC)
VectorType * getType() const
Overload to return most specific vector type.
static Instruction * foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt)
Try to fold an extract+insert element into an existing identity shuffle by changing the shuffle's mas...
static Constant * get(ArrayRef< Constant *> V)
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
const BasicBlock * getParent() const
This instruction inserts a struct field of array element value into an aggregate value.