[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / Transforms / InstCombine / InstCombineSimplifyDemanded.cpp
blob502bd15f9bad0b54d17422790004e3356b53730b
1 //===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains logic for simplifying instructions based on information
10 // about how they are used.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/TargetTransformInfo.h"
16 #include "llvm/Analysis/ValueTracking.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Support/KnownBits.h"
20 #include "llvm/Transforms/InstCombine/InstCombiner.h"
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
25 #define DEBUG_TYPE "instcombine"
27 /// Check to see if the specified operand of the specified instruction is a
28 /// constant integer. If so, check to see if there are any bits set in the
29 /// constant that are not demanded. If so, shrink the constant and return true.
30 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
31 const APInt &Demanded) {
32 assert(I && "No instruction?");
33 assert(OpNo < I->getNumOperands() && "Operand index too large");
35 // The operand must be a constant integer or splat integer.
36 Value *Op = I->getOperand(OpNo);
37 const APInt *C;
38 if (!match(Op, m_APInt(C)))
39 return false;
41 // If there are no bits set that aren't demanded, nothing to do.
42 if (C->isSubsetOf(Demanded))
43 return false;
45 // This instruction is producing bits that are not demanded. Shrink the RHS.
46 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
48 return true;
53 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
54 /// the instruction has any properties that allow us to simplify its operands.
55 bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst) {
56 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
57 KnownBits Known(BitWidth);
58 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
60 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
61 0, &Inst);
62 if (!V) return false;
63 if (V == &Inst) return true;
64 replaceInstUsesWith(Inst, V);
65 return true;
68 /// This form of SimplifyDemandedBits simplifies the specified instruction
69 /// operand if possible, updating it in place. It returns true if it made any
70 /// change and false otherwise.
71 bool InstCombinerImpl::SimplifyDemandedBits(Instruction *I, unsigned OpNo,
72 const APInt &DemandedMask,
73 KnownBits &Known, unsigned Depth) {
74 Use &U = I->getOperandUse(OpNo);
75 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
76 Depth, I);
77 if (!NewVal) return false;
78 if (Instruction* OpInst = dyn_cast<Instruction>(U))
79 salvageDebugInfo(*OpInst);
81 replaceUse(U, NewVal);
82 return true;
85 /// This function attempts to replace V with a simpler value based on the
86 /// demanded bits. When this function is called, it is known that only the bits
87 /// set in DemandedMask of the result of V are ever used downstream.
88 /// Consequently, depending on the mask and V, it may be possible to replace V
89 /// with a constant or one of its operands. In such cases, this function does
90 /// the replacement and returns true. In all other cases, it returns false after
91 /// analyzing the expression and setting KnownOne and known to be one in the
92 /// expression. Known.Zero contains all the bits that are known to be zero in
93 /// the expression. These are provided to potentially allow the caller (which
94 /// might recursively be SimplifyDemandedBits itself) to simplify the
95 /// expression.
96 /// Known.One and Known.Zero always follow the invariant that:
97 /// Known.One & Known.Zero == 0.
98 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and
99 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note
100 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
101 /// be the same.
103 /// This returns null if it did not change anything and it permits no
104 /// simplification. This returns V itself if it did some simplification of V's
105 /// operands based on the information about what bits are demanded. This returns
106 /// some other non-null value if it found out that V is equal to another value
107 /// in the context where the specified bits are demanded, but not for all users.
108 Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
109 KnownBits &Known,
110 unsigned Depth,
111 Instruction *CxtI) {
112 assert(V != nullptr && "Null pointer of Value???");
113 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
114 uint32_t BitWidth = DemandedMask.getBitWidth();
115 Type *VTy = V->getType();
116 assert(
117 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
118 Known.getBitWidth() == BitWidth &&
119 "Value *V, DemandedMask and Known must have same BitWidth");
121 if (isa<Constant>(V)) {
122 computeKnownBits(V, Known, Depth, CxtI);
123 return nullptr;
126 Known.resetAll();
127 if (DemandedMask.isNullValue()) // Not demanding any bits from V.
128 return UndefValue::get(VTy);
130 if (Depth == MaxAnalysisRecursionDepth)
131 return nullptr;
133 if (isa<ScalableVectorType>(VTy))
134 return nullptr;
136 Instruction *I = dyn_cast<Instruction>(V);
137 if (!I) {
138 computeKnownBits(V, Known, Depth, CxtI);
139 return nullptr; // Only analyze instructions.
142 // If there are multiple uses of this value and we aren't at the root, then
143 // we can't do any simplifications of the operands, because DemandedMask
144 // only reflects the bits demanded by *one* of the users.
145 if (Depth != 0 && !I->hasOneUse())
146 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
148 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
150 // If this is the root being simplified, allow it to have multiple uses,
151 // just set the DemandedMask to all bits so that we can try to simplify the
152 // operands. This allows visitTruncInst (for example) to simplify the
153 // operand of a trunc without duplicating all the logic below.
154 if (Depth == 0 && !V->hasOneUse())
155 DemandedMask.setAllBits();
157 switch (I->getOpcode()) {
158 default:
159 computeKnownBits(I, Known, Depth, CxtI);
160 break;
161 case Instruction::And: {
162 // If either the LHS or the RHS are Zero, the result is zero.
163 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
164 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
165 Depth + 1))
166 return I;
167 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
168 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
170 Known = LHSKnown & RHSKnown;
172 // If the client is only demanding bits that we know, return the known
173 // constant.
174 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
175 return Constant::getIntegerValue(VTy, Known.One);
177 // If all of the demanded bits are known 1 on one side, return the other.
178 // These bits cannot contribute to the result of the 'and'.
179 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
180 return I->getOperand(0);
181 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
182 return I->getOperand(1);
184 // If the RHS is a constant, see if we can simplify it.
185 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
186 return I;
188 break;
190 case Instruction::Or: {
191 // If either the LHS or the RHS are One, the result is One.
192 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
193 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
194 Depth + 1))
195 return I;
196 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
197 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
199 Known = LHSKnown | RHSKnown;
201 // If the client is only demanding bits that we know, return the known
202 // constant.
203 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
204 return Constant::getIntegerValue(VTy, Known.One);
206 // If all of the demanded bits are known zero on one side, return the other.
207 // These bits cannot contribute to the result of the 'or'.
208 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
209 return I->getOperand(0);
210 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
211 return I->getOperand(1);
213 // If the RHS is a constant, see if we can simplify it.
214 if (ShrinkDemandedConstant(I, 1, DemandedMask))
215 return I;
217 break;
219 case Instruction::Xor: {
220 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
221 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
222 return I;
223 Value *LHS, *RHS;
224 if (DemandedMask == 1 &&
225 match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
226 match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
227 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
228 IRBuilderBase::InsertPointGuard Guard(Builder);
229 Builder.SetInsertPoint(I);
230 auto *Xor = Builder.CreateXor(LHS, RHS);
231 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
234 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
235 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
237 Known = LHSKnown ^ RHSKnown;
239 // If the client is only demanding bits that we know, return the known
240 // constant.
241 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
242 return Constant::getIntegerValue(VTy, Known.One);
244 // If all of the demanded bits are known zero on one side, return the other.
245 // These bits cannot contribute to the result of the 'xor'.
246 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
247 return I->getOperand(0);
248 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
249 return I->getOperand(1);
251 // If all of the demanded bits are known to be zero on one side or the
252 // other, turn this into an *inclusive* or.
253 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
254 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
255 Instruction *Or =
256 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
257 I->getName());
258 return InsertNewInstWith(Or, *I);
261 // If all of the demanded bits on one side are known, and all of the set
262 // bits on that side are also known to be set on the other side, turn this
263 // into an AND, as we know the bits will be cleared.
264 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
265 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
266 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
267 Constant *AndC = Constant::getIntegerValue(VTy,
268 ~RHSKnown.One & DemandedMask);
269 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
270 return InsertNewInstWith(And, *I);
273 // If the RHS is a constant, see if we can change it. Don't alter a -1
274 // constant because that's a canonical 'not' op, and that is better for
275 // combining, SCEV, and codegen.
276 const APInt *C;
277 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnesValue()) {
278 if ((*C | ~DemandedMask).isAllOnesValue()) {
279 // Force bits to 1 to create a 'not' op.
280 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
281 return I;
283 // If we can't turn this into a 'not', try to shrink the constant.
284 if (ShrinkDemandedConstant(I, 1, DemandedMask))
285 return I;
288 // If our LHS is an 'and' and if it has one use, and if any of the bits we
289 // are flipping are known to be set, then the xor is just resetting those
290 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
291 // simplifying both of them.
292 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
293 ConstantInt *AndRHS, *XorRHS;
294 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
295 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
296 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
297 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
298 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
300 Constant *AndC =
301 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
302 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
303 InsertNewInstWith(NewAnd, *I);
305 Constant *XorC =
306 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
307 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
308 return InsertNewInstWith(NewXor, *I);
311 break;
313 case Instruction::Select: {
314 Value *LHS, *RHS;
315 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
316 if (SPF == SPF_UMAX) {
317 // UMax(A, C) == A if ...
318 // The lowest non-zero bit of DemandMask is higher than the highest
319 // non-zero bit of C.
320 const APInt *C;
321 unsigned CTZ = DemandedMask.countTrailingZeros();
322 if (match(RHS, m_APInt(C)) && CTZ >= C->getActiveBits())
323 return LHS;
324 } else if (SPF == SPF_UMIN) {
325 // UMin(A, C) == A if ...
326 // The lowest non-zero bit of DemandMask is higher than the highest
327 // non-one bit of C.
328 // This comes from using DeMorgans on the above umax example.
329 const APInt *C;
330 unsigned CTZ = DemandedMask.countTrailingZeros();
331 if (match(RHS, m_APInt(C)) &&
332 CTZ >= C->getBitWidth() - C->countLeadingOnes())
333 return LHS;
336 // If this is a select as part of any other min/max pattern, don't simplify
337 // any further in case we break the structure.
338 if (SPF != SPF_UNKNOWN)
339 return nullptr;
341 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
342 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
343 return I;
344 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
345 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
347 // If the operands are constants, see if we can simplify them.
348 // This is similar to ShrinkDemandedConstant, but for a select we want to
349 // try to keep the selected constants the same as icmp value constants, if
350 // we can. This helps not break apart (or helps put back together)
351 // canonical patterns like min and max.
352 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
353 const APInt &DemandedMask) {
354 const APInt *SelC;
355 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
356 return false;
358 // Get the constant out of the ICmp, if there is one.
359 // Only try this when exactly 1 operand is a constant (if both operands
360 // are constant, the icmp should eventually simplify). Otherwise, we may
361 // invert the transform that reduces set bits and infinite-loop.
362 Value *X;
363 const APInt *CmpC;
364 ICmpInst::Predicate Pred;
365 if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
366 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
367 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
369 // If the constant is already the same as the ICmp, leave it as-is.
370 if (*CmpC == *SelC)
371 return false;
372 // If the constants are not already the same, but can be with the demand
373 // mask, use the constant value from the ICmp.
374 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
375 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
376 return true;
378 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
380 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
381 CanonicalizeSelectConstant(I, 2, DemandedMask))
382 return I;
384 // Only known if known in both the LHS and RHS.
385 Known = KnownBits::commonBits(LHSKnown, RHSKnown);
386 break;
388 case Instruction::ZExt:
389 case Instruction::Trunc: {
390 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
392 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
393 KnownBits InputKnown(SrcBitWidth);
394 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1))
395 return I;
396 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
397 Known = InputKnown.zextOrTrunc(BitWidth);
398 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
399 break;
401 case Instruction::BitCast:
402 if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
403 return nullptr; // vector->int or fp->int?
405 if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
406 if (VectorType *SrcVTy =
407 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
408 if (cast<FixedVectorType>(DstVTy)->getNumElements() !=
409 cast<FixedVectorType>(SrcVTy)->getNumElements())
410 // Don't touch a bitcast between vectors of different element counts.
411 return nullptr;
412 } else
413 // Don't touch a scalar-to-vector bitcast.
414 return nullptr;
415 } else if (I->getOperand(0)->getType()->isVectorTy())
416 // Don't touch a vector-to-scalar bitcast.
417 return nullptr;
419 if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1))
420 return I;
421 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
422 break;
423 case Instruction::SExt: {
424 // Compute the bits in the result that are not present in the input.
425 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
427 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
429 // If any of the sign extended bits are demanded, we know that the sign
430 // bit is demanded.
431 if (DemandedMask.getActiveBits() > SrcBitWidth)
432 InputDemandedBits.setBit(SrcBitWidth-1);
434 KnownBits InputKnown(SrcBitWidth);
435 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
436 return I;
438 // If the input sign bit is known zero, or if the NewBits are not demanded
439 // convert this into a zero extension.
440 if (InputKnown.isNonNegative() ||
441 DemandedMask.getActiveBits() <= SrcBitWidth) {
442 // Convert to ZExt cast.
443 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
444 return InsertNewInstWith(NewCast, *I);
447 // If the sign bit of the input is known set or clear, then we know the
448 // top bits of the result.
449 Known = InputKnown.sext(BitWidth);
450 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
451 break;
453 case Instruction::Add:
454 if ((DemandedMask & 1) == 0) {
455 // If we do not need the low bit, try to convert bool math to logic:
456 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
457 Value *X, *Y;
458 if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
459 m_OneUse(m_SExt(m_Value(Y))))) &&
460 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
461 // Truth table for inputs and output signbits:
462 // X:0 | X:1
463 // ----------
464 // Y:0 | 0 | 0 |
465 // Y:1 | -1 | 0 |
466 // ----------
467 IRBuilderBase::InsertPointGuard Guard(Builder);
468 Builder.SetInsertPoint(I);
469 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
470 return Builder.CreateSExt(AndNot, VTy);
473 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
474 // TODO: Relax the one-use checks because we are removing an instruction?
475 if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))),
476 m_OneUse(m_SExt(m_Value(Y))))) &&
477 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
478 // Truth table for inputs and output signbits:
479 // X:0 | X:1
480 // -----------
481 // Y:0 | -1 | -1 |
482 // Y:1 | -1 | 0 |
483 // -----------
484 IRBuilderBase::InsertPointGuard Guard(Builder);
485 Builder.SetInsertPoint(I);
486 Value *Or = Builder.CreateOr(X, Y);
487 return Builder.CreateSExt(Or, VTy);
490 LLVM_FALLTHROUGH;
491 case Instruction::Sub: {
492 /// If the high-bits of an ADD/SUB are not demanded, then we do not care
493 /// about the high bits of the operands.
494 unsigned NLZ = DemandedMask.countLeadingZeros();
495 // Right fill the mask of bits for this ADD/SUB to demand the most
496 // significant bit and all those below it.
497 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
498 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
499 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
500 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
501 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
502 if (NLZ > 0) {
503 // Disable the nsw and nuw flags here: We can no longer guarantee that
504 // we won't wrap after simplification. Removing the nsw/nuw flags is
505 // legal here because the top bit is not demanded.
506 BinaryOperator &BinOP = *cast<BinaryOperator>(I);
507 BinOP.setHasNoSignedWrap(false);
508 BinOP.setHasNoUnsignedWrap(false);
510 return I;
513 // If we are known to be adding/subtracting zeros to every bit below
514 // the highest demanded bit, we just return the other side.
515 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
516 return I->getOperand(0);
517 // We can't do this with the LHS for subtraction, unless we are only
518 // demanding the LSB.
519 if ((I->getOpcode() == Instruction::Add ||
520 DemandedFromOps.isOneValue()) &&
521 DemandedFromOps.isSubsetOf(LHSKnown.Zero))
522 return I->getOperand(1);
524 // Otherwise just compute the known bits of the result.
525 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
526 Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add,
527 NSW, LHSKnown, RHSKnown);
528 break;
530 case Instruction::Shl: {
531 const APInt *SA;
532 if (match(I->getOperand(1), m_APInt(SA))) {
533 const APInt *ShrAmt;
534 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
535 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
536 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
537 DemandedMask, Known))
538 return R;
540 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
541 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
543 // If the shift is NUW/NSW, then it does demand the high bits.
544 ShlOperator *IOp = cast<ShlOperator>(I);
545 if (IOp->hasNoSignedWrap())
546 DemandedMaskIn.setHighBits(ShiftAmt+1);
547 else if (IOp->hasNoUnsignedWrap())
548 DemandedMaskIn.setHighBits(ShiftAmt);
550 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
551 return I;
552 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
554 bool SignBitZero = Known.Zero.isSignBitSet();
555 bool SignBitOne = Known.One.isSignBitSet();
556 Known.Zero <<= ShiftAmt;
557 Known.One <<= ShiftAmt;
558 // low bits known zero.
559 if (ShiftAmt)
560 Known.Zero.setLowBits(ShiftAmt);
562 // If this shift has "nsw" keyword, then the result is either a poison
563 // value or has the same sign bit as the first operand.
564 if (IOp->hasNoSignedWrap()) {
565 if (SignBitZero)
566 Known.Zero.setSignBit();
567 else if (SignBitOne)
568 Known.One.setSignBit();
569 if (Known.hasConflict())
570 return UndefValue::get(I->getType());
572 } else {
573 // This is a variable shift, so we can't shift the demand mask by a known
574 // amount. But if we are not demanding high bits, then we are not
575 // demanding those bits from the pre-shifted operand either.
576 if (unsigned CTLZ = DemandedMask.countLeadingZeros()) {
577 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
578 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) {
579 // We can't guarantee that nsw/nuw hold after simplifying the operand.
580 I->dropPoisonGeneratingFlags();
581 return I;
584 computeKnownBits(I, Known, Depth, CxtI);
586 break;
588 case Instruction::LShr: {
589 const APInt *SA;
590 if (match(I->getOperand(1), m_APInt(SA))) {
591 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
593 // Unsigned shift right.
594 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
596 // If the shift is exact, then it does demand the low bits (and knows that
597 // they are zero).
598 if (cast<LShrOperator>(I)->isExact())
599 DemandedMaskIn.setLowBits(ShiftAmt);
601 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
602 return I;
603 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
604 Known.Zero.lshrInPlace(ShiftAmt);
605 Known.One.lshrInPlace(ShiftAmt);
606 if (ShiftAmt)
607 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
608 } else {
609 computeKnownBits(I, Known, Depth, CxtI);
611 break;
613 case Instruction::AShr: {
614 // If this is an arithmetic shift right and only the low-bit is set, we can
615 // always convert this into a logical shr, even if the shift amount is
616 // variable. The low bit of the shift cannot be an input sign bit unless
617 // the shift amount is >= the size of the datatype, which is undefined.
618 if (DemandedMask.isOneValue()) {
619 // Perform the logical shift right.
620 Instruction *NewVal = BinaryOperator::CreateLShr(
621 I->getOperand(0), I->getOperand(1), I->getName());
622 return InsertNewInstWith(NewVal, *I);
625 // If the sign bit is the only bit demanded by this ashr, then there is no
626 // need to do it, the shift doesn't change the high bit.
627 if (DemandedMask.isSignMask())
628 return I->getOperand(0);
630 const APInt *SA;
631 if (match(I->getOperand(1), m_APInt(SA))) {
632 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
634 // Signed shift right.
635 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
636 // If any of the high bits are demanded, we should set the sign bit as
637 // demanded.
638 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
639 DemandedMaskIn.setSignBit();
641 // If the shift is exact, then it does demand the low bits (and knows that
642 // they are zero).
643 if (cast<AShrOperator>(I)->isExact())
644 DemandedMaskIn.setLowBits(ShiftAmt);
646 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
647 return I;
649 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
651 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
652 // Compute the new bits that are at the top now plus sign bits.
653 APInt HighBits(APInt::getHighBitsSet(
654 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
655 Known.Zero.lshrInPlace(ShiftAmt);
656 Known.One.lshrInPlace(ShiftAmt);
658 // If the input sign bit is known to be zero, or if none of the top bits
659 // are demanded, turn this into an unsigned shift right.
660 assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
661 if (Known.Zero[BitWidth-ShiftAmt-1] ||
662 !DemandedMask.intersects(HighBits)) {
663 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
664 I->getOperand(1));
665 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
666 return InsertNewInstWith(LShr, *I);
667 } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
668 Known.One |= HighBits;
670 } else {
671 computeKnownBits(I, Known, Depth, CxtI);
673 break;
675 case Instruction::UDiv: {
676 // UDiv doesn't demand low bits that are zero in the divisor.
677 const APInt *SA;
678 if (match(I->getOperand(1), m_APInt(SA))) {
679 // If the shift is exact, then it does demand the low bits.
680 if (cast<UDivOperator>(I)->isExact())
681 break;
683 // FIXME: Take the demanded mask of the result into account.
684 unsigned RHSTrailingZeros = SA->countTrailingZeros();
685 APInt DemandedMaskIn =
686 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
687 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1))
688 return I;
690 // Propagate zero bits from the input.
691 Known.Zero.setHighBits(std::min(
692 BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros));
693 } else {
694 computeKnownBits(I, Known, Depth, CxtI);
696 break;
698 case Instruction::SRem: {
699 ConstantInt *Rem;
700 if (match(I->getOperand(1), m_ConstantInt(Rem))) {
701 // X % -1 demands all the bits because we don't want to introduce
702 // INT_MIN % -1 (== undef) by accident.
703 if (Rem->isMinusOne())
704 break;
705 APInt RA = Rem->getValue().abs();
706 if (RA.isPowerOf2()) {
707 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
708 return I->getOperand(0);
710 APInt LowBits = RA - 1;
711 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
712 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
713 return I;
715 // The low bits of LHS are unchanged by the srem.
716 Known.Zero = LHSKnown.Zero & LowBits;
717 Known.One = LHSKnown.One & LowBits;
719 // If LHS is non-negative or has all low bits zero, then the upper bits
720 // are all zero.
721 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
722 Known.Zero |= ~LowBits;
724 // If LHS is negative and not all low bits are zero, then the upper bits
725 // are all one.
726 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
727 Known.One |= ~LowBits;
729 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
730 break;
734 // The sign bit is the LHS's sign bit, except when the result of the
735 // remainder is zero.
736 if (DemandedMask.isSignBitSet()) {
737 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
738 // If it's known zero, our sign bit is also zero.
739 if (LHSKnown.isNonNegative())
740 Known.makeNonNegative();
742 break;
744 case Instruction::URem: {
745 KnownBits Known2(BitWidth);
746 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
747 if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) ||
748 SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1))
749 return I;
751 unsigned Leaders = Known2.countMinLeadingZeros();
752 Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
753 break;
755 case Instruction::Call: {
756 bool KnownBitsComputed = false;
757 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
758 switch (II->getIntrinsicID()) {
759 case Intrinsic::abs: {
760 if (DemandedMask == 1)
761 return II->getArgOperand(0);
762 break;
764 case Intrinsic::ctpop: {
765 // Checking if the number of clear bits is odd (parity)? If the type has
766 // an even number of bits, that's the same as checking if the number of
767 // set bits is odd, so we can eliminate the 'not' op.
768 Value *X;
769 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
770 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
771 Function *Ctpop = Intrinsic::getDeclaration(
772 II->getModule(), Intrinsic::ctpop, II->getType());
773 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), *I);
775 break;
777 case Intrinsic::bswap: {
778 // If the only bits demanded come from one byte of the bswap result,
779 // just shift the input byte into position to eliminate the bswap.
780 unsigned NLZ = DemandedMask.countLeadingZeros();
781 unsigned NTZ = DemandedMask.countTrailingZeros();
783 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
784 // we need all the bits down to bit 8. Likewise, round NLZ. If we
785 // have 14 leading zeros, round to 8.
786 NLZ &= ~7;
787 NTZ &= ~7;
788 // If we need exactly one byte, we can do this transformation.
789 if (BitWidth-NLZ-NTZ == 8) {
790 unsigned ResultBit = NTZ;
791 unsigned InputBit = BitWidth-NTZ-8;
793 // Replace this with either a left or right shift to get the byte into
794 // the right place.
795 Instruction *NewVal;
796 if (InputBit > ResultBit)
797 NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
798 ConstantInt::get(I->getType(), InputBit-ResultBit));
799 else
800 NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
801 ConstantInt::get(I->getType(), ResultBit-InputBit));
802 NewVal->takeName(I);
803 return InsertNewInstWith(NewVal, *I);
805 break;
807 case Intrinsic::fshr:
808 case Intrinsic::fshl: {
809 const APInt *SA;
810 if (!match(I->getOperand(2), m_APInt(SA)))
811 break;
813 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
814 // defined, so no need to special-case zero shifts here.
815 uint64_t ShiftAmt = SA->urem(BitWidth);
816 if (II->getIntrinsicID() == Intrinsic::fshr)
817 ShiftAmt = BitWidth - ShiftAmt;
819 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
820 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
821 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
822 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
823 return I;
825 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
826 RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
827 Known.One = LHSKnown.One.shl(ShiftAmt) |
828 RHSKnown.One.lshr(BitWidth - ShiftAmt);
829 KnownBitsComputed = true;
830 break;
832 case Intrinsic::umax: {
833 // UMax(A, C) == A if ...
834 // The lowest non-zero bit of DemandMask is higher than the highest
835 // non-zero bit of C.
836 const APInt *C;
837 unsigned CTZ = DemandedMask.countTrailingZeros();
838 if (match(II->getArgOperand(1), m_APInt(C)) &&
839 CTZ >= C->getActiveBits())
840 return II->getArgOperand(0);
841 break;
843 case Intrinsic::umin: {
844 // UMin(A, C) == A if ...
845 // The lowest non-zero bit of DemandMask is higher than the highest
846 // non-one bit of C.
847 // This comes from using DeMorgans on the above umax example.
848 const APInt *C;
849 unsigned CTZ = DemandedMask.countTrailingZeros();
850 if (match(II->getArgOperand(1), m_APInt(C)) &&
851 CTZ >= C->getBitWidth() - C->countLeadingOnes())
852 return II->getArgOperand(0);
853 break;
855 default: {
856 // Handle target specific intrinsics
857 Optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
858 *II, DemandedMask, Known, KnownBitsComputed);
859 if (V.hasValue())
860 return V.getValue();
861 break;
866 if (!KnownBitsComputed)
867 computeKnownBits(V, Known, Depth, CxtI);
868 break;
872 // If the client is only demanding bits that we know, return the known
873 // constant.
874 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
875 return Constant::getIntegerValue(VTy, Known.One);
876 return nullptr;
879 /// Helper routine of SimplifyDemandedUseBits. It computes Known
880 /// bits. It also tries to handle simplifications that can be done based on
881 /// DemandedMask, but without modifying the Instruction.
882 Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits(
883 Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
884 Instruction *CxtI) {
885 unsigned BitWidth = DemandedMask.getBitWidth();
886 Type *ITy = I->getType();
888 KnownBits LHSKnown(BitWidth);
889 KnownBits RHSKnown(BitWidth);
891 // Despite the fact that we can't simplify this instruction in all User's
892 // context, we can at least compute the known bits, and we can
893 // do simplifications that apply to *just* the one user if we know that
894 // this instruction has a simpler value in that context.
895 switch (I->getOpcode()) {
896 case Instruction::And: {
897 // If either the LHS or the RHS are Zero, the result is zero.
898 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
899 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
900 CxtI);
902 Known = LHSKnown & RHSKnown;
904 // If the client is only demanding bits that we know, return the known
905 // constant.
906 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
907 return Constant::getIntegerValue(ITy, Known.One);
909 // If all of the demanded bits are known 1 on one side, return the other.
910 // These bits cannot contribute to the result of the 'and' in this
911 // context.
912 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
913 return I->getOperand(0);
914 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
915 return I->getOperand(1);
917 break;
919 case Instruction::Or: {
920 // We can simplify (X|Y) -> X or Y in the user's context if we know that
921 // only bits from X or Y are demanded.
923 // If either the LHS or the RHS are One, the result is One.
924 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
925 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
926 CxtI);
928 Known = LHSKnown | RHSKnown;
930 // If the client is only demanding bits that we know, return the known
931 // constant.
932 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
933 return Constant::getIntegerValue(ITy, Known.One);
935 // If all of the demanded bits are known zero on one side, return the
936 // other. These bits cannot contribute to the result of the 'or' in this
937 // context.
938 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
939 return I->getOperand(0);
940 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
941 return I->getOperand(1);
943 break;
945 case Instruction::Xor: {
946 // We can simplify (X^Y) -> X or Y in the user's context if we know that
947 // only bits from X or Y are demanded.
949 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
950 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1,
951 CxtI);
953 Known = LHSKnown ^ RHSKnown;
955 // If the client is only demanding bits that we know, return the known
956 // constant.
957 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
958 return Constant::getIntegerValue(ITy, Known.One);
960 // If all of the demanded bits are known zero on one side, return the
961 // other.
962 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
963 return I->getOperand(0);
964 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
965 return I->getOperand(1);
967 break;
969 case Instruction::AShr: {
970 // Compute the Known bits to simplify things downstream.
971 computeKnownBits(I, Known, Depth, CxtI);
973 // If this user is only demanding bits that we know, return the known
974 // constant.
975 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
976 return Constant::getIntegerValue(ITy, Known.One);
978 // If the right shift operand 0 is a result of a left shift by the same
979 // amount, this is probably a zero/sign extension, which may be unnecessary,
980 // if we do not demand any of the new sign bits. So, return the original
981 // operand instead.
982 const APInt *ShiftRC;
983 const APInt *ShiftLC;
984 Value *X;
985 unsigned BitWidth = DemandedMask.getBitWidth();
986 if (match(I,
987 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
988 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
989 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
990 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
991 return X;
994 break;
996 default:
997 // Compute the Known bits to simplify things downstream.
998 computeKnownBits(I, Known, Depth, CxtI);
1000 // If this user is only demanding bits that we know, return the known
1001 // constant.
1002 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1003 return Constant::getIntegerValue(ITy, Known.One);
1005 break;
1008 return nullptr;
1011 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1012 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1013 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1014 /// of "C2-C1".
1016 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1017 /// ..., bn}, without considering the specific value X is holding.
1018 /// This transformation is legal iff one of following conditions is hold:
1019 /// 1) All the bit in S are 0, in this case E1 == E2.
1020 /// 2) We don't care those bits in S, per the input DemandedMask.
1021 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1022 /// rest bits.
1024 /// Currently we only test condition 2).
1026 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1027 /// not successful.
1028 Value *InstCombinerImpl::simplifyShrShlDemandedBits(
1029 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1030 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1031 if (!ShlOp1 || !ShrOp1)
1032 return nullptr; // No-op.
1034 Value *VarX = Shr->getOperand(0);
1035 Type *Ty = VarX->getType();
1036 unsigned BitWidth = Ty->getScalarSizeInBits();
1037 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1038 return nullptr; // Undef.
1040 unsigned ShlAmt = ShlOp1.getZExtValue();
1041 unsigned ShrAmt = ShrOp1.getZExtValue();
1043 Known.One.clearAllBits();
1044 Known.Zero.setLowBits(ShlAmt - 1);
1045 Known.Zero &= DemandedMask;
1047 APInt BitMask1(APInt::getAllOnesValue(BitWidth));
1048 APInt BitMask2(APInt::getAllOnesValue(BitWidth));
1050 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1051 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1052 (BitMask1.ashr(ShrAmt) << ShlAmt);
1054 if (ShrAmt <= ShlAmt) {
1055 BitMask2 <<= (ShlAmt - ShrAmt);
1056 } else {
1057 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1058 BitMask2.ashr(ShrAmt - ShlAmt);
1061 // Check if condition-2 (see the comment to this function) is satified.
1062 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1063 if (ShrAmt == ShlAmt)
1064 return VarX;
1066 if (!Shr->hasOneUse())
1067 return nullptr;
1069 BinaryOperator *New;
1070 if (ShrAmt < ShlAmt) {
1071 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1072 New = BinaryOperator::CreateShl(VarX, Amt);
1073 BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1074 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1075 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1076 } else {
1077 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1078 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1079 BinaryOperator::CreateAShr(VarX, Amt);
1080 if (cast<BinaryOperator>(Shr)->isExact())
1081 New->setIsExact(true);
1084 return InsertNewInstWith(New, *Shl);
1087 return nullptr;
1090 /// The specified value produces a vector with any number of elements.
1091 /// This method analyzes which elements of the operand are undef or poison and
1092 /// returns that information in UndefElts.
1094 /// DemandedElts contains the set of elements that are actually used by the
1095 /// caller, and by default (AllowMultipleUsers equals false) the value is
1096 /// simplified only if it has a single caller. If AllowMultipleUsers is set
1097 /// to true, DemandedElts refers to the union of sets of elements that are
1098 /// used by all callers.
1100 /// If the information about demanded elements can be used to simplify the
1101 /// operation, the operation is simplified, then the resultant value is
1102 /// returned. This returns null if no change was made.
1103 Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V,
1104 APInt DemandedElts,
1105 APInt &UndefElts,
1106 unsigned Depth,
1107 bool AllowMultipleUsers) {
1108 // Cannot analyze scalable type. The number of vector elements is not a
1109 // compile-time constant.
1110 if (isa<ScalableVectorType>(V->getType()))
1111 return nullptr;
1113 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1114 APInt EltMask(APInt::getAllOnesValue(VWidth));
1115 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1117 if (match(V, m_Undef())) {
1118 // If the entire vector is undef or poison, just return this info.
1119 UndefElts = EltMask;
1120 return nullptr;
1123 if (DemandedElts.isNullValue()) { // If nothing is demanded, provide poison.
1124 UndefElts = EltMask;
1125 return PoisonValue::get(V->getType());
1128 UndefElts = 0;
1130 if (auto *C = dyn_cast<Constant>(V)) {
1131 // Check if this is identity. If so, return 0 since we are not simplifying
1132 // anything.
1133 if (DemandedElts.isAllOnesValue())
1134 return nullptr;
1136 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1137 Constant *Poison = PoisonValue::get(EltTy);
1138 SmallVector<Constant*, 16> Elts;
1139 for (unsigned i = 0; i != VWidth; ++i) {
1140 if (!DemandedElts[i]) { // If not demanded, set to poison.
1141 Elts.push_back(Poison);
1142 UndefElts.setBit(i);
1143 continue;
1146 Constant *Elt = C->getAggregateElement(i);
1147 if (!Elt) return nullptr;
1149 Elts.push_back(Elt);
1150 if (isa<UndefValue>(Elt)) // Already undef or poison.
1151 UndefElts.setBit(i);
1154 // If we changed the constant, return it.
1155 Constant *NewCV = ConstantVector::get(Elts);
1156 return NewCV != C ? NewCV : nullptr;
1159 // Limit search depth.
1160 if (Depth == 10)
1161 return nullptr;
1163 if (!AllowMultipleUsers) {
1164 // If multiple users are using the root value, proceed with
1165 // simplification conservatively assuming that all elements
1166 // are needed.
1167 if (!V->hasOneUse()) {
1168 // Quit if we find multiple users of a non-root value though.
1169 // They'll be handled when it's their turn to be visited by
1170 // the main instcombine process.
1171 if (Depth != 0)
1172 // TODO: Just compute the UndefElts information recursively.
1173 return nullptr;
1175 // Conservatively assume that all elements are needed.
1176 DemandedElts = EltMask;
1180 Instruction *I = dyn_cast<Instruction>(V);
1181 if (!I) return nullptr; // Only analyze instructions.
1183 bool MadeChange = false;
1184 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1185 APInt Demanded, APInt &Undef) {
1186 auto *II = dyn_cast<IntrinsicInst>(Inst);
1187 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1188 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1189 replaceOperand(*Inst, OpNum, V);
1190 MadeChange = true;
1194 APInt UndefElts2(VWidth, 0);
1195 APInt UndefElts3(VWidth, 0);
1196 switch (I->getOpcode()) {
1197 default: break;
1199 case Instruction::GetElementPtr: {
1200 // The LangRef requires that struct geps have all constant indices. As
1201 // such, we can't convert any operand to partial undef.
1202 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1203 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1204 I != E; I++)
1205 if (I.isStruct())
1206 return true;;
1207 return false;
1209 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1210 break;
1212 // Conservatively track the demanded elements back through any vector
1213 // operands we may have. We know there must be at least one, or we
1214 // wouldn't have a vector result to get here. Note that we intentionally
1215 // merge the undef bits here since gepping with either an undef base or
1216 // index results in undef.
1217 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1218 if (match(I->getOperand(i), m_Undef())) {
1219 // If the entire vector is undefined, just return this info.
1220 UndefElts = EltMask;
1221 return nullptr;
1223 if (I->getOperand(i)->getType()->isVectorTy()) {
1224 APInt UndefEltsOp(VWidth, 0);
1225 simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp);
1226 UndefElts |= UndefEltsOp;
1230 break;
1232 case Instruction::InsertElement: {
1233 // If this is a variable index, we don't know which element it overwrites.
1234 // demand exactly the same input as we produce.
1235 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1236 if (!Idx) {
1237 // Note that we can't propagate undef elt info, because we don't know
1238 // which elt is getting updated.
1239 simplifyAndSetOp(I, 0, DemandedElts, UndefElts2);
1240 break;
1243 // The element inserted overwrites whatever was there, so the input demanded
1244 // set is simpler than the output set.
1245 unsigned IdxNo = Idx->getZExtValue();
1246 APInt PreInsertDemandedElts = DemandedElts;
1247 if (IdxNo < VWidth)
1248 PreInsertDemandedElts.clearBit(IdxNo);
1250 // If we only demand the element that is being inserted and that element
1251 // was extracted from the same index in another vector with the same type,
1252 // replace this insert with that other vector.
1253 // Note: This is attempted before the call to simplifyAndSetOp because that
1254 // may change UndefElts to a value that does not match with Vec.
1255 Value *Vec;
1256 if (PreInsertDemandedElts == 0 &&
1257 match(I->getOperand(1),
1258 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1259 Vec->getType() == I->getType()) {
1260 return Vec;
1263 simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts);
1265 // If this is inserting an element that isn't demanded, remove this
1266 // insertelement.
1267 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1268 Worklist.push(I);
1269 return I->getOperand(0);
1272 // The inserted element is defined.
1273 UndefElts.clearBit(IdxNo);
1274 break;
1276 case Instruction::ShuffleVector: {
1277 auto *Shuffle = cast<ShuffleVectorInst>(I);
1278 assert(Shuffle->getOperand(0)->getType() ==
1279 Shuffle->getOperand(1)->getType() &&
1280 "Expected shuffle operands to have same type");
1281 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1282 ->getNumElements();
1283 // Handle trivial case of a splat. Only check the first element of LHS
1284 // operand.
1285 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1286 DemandedElts.isAllOnesValue()) {
1287 if (!match(I->getOperand(1), m_Undef())) {
1288 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1289 MadeChange = true;
1291 APInt LeftDemanded(OpWidth, 1);
1292 APInt LHSUndefElts(OpWidth, 0);
1293 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1294 if (LHSUndefElts[0])
1295 UndefElts = EltMask;
1296 else
1297 UndefElts.clearAllBits();
1298 break;
1301 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1302 for (unsigned i = 0; i < VWidth; i++) {
1303 if (DemandedElts[i]) {
1304 unsigned MaskVal = Shuffle->getMaskValue(i);
1305 if (MaskVal != -1u) {
1306 assert(MaskVal < OpWidth * 2 &&
1307 "shufflevector mask index out of range!");
1308 if (MaskVal < OpWidth)
1309 LeftDemanded.setBit(MaskVal);
1310 else
1311 RightDemanded.setBit(MaskVal - OpWidth);
1316 APInt LHSUndefElts(OpWidth, 0);
1317 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1319 APInt RHSUndefElts(OpWidth, 0);
1320 simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts);
1322 // If this shuffle does not change the vector length and the elements
1323 // demanded by this shuffle are an identity mask, then this shuffle is
1324 // unnecessary.
1326 // We are assuming canonical form for the mask, so the source vector is
1327 // operand 0 and operand 1 is not used.
1329 // Note that if an element is demanded and this shuffle mask is undefined
1330 // for that element, then the shuffle is not considered an identity
1331 // operation. The shuffle prevents poison from the operand vector from
1332 // leaking to the result by replacing poison with an undefined value.
1333 if (VWidth == OpWidth) {
1334 bool IsIdentityShuffle = true;
1335 for (unsigned i = 0; i < VWidth; i++) {
1336 unsigned MaskVal = Shuffle->getMaskValue(i);
1337 if (DemandedElts[i] && i != MaskVal) {
1338 IsIdentityShuffle = false;
1339 break;
1342 if (IsIdentityShuffle)
1343 return Shuffle->getOperand(0);
1346 bool NewUndefElts = false;
1347 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1348 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1349 bool LHSUniform = true;
1350 bool RHSUniform = true;
1351 for (unsigned i = 0; i < VWidth; i++) {
1352 unsigned MaskVal = Shuffle->getMaskValue(i);
1353 if (MaskVal == -1u) {
1354 UndefElts.setBit(i);
1355 } else if (!DemandedElts[i]) {
1356 NewUndefElts = true;
1357 UndefElts.setBit(i);
1358 } else if (MaskVal < OpWidth) {
1359 if (LHSUndefElts[MaskVal]) {
1360 NewUndefElts = true;
1361 UndefElts.setBit(i);
1362 } else {
1363 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1364 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1365 LHSUniform = LHSUniform && (MaskVal == i);
1367 } else {
1368 if (RHSUndefElts[MaskVal - OpWidth]) {
1369 NewUndefElts = true;
1370 UndefElts.setBit(i);
1371 } else {
1372 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1373 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1374 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1379 // Try to transform shuffle with constant vector and single element from
1380 // this constant vector to single insertelement instruction.
1381 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1382 // insertelement V, C[ci], ci-n
1383 if (OpWidth ==
1384 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1385 Value *Op = nullptr;
1386 Constant *Value = nullptr;
1387 unsigned Idx = -1u;
1389 // Find constant vector with the single element in shuffle (LHS or RHS).
1390 if (LHSIdx < OpWidth && RHSUniform) {
1391 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1392 Op = Shuffle->getOperand(1);
1393 Value = CV->getOperand(LHSValIdx);
1394 Idx = LHSIdx;
1397 if (RHSIdx < OpWidth && LHSUniform) {
1398 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1399 Op = Shuffle->getOperand(0);
1400 Value = CV->getOperand(RHSValIdx);
1401 Idx = RHSIdx;
1404 // Found constant vector with single element - convert to insertelement.
1405 if (Op && Value) {
1406 Instruction *New = InsertElementInst::Create(
1407 Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx),
1408 Shuffle->getName());
1409 InsertNewInstWith(New, *Shuffle);
1410 return New;
1413 if (NewUndefElts) {
1414 // Add additional discovered undefs.
1415 SmallVector<int, 16> Elts;
1416 for (unsigned i = 0; i < VWidth; ++i) {
1417 if (UndefElts[i])
1418 Elts.push_back(UndefMaskElem);
1419 else
1420 Elts.push_back(Shuffle->getMaskValue(i));
1422 Shuffle->setShuffleMask(Elts);
1423 MadeChange = true;
1425 break;
1427 case Instruction::Select: {
1428 // If this is a vector select, try to transform the select condition based
1429 // on the current demanded elements.
1430 SelectInst *Sel = cast<SelectInst>(I);
1431 if (Sel->getCondition()->getType()->isVectorTy()) {
1432 // TODO: We are not doing anything with UndefElts based on this call.
1433 // It is overwritten below based on the other select operands. If an
1434 // element of the select condition is known undef, then we are free to
1435 // choose the output value from either arm of the select. If we know that
1436 // one of those values is undef, then the output can be undef.
1437 simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1440 // Next, see if we can transform the arms of the select.
1441 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1442 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1443 for (unsigned i = 0; i < VWidth; i++) {
1444 // isNullValue() always returns false when called on a ConstantExpr.
1445 // Skip constant expressions to avoid propagating incorrect information.
1446 Constant *CElt = CV->getAggregateElement(i);
1447 if (isa<ConstantExpr>(CElt))
1448 continue;
1449 // TODO: If a select condition element is undef, we can demand from
1450 // either side. If one side is known undef, choosing that side would
1451 // propagate undef.
1452 if (CElt->isNullValue())
1453 DemandedLHS.clearBit(i);
1454 else
1455 DemandedRHS.clearBit(i);
1459 simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2);
1460 simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3);
1462 // Output elements are undefined if the element from each arm is undefined.
1463 // TODO: This can be improved. See comment in select condition handling.
1464 UndefElts = UndefElts2 & UndefElts3;
1465 break;
1467 case Instruction::BitCast: {
1468 // Vector->vector casts only.
1469 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1470 if (!VTy) break;
1471 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1472 APInt InputDemandedElts(InVWidth, 0);
1473 UndefElts2 = APInt(InVWidth, 0);
1474 unsigned Ratio;
1476 if (VWidth == InVWidth) {
1477 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1478 // elements as are demanded of us.
1479 Ratio = 1;
1480 InputDemandedElts = DemandedElts;
1481 } else if ((VWidth % InVWidth) == 0) {
1482 // If the number of elements in the output is a multiple of the number of
1483 // elements in the input then an input element is live if any of the
1484 // corresponding output elements are live.
1485 Ratio = VWidth / InVWidth;
1486 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1487 if (DemandedElts[OutIdx])
1488 InputDemandedElts.setBit(OutIdx / Ratio);
1489 } else if ((InVWidth % VWidth) == 0) {
1490 // If the number of elements in the input is a multiple of the number of
1491 // elements in the output then an input element is live if the
1492 // corresponding output element is live.
1493 Ratio = InVWidth / VWidth;
1494 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1495 if (DemandedElts[InIdx / Ratio])
1496 InputDemandedElts.setBit(InIdx);
1497 } else {
1498 // Unsupported so far.
1499 break;
1502 simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2);
1504 if (VWidth == InVWidth) {
1505 UndefElts = UndefElts2;
1506 } else if ((VWidth % InVWidth) == 0) {
1507 // If the number of elements in the output is a multiple of the number of
1508 // elements in the input then an output element is undef if the
1509 // corresponding input element is undef.
1510 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1511 if (UndefElts2[OutIdx / Ratio])
1512 UndefElts.setBit(OutIdx);
1513 } else if ((InVWidth % VWidth) == 0) {
1514 // If the number of elements in the input is a multiple of the number of
1515 // elements in the output then an output element is undef if all of the
1516 // corresponding input elements are undef.
1517 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1518 APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1519 if (SubUndef.countPopulation() == Ratio)
1520 UndefElts.setBit(OutIdx);
1522 } else {
1523 llvm_unreachable("Unimp");
1525 break;
1527 case Instruction::FPTrunc:
1528 case Instruction::FPExt:
1529 simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1530 break;
1532 case Instruction::Call: {
1533 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1534 if (!II) break;
1535 switch (II->getIntrinsicID()) {
1536 case Intrinsic::masked_gather: // fallthrough
1537 case Intrinsic::masked_load: {
1538 // Subtlety: If we load from a pointer, the pointer must be valid
1539 // regardless of whether the element is demanded. Doing otherwise risks
1540 // segfaults which didn't exist in the original program.
1541 APInt DemandedPtrs(APInt::getAllOnesValue(VWidth)),
1542 DemandedPassThrough(DemandedElts);
1543 if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1544 for (unsigned i = 0; i < VWidth; i++) {
1545 Constant *CElt = CV->getAggregateElement(i);
1546 if (CElt->isNullValue())
1547 DemandedPtrs.clearBit(i);
1548 else if (CElt->isAllOnesValue())
1549 DemandedPassThrough.clearBit(i);
1551 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1552 simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2);
1553 simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3);
1555 // Output elements are undefined if the element from both sources are.
1556 // TODO: can strengthen via mask as well.
1557 UndefElts = UndefElts2 & UndefElts3;
1558 break;
1560 default: {
1561 // Handle target specific intrinsics
1562 Optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1563 *II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
1564 simplifyAndSetOp);
1565 if (V.hasValue())
1566 return V.getValue();
1567 break;
1569 } // switch on IntrinsicID
1570 break;
1571 } // case Call
1572 } // switch on Opcode
1574 // TODO: We bail completely on integer div/rem and shifts because they have
1575 // UB/poison potential, but that should be refined.
1576 BinaryOperator *BO;
1577 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1578 simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1579 simplifyAndSetOp(I, 1, DemandedElts, UndefElts2);
1581 // Any change to an instruction with potential poison must clear those flags
1582 // because we can not guarantee those constraints now. Other analysis may
1583 // determine that it is safe to re-apply the flags.
1584 if (MadeChange)
1585 BO->dropPoisonGeneratingFlags();
1587 // Output elements are undefined if both are undefined. Consider things
1588 // like undef & 0. The result is known zero, not undef.
1589 UndefElts &= UndefElts2;
1592 // If we've proven all of the lanes undef, return an undef value.
1593 // TODO: Intersect w/demanded lanes
1594 if (UndefElts.isAllOnesValue())
1595 return UndefValue::get(I->getType());;
1597 return MadeChange ? I : nullptr;