25 #define DEBUG_TYPE "instcombine" 34 Offset = CI->getZExtValue();
48 if (
ConstantInt *RHS = dyn_cast<ConstantInt>(
I->getOperand(1))) {
49 if (
I->getOpcode() == Instruction::Shl) {
51 Scale = UINT64_C(1) << RHS->getZExtValue();
53 return I->getOperand(0);
56 if (
I->getOpcode() == Instruction::Mul) {
58 Scale = RHS->getZExtValue();
60 return I->getOperand(0);
69 Offset += RHS->getZExtValue();
89 AllocaBuilder.SetInsertPoint(&AI);
96 unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
97 unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
98 if (CastElTyAlign < AllocElTyAlign)
return nullptr;
103 if (!AI.
hasOneUse() && CastElTyAlign == AllocElTyAlign)
return nullptr;
105 uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
106 uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
107 if (CastElTySize == 0 || AllocElTySize == 0)
return nullptr;
111 uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
112 uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
113 if (!AI.
hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize)
return nullptr;
117 unsigned ArraySizeScale;
118 uint64_t ArrayOffset;
124 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
125 (AllocElTySize*ArrayOffset ) % CastElTySize != 0)
return nullptr;
127 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
128 Value *Amt =
nullptr;
134 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
137 if (uint64_t
Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
140 Amt = AllocaBuilder.CreateAdd(Amt, Off);
143 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
154 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.
getType(),
"tmpcast");
155 replaceInstUsesWith(AI, NewCast);
157 return replaceInstUsesWith(CI, New);
164 if (
Constant *
C = dyn_cast<Constant>(V)) {
178 case Instruction::Sub:
179 case Instruction::Mul:
180 case Instruction::And:
181 case Instruction::Or:
182 case Instruction::Xor:
183 case Instruction::AShr:
184 case Instruction::LShr:
185 case Instruction::Shl:
186 case Instruction::UDiv:
187 case Instruction::URem: {
193 case Instruction::Trunc:
194 case Instruction::ZExt:
195 case Instruction::SExt:
205 Opc == Instruction::SExt);
209 Value *False = EvaluateInDifferentType(I->
getOperand(2), Ty, isSigned);
213 case Instruction::PHI: {
230 return InsertNewInstWith(Res, *I);
248 DstTy, SrcIntPtrTy, MidIntPtrTy,
253 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
254 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
265 if (
auto *CSrc = dyn_cast<CastInst>(Src)) {
272 if (CSrc->hasOneUse())
278 if (
auto *Sel = dyn_cast<SelectInst>(Src)) {
284 if (!Cmp || Cmp->getOperand(0)->getType() != Sel->getType())
292 if (
auto *PN = dyn_cast<PHINode>(Src)) {
307 if (isa<Constant>(V))
320 assert(!isa<Constant>(V) &&
"Constant should already be handled.");
321 if (!isa<Instruction>(V))
349 auto *
I = cast<Instruction>(V);
351 switch (
I->getOpcode()) {
353 case Instruction::Sub:
354 case Instruction::Mul:
355 case Instruction::And:
356 case Instruction::Or:
357 case Instruction::Xor:
362 case Instruction::UDiv:
363 case Instruction::URem: {
365 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
367 assert(BitWidth < OrigBitWidth &&
"Unexpected bitwidths!");
369 if (IC.MaskedValueIsZero(
I->getOperand(0),
Mask, 0, CxtI) &&
370 IC.MaskedValueIsZero(
I->getOperand(1),
Mask, 0, CxtI)) {
376 case Instruction::Shl: {
387 case Instruction::LShr: {
393 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
396 IC.MaskedValueIsZero(
I->getOperand(0),
403 case Instruction::AShr: {
411 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
414 OrigBitWidth - BitWidth <
415 IC.ComputeNumSignBits(
I->getOperand(0), 0, CxtI))
420 case Instruction::Trunc:
423 case Instruction::ZExt:
424 case Instruction::SExt:
433 case Instruction::PHI: {
460 if (!TruncOp->
hasOneUse() || !isa<IntegerType>(DestType))
463 Value *VecInput =
nullptr;
468 !isa<VectorType>(VecInput->
getType()))
474 unsigned ShiftAmount = ShiftVal ? ShiftVal->
getZExtValue() : 0;
476 if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0))
481 unsigned NumVecElts = VecWidth / DestWidth;
487 unsigned Elt = ShiftAmount / DestWidth;
489 Elt = NumVecElts - 1 - Elt;
499 "Don't narrow to an illegal scalar type");
514 Value *ShVal, *ShAmt0, *ShAmt1;
519 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->
getOpcode();
520 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->
getOpcode();
521 if (ShiftOpcode0 == ShiftOpcode1)
526 auto matchShiftAmount = [](
Value *L,
Value *R,
unsigned Width) ->
Value * {
535 unsigned Mask = Width - 1;
548 Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, NarrowWidth);
549 bool SubIsOnLHS =
false;
551 ShAmt = matchShiftAmount(ShAmt1, ShAmt0, NarrowWidth);
568 Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy);
569 Value *
X = Builder.CreateTrunc(ShVal, DestTy);
570 bool IsFshl = (!SubIsOnLHS && ShiftOpcode0 == BinaryOperator::Shl) ||
571 (SubIsOnLHS && ShiftOpcode1 == BinaryOperator::Shl);
583 if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy))
593 case Instruction::And:
594 case Instruction::Or:
595 case Instruction::Xor:
597 case Instruction::Sub:
598 case Instruction::Mul: {
603 Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy);
609 Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy);
615 Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy);
620 Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy);
641 if (Shuf && Shuf->hasOneUse() && isa<UndefValue>(Shuf->getOperand(1)) &&
642 Shuf->getMask()->getSplatValue() &&
643 Shuf->getType() == Shuf->getOperand(0)->getType()) {
661 assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) &&
662 "Unexpected instruction for shrinking");
665 if (!InsElt || !InsElt->hasOneUse())
670 Value *VecOp = InsElt->getOperand(0);
671 Value *ScalarOp = InsElt->getOperand(1);
674 if (isa<UndefValue>(VecOp)) {
686 if (
Instruction *Result = commonCastTransforms(CI))
696 if ((DestTy->
isVectorTy() || shouldChangeType(SrcTy, DestTy)) &&
702 dbgs() <<
"ICE: EvaluateInDifferentType converting expression type" 705 Value *Res = EvaluateInDifferentType(Src, DestTy,
false);
707 return replaceInstUsesWith(CI, Res);
721 if (SimplifyDemandedInstructionBits(CI))
742 APInt MaskC =
APInt(SrcTy->getScalarSizeInBits(), 1).shl(*C);
749 APInt MaskC =
APInt(SrcTy->getScalarSizeInBits(), 1).shl(*C) | 1;
789 Value *SExt = cast<Instruction>(Src)->getOperand(0);
793 const unsigned MaxAmt = SExtSize -
std::max(CISize, ASize);
801 if (ShiftAmt <= MaxAmt) {
804 std::min(ShiftAmt, ASize - 1)));
806 Value *Shift = Builder.CreateAShr(A, std::min(ShiftAmt, ASize - 1));
822 if (Src->
hasOneUse() && isa<IntegerType>(SrcTy) &&
823 shouldChangeType(SrcTy, DestTy)) {
832 Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->
getName() +
".tr");
835 Instruction::Shl, NewTrunc,
859 if (!DoTransform)
return ICI;
864 In = Builder.CreateLShr(In, Sh, In->
getName() +
".lobit");
865 if (In->getType() != CI.
getType())
866 In = Builder.CreateIntCast(In, CI.
getType(),
false );
870 In = Builder.CreateXor(In, One, In->
getName() +
".not");
873 return replaceInstUsesWith(CI, In);
891 if (KnownZeroMask.isPowerOf2()) {
892 if (!DoTransform)
return ICI;
895 if (!Op1CV->
isNullValue() && (*Op1CV != KnownZeroMask)) {
899 return replaceInstUsesWith(CI, Res);
902 uint32_t ShAmt = KnownZeroMask.logBase2();
913 In = Builder.CreateXor(In, One);
917 return replaceInstUsesWith(CI, In);
919 Value *IntCast = Builder.CreateIntCast(In, CI.
getType(),
false);
920 return replaceInstUsesWith(CI, IntCast);
936 if (KnownLHS.
Zero == KnownRHS.
Zero && KnownLHS.
One == KnownRHS.
One) {
938 APInt UnknownBit = ~KnownBits;
940 if (!DoTransform)
return ICI;
942 Value *Result = Builder.CreateXor(LHS, RHS);
945 if (KnownLHS.
One.
uge(UnknownBit))
946 Result = Builder.CreateAnd(Result,
950 Result = Builder.CreateLShr(
956 return replaceInstUsesWith(CI, Result);
991 auto *
I = cast<Instruction>(V);
993 switch (
I->getOpcode()) {
994 case Instruction::ZExt:
995 case Instruction::SExt:
996 case Instruction::Trunc:
998 case Instruction::And:
999 case Instruction::Or:
1000 case Instruction::Xor:
1002 case Instruction::Sub:
1003 case Instruction::Mul:
1008 if (BitsToClear == 0 && Tmp == 0)
1013 if (Tmp == 0 &&
I->isBitwiseLogicOp()) {
1017 if (IC.MaskedValueIsZero(
I->getOperand(1),
1022 if (
I->getOpcode() == Instruction::And)
1031 case Instruction::Shl: {
1039 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
1044 case Instruction::LShr: {
1068 case Instruction::PHI: {
1096 if (
Instruction *Result = commonCastTransforms(CI))
1103 unsigned BitsToClear;
1104 if (shouldChangeType(SrcTy, DestTy) &&
1107 "Can't clear more bits than in SrcTy");
1111 dbgs() <<
"ICE: EvaluateInDifferentType converting expression type" 1112 " to avoid zero extend: " 1114 Value *Res = EvaluateInDifferentType(Src, DestTy,
false);
1118 if (
auto *
SrcOp = dyn_cast<Instruction>(Src))
1119 if (
SrcOp->hasOneUse())
1123 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1129 DestBitSize-SrcBitsKept),
1131 return replaceInstUsesWith(CI, Res);
1136 return BinaryOperator::CreateAnd(Res, C);
1142 if (
TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {
1147 Value *A = CSrc->getOperand(0);
1149 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
1155 if (SrcSize < DstSize) {
1158 Value *And = Builder.CreateAnd(A, AndConst, CSrc->
getName() +
".mask");
1162 if (SrcSize == DstSize) {
1167 if (SrcSize > DstSize) {
1170 return BinaryOperator::CreateAnd(Trunc,
1176 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1177 return transformZExtICmp(ICI, CI);
1180 if (SrcI && SrcI->
getOpcode() == Instruction::Or) {
1186 if (LHS && RHS && LHS->
hasOneUse() && RHS->hasOneUse() &&
1187 (transformZExtICmp(LHS, CI,
false) ||
1188 transformZExtICmp(RHS, CI,
false))) {
1191 Value *RCast = Builder.CreateZExt(RHS, CI.
getType(), RHS->getName());
1195 if (
auto *LZExt = dyn_cast<ZExtInst>(LCast))
1196 transformZExtICmp(LHS, *LZExt);
1197 if (
auto *RZExt = dyn_cast<ZExtInst>(RCast))
1198 transformZExtICmp(RHS, *RZExt);
1218 return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC);
1230 if (!Op1->getType()->isIntOrIntVectorTy())
1239 Value *
In = Builder.CreateAShr(Op0, Sh, Op0->
getName() +
".lobit");
1240 if (In->getType() != CI.
getType())
1241 In = Builder.CreateIntCast(In, CI.
getType(),
true );
1244 In = Builder.CreateNot(In, In->getName() +
".not");
1245 return replaceInstUsesWith(CI, In);
1248 if (
ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1253 ICI->
isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
1261 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
1265 return replaceInstUsesWith(CI, V);
1274 In = Builder.CreateLShr(In,
1279 In = Builder.CreateAdd(In,
1288 In = Builder.CreateShl(In,
1297 return replaceInstUsesWith(CI, In);
1315 "Can't sign extend type to a smaller type");
1321 auto *
I = cast<Instruction>(V);
1322 switch (
I->getOpcode()) {
1323 case Instruction::SExt:
1324 case Instruction::ZExt:
1325 case Instruction::Trunc:
1327 case Instruction::And:
1328 case Instruction::Or:
1329 case Instruction::Xor:
1331 case Instruction::Sub:
1332 case Instruction::Mul:
1344 case Instruction::PHI: {
1377 Value *ZExt = Builder.CreateZExt(Src, DestTy);
1378 return replaceInstUsesWith(CI, ZExt);
1385 dbgs() <<
"ICE: EvaluateInDifferentType converting expression type" 1386 " to avoid sign extend: " 1388 Value *Res = EvaluateInDifferentType(Src, DestTy,
true);
1392 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1397 return replaceInstUsesWith(CI, Res);
1401 return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt,
"sext"),
1411 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1413 return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt);
1416 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1417 return transformSExtICmp(ICI, CI);
1440 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1442 A = Builder.CreateShl(A, ShAmtV, CI.
getName());
1443 return BinaryOperator::CreateAShr(A, ShAmtV);
1481 if (!CV || !CV->getType()->isVectorTy())
1484 Type *MinType =
nullptr;
1487 for (
unsigned i = 0; i != NumElts; ++i) {
1488 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
1508 if (
auto *FPExt = dyn_cast<FPExtInst>(V))
1509 return FPExt->getOperand(0)->getType();
1514 if (
auto *CFP = dyn_cast<ConstantFP>(V))
1543 unsigned RHSWidth = RHSMinType->getFPMantissaWidth();
1544 unsigned SrcWidth =
std::max(LHSWidth, RHSWidth);
1548 case Instruction::FAdd:
1549 case Instruction::FSub:
1568 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1576 case Instruction::FMul:
1582 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1588 case Instruction::FDiv:
1595 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1601 case Instruction::FRem: {
1606 if (SrcWidth == OpWidth)
1609 if (LHSWidth == SrcWidth) {
1610 LHS = Builder.CreateFPTrunc(OpI->
getOperand(0), LHSMinType);
1611 RHS = Builder.CreateFPTrunc(OpI->
getOperand(1), LHSMinType);
1613 LHS = Builder.CreateFPTrunc(OpI->
getOperand(0), RHSMinType);
1614 RHS = Builder.CreateFPTrunc(OpI->
getOperand(1), RHSMinType);
1617 Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, OpI);
1625 Value *InnerTrunc = Builder.CreateFPTrunc(X, Ty);
1630 if (
auto *II = dyn_cast<IntrinsicInst>(FPT.
getOperand(0))) {
1631 switch (II->getIntrinsicID()) {
1640 Value *Src = II->getArgOperand(0);
1649 if (!FPExtSrc || FPExtSrc->
getSrcTy() != Ty)
1655 Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty);
1657 II->getIntrinsicID(), Ty);
1659 II->getOperandBundlesAsDefs(OpBundles);
1675 return commonCastTransforms(CI);
1690 Type *SrcTy = SrcI->getType();
1691 bool IsInputSigned = isa<SIToFPInst>(OpI);
1692 bool IsOutputSigned = isa<FPToSIInst>(FI);
1705 int ActualSize = std::min(InputSize, OutputSize);
1707 if (ActualSize <= OpITy->getFPMantissaWidth()) {
1709 if (IsInputSigned && IsOutputSigned)
1716 return replaceInstUsesWith(FI, SrcI);
1725 return commonCastTransforms(FI);
1730 return commonCastTransforms(FI);
1736 return commonCastTransforms(FI);
1741 return commonCastTransforms(FI);
1745 return commonCastTransforms(CI);
1749 return commonCastTransforms(CI);
1758 DL.getPointerSizeInBits(AS)) {
1780 if (
GEP->hasAllZeroIndices() &&
1784 (!isa<AddrSpaceCastInst>(CI) ||
1785 GEP->getType() ==
GEP->getPointerOperandType())) {
1795 return commonCastTransforms(CI);
1807 return commonPointerCastTransforms(CI);
1861 for (
unsigned i = 0, e = SrcElts; i != e; ++i)
1865 for (
unsigned i = 0, e = DestTy->
getNumElements()-SrcElts; i != e; ++i)
1894 Type *VecEltTy,
bool isBigEndian) {
1896 "Shift should be a multiple of the element type size");
1899 if (isa<UndefValue>(V))
return true;
1903 if (V->
getType() == VecEltTy) {
1905 if (
Constant *
C = dyn_cast<Constant>(V))
1906 if (
C->isNullValue())
1911 ElementIndex = Elements.
size() - ElementIndex - 1;
1914 if (Elements[ElementIndex])
1917 Elements[ElementIndex] = V;
1921 if (
Constant *
C = dyn_cast<Constant>(V)) {
1930 Shift, Elements, VecEltTy, isBigEndian);
1934 if (!isa<IntegerType>(
C->
getType()))
1940 for (
unsigned i = 0; i != NumElts; ++i) {
1941 unsigned ShiftI = Shift+i*ElementSize;
1955 if (!I)
return false;
1957 default:
return false;
1958 case Instruction::BitCast:
1961 case Instruction::ZExt:
1968 case Instruction::Or:
1973 case Instruction::Shl: {
1976 if (!CI)
return false;
2016 for (
unsigned i = 0, e = Elements.size(); i != e; ++i) {
2017 if (!Elements[i])
continue;
2034 if (!ExtElt || !ExtElt->hasOneUse())
2043 unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements();
2068 X->
getType() == DestTy && !isa<Constant>(
X)) {
2075 X->
getType() == DestTy && !isa<Constant>(
X)) {
2099 Value *Cond, *TVal, *FVal;
2121 auto *Sel = cast<Instruction>(BitCast.
getOperand(0));
2124 !isa<Constant>(
X)) {
2131 !isa<Constant>(
X)) {
2143 if (!isa<StoreInst>(U))
2175 while (!PhiWorklist.
empty()) {
2177 for (
Value *IncValue : OldPN->incoming_values()) {
2178 if (isa<Constant>(IncValue))
2181 if (
auto *LI = dyn_cast<LoadInst>(IncValue)) {
2186 Value *Addr = LI->getOperand(0);
2187 if (Addr == &CI || isa<LoadInst>(Addr))
2189 if (LI->hasOneUse() && LI->isSimple())
2196 if (
auto *PNode = dyn_cast<PHINode>(IncValue)) {
2197 if (OldPhiNodes.
insert(PNode))
2208 Type *TyA = BCI->getOperand(0)->getType();
2209 Type *TyB = BCI->getType();
2210 if (TyA != DestTy || TyB != SrcTy)
2217 for (
auto *OldPN : OldPhiNodes) {
2218 Builder.SetInsertPoint(OldPN);
2219 PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands());
2220 NewPNodes[OldPN] = NewPN;
2224 for (
auto *OldPN : OldPhiNodes) {
2225 PHINode *NewPN = NewPNodes[OldPN];
2226 for (
unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) {
2227 Value *V = OldPN->getOperand(j);
2228 Value *NewV =
nullptr;
2229 if (
auto *
C = dyn_cast<Constant>(V)) {
2231 }
else if (
auto *LI = dyn_cast<LoadInst>(V)) {
2232 Builder.SetInsertPoint(LI->getNextNode());
2233 NewV = Builder.CreateBitCast(LI, DestTy);
2235 }
else if (
auto *BCI = dyn_cast<BitCastInst>(V)) {
2236 NewV = BCI->getOperand(0);
2237 }
else if (
auto *PrevPN = dyn_cast<PHINode>(V)) {
2238 NewV = NewPNodes[PrevPN];
2241 NewPN->
addIncoming(NewV, OldPN->getIncomingBlock(j));
2248 if (
SI &&
SI->isSimple() &&
SI->getOperand(0) == PN) {
2249 Builder.SetInsertPoint(
SI);
2251 cast<BitCastInst>(Builder.CreateBitCast(NewPNodes[PN], SrcTy));
2252 SI->setOperand(0, NewBC);
2258 return replaceInstUsesWith(CI, NewPNodes[PN]);
2271 return replaceInstUsesWith(CI, Src);
2273 if (
PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
2275 Type *DstElTy = DstPTy->getElementType();
2280 if ((DstElTy == SrcElTy) &&
2288 if (
AllocaInst *AI = dyn_cast<AllocaInst>(Src))
2289 if (
Instruction *V = PromoteCastOfAllocation(CI, *AI))
2302 unsigned NumZeros = 0;
2303 while (SrcElTy != DstElTy &&
2304 isa<CompositeType>(SrcElTy) && !SrcElTy->
isPointerTy() &&
2306 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
2311 if (SrcElTy == DstElTy) {
2317 if (
VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
2318 if (DestVTy->getNumElements() == 1 && !SrcTy->
isVectorTy()) {
2319 Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType());
2325 if (isa<IntegerType>(SrcTy)) {
2329 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
2330 CastInst *SrcCast = cast<CastInst>(Src);
2332 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
2334 cast<VectorType>(DestTy), *
this))
2342 return replaceInstUsesWith(CI, V);
2346 if (
VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
2347 if (SrcVTy->getNumElements() == 1) {
2352 Builder.CreateExtractElement(Src,
2360 dyn_cast<InsertElementInst>(CI.
getOperand(0)))
2369 if (SVI->hasOneUse() && DestTy->
isVectorTy() &&
2371 SVI->getType()->getNumElements() ==
2372 SVI->getOperand(0)->getType()->getVectorNumElements()) {
2377 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
2379 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
2381 Value *LHS = Builder.CreateBitCast(SVI->getOperand(0), DestTy);
2382 Value *RHS = Builder.CreateBitCast(SVI->getOperand(1), DestTy);
2391 if (
PHINode *PN = dyn_cast<PHINode>(Src))
2405 return commonPointerCastTransforms(CI);
2406 return commonCastTransforms(CI);
2417 Type *DestElemTy = DestTy->getElementType();
2425 Value *NewBitCast = Builder.CreateBitCast(Src, MidTy);
2429 return commonPointerCastTransforms(CI);
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, BinaryOperator *FMFSource, const Twine &Name="")
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
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, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static Type * getDoubleTy(LLVMContext &C)
Type * getSrcTy() const
Return the source type, as a convenience.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
uint64_t getZExtValue() const
Get zero extended value.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
DiagnosticInfoOptimizationBase::Argument NV
This class represents lattice values for constants.
BinaryOps getOpcode() const
Instruction * visitBitCast(BitCastInst &CI)
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
void setAlignment(unsigned Align)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This class represents zero extension of integer types.
Instruction * commonCastTransforms(CastInst &CI)
Implement the transforms common to all CastInst visitors.
void push_back(const T &Elt)
This class represents a function call, abstracting a target machine's calling convention.
static Type * shrinkFPConstant(ConstantFP *CFP)
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
const Value * getTrueValue() const
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
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.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
APInt trunc(unsigned width) const
Truncate to new width.
This class represents a sign extension of integer types.
bool isVectorTy() const
True if this is an instance of VectorType.
static bool isBitwiseLogicOp(unsigned Opcode)
Determine if the Opcode is and/or/xor.
Instruction * visitUIToFP(CastInst &CI)
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
unsigned getBitWidth() const
Return the number of bits in the APInt.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Instruction * visitFPExt(CastInst &CI)
Instruction * FoldItoFPtoI(Instruction &FI)
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
bool match(Val *V, const Pattern &P)
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Instruction * visitFPToUI(FPToUIInst &FI)
This class represents a conversion between pointers from one address space to another.
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
This class represents the LLVM 'select' instruction.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
static bool hasStoreUsersOnly(CastInst &CI)
Check if all users of CI are StoreInsts.
static Type * getFloatTy(LLVMContext &C)
This is the base class for all instructions that perform data casts.
PointerType * getType() const
Overload to return most specific pointer type.
'undef' values are things that do not have specified contents.
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear, InstCombiner &IC, Instruction *CxtI)
Determine if the specified value can be computed in the specified wider type and produce the same low...
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
bool isIntegerTy() const
True if this is an instance of IntegerType.
The core instruction combiner logic.
static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC, Instruction *CxtI)
Return true if we can evaluate the specified expression tree as type Ty instead of its larger type...
static Instruction * canonicalizeBitCastExtElt(BitCastInst &BitCast, InstCombiner &IC)
Canonicalize scalar bitcasts of extracted elements into a bitcast of the vector followed by extract e...
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.
Instruction * visitIntToPtr(IntToPtrInst &CI)
static Instruction * optimizeVectorResize(Value *InVal, VectorType *DestTy, InstCombiner &IC)
This input value (which is known to have vector type) is being zero extended or truncated to the spec...
Instruction * visitAddrSpaceCast(AddrSpaceCastInst &CI)
uint64_t getNumElements() const
static Type * getPPC_FP128Ty(LLVMContext &C)
static unsigned getTypeSizeIndex(unsigned Value, Type *Ty)
This class represents a cast from a pointer to an integer.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
static bool isMultipleOfTypeSize(unsigned Value, Type *Ty)
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static bool collectInsertionElements(Value *V, unsigned Shift, SmallVectorImpl< Value *> &Elements, Type *VecEltTy, bool isBigEndian)
V is a value which is inserted into a vector of VecEltTy.
This class represents a no-op cast from one type to another.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Get a value with upper bits starting at loBit set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
int getFPMantissaWidth() const
Return the width of the mantissa of this type.
This class represents a cast from floating point to signed integer.
static Value * optimizeIntegerToVectorInsertions(BitCastInst &CI, InstCombiner &IC)
If the input is an 'or' instruction, we may be doing shifts and ors to assemble the elements of the v...
static const fltSemantics & IEEEdouble() LLVM_READNONE
bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
static Type * getMinimumFPType(Value *V)
Find the minimum FP type we can safely truncate to.
void takeName(Value *V)
Transfer the name from V to this value.
static Instruction * foldBitCastSelect(BitCastInst &BitCast, InstCombiner::BuilderTy &Builder)
Change the type of a select if we can eliminate a bitcast.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
This class represents a truncation of integer types.
Value * getOperand(unsigned i) const
Class to represent pointers.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
const DataLayout & getDataLayout() const
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
OneUse_match< T > m_OneUse(const T &SubPattern)
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
static Instruction * foldBitCastBitwiseLogic(BitCastInst &BitCast, InstCombiner::BuilderTy &Builder)
Change the type of a bitwise logic operation if we can eliminate a bitcast.
This instruction inserts a single (scalar) element into a VectorType value.
bool isAllOnesValue() const
Determine if all bits are set.
static bool canNotEvaluateInType(Value *V, Type *Ty)
Filter out values that we can not evaluate in the destination type for free.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
unsigned countPopulation() const
Count the number of bits set.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
bool ult(const APInt &RHS) const
Unsigned less than comparison.
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
This is an important base class in LLVM.
unsigned getNumContainedTypes() const
Return the number of types in the derived type.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
bool isPointerTy() const
True if this is an instance of PointerType.
ConstantFP - Floating Point Values [float, double].
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
static Value * decomposeSimpleLinearExpr(Value *Val, unsigned &Scale, uint64_t &Offset)
Analyze 'Val', seeing if it is a simple linear expression.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl...
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, CastClass_match< OpTy, Instruction::SExt > > m_ZExtOrSExt(const OpTy &Op)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
Class to represent integer types.
static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem)
Return a Constant* for the specified floating-point constant if it fits in the specified FP type with...
This class represents a cast from an integer to a pointer.
static Constant * getAllOnesValue(Type *Ty)
Instruction * visitFPToSI(FPToSIInst &FI)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * getArraySize() const
Get the number of elements allocated.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
deferredval_ty< Value > m_Deferred(Value *const &V)
A commutative-friendly version of m_Specific().
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
const APFloat & getValueAPF() const
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
static Type * getHalfTy(LLVMContext &C)
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
static const fltSemantics & IEEEsingle() LLVM_READNONE
static CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
A SetVector that performs no allocations if smaller than a certain size.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
This is the shared class of boolean and integer constants.
static const fltSemantics & IEEEhalf() LLVM_READNONE
SelectPatternFlavor Flavor
static Instruction * shrinkInsertElt(CastInst &Trunc, InstCombiner::BuilderTy &Builder)
Try to narrow the width of an insert element.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
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...
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
static Instruction * shrinkSplatShuffle(TruncInst &Trunc, InstCombiner::BuilderTy &Builder)
Try to narrow the width of a splat shuffle.
Instruction * visitSExt(SExtInst &CI)
This class represents a cast from floating point to unsigned integer.
LLVM_NODISCARD T pop_back_val()
Instruction * visitZExt(ZExtInst &CI)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static CastInst * CreateFPCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create an FPExt, BitCast, or FPTrunc for fp -> fp casts.
static unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, Type *DstIntPtrTy)
Determine how a pair of casts can be eliminated, if they can be at all.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
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...
Type * getDestTy() const
Return the destination type, as a convenience.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, BinaryOperator *FMFSource, const Twine &Name="")
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
unsigned getVectorNumElements() const
Class to represent vector types.
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.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
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()
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
const Value * getFalseValue() const
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 ...
Predicate getPredicate() const
Return the predicate for this instruction.
Instruction * visitTrunc(TruncInst &CI)
static Type * shrinkFPConstantVector(Value *V)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM_NODISCARD bool empty() const
Instruction * visitSIToFP(CastInst &CI)
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static Instruction * foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC)
Given a vector that is bitcast to an integer, optionally logically right-shifted, and truncated...
static BinaryOperator * CreateFNegFMF(Value *Op, BinaryOperator *FMFSource, const Twine &Name="")
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class represents a truncation of floating point types.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM Value Representation.
This file provides internal interfaces used to implement the InstCombine.
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
static bool canEvaluateSExtd(Value *V, Type *Ty)
Return true if we can take the specified value and return it as type Ty without inserting any new cas...
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.
Instruction * commonPointerCastTransforms(CastInst &CI)
Implement the transforms for cast of pointer (bitcast/ptrtoint)
Type * getElementType() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
static bool canAlwaysEvaluateInType(Value *V, Type *Ty)
Constants and extensions/truncates from the destination type are always free to be evaluated in that ...
bool isNonNegative() const
Returns true if this value is known to be non-negative.
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
specific_intval m_SpecificInt(uint64_t V)
Match a specific integer value or vector with all elements equal to the value.
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
Instruction * visitPtrToInt(PtrToIntInst &CI)
op_range incoming_values()
This class represents an extension of floating point types.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Type * getElementType() const
bool isNullValue() const
Determine if all bits are clear.
an instruction to allocate memory on the stack
Instruction * visitFPTrunc(FPTruncInst &CI)
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property...